blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ca89bcacf79024769a12105a902d13753f18373a | 51c20f8d06ab05efdad94c76a359bcf01ded6894 | /assign2/src/assisgn2.cpp | 53305cd97d845eb5696d8d3a4a62b9e6376b6347 | [] | no_license | yashguptaab99/Priority-Queue | 02a2887f1b2051a4f0ff30733a279d05e0389d1d | b26b801e56e2575a602d8e219e436539f30a1da4 | refs/heads/master | 2020-06-08T09:37:31.752510 | 2019-06-22T07:48:47 | 2019-06-22T07:48:47 | 193,206,847 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,285 | cpp | //============================================================================
// Class : SE9
// Batch : F9
// Roll No. : 23121
// Author : Yash Gupta
// Assignment No. : 1
// Problem Statement: Implement priority queue as ADT using single linked list for servicing
// patients in an hospital with priorities as i) Serious (top priority) ii) medium
// illness (medium priority) iii) General (Least priority)
//============================================================================
#include<iostream>
#include "queue.h"
using namespace std;
int main()
{
queue_adt patient;//Priority Queue object
int choice;
do
{
//MENU
cout<<"\n\n\t*********************\n";
cout<<"\tWELCOME TO THE MENU ! \n";
cout<<"\t*********************\n";
cout<<"\n\t1.Entry For A Patient\n\n\t2.Display Priority Queue for Patients\n\n\t3.Delete an Entry (According to Priority)\n\n\t4.Exit";
cout<<"\n\nEnter the Choice :";
cin>>choice;
switch(choice)
{
case 1:
patient.enqueue();
break;
case 2:
patient.display();
break;
case 3:
patient.dequeue();
break;
case 4://Exit
cout<<"\n\tProgram Terminated Successfully !!";
break;
}
}while(choice!=4);
return 0;
}
| [
"noreply@github.com"
] | yashguptaab99.noreply@github.com |
85eb77008db888777e71d34b53f399b25de6bccb | dcf3b364645a1c6ce9c0ac17bfa3f1a4c7b9b7ae | /server/Apps/FightServer/GameLogic.h | 54478836c72df0fff7a15520f53e253bd757d647 | [] | no_license | cu8Fsuz/Kurumi | 73235466850f66461b82ca362d00a087fdaf9baf | aaa3e4fca3205686bbb5b02662dffac6d6f0d1c8 | refs/heads/master | 2023-07-24T14:01:47.828798 | 2021-09-01T03:41:04 | 2021-09-01T03:41:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,611 | h | #pragma once
#include "game/GGameWorld.h"
#include "GamePlayer.h"
#include "GameProto.h"
// 服务器游戏同步逻辑
class GameLogic
{
public:
GameLogic();
~GameLogic();
err::Code init(const GGameWorldInitArgs &args, const ::google::protobuf::RepeatedPtrField< ::svr_msg::FightRoleSpawnInfo >& roles);
void update(float dt);
// 获取当前逻辑帧
uint32_t getGameLogicFrame() const;
// 获取当前状态
int32_t getGameStatus() const;
public:
err::Code joinCode(uint32_t sessionID, const msg::JoinFightReq& req);
void doJoin(uint32_t sessionID, const msg::JoinFightReq& req);
void exitGame(int64_t playerID);
err::Code exitGameWithSessionID(uint32_t sessionID);
public:
G_SYNTHESIZE_PASS_BY_REF(GGameWorldInitArgs, m_initArgs, InitArgs);
G_SYNTHESIZE(bool, m_isFinish, IsFinish);
G_SYNTHESIZE(int32_t, m_uuid, uuid);
protected:
void pingUpdate(float dt);
void update_WaitConnect(float dt);
void update_Ready(float dt);
void update_Run(float dt);
void update_Wait(float dt);
GamePlayer* getPlayerBySessionID(uint32_t sessionID);
// 获取逻辑帧最慢的一个玩家
GamePlayer* getSlowestPlayer();
bool containPlayer(int64_t playerID);
void sendToAllPlayer(MessageID msgID, const ::google::protobuf::MessageLite& msg);
// 广播所有玩家加载信息
void sendLoadingPercentToAllPlayer();
// 向玩家推帧
void pushFrameInfo(uint32_t startFrame, uint32_t sessionID);
protected:
void onMsg_RunNextFrameReq(uint32_t sessionID, const msg::RunNextFrameReq& req);
void onMsg_PlayerLoadingReq(uint32_t sessionID, const msg::PlayerLoadingReq& req);
void onMsg_Pong(uint32_t sessionID, const msg::Pong& req);
private:
std::unique_ptr<GGameWorld> m_world;
GNetService* m_pNetService;
GApplication* m_pApplication;
// 本局游戏玩家数量
int32_t m_playerCount;
std::unique_ptr<GamePlayer> m_players[G_FIGHT_MAX_PLAYER_COUNT];
std::set<int64_t> m_playerIDSet;
enum RUN_STATE
{
WAIT_CONNECT = 0, // 等待客户端连接服务器
READY, // 准备状态,等待玩家全部准备完毕
RUN, // 正常运行状态
WAIT // 等待状态,等待逻辑帧最慢的客户端跟上服务器逻辑帧
};
RUN_STATE m_state;
float m_waitTime;
// 游戏最后一次执行逻辑时间
float m_lastRunTime;
// 游戏累计运行时间
float m_accumilatedTime;
msg::PlayerRecords m_pastRecords;
//std::vector<msg::PlayerFrameInput*> m_curFrameInputs;
msg::RunNextFrameAck m_runNextFrameAckCache;
msg::PlayerFrameInput* m_pCacheFrameInputs[G_FIGHT_MAX_PLAYER_COUNT];
float m_pingTime;
float m_pingPushTime;
};
| [
"www.tkzc@foxmail.com"
] | www.tkzc@foxmail.com |
859e50e761fbcef1e9a0c0aa439f09527cdc280d | 2248e62ab73c5b36e31ab5306eec47252ed3671b | /Chapter 2/2_1_3.cpp | 188b4f5decb510d8c15d36a9a5045a34429cdda8 | [] | no_license | ShadowHu/CppPrimer5th | 845c9e9478ea4133adbae1b14e508db8d8420163 | 849263129dadea6743b759a79175a105cabc415c | refs/heads/master | 2021-01-01T05:24:23.295908 | 2017-05-11T09:22:49 | 2017-05-11T09:22:49 | 57,224,274 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 367 | cpp | /*************************************************************************
> File Name: 2_1_3.cpp
> Author: ma6174
> Mail: ma6174@163.com
> Created Time: 2014年08月11日 星期一 14时31分11秒
************************************************************************/
#include<iostream>
using namespace std;
int main(){
cout<<"\x1234";
return 0;
}
| [
"shadow_hu1441@163.com"
] | shadow_hu1441@163.com |
62eebfea848587478ff383beee45ce30e19e796c | 14d1a24f4e3b687b64a928d7e77737047bfb6a78 | /WinApi/WndProc.cpp | f6cc56b0745454505e918acf9956ea9244002ca5 | [] | no_license | chan328/WinAPI | 612969832fdda3daf0498254a896da89c1c158e3 | 9fa57e4dc8b1d54cf8c46ce31517668f3bcb7736 | refs/heads/master | 2020-03-28T06:01:08.312821 | 2018-09-16T12:13:28 | 2018-09-16T12:13:28 | 147,809,285 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,976 | cpp | // WndProc
// 메시지 처리 함수란 메시지가 발생할 대 반응을 처리하는 일을 하며
// WinMain 함수와는 별도로 WndProc이라는 이름으로 존재한다.
// 윈도우 프로시저(Window Procedure)라는 뜻을 가지고있지만, 윈드 프록이라고 읽는다.
// WndProc은 WinMain에서 호출하는 것이 아닌 윈도우즈에 의해 호출된다.
// WinMain내의 메시지 루프는 메시지를 메시지 처리 함수로 배내주기만 할 뿐이며
// WndProc은 메시지가 입력되면 윈도우즈에 의해 호출이 되어 메시지를 처리함.
// 이렇게 운영체제에 의해 호출되는 응용 프로그램내의 함수를 CallBakc(콜백 함수)라고 한다.
// WndProc의 인수는 모두 4개이며 MSG구조체의 멤버 4개와 동일하다.
// hWnd는 메시지를 받을 윈도우의 핸들이며
// iMessage는 어떤 종류의 메시지인가, 즉 어떤 변화가 발생했는가에 대한 정보를 가진다.
// ex) iMessage가 WM_MOVE면 윈도우의 위치가 변경되었음을 알리고 WM_DESTROY면
// 윈도우가 파괴되었음을 알리는 것이다.
//wParam, IParam은 iMessage의 메시지에 따른 부가적인 정보를 가진다.
// WndProc의 구조는 대체로 다음과 같은 형태를 가진다. 메시지의 종류에 따라
// 다중분기하여 메시지별로 처리를 진행한다.
switch (iMessage)
{
case Msg1: // Msg1 메시지가 전달되면 처리 1을 한 후 리턴하고
char "처리1";
break;
case Msg2: // Msg2 메시지가 전달되면 처리 2를 한 후 리턴한다.
char "처리2";
break;
case Msg3: // case 문은 메시지가 전달된 만큼 반복된다.
char "처리3";
break;
default:
return DefWindowProc(...);
break; // DefWindwoProc 함수는 WndProc에서 처리하지 않은 나머지 메시지에 대한
// 처리를 해준다.
}
// 예를 들어 시스템 메뉴를 더블클릭하면 프로그램이 종료되는데 이런 처리는 별도로
// 처리 하지 않아도 DefWindowProc으로 넘겨주기만 하면 된다.
// 예제의 메시지 처리 함수는 다음과 같이 되어있다.
LRESULT CALLBACK WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
switch (iMessage)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return(DefWindowProc(hWnd, iMessage, wParam, IParam));
}
// 위 예제는 WM_DESTROY 메시지만을 처리하고 있으며 나머지 메시지에 대해서는
// DefWindowProc에 맡긴다. WndProc에서 이 메시지가 발생하면 PostQuitMessage 함수를
// 호출하여 WM_QUIT 메시지를 보낸다. WM_QUIT 메시지가 입력되면 메시지 루프의
// GetMessage 함수 리턴값이 False가 되어 프로그램이 종료한다.
// WM_DESTROY 이외의 메시지는 모두 DefWindowProc 함수로 전달되며 이 함수에서
// 디폴트 처리를 수행해 준다. WndProc은 메시지를 처리했을 경우 반드시 0을 return
// 해줘야 한다. | [
"rkdcks020328@gmail.com"
] | rkdcks020328@gmail.com |
8b2a9106a9f5ff795515e1a36cf6c03644126c18 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/f0/eb82ad8d237988/main.cpp | a75c149765b86ea8e5905b622de5b6eba96b331d | [] | 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 | 886 | cpp | #include <iostream>
#include <string>
#include <utility>
struct A {
struct Tag{};
std::string name;
int value;
A (const std::string& n, int v) : name(n), value(v) {}
A (const std::string& n, int v, Tag) : name(n), value(v) {std::cout << "Constructor with Tag called.\n";}
};
struct B : A {using A::A;};
struct C : B {using B::B;};
struct D : C {
char special;
template < typename ... ARGS >
D( const std::string& n, int v, char s, ARGS&&... args ) : C( n, v, std::forward<ARGS>(args)... ), special(s) {}
};
struct E : B {
double special;
template < typename ... ARGS >
E( const std::string& n, int v, double d, ARGS&&... args ) : B( n, v, std::forward<ARGS>(args)... ), special(d) {}
};
int main() {
A a("a", 1, A::Tag{});
B b("a", 2, A::Tag{});
C c("c", 3, A::Tag{});
D d("d", 4, 'd', A::Tag{});
E e("e", 5, 3.14, A::Tag{});
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
b3eecbc41394637c051c25b6e35f0bf1aa5cc43b | e5dc90655caa598fae65f95a14bc2a93084cf854 | /src/cpu/x64/jit_avx512_core_f32_wino_conv_4x3.cpp | c0355973253b7526f6a836a12d9fec12d198197c | [
"Apache-2.0",
"BSD-3-Clause",
"BSL-1.0",
"BSD-2-Clause"
] | permissive | dongxiao92/ZenDNN | d4bedf41c2166f63f55eea4b08e1801be04a8404 | 99e79349fe4bd512711ebc4d63deba69a732a18e | refs/heads/main | 2023-07-10T01:30:57.527781 | 2021-08-11T13:30:35 | 2021-08-11T13:30:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,148 | cpp | /*******************************************************************************
* Modifications Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.
* Notified per clause 4(b) of the license.
*******************************************************************************/
/*******************************************************************************
* Copyright 2017-2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifdef __INTEL_COMPILER
#include <immintrin.h>
#endif
#include "zendnn_types.h"
#include "common/c_types_map.hpp"
#include "common/zendnn_thread.hpp"
#include "common/type_helpers.hpp"
#include "common/utils.hpp"
#include "cpu/x64/jit_avx512_core_f32_wino_conv_4x3.hpp"
#ifndef _MSC_VER
#define pragma_unroll _Pragma("unroll")
#else
#define pragma_unroll
#endif
namespace zendnn {
namespace impl {
namespace cpu {
namespace x64 {
using namespace zendnn::impl::status;
using namespace zendnn::impl::memory_tracking::names;
using namespace zendnn::impl::utils;
template <bool is_fwd>
void _jit_avx512_core_f32_wino_conv_4x3_t<is_fwd>::weight_transform_data(
const jit_conv_winograd_conf_t &jcp, float *wp, float *twp) const {
float G[] = {0.26890756302521f, 0.688403361344538f, 0.119514472455649f,
1.13777777777778f, 0.430252100840336f, 0.179271708683473f};
const int kh = 3;
const int kw = 3;
float Fw[alpha][alpha][simd_w][simd_w];
float F[kh][kw][simd_w][simd_w];
float T[alpha][3][simd_w];
auto p = jit_wino_transform_call_s();
p.src = wp;
p.dst = twp;
p.G = G;
p.M = F;
p.Mw = Fw;
p.T = T;
kernel_->weights_transform_data_ker(&p);
}
template <bool is_fwd>
void _jit_avx512_core_f32_wino_conv_4x3_t<is_fwd>::output_transform_data(
int image, const jit_conv_winograd_conf_t &jcp, const post_ops_t &p_ops,
float *toutp, float *pout_b, float *bias) const {
float G[] = {0.625f, 1.5f, 0.390625f, 2.25f, 0.244140625f, 3.375f};
float Ow[alpha][alpha][simd_w];
float O[tile_size][tile_size][simd_w];
float T[tile_size][alpha][simd_w];
auto p = jit_wino_transform_call_s();
p.src = toutp;
p.dst = pout_b;
p.G = G;
p.M = O;
p.Mw = Ow;
p.T = T;
p.bias = bias;
int tile_base_index = image * jcp.itiles * jcp.jtiles;
int tile_block_ur = tile_base_index % jcp.tile_block_ur;
int nb_tile_block_ur
= (tile_base_index / jcp.tile_block_ur) % jcp.nb_tile_block_ur;
int tile_block
= (tile_base_index / jcp.tile_block_ur) / jcp.nb_tile_block_ur;
for (int tj = 0; tj < jcp.jtiles; tj++) {
for (int ti = 0; ti < jcp.itiles; ti++) {
p.tile_block_ur = tile_block_ur;
p.nb_tile_block_ur = nb_tile_block_ur;
p.tile_block = tile_block;
p.tj = tj;
p.ti = ti;
kernel_->output_transform_data_ker(&p);
tile_block_ur++;
if (tile_block_ur >= jcp.tile_block_ur) {
tile_block_ur = 0;
nb_tile_block_ur++;
}
if (nb_tile_block_ur >= jcp.nb_tile_block_ur) {
nb_tile_block_ur = 0;
tile_block++;
}
}
}
}
template <bool is_fwd>
void _jit_avx512_core_f32_wino_conv_4x3_t<
is_fwd>::output_transform_tileblock_data(int tile_block,
const jit_conv_winograd_conf_t &jcp, const post_ops_t &p_ops,
float *toutp, float *outp, float *bias) const {
float G[] = {0.625f, 1.5f, 0.390625f, 2.25f, 0.244140625f, 3.375f};
float Ow[alpha][alpha][simd_w];
float O[tile_size][tile_size][simd_w];
float T[tile_size][alpha][simd_w];
auto p = jit_wino_transform_call_s();
p.src = toutp;
p.dst = outp;
p.G = G;
p.M = O;
p.Mw = Ow;
p.T = T;
p.bias = bias;
int outw = is_fwd ? jcp.ow : jcp.iw;
int outh = is_fwd ? jcp.oh : jcp.ih;
int tile_index = tile_block * jcp.nb_tile_block_ur * jcp.tile_block_ur;
for (int nb_tile_block_ur = 0; nb_tile_block_ur < jcp.nb_tile_block_ur;
nb_tile_block_ur++) {
for (int tile_block_ur = 0; tile_block_ur < jcp.tile_block_ur;
tile_block_ur++) {
int img = tile_index / (jcp.jtiles * jcp.itiles);
int ti = tile_index % jcp.itiles;
int tj = (tile_index / jcp.itiles) % jcp.jtiles;
p.tile_block_ur = tile_block_ur;
p.nb_tile_block_ur = nb_tile_block_ur;
p.tile_block = tile_block;
p.tj = tj;
p.ti = ti;
p.dst = outp
+ img * (jcp.dimM / jcp.dimM_simd_block) * outh * outw
* jcp.dimM_simd_block;
kernel_->output_transform_data_ker(&p);
tile_index++;
}
}
}
template <bool is_fwd>
void _jit_avx512_core_f32_wino_conv_4x3_t<is_fwd>::input_transform_data(
int image, const jit_conv_winograd_conf_t &jcp, float *inp,
float *tinp) const {
float G[] = {-2.25f, -0.390625f, 0.87890625f, -2.640625f, 0.625f, -0.625f,
1.5f, -1.5f, -2.640625f};
float Iw[alpha][alpha][simd_w];
float I[alpha][alpha][simd_w];
float T[alpha][alpha][simd_w];
auto p = jit_wino_transform_call_s();
p.src = inp;
p.dst = tinp;
p.G = G;
p.M = I;
p.Mw = Iw;
p.T = T;
int tile_base_index = image * jcp.itiles * jcp.jtiles;
int tile_block_ur = tile_base_index % jcp.tile_block_ur;
int nb_tile_block_ur
= (tile_base_index / jcp.tile_block_ur) % jcp.nb_tile_block_ur;
int tile_block
= (tile_base_index / jcp.tile_block_ur) / jcp.nb_tile_block_ur;
for (int tj = 0; tj < jcp.jtiles; tj++) {
for (int ti = 0; ti < jcp.itiles; ti++) {
p.tile_block_ur = tile_block_ur;
p.nb_tile_block_ur = nb_tile_block_ur;
p.tile_block = tile_block;
p.tj = tj;
p.ti = ti;
kernel_->input_transform_data_ker(&p);
tile_block_ur++;
if (tile_block_ur >= jcp.tile_block_ur) {
tile_block_ur = 0;
nb_tile_block_ur++;
}
if (nb_tile_block_ur >= jcp.nb_tile_block_ur) {
nb_tile_block_ur = 0;
tile_block++;
}
}
}
}
template <bool is_fwd>
void _jit_avx512_core_f32_wino_conv_4x3_t<
is_fwd>::input_transform_tileblock_data(int tile_block,
const jit_conv_winograd_conf_t &jcp, float *inp, float *tinp) const {
float G[] = {-2.25f, -0.390625f, 0.87890625f, -2.640625f, 0.625f, -0.625f,
1.5f, -1.5f, -2.640625f};
float Iw[alpha][alpha][simd_w];
float I[alpha][alpha][simd_w];
float T[alpha][alpha][simd_w];
const int inph = is_fwd ? jcp.ih : jcp.oh;
const int inpw = is_fwd ? jcp.iw : jcp.ow;
array_offset_calculator<float, 5> input(
inp, jcp.mb, jcp.dimK / simd_w, inph, inpw, simd_w);
array_offset_calculator<float, 7> output(tinp, alpha, alpha, jcp.dimN_block,
jcp.dimK_nb_block, jcp.dimK_block, jcp.dimN_reg_block,
jcp.dimK_reg_block);
auto p = jit_wino_transform_call_s();
p.dst = tinp;
p.G = G;
p.M = I;
p.Mw = Iw;
p.T = T;
int tile_index = tile_block * jcp.nb_tile_block_ur * jcp.tile_block_ur;
for (int nb_tile_block_ur = 0; nb_tile_block_ur < jcp.nb_tile_block_ur;
nb_tile_block_ur++) {
for (int tile_block_ur = 0; tile_block_ur < jcp.tile_block_ur;
tile_block_ur++) {
int img = tile_index / (jcp.jtiles * jcp.itiles);
int ti = tile_index % jcp.itiles;
int tj = (tile_index / jcp.itiles) % jcp.jtiles;
float *pinp_b = &(input(img, 0, 0, 0, 0));
p.src = pinp_b;
p.tile_block_ur = tile_block_ur;
p.nb_tile_block_ur = nb_tile_block_ur;
p.tj = tj;
p.ti = ti;
kernel_->input_transform_data_ker(&p);
tile_index++;
}
}
}
template <bool is_fwd>
void _jit_avx512_core_f32_wino_conv_4x3_t<is_fwd>::_execute_data_W_S_G_D(
float *inp_ptr, float *out_ptr, float *wei_ptr, float *bias_ptr,
const memory_tracking::grantor_t &scratchpad) const {
const auto &jcp = kernel_->jcp;
const auto &p_ops = attr_->post_ops_;
const int inph = is_fwd ? jcp.ih : jcp.oh;
const int inpw = is_fwd ? jcp.iw : jcp.ow;
const int outh = is_fwd ? jcp.oh : jcp.ih;
const int outw = is_fwd ? jcp.ow : jcp.iw;
/* Notation:
FWD: dimM:oc, dimN:ntiles, dimK:ic,
BWD: dimM:ic, dimN:ntiles, dimK:oc,
FWD/BWD: V: src/diff_dst transform, U:weight transform,
M:dst/diff_src transform */
array_offset_calculator<float, 5> input(inp_ptr, jcp.mb,
jcp.dimK / jcp.dimK_reg_block, inph, inpw, jcp.dimK_reg_block);
array_offset_calculator<float, 5> output(out_ptr, jcp.mb,
jcp.dimM / jcp.dimM_simd_block, outh, outw, jcp.dimM_simd_block);
array_offset_calculator<float, 6> weights(wei_ptr,
jcp.oc / jcp.oc_simd_block, jcp.ic / jcp.ic_simd_block, jcp.kh,
jcp.kw, jcp.ic_simd_block, jcp.oc_simd_block);
array_offset_calculator<float, 2> bias(
bias_ptr, jcp.dimM / jcp.dimM_simd_block, jcp.dimM_simd_block);
array_offset_calculator<float, 8> M(is_fwd
? scratchpad.template get<float>(key_wino_M)
: scratchpad.template get<float>(key_wino_V),
jcp.dimN_nb_block, jcp.dimM_nb_block, alpha, alpha, jcp.dimN_block,
jcp.dimM_block * jcp.dimM_reg_block, jcp.dimN_reg_block,
jcp.dimM_simd_block);
auto wino_wei = (jcp.prop_kind == prop_kind::forward_inference)
? wei_ptr
: scratchpad.template get<float>(key_wino_U);
array_offset_calculator<float, 8> U(wino_wei, jcp.dimM_nb_block, alpha,
alpha, jcp.dimK_nb_block, jcp.dimM_block * jcp.dimM_reg_block,
jcp.dimK_block, jcp.dimK_reg_block, jcp.dimM_simd_block);
array_offset_calculator<float, 8> V(is_fwd
? scratchpad.template get<float>(key_wino_V)
: scratchpad.template get<float>(key_wino_M),
jcp.dimN_nb_block, alpha, alpha, jcp.dimN_block, jcp.dimK_nb_block,
jcp.dimK_block, jcp.dimN_reg_block, jcp.dimK_reg_block);
const bool wants_padded_bias
= jcp.with_bias && jcp.oc_without_padding != jcp.oc;
float last_slice_bias[simd_w] = {0};
if (wants_padded_bias) {
for (int oc = 0; oc < jcp.oc_without_padding % jcp.oc_simd_block; ++oc)
last_slice_bias[oc] = bias(jcp.dimM / jcp.dimM_simd_block - 1, oc);
}
parallel_nd(jcp.mb, jcp.dimK_nb_block, jcp.dimK_block,
[&](int img, int K_blk1, int K_blk2) {
input_transform_data(img, jcp,
&(input(img, K_blk1 * jcp.dimK_block + K_blk2, 0, 0,
0)),
&(V(0, 0, 0, 0, K_blk1, K_blk2, 0, 0)));
});
if (jcp.prop_kind != prop_kind::forward_inference) {
parallel_nd(jcp.nb_oc, jcp.nb_ic, (jcp.oc_block * jcp.oc_reg_block),
(jcp.ic_block * jcp.ic_reg_block),
[&](int ofm1, int ifm1, int ofm2, int ifm2) {
float *U_base_ptr = is_fwd
? &(U(ofm1, 0, 0, ifm1, ofm2, ifm2, 0, 0))
: &(U(ifm1, 0, 0, ofm1, ifm2, ofm2, 0, 0));
weight_transform_data(jcp,
&(weights(ofm1 * jcp.oc_block * jcp.oc_reg_block
+ ofm2,
ifm1 * jcp.ic_block * jcp.ic_reg_block
+ ifm2,
0, 0, 0, 0)),
U_base_ptr);
});
}
parallel_nd(jcp.dimN_nb_block, alpha, alpha, jcp.dimM_nb_block,
[&](int N_blk1, int oj, int oi, int M_blk1) {
for (int K_blk1 = 0; K_blk1 < jcp.dimK_nb_block; K_blk1++)
for (int N_blk2 = 0; N_blk2 < jcp.dimN_block; N_blk2++)
kernel_->gemm_loop_ker((float *)&(M(N_blk1, M_blk1, oj,
oi, N_blk2, 0, 0, 0)),
(const float *)&(
U(M_blk1, oj, oi, K_blk1, 0, 0, 0, 0)),
(const float *)&(V(N_blk1, oj, oi, N_blk2,
K_blk1, 0, 0, 0)),
K_blk1);
});
parallel_nd(jcp.mb, jcp.dimM_nb_block,
(jcp.dimM_block * jcp.dimM_reg_block),
[&](int img, int M_blk1, int M_blk2) {
const int M_blk
= M_blk1 * jcp.dimM_block * jcp.dimM_reg_block + M_blk2;
float *bias_ptr = wants_padded_bias
&& M_blk == jcp.dimM / jcp.dimM_simd_block - 1
? last_slice_bias
: &bias(M_blk, 0);
output_transform_data(img, jcp, p_ops,
&(M(0, M_blk1, 0, 0, 0, M_blk2, 0, 0)),
&(output(img, M_blk, 0, 0, 0)), bias_ptr);
});
}
template <bool is_fwd>
void _jit_avx512_core_f32_wino_conv_4x3_t<is_fwd>::_execute_data_W_SGD(
float *inp_ptr, float *out_ptr, float *wei_ptr, float *bias_ptr,
const memory_tracking::grantor_t &scratchpad) const {
const auto &jcp = kernel_->jcp;
const auto &p_ops = attr_->post_ops_;
const int inph = is_fwd ? jcp.ih : jcp.oh;
const int inpw = is_fwd ? jcp.iw : jcp.ow;
const int outh = is_fwd ? jcp.oh : jcp.ih;
const int outw = is_fwd ? jcp.ow : jcp.iw;
array_offset_calculator<float, 5> input(inp_ptr, jcp.mb,
jcp.dimK / jcp.dimK_reg_block, inph, inpw, jcp.dimK_reg_block);
array_offset_calculator<float, 5> output(out_ptr, jcp.mb,
jcp.dimM / jcp.dimM_simd_block, outh, outw, jcp.dimM_simd_block);
array_offset_calculator<float, 6> weights(wei_ptr,
jcp.oc / jcp.oc_simd_block, jcp.ic / jcp.ic_simd_block, jcp.kh,
jcp.kw, jcp.ic_simd_block, jcp.oc_simd_block);
array_offset_calculator<float, 2> bias(
bias_ptr, jcp.oc / jcp.oc_simd_block, jcp.oc_simd_block);
auto wino_wei = (jcp.prop_kind == prop_kind::forward_inference)
? wei_ptr
: scratchpad.template get<float>(key_wino_U);
array_offset_calculator<float, 8> U(wino_wei, jcp.dimM_nb_block, alpha,
alpha, jcp.dimK_nb_block, jcp.dimM_block * jcp.dimM_reg_block,
jcp.dimK_block, jcp.dimK_reg_block, jcp.dimM_simd_block);
array_offset_calculator<float, 8> M(is_fwd
? scratchpad.template get<float>(key_wino_M)
: scratchpad.template get<float>(key_wino_V),
0, jcp.dimM_nb_block, alpha, alpha, jcp.dimN_block,
jcp.dimM_block * jcp.dimM_reg_block, jcp.dimN_reg_block,
jcp.dimM_simd_block);
array_offset_calculator<float, 8> V(is_fwd
? scratchpad.template get<float>(key_wino_V)
: scratchpad.template get<float>(key_wino_M),
0, alpha, alpha, jcp.dimN_block, jcp.dimK_nb_block, jcp.dimK_block,
jcp.dimN_reg_block, jcp.dimK_reg_block);
const bool wants_padded_bias
= jcp.with_bias && jcp.oc_without_padding != jcp.oc;
float last_slice_bias[simd_w] = {0};
if (wants_padded_bias) {
for (int oc = 0; oc < jcp.oc_without_padding % jcp.oc_simd_block; ++oc)
last_slice_bias[oc] = bias(jcp.dimM / jcp.dimM_simd_block - 1, oc);
}
if (jcp.prop_kind != prop_kind::forward_inference) {
parallel_nd(jcp.nb_oc, jcp.nb_ic, (jcp.oc_block * jcp.oc_reg_block),
(jcp.ic_block * jcp.ic_reg_block),
[&](int ofm1, int ifm1, int ofm2, int ifm2) {
float *U_base_ptr = is_fwd
? &(U(ofm1, 0, 0, ifm1, ofm2, ifm2, 0, 0))
: &(U(ifm1, 0, 0, ofm1, ifm2, ofm2, 0, 0));
weight_transform_data(jcp,
&(weights(ofm1 * jcp.oc_block * jcp.oc_reg_block
+ ofm2,
ifm1 * jcp.ic_block * jcp.ic_reg_block
+ ifm2,
0, 0, 0, 0)),
U_base_ptr);
});
}
parallel_nd_ext(
jcp.nthr, jcp.tile_block, [&](int ithr, int nthr, int tile_block) {
assert(nthr <= jcp.nthr);
MAYBE_UNUSED(nthr);
for (int K_blk1 = 0; K_blk1 < jcp.dimK_nb_block; K_blk1++) {
for (int K_blk2 = 0; K_blk2 < jcp.dimK_block; K_blk2++) {
input_transform_tileblock_data(tile_block, jcp,
&(input(0, K_blk1 * jcp.dimK_block + K_blk2, 0,
0, 0)),
&(V(ithr, 0, 0, 0, K_blk1, K_blk2, 0, 0)));
}
}
for (int oj = 0; oj < alpha; oj++) {
for (int oi = 0; oi < alpha; oi++) {
for_(int M_blk1 = 0; M_blk1 < jcp.dimM_nb_block;
M_blk1++)
for_(int K_blk1 = 0; K_blk1 < jcp.dimK_nb_block;
K_blk1++)
for (int N_blk = 0; N_blk < jcp.dimN_block; N_blk++)
kernel_->gemm_loop_ker(
(float *)&(M(ithr, M_blk1, oj, oi, N_blk, 0,
0, 0)),
(const float *)&(U(M_blk1, oj, oi, K_blk1,
0, 0, 0, 0)),
(const float *)&(V(ithr, oj, oi, N_blk,
K_blk1, 0, 0, 0)),
K_blk1);
}
}
for (int M_blk1 = 0; M_blk1 < jcp.dimM_nb_block; M_blk1++) {
for (int M_blk2 = 0;
M_blk2 < jcp.dimM_block * jcp.dimM_reg_block;
M_blk2++) {
const int M_blk
= M_blk1 * jcp.dimM_block * jcp.dimM_reg_block
+ M_blk2;
float *bias_ptr = wants_padded_bias
&& M_blk
== jcp.dimM / jcp.dimM_simd_block
- 1
? last_slice_bias
: &bias(M_blk, 0);
output_transform_tileblock_data(tile_block, jcp, p_ops,
&(M(ithr, M_blk1, 0, 0, 0, M_blk2, 0, 0)),
&(output(0, M_blk, 0, 0, 0)), bias_ptr);
}
}
});
}
template struct _jit_avx512_core_f32_wino_conv_4x3_t<true>;
template struct _jit_avx512_core_f32_wino_conv_4x3_t<false>;
namespace {
void subarray_sum(size_t num_arrs, float *output, size_t nelems,
float *input_ptrs[], size_t input_starts[], size_t input_ends[]) {
using namespace nstl;
const size_t block_size = 16 * 1024 / sizeof(float);
const size_t blocks_number = nelems / block_size;
const size_t tail = nelems % block_size;
PRAGMA_OMP(parallel)
{
const int ithr = OMP_GET_THREAD_NUM();
const int nthr = OMP_GET_NUM_THREADS();
size_t start {0}, end {0};
balance211(blocks_number, nthr, ithr, start, end);
for (size_t nb = start; nb < end; ++nb) {
size_t start_e = nb * block_size;
size_t end_e = start_e + block_size;
size_t input_start = max(start_e, min(input_starts[0], end_e));
size_t input_end = max(start_e, min(input_ends[0], end_e));
ZENDNN_PRAGMA_OMP_SIMD()
for (size_t e = start_e; e < input_start; e++) {
output[e] = 0.f;
}
ZENDNN_PRAGMA_OMP_SIMD()
for (size_t e = input_start; e < input_end; e++) {
output[e] = input_ptrs[0][e];
}
ZENDNN_PRAGMA_OMP_SIMD()
for (size_t e = input_end; e < end_e; e++) {
output[e] = 0.f;
}
for (size_t a = 1; a < num_arrs; a++) {
input_start = max(start_e, input_starts[a]);
input_end = min(input_ends[a], end_e);
ZENDNN_PRAGMA_OMP_SIMD()
for (size_t e = input_start; e < input_end; e++) {
output[e] += input_ptrs[a][e];
}
}
}
if (tail != 0 && ithr == nthr - 1) {
size_t start_e = nelems - tail;
size_t end_e = nelems;
size_t input_start = max(start_e, min(input_starts[0], end_e));
size_t input_end = max(start_e, min(input_ends[0], end_e));
ZENDNN_PRAGMA_OMP_SIMD()
for (size_t e = start_e; e < input_start; e++) {
output[e] = 0.f;
}
ZENDNN_PRAGMA_OMP_SIMD()
for (size_t e = input_start; e < input_end; e++) {
output[e] = input_ptrs[0][e];
}
ZENDNN_PRAGMA_OMP_SIMD()
for (size_t e = input_end; e < end_e; e++) {
output[e] = 0.f;
}
for (size_t a = 1; a < num_arrs; a++) {
input_start = max(start_e, input_starts[a]);
input_end = min(input_ends[a], end_e);
ZENDNN_PRAGMA_OMP_SIMD()
for (size_t e = input_start; e < input_end; e++) {
output[e] += input_ptrs[a][e];
}
}
}
}
}
const int max_threads_number = 1024;
// Sum to the first buffer array
void array_sum(size_t num_arrs, float *output, size_t nelems,
float *input_ptrs[], bool reduce_to_first = true) {
const size_t block_size = 16 * 1024 / sizeof(float);
const size_t blocks_number = nelems / block_size;
const size_t tail = nelems % block_size;
PRAGMA_OMP(parallel)
{
const size_t ithr = OMP_GET_THREAD_NUM();
const size_t nthr = OMP_GET_NUM_THREADS();
size_t start {0}, end {0};
balance211(blocks_number, nthr, ithr, start, end);
for (size_t nb = start; nb < end; ++nb) {
size_t start_e = nb * block_size;
size_t end_e = start_e + block_size;
if (!reduce_to_first) {
ZENDNN_PRAGMA_OMP_SIMD()
for (size_t e = start_e; e < end_e; e++) {
output[e] = input_ptrs[0][e];
}
}
for (size_t a = 1; a < num_arrs; a++) {
ZENDNN_PRAGMA_OMP_SIMD()
for (size_t e = start_e; e < end_e; e++) {
output[e] += input_ptrs[a][e];
}
}
}
if (tail != 0 && ithr == nthr - 1) {
size_t start_e = nelems - tail;
size_t end_e = nelems;
if (!reduce_to_first) {
ZENDNN_PRAGMA_OMP_SIMD()
for (size_t e = start_e; e < end_e; e++) {
output[e] = input_ptrs[0][e];
}
}
for (size_t a = 1; a < num_arrs; a++) {
ZENDNN_PRAGMA_OMP_SIMD()
for (size_t e = start_e; e < end_e; e++) {
output[e] += input_ptrs[a][e];
}
}
}
}
}
} // namespace
void jit_avx512_core_f32_wino_conv_4x3_bwd_weights_t::
_execute_backward_weights_SDGtWo(const float *ptr_src,
const float *ptr_diff_dst, float *ptr_diff_weights,
float *ptr_diff_bias,
const memory_tracking::grantor_t &scratchpad) const {
const auto &jcp = kernel_->jcp;
const int nthreads = jcp.nthr;
array_offset_calculator<float, 5> src(
(float *)ptr_src, jcp.mb, jcp.ic / simd_w, jcp.ih, jcp.iw, simd_w);
array_offset_calculator<float, 5> diff_dst((float *)ptr_diff_dst, jcp.mb,
jcp.oc / simd_w, jcp.oh, jcp.ow, simd_w);
array_offset_calculator<float, 6> diff_weights(ptr_diff_weights,
jcp.oc / simd_w, jcp.ic / simd_w, jcp.kh, jcp.kw, simd_w, simd_w);
array_offset_calculator<float, 8> Us(scratchpad.get<float>(key_wino_U), 0,
alpha, alpha, jcp.oc_block, jcp.ic_block, jcp.ic_simd_block,
jcp.oc_reg_block, jcp.oc_simd_block);
const int U_sz = nthreads * alpha * alpha * jcp.oc / jcp.nb_oc * jcp.ic
/ jcp.nb_ic;
array_offset_calculator<float, 7> diff_weights_prv(
scratchpad.get<float>(key_wino_U) + U_sz, 0, jcp.oc / simd_w,
jcp.ic / simd_w, jcp.kh, jcp.kw, simd_w, simd_w);
array_offset_calculator<float, 8> M(scratchpad.get<float>(key_wino_M), 0,
alpha, alpha, jcp.oc_block, jcp.nb_tile_block_ur, jcp.tile_block_ur,
jcp.oc_reg_block, jcp.oc_simd_block);
array_offset_calculator<float, 7> V(scratchpad.get<float>(key_wino_V), 0,
alpha, alpha, jcp.ic_block, jcp.nb_tile_block_ur, jcp.tile_block_ur,
jcp.ic_simd_block);
array_offset_calculator<float, 2> diff_bias_prv(
scratchpad.get<float>(key_conv_bia_reduction), nthreads, jcp.oc);
auto trans_ker_p = jit_wino_transform_call_s();
float I[alpha][alpha][simd_w];
float T[alpha][alpha][simd_w];
float G_I_3x3_4x4[9] = {-2.25f, -0.390625f, 0.87890625f, -2.640625f, 0.625f,
-0.625f, 1.5f, -1.5f, -2.640625f};
float G_W_3x3_4x4[8] = {0.26890756302521f, -0.688403361344538f,
0.119514472455649f, 0.430252100840336f, 0.168067226890756f,
0.179271708683473f, 0.403361344537815f, 1.13777777777778f};
float G_O_3x3_4x4[4] = {2.25f, 0.625f, 1.5f, 0.390625f};
PRAGMA_OMP(parallel num_threads(nthreads) firstprivate(trans_ker_p, I, T))
{
if (jcp.with_bias) {
parallel_nd_in_omp(
nthreads, jcp.oc / simd_w, [&](int ithr, int ofm) {
float *pdbias = &(diff_bias_prv(ithr, ofm * simd_w));
ZENDNN_PRAGMA_OMP_SIMD()
for (int v = 0; v < simd_w; v++) {
pdbias[v] = 0.0f;
}
});
}
int ithr = OMP_GET_THREAD_NUM();
for (int ifm1 = 0; ifm1 < jcp.nb_ic; ++ifm1) {
int first_tblk = 0;
PRAGMA_OMP(for)
for (int tblk1 = 0; tblk1 < jcp.tile_block; ++tblk1) {
int tile_index
= tblk1 * jcp.nb_tile_block_ur * jcp.tile_block_ur;
int img = tile_index / (jcp.itiles * jcp.jtiles);
trans_ker_p.ti = tile_index % jcp.itiles;
trans_ker_p.tj = (tile_index / jcp.itiles) % jcp.jtiles;
trans_ker_p.M = I;
trans_ker_p.T = T;
trans_ker_p.G = G_I_3x3_4x4;
for (int ifm2 = 0; ifm2 < jcp.ic_block; ++ifm2) {
int ifm = ifm1 * jcp.ic_block + ifm2;
trans_ker_p.src = (float *)&(src(img, ifm, 0, 0, 0));
trans_ker_p.dst = (float *)&(V(ithr, 0, 0, ifm2, 0, 0, 0));
kernel_->src_transform(&trans_ker_p);
}
for (int ofm1 = 0; ofm1 < jcp.nb_oc; ++ofm1) {
trans_ker_p.G = G_W_3x3_4x4;
for (int ofm2 = 0; ofm2 < jcp.oc_block; ++ofm2) {
int ofm = (ofm1 * jcp.oc_block + ofm2)
* jcp.oc_reg_block;
trans_ker_p.src
= (float *)&(diff_dst(img, ofm, 0, 0, 0));
trans_ker_p.dst
= (float *)&(M(ithr, 0, 0, ofm2, 0, 0, 0, 0));
if (jcp.with_bias && ifm1 == 0) {
trans_ker_p.bias = (float *)&(
diff_bias_prv(ithr, ofm * simd_w));
kernel_->diff_dst_transform_wbias(&trans_ker_p);
} else {
kernel_->diff_dst_transform(&trans_ker_p);
}
}
for (int oj = 0; oj < alpha; ++oj) {
for (int oi = 0; oi < alpha; ++oi) {
kernel_->gemm_loop_ker_first_iter(
&(Us(ithr, oj, oi, 0, 0, 0, 0, 0)),
&(M(ithr, oj, oi, 0, 0, 0, 0, 0)),
&(V(ithr, oj, oi, 0, 0, 0, 0)));
}
}
trans_ker_p.G = G_O_3x3_4x4;
for (int ofm2 = 0; ofm2 < jcp.oc_block; ++ofm2) {
for (int ofm3 = 0; ofm3 < jcp.oc_reg_block; ++ofm3) {
int ofm = (ofm1 * jcp.oc_block + ofm2)
* jcp.oc_reg_block
+ ofm3;
for (int ifm2 = 0; ifm2 < jcp.ic_block; ++ifm2) {
int ifm = ifm1 * jcp.ic_block + ifm2;
trans_ker_p.src = (float *)&(
Us(ithr, 0, 0, ofm2, ifm2, 0, ofm3, 0));
trans_ker_p.dst = (float *)&(diff_weights_prv(
ithr, ofm, ifm, 0, 0, 0, 0));
if (first_tblk == 0) {
kernel_->diff_weights_transform(
&trans_ker_p);
} else {
kernel_->diff_weights_transform_accum(
&trans_ker_p);
}
}
}
}
}
++first_tblk;
}
}
}
// Reduce diff-weights
{
float *output = ptr_diff_weights;
float *input_base = scratchpad.get<float>(key_wino_U) + U_sz;
int nelems = jcp.oc * jcp.ic * jcp.kh * jcp.kw;
float *input_ptrs[max_threads_number];
for (int i = 0; i < nthreads; ++i) {
input_ptrs[i] = input_base + nelems * i;
}
array_sum(nthreads, output, nelems, input_ptrs, false);
if (jcp.with_bias) {
output = ptr_diff_bias;
input_base = scratchpad.get<float>(key_conv_bia_reduction);
for (int i = 0; i < nthreads; ++i) {
input_ptrs[i] = input_base + jcp.oc * i;
}
array_sum(nthreads, output, jcp.oc_without_padding, input_ptrs,
false);
}
}
}
void jit_avx512_core_f32_wino_conv_4x3_bwd_weights_t::
_execute_backward_weights_S_D_Giot_W(const float *ptr_src,
const float *ptr_diff_dst, float *ptr_diff_weights,
float *ptr_diff_bias,
const memory_tracking::grantor_t &scratchpad) const {
const auto &jcp = kernel_->jcp;
const int nthreads = jcp.nthr;
array_offset_calculator<float, 5> src(
(float *)ptr_src, jcp.mb, jcp.ic / simd_w, jcp.ih, jcp.iw, simd_w);
array_offset_calculator<float, 5> diff_dst((float *)ptr_diff_dst, jcp.mb,
jcp.oc / simd_w, jcp.oh, jcp.ow, simd_w);
array_offset_calculator<float, 6> diff_weights((float *)ptr_diff_weights,
jcp.oc / simd_w, jcp.ic / simd_w, jcp.kh, jcp.kw, simd_w, simd_w);
array_offset_calculator<float, 1> diff_bias((float *)ptr_diff_bias, jcp.oc);
array_offset_calculator<float, 9> U(scratchpad.get<float>(key_wino_U),
jcp.nb_ic, jcp.nb_oc, alpha, alpha, jcp.oc_block, jcp.ic_block,
jcp.ic_simd_block, jcp.oc_reg_block, jcp.oc_simd_block);
const int U_size = jcp.oc * jcp.ic * alpha * alpha;
array_offset_calculator<float, 10> Us(
scratchpad.get<float>(key_wino_U) + U_size, 0, jcp.nb_ic, jcp.nb_oc,
alpha, alpha, jcp.oc_block, jcp.ic_block, jcp.ic_simd_block,
jcp.oc_reg_block, jcp.oc_simd_block);
array_offset_calculator<float, 9> M(scratchpad.get<float>(key_wino_M),
jcp.nb_oc, jcp.tile_block, alpha, alpha, jcp.oc_block,
jcp.nb_tile_block_ur, jcp.tile_block_ur, jcp.oc_reg_block,
jcp.oc_simd_block);
array_offset_calculator<float, 8> V(scratchpad.get<float>(key_wino_V),
jcp.nb_ic, jcp.tile_block, alpha, alpha, jcp.ic_block,
jcp.nb_tile_block_ur, jcp.tile_block_ur, jcp.ic_simd_block);
array_offset_calculator<float, 2> diff_bias_prv(
scratchpad.get<float>(key_conv_bia_reduction), nthreads, jcp.oc);
size_t input_starts[max_threads_number] = {0};
size_t input_ends[max_threads_number] = {0};
size_t first_tblk = 0;
auto trans_ker_p = jit_wino_transform_call_s();
float G_I_3x3_4x4[9] = {-2.25f, -0.390625f, 0.87890625f, -2.640625f, 0.625f,
-0.625f, 1.5f, -1.5f, -2.640625f};
float G_W_3x3_4x4[8] = {0.26890756302521f, -0.688403361344538f,
0.119514472455649f, 0.430252100840336f, 0.168067226890756f,
0.179271708683473f, 0.403361344537815f, 1.13777777777778f};
float G_O_3x3_4x4[4] = {2.25f, 0.625f, 1.5f, 0.390625f};
float I[alpha][alpha][simd_w];
float T[alpha][alpha][simd_w];
PRAGMA_OMP(parallel firstprivate(first_tblk, trans_ker_p, I, T))
{
if (jcp.with_bias) {
parallel_nd_in_omp(nthreads, jcp.oc, [&](int ithr, int ofm) {
diff_bias_prv(ithr, ofm) = 0.0f;
});
}
trans_ker_p.G = G_I_3x3_4x4;
trans_ker_p.M = I;
trans_ker_p.T = T;
parallel_nd_in_omp(jcp.nb_ic, jcp.ic_block, jcp.mb,
[&](int ifm1, int ifm2, int img) {
size_t ifm = ifm1 * jcp.ic_block + ifm2;
size_t tile_base_index = img * (jcp.itiles * jcp.jtiles);
size_t tblk3 = tile_base_index % jcp.tile_block_ur;
size_t tblk2 = (tile_base_index / jcp.tile_block_ur)
% jcp.nb_tile_block_ur;
size_t tblk1 = (tile_base_index / jcp.tile_block_ur)
/ jcp.nb_tile_block_ur;
trans_ker_p.tile_count = tblk2 * jcp.tile_block_ur + tblk3;
trans_ker_p.src = (float *)&(src(img, ifm, 0, 0, 0));
trans_ker_p.dst
= (float *)&(V(ifm1, tblk1, 0, 0, ifm2, 0, 0, 0));
kernel_->src_transform(&trans_ker_p);
});
int ithr = OMP_GET_THREAD_NUM();
trans_ker_p.G = G_W_3x3_4x4;
parallel_nd_in_omp(jcp.nb_oc, jcp.oc_block, jcp.mb,
[&](int ofm1, int ofm2, int img) {
int ofm = (ofm1 * jcp.oc_block + ofm2) * jcp.oc_reg_block;
size_t tile_base_index = img * (jcp.itiles * jcp.jtiles);
size_t tblk3 = tile_base_index % jcp.tile_block_ur;
size_t tblk2 = (tile_base_index / jcp.tile_block_ur)
% jcp.nb_tile_block_ur;
size_t tblk1 = (tile_base_index / jcp.tile_block_ur)
/ jcp.nb_tile_block_ur;
trans_ker_p.tile_count = tblk2 * jcp.tile_block_ur + tblk3;
trans_ker_p.src = (float *)&(diff_dst(img, ofm, 0, 0, 0));
trans_ker_p.dst = (float *)&(
M(ofm1, tblk1, 0, 0, ofm2, 0, 0, 0, 0));
if (jcp.with_bias) {
trans_ker_p.bias
= (float *)&(diff_bias_prv(ithr, ofm * simd_w));
kernel_->diff_dst_transform_wbias(&trans_ker_p);
} else {
kernel_->diff_dst_transform(&trans_ker_p);
}
});
PRAGMA_OMP(barrier)
parallel_nd_in_omp(jcp.nb_ic, jcp.nb_oc, alpha, alpha, jcp.tile_block,
[&](int ifm1, int ofm1, int oj, int oi, int tblk1) {
if (first_tblk == 0) {
input_starts[ithr] = (float *)&(Us(ithr, ifm1, ofm1, oj,
oi, 0, 0, 0, 0, 0))
- (float *)&(
Us(ithr, 0, 0, 0, 0, 0, 0, 0, 0, 0));
input_ends[ithr] = input_starts[ithr]
+ jcp.oc_block * jcp.ic_block
* jcp.ic_simd_block * jcp.oc_reg_block
* jcp.oc_simd_block;
} else if (tblk1 == 0) {
input_ends[ithr] += jcp.oc_block * jcp.ic_block
* jcp.ic_simd_block * jcp.oc_reg_block
* jcp.oc_simd_block;
}
if (first_tblk == 0 || tblk1 == 0) {
kernel_->gemm_loop_ker_first_iter(
&(Us(ithr, ifm1, ofm1, oj, oi, 0, 0, 0, 0, 0)),
&(M(ofm1, tblk1, oj, oi, 0, 0, 0, 0, 0)),
&(V(ifm1, tblk1, oj, oi, 0, 0, 0, 0)));
} else {
kernel_->gemm_loop_ker(
&(Us(ithr, ifm1, ofm1, oj, oi, 0, 0, 0, 0, 0)),
&(M(ofm1, tblk1, oj, oi, 0, 0, 0, 0, 0)),
&(V(ifm1, tblk1, oj, oi, 0, 0, 0, 0)));
}
++first_tblk;
});
}
// Reduce diff-weights
{
float *output = &(U(0, 0, 0, 0, 0, 0, 0, 0, 0));
size_t nelems = jcp.ic * jcp.oc * alpha * alpha;
float *input_ptrs[max_threads_number];
for (int i = 0; i < nthreads; ++i)
input_ptrs[i] = output + nelems * (i + 1);
subarray_sum(
nthreads, output, nelems, input_ptrs, input_starts, input_ends);
}
trans_ker_p.G = G_O_3x3_4x4;
PRAGMA_OMP(parallel firstprivate(trans_ker_p))
{
parallel_nd_in_omp(jcp.nb_ic, jcp.nb_oc, jcp.oc_block, jcp.ic_block,
jcp.oc_reg_block,
[&](int ifm1, int ofm1, int ofm2, int ifm2, int ofm3) {
int ofm = (ofm1 * jcp.oc_block + ofm2) * jcp.oc_reg_block
+ ofm3;
int ifm = ifm1 * jcp.ic_block + ifm2;
trans_ker_p.src = (float *)&(
U(ifm1, ofm1, 0, 0, ofm2, ifm2, 0, ofm3, 0));
trans_ker_p.dst
= (float *)&(diff_weights(ofm, ifm, 0, 0, 0, 0));
kernel_->diff_weights_transform(&trans_ker_p);
});
}
if (jcp.with_bias) {
parallel_nd(jcp.oc / simd_w, [&](int ofm1) {
float *pbias = &(diff_bias(ofm1 * simd_w));
float *pbias_prv = &(diff_bias_prv(0, ofm1 * simd_w));
const int blk_sz = ofm1 == jcp.oc / simd_w - 1
? jcp.oc_without_padding - ofm1 * simd_w
: simd_w;
ZENDNN_PRAGMA_OMP_SIMD()
for (int ofm2 = 0; ofm2 < blk_sz; ++ofm2) {
pbias[ofm2] = pbias_prv[ofm2];
}
for (int ithr = 1; ithr < nthreads; ++ithr) {
pbias_prv = &(diff_bias_prv(ithr, ofm1 * simd_w));
ZENDNN_PRAGMA_OMP_SIMD()
for (int ofm2 = 0; ofm2 < blk_sz; ++ofm2) {
pbias[ofm2] += pbias_prv[ofm2];
}
}
});
}
}
} // namespace x64
} // namespace cpu
} // namespace impl
} // namespace zendnn
// vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s
| [
"ratan.prasad2@amd.com"
] | ratan.prasad2@amd.com |
a0178bbadc17cab17979f55979921f5b9ac81e39 | df2716dd990b3fb616fb0329ba85d13b2801e367 | /src/card.cc | bf051eb1272d60cd4006d451d990f7c4e3c8d93e | [] | no_license | vila/rftgscore | 931275efc14207956c6927f66acfe74542d3b625 | 906dbb072473fbf06f4ca281368f84c2ffe1510c | refs/heads/master | 2020-06-02T14:08:07.474573 | 2012-07-22T14:18:45 | 2012-07-22T14:18:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,364 | cc | #include "card.hh"
#include "misc.hh"
#include <sstream>
#include <string>
#include <vector>
#include <iomanip>
#include <algorithm>
using namespace rftgscore;
using namespace std;
// base 6dev
static int score_free_trade_association(const vector<Card> &tableau);
static int score_galactic_imperium(const vector<Card> &tableau);
static int score_alien_tech_institute(const vector<Card> &tableau);
static int score_galactic_federation(const vector<Card> &tableau);
static int score_galactic_renaissance(const vector<Card> &tableau);
static int score_galactic_survey_seti(const vector<Card> &tableau);
static int score_merchant_guild(const vector<Card> &tableau);
static int score_mining_league(const vector<Card> &tableau);
static int score_new_economy(const vector<Card> &tableau);
static int score_new_galactic_order(const vector<Card> &tableau);
static int score_pan_galactic_league(const vector<Card> &tableau);
static int score_trade_league(const vector<Card> &tableau);
// tgs 6dev
static int score_galactic_genome_project(const vector<Card> &tableau);
static int score_imperium_lords(const vector<Card> &tableau);
static int score_terraforming_guild(const vector<Card> &tableau);
int rftgscore::score_tableau(const vector<Card> &tableau) {
int score = 0;
for_each(begin(tableau), end(tableau),
[&](Card c) { score += c.score(tableau); });
return score;
}
int Card::score(const vector<Card> &tableau) {
int score = value;
// TODO: handle all 6-developments
switch(id) {
// base
case 356848: score = score_free_trade_association(tableau); break;
case 356852: score = score_galactic_imperium(tableau); break;
case 354518: score = score_alien_tech_institute(tableau); break;
case 356847: score = score_galactic_federation(tableau); break;
case 340468: score = score_galactic_renaissance(tableau); break;
case 354517: score = score_galactic_survey_seti(tableau); break;
case 341376: score = score_merchant_guild(tableau); break;
case 341710: score = score_mining_league(tableau); break;
case 340466: score = score_new_economy(tableau); break;
case 340904: score = score_new_galactic_order(tableau); break;
case 356846: score = score_pan_galactic_league(tableau); break;
case 340448: score = score_trade_league(tableau); break;
// tgs
case 451438: score = score_galactic_genome_project(tableau); break;
case 451441: score = score_imperium_lords(tableau); break;
case 451435: score = score_terraforming_guild(tableau); break;
}
return score;
}
string Card::to_string() {
stringstream ss;
string tmp = name;
switch(sub_type) {
case CardSubType::ALIEN: str_replace(tmp, "ALIEN", "[ALIEN]"); break;
case CardSubType::UPLIFT: str_replace(tmp, "UPLIFT", "[UPLIFT]"); break;
case CardSubType::REBEL: str_replace(tmp, "REBEL", "[REBEL]"); break;
case CardSubType::IMPERIUM: str_replace(tmp, "IMPERIUM", "[IMPERIUM]"); break;
case CardSubType::TERRAFORMING: str_replace(tmp, "TERRAFORMING", "[TERRAFORMING]"); break;
case CardSubType::NONE: break;
}
// name and cost/value
ss << id << ": " << left << setw(35) << tmp;
ss << " (" << cost << "/" << value << ") ";
// Powers
ss << "[";
ss << ((powers & POWER_EXPLORE) ? "1" : "-");
ss << ((powers & POWER_DEVELOP) ? "2" : "-");
ss << ((powers & POWER_SETTLE) ? "3" : "-");
ss << ((powers & POWER_TRADE) ? "$" : "-");
ss << ((powers & POWER_CONSUME) ? "4" : "-");
ss << ((powers & POWER_PRODUCE) ? "5" : "-");
ss << "] ";
if(military) {
ss << "Mil. ";
}
switch(type) {
case CardType::DEVELOPMENT: ss << "Development"; break;
case CardType::PLANET: ss << "Planet"; break;
case CardType::PLANET_NOVELTY: ss << "Planet (Novelty)"; break;
case CardType::PLANET_NOVELTY_WINDFALL: ss << "Planet (Novelty/Windfall)"; break;
case CardType::PLANET_RARE: ss << "Planet (Rare)"; break;
case CardType::PLANET_RARE_WINDFALL: ss << "Planet (Rare/Windfall)"; break;
case CardType::PLANET_GENE: ss << "Planet (Gene)"; break;
case CardType::PLANET_GENE_WINDFALL: ss << "Planet (Gene/Windfall)"; break;
case CardType::PLANET_ALIEN: ss << "Planet (Alien)"; break;
case CardType::PLANET_ALIEN_WINDFALL: ss << "Planet (Alien/Windfall)"; break;
}
if(increase_military != 0) {
ss << ((increase_military > 0) ? " (+" : " (");
ss << increase_military << " mil.)";
}
return ss.str();
}
// Six Devs
static int score_free_trade_association(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
// Consumer Markets/Expanding Colony
if(it->id == 354516 || it->id == 357384)
score += 2;
if(it->type == Card::CardType::PLANET_NOVELTY)
score += 2;
if(it->type == Card::CardType::PLANET_NOVELTY_WINDFALL)
score += 1;
}
return score;
}
static int score_galactic_imperium(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
if(it->military)
score += (it->sub_type == Card::CardSubType::REBEL) ? 2 : 1;
}
return score;
}
static int score_alien_tech_institute(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
if(it->type == Card::CardType::PLANET_ALIEN)
score += 3;
else if(it->type == Card::CardType::PLANET_ALIEN_WINDFALL)
score += 2;
else if(it->sub_type == Card::CardSubType::ALIEN)
score += 2;
}
return score;
}
static int score_galactic_federation(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
if(it->type == Card::CardType::DEVELOPMENT)
score += (it->cost == 6) ? 2 : 1;
}
return score;
}
static int score_galactic_renaissance(const vector<Card> &tableau) {
int score = 0;
// TODO add warning for the vp chip bonus not included in score
for(auto it = begin(tableau); it != end(tableau); ++it) {
// Research Lab / Artist Colony / Galactic Trendsetters
if(it->id == 340449 || it->id == 356855 || it->id == 341379)
score += (it->cost == 6) ? 2 : 1;
}
return score;
}
static int score_galactic_survey_seti(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
if(it->powers & Card::POWER_EXPLORE)
score += (it->type == Card::CardType::DEVELOPMENT) ? 1 : 2;
else if(it->type != Card::CardType::DEVELOPMENT)
score += 1; // other world
}
return score;
}
static int score_merchant_guild(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
if(it->type == Card::CardType::PLANET_NOVELTY ||
it->type == Card::CardType::PLANET_RARE ||
it->type == Card::CardType::PLANET_GENE ||
it->type == Card::CardType::PLANET_ALIEN)
score += 2;
}
return score;
}
static int score_mining_league(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
// Mining Robots / Mining Conglomerate
if(it->id == 354961 || it->id == 340490)
score += 2;
else if(it->type == Card::CardType::PLANET_RARE_WINDFALL)
score += 1;
else if(it->type == Card::CardType::PLANET_RARE)
score += 2;
}
return score;
}
static int score_new_economy(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
if(it->powers & Card::POWER_CONSUME)
score += (it->type == Card::CardType::DEVELOPMENT) ? 2 : 1;
}
return score;
}
static int score_new_galactic_order(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
score += it->increase_military;
}
return score;
}
static int score_pan_galactic_league(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
// Contact Specialist
if(it->id == 340758)
score += 3;
else if(it->type == Card::CardType::PLANET_GENE ||
it->type == Card::CardType::PLANET_GENE_WINDFALL)
score += 2;
else if(it->type != Card::CardType::DEVELOPMENT && it->military)
score += 1;
}
return score;
}
static int score_trade_league(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
if(it->powers & Card::POWER_TRADE)
score += (it->type == Card::CardType::DEVELOPMENT) ? 2 : 1;
}
return score;
}
// tgs 6devs
static int score_galactic_genome_project(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
// Genetics Lab
if(it->id == 340760)
score += 3;
if(it->type == Card::CardType::PLANET_GENE ||
it->type == Card::CardType::PLANET_GENE_WINDFALL)
score += 2;
}
return score;
}
static int score_imperium_lords(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
if(it->sub_type == Card::CardSubType::IMPERIUM)
score += 2;
else if(it->type != Card::CardType::DEVELOPMENT && it->military)
score += 1;
}
return score;
}
static int score_terraforming_guild(const vector<Card> &tableau) {
int score = 0;
for(auto it = begin(tableau); it != end(tableau); ++it) {
if(it->type == Card::CardType::PLANET_NOVELTY_WINDFALL ||
it->type == Card::CardType::PLANET_RARE_WINDFALL ||
it->type == Card::CardType::PLANET_GENE_WINDFALL ||
it->type == Card::CardType::PLANET_ALIEN_WINDFALL)
score += 2;
else if(it->sub_type == Card::CardSubType::TERRAFORMING)
score += 2;
}
return score;
}
| [
"viktor.vila.larsson@gmail.com"
] | viktor.vila.larsson@gmail.com |
c28520a59a76d45016bb14fc2a40c9071ab5d32c | d4135e21667c66936191d0f761db99525c66799b | /masternetwork/include/CJsonCommand.h | a08e97a7637d3aca750bfd45dc2274960ede06d9 | [
"MIT"
] | permissive | wen96/pl-man2 | 6d2656f96b0e0029a646a9a343de103a5ee0ee98 | b861fd8adaf28b81747d09934c6437cbb259370b | refs/heads/master | 2021-01-22T19:21:41.429627 | 2015-04-15T12:06:24 | 2015-04-15T12:06:24 | 33,990,808 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,875 | h | #pragma once
#include "CJsonSerializer.h"
#include <vector>
#include <map>
#include <string>
class CJsonCommand : public CJsonSerializer
{
public:
// Enumeration of command types -------------------------
/// Enum of all possible CJsonCommands
enum ECommand {
CM_NULL, //< Null command (do nothing)
CM_INIT, //< Command to init the world and return them
CM_SEE, //< Command to see your environment
CM_GET, //< Command to get an object
CM_DROP, //< Command to drop an object
CM_USE, //< Command to use an object
CM_MOVE, //< Command to make movements
CM_INTERACT, //< Command to make movements
CM_EXIT, //< Command to exit from the game
CM_LEFT, //< Direction
CM_UP, //< Direction
CM_RIGHT, //< Direction
CM_DOWN, //< Direction
CM_UPLEFT, //< Direction
CM_UPRIGHT, //< Direction
CM_DOWNLEFT, //< Direction
CM_DOWNRIGHT, //< Direction
CM_NONE,
CM_NUMCOMMANDS //< Item to count the number of commands available
};
// Virtual Methods ----------------------------------------------
virtual ~CJsonCommand();
virtual void write2json (Json::Value& v) const;
virtual void setFromJson (const Json::Value& v);
virtual IJsonSerializable* createNewInstance() const;
virtual void destroy ();
// Methods ----------------------------------------------
CJsonCommand(ECommand c = CM_NULL);
CJsonCommand(const CJsonCommand& _comm);
CJsonCommand& operator=(const CJsonCommand& _comm);
void addParameter (IJsonSerializable* p);
void reset();
ECommand getCommand() {return m_command;};
std::vector<ECommand> getParameters() {
std::vector<ECommand> parameters;
for(unsigned int i = 0; i < m_parameters.size(); i++)
{
parameters.push_back(((CJsonCommand*)m_parameters[i])->getCommand());
}
return parameters;
};
IJsonSerializable* getParameter(int i) {
if(i >= 0 && (unsigned int)i < m_parameters.size())
{
return m_parameters[i];
}
return NULL;
};
ECommand stringToCommand(std::string _cmd){return m_string2Command[_cmd];}
bool isActionCommand();
static bool isActionCommand(ECommand c);
private:
void copy(const CJsonCommand& _comm);
ECommand m_command; //< The command this object represents
std::map <ECommand, std::string> m_command2String; //< Translations from command enumerates to strings
std::map <std::string, ECommand> m_string2Command; //< Inverse translations from strings to command enumerates
std::vector< IJsonSerializable* > m_parameters; //< List of parameters for this command
};
| [
"yosoyruben@gmail.com"
] | yosoyruben@gmail.com |
728be624556ff724bc9e8b26b700c273595dfa15 | 0174f58687dabfd4bd9c36e81e4d3b645d5013b5 | /A_Nastia_and_Nearly_Good_Numbers.cpp | b590cb763ba003965d3964a81e12932a0f78f9b7 | [] | no_license | lakshmendraB95/CPpractice | d6526b8d17c4ba4e239bf180c1aa1e7a078e35a7 | 9056c077e31c487d9161ad38fa0fcb93f907abd4 | refs/heads/main | 2023-07-28T10:34:44.426574 | 2021-09-13T09:54:41 | 2021-09-13T09:54:41 | 381,072,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 706 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll MOD = 998244353;
#define rep(i,e) for(ll i = 0; i < e; i++)
#define endl "\n"
#define dbg(x) cout<<#x<<" = "<<x<<endl
#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
#define mod 1000000007
#define modadd(a,b,c) ((a%c)+(b%c))%c
#define modmul(a,b,c) ((a%c)*(b%c))%c
#define modsub(a,b,c) ((a%c)-(b%c))%c
int main()
{
fast_cin();
ll t;
cin >> t;
while(t--)
{
ll a,b;
cin>>a>>b;
ll x=a*b;
if(b==1)
{
cout<<"NO"<<endl;
}
else
{
cout<<"YES"<<endl;
cout<<a<<" "<<x<<" "<<a+x<<endl;
}
}
return 0;
} | [
"luckysingh@LUCKYs-MacBook-Air.local"
] | luckysingh@LUCKYs-MacBook-Air.local |
2252cf0875577b97a7be6a4f31305b5581030285 | 740f6f53f8628e59e5f7734c2240a31fae86b64a | /src/NativeScript/NativeScript/JSWeakRefConstructor.cpp | 84287daa98177f5cf8548c844065a3d9d6c6d6f6 | [
"Apache-2.0"
] | permissive | x412418908/ios-runtime | f30161951db239dd86efa9e778f16e7bbbea8e06 | 82bf4c0fd23fae55236b32d71b622aa7a5ccf9ad | refs/heads/master | 2021-01-24T19:50:24.717788 | 2015-03-31T21:59:47 | 2015-03-31T21:59:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,817 | cpp | //
// JSWeakRefConstructor.cpp
// NativeScript
//
// Created by Yavor Georgiev on 02.10.14.
// Copyright (c) 2014 г. Telerik. All rights reserved.
//
#include "JSWeakRefConstructor.h"
#include "JSWeakRefPrototype.h"
#include "JSWeakRefInstance.h"
namespace NativeScript {
using namespace JSC;
static EncodedJSValue JSC_HOST_CALL construct(ExecState* execState) {
JSValue argument = execState->argument(0);
if (!argument.isCell()) {
return JSValue::encode(execState->vm().throwException(execState, createTypeError(execState, WTF::ASCIILiteral("Argument must be an object."))));
}
GlobalObject* globalObject = jsCast<GlobalObject*>(execState->lexicalGlobalObject());
JSWeakRefInstance* weakRef = JSWeakRefInstance::create(execState->vm(), globalObject->weakRefInstanceStructure(), argument.asCell());
return JSValue::encode(weakRef);
}
const ClassInfo JSWeakRefConstructor::s_info = { "WeakRef", &Base::s_info, 0, 0, CREATE_METHOD_TABLE(JSWeakRefConstructor) };
JSWeakRefConstructor::JSWeakRefConstructor(VM& vm, Structure* structure)
: Base(vm, structure) {
}
void JSWeakRefConstructor::finishCreation(VM& vm, JSWeakRefPrototype* prototype) {
Base::finishCreation(vm, WTF::ASCIILiteral("WeakRef"));
this->putDirectWithoutTransition(vm, vm.propertyNames->prototype, prototype, DontEnum | DontDelete | ReadOnly);
this->putDirectWithoutTransition(vm, vm.propertyNames->length, jsNumber(1), ReadOnly | DontEnum | DontDelete);
}
ConstructType JSWeakRefConstructor::getConstructData(JSCell* cell, ConstructData& constructData) {
constructData.native.function = construct;
return ConstructTypeHost;
}
CallType JSWeakRefConstructor::getCallData(JSCell* cell, CallData& callData) {
callData.native.function = construct;
return CallTypeHost;
}
} | [
"ivanbuhov@gmail.com"
] | ivanbuhov@gmail.com |
b51ac15f6c574c878f6f673a6d804ca1939cae7c | 6ced41da926682548df646099662e79d7a6022c5 | /aws-cpp-sdk-cloudtrail/include/aws/cloudtrail/model/PutInsightSelectorsResult.h | bb77366a8d3166d90d2a4f3b24e23e058cee1b3e | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | irods/aws-sdk-cpp | 139104843de529f615defa4f6b8e20bc95a6be05 | 2c7fb1a048c96713a28b730e1f48096bd231e932 | refs/heads/main | 2023-07-25T12:12:04.363757 | 2022-08-26T15:33:31 | 2022-08-26T15:33:31 | 141,315,346 | 0 | 1 | Apache-2.0 | 2022-08-26T17:45:09 | 2018-07-17T16:24:06 | C++ | UTF-8 | C++ | false | false | 5,301 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/cloudtrail/CloudTrail_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/cloudtrail/model/InsightSelector.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace CloudTrail
{
namespace Model
{
class AWS_CLOUDTRAIL_API PutInsightSelectorsResult
{
public:
PutInsightSelectorsResult();
PutInsightSelectorsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
PutInsightSelectorsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The Amazon Resource Name (ARN) of a trail for which you want to change or add
* Insights selectors.</p>
*/
inline const Aws::String& GetTrailARN() const{ return m_trailARN; }
/**
* <p>The Amazon Resource Name (ARN) of a trail for which you want to change or add
* Insights selectors.</p>
*/
inline void SetTrailARN(const Aws::String& value) { m_trailARN = value; }
/**
* <p>The Amazon Resource Name (ARN) of a trail for which you want to change or add
* Insights selectors.</p>
*/
inline void SetTrailARN(Aws::String&& value) { m_trailARN = std::move(value); }
/**
* <p>The Amazon Resource Name (ARN) of a trail for which you want to change or add
* Insights selectors.</p>
*/
inline void SetTrailARN(const char* value) { m_trailARN.assign(value); }
/**
* <p>The Amazon Resource Name (ARN) of a trail for which you want to change or add
* Insights selectors.</p>
*/
inline PutInsightSelectorsResult& WithTrailARN(const Aws::String& value) { SetTrailARN(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of a trail for which you want to change or add
* Insights selectors.</p>
*/
inline PutInsightSelectorsResult& WithTrailARN(Aws::String&& value) { SetTrailARN(std::move(value)); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of a trail for which you want to change or add
* Insights selectors.</p>
*/
inline PutInsightSelectorsResult& WithTrailARN(const char* value) { SetTrailARN(value); return *this;}
/**
* <p>A JSON string that contains the Insights event types that you want to log on
* a trail. The valid Insights types in this release are
* <code>ApiErrorRateInsight</code> and <code>ApiCallRateInsight</code>.</p>
*/
inline const Aws::Vector<InsightSelector>& GetInsightSelectors() const{ return m_insightSelectors; }
/**
* <p>A JSON string that contains the Insights event types that you want to log on
* a trail. The valid Insights types in this release are
* <code>ApiErrorRateInsight</code> and <code>ApiCallRateInsight</code>.</p>
*/
inline void SetInsightSelectors(const Aws::Vector<InsightSelector>& value) { m_insightSelectors = value; }
/**
* <p>A JSON string that contains the Insights event types that you want to log on
* a trail. The valid Insights types in this release are
* <code>ApiErrorRateInsight</code> and <code>ApiCallRateInsight</code>.</p>
*/
inline void SetInsightSelectors(Aws::Vector<InsightSelector>&& value) { m_insightSelectors = std::move(value); }
/**
* <p>A JSON string that contains the Insights event types that you want to log on
* a trail. The valid Insights types in this release are
* <code>ApiErrorRateInsight</code> and <code>ApiCallRateInsight</code>.</p>
*/
inline PutInsightSelectorsResult& WithInsightSelectors(const Aws::Vector<InsightSelector>& value) { SetInsightSelectors(value); return *this;}
/**
* <p>A JSON string that contains the Insights event types that you want to log on
* a trail. The valid Insights types in this release are
* <code>ApiErrorRateInsight</code> and <code>ApiCallRateInsight</code>.</p>
*/
inline PutInsightSelectorsResult& WithInsightSelectors(Aws::Vector<InsightSelector>&& value) { SetInsightSelectors(std::move(value)); return *this;}
/**
* <p>A JSON string that contains the Insights event types that you want to log on
* a trail. The valid Insights types in this release are
* <code>ApiErrorRateInsight</code> and <code>ApiCallRateInsight</code>.</p>
*/
inline PutInsightSelectorsResult& AddInsightSelectors(const InsightSelector& value) { m_insightSelectors.push_back(value); return *this; }
/**
* <p>A JSON string that contains the Insights event types that you want to log on
* a trail. The valid Insights types in this release are
* <code>ApiErrorRateInsight</code> and <code>ApiCallRateInsight</code>.</p>
*/
inline PutInsightSelectorsResult& AddInsightSelectors(InsightSelector&& value) { m_insightSelectors.push_back(std::move(value)); return *this; }
private:
Aws::String m_trailARN;
Aws::Vector<InsightSelector> m_insightSelectors;
};
} // namespace Model
} // namespace CloudTrail
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
0b2890d58d0fe0d4256625d0b1fa700e3f6d749a | 908475a180b29188e897041481407da165059004 | /Lab homeworks/analogRGBControl.ino | 39967cb661c832b4022ab859dbeed00cddf2a50b | [] | no_license | Telera/Introduction-to-robotics | 12b21a7bc5caa1143ee4961cef0ca510fbbbd731 | 484eae2d7c1a33bac4334346eda1f238e8c60cdf | refs/heads/master | 2020-08-29T17:46:16.682824 | 2020-02-26T00:56:24 | 2020-02-26T00:56:24 | 218,116,099 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,285 | ino | const int pinRedLed = 11;
const int pinGreenLed = 10;
const int pinBlueLed = 9;
const int pinRedPot = A0;
const int pinGreenPot = A1;
const int pinBluePot = A2;
int valueRedPot = 0;
int valueGreenPot = 0;
int valueBluePot = 0;
int mappedRedValuePot = 0;
int mappedGreenValuePot = 0;
int mappedBlueValuePot = 0;
void setup() {
pinMode(pinRedLed, OUTPUT);
pinMode(pinGreenLed, OUTPUT);
pinMode(pinBlueLed, OUTPUT);
pinMode(pinRedPot, INPUT);
pinMode(pinGreenPot, INPUT);
pinMode(pinBluePot, INPUT);
}
void loop() {
valueRedPot = analogRead(pinRedPot); //potentiometer value acquisition
mappedRedValuePot = map(valueRedPot, 0, 1023, 0, 255); //map the value of the potentiometer
valueGreenPot = analogRead(pinGreenPot);
mappedGreenValuePot = map(valueGreenPot, 0, 1023, 0, 255);
valueBluePot = analogRead(pinBluePot);
mappedBlueValuePot = map(valueBluePot, 0, 1023, 0, 255);
setColor(mappedRedValuePot, mappedGreenValuePot, mappedBlueValuePot); //call the function using mapped values from potentiometers
}
//function that manage each leds of our RGB led
void setColor(int red, int green, int blue) {
analogWrite(pinRedLed, red);
analogWrite(pinGreenLed, green);
analogWrite(pinBlueLed, blue);
}
| [
"noreply@github.com"
] | Telera.noreply@github.com |
5210193eb66060792927b67fb34e87b10502cdb7 | 8c1e1569726adca8e52c9860cbb03d8b6dd0b056 | /ADXLib/Library/Random.h | 40a4ac1cf70d8fa0edb0f45007dc53269c5f9dfd | [] | no_license | y2a3k2/ADXLib | ed2c7d7e29f3d10221a868922aa007e9b8d241da | 26ac71cdee076e4d3c194831669d580f327594d6 | refs/heads/main | 2020-09-04T22:27:52.910881 | 2019-11-26T00:59:35 | 2019-11-26T00:59:35 | 219,909,037 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 316 | h | #pragma once
class Random {
// ランダム抽選した結果、当たったらtrueを返す(母数の数,当たりの数)
static bool GetHit(int all, int win = 1);
// そのくじの当たる確率を求める。戻り値は1〜0(母数の数,当たりの数)
static float GetProb(int all, int win = 1);
};
| [
"k175001@kccollege.ac.jp"
] | k175001@kccollege.ac.jp |
bed88c68b57e8fc0f94e2bea161ca07bcf1c1d75 | b023dfaf1609b38aae2de830dcc98b65159e2a5b | /jni/gloox/gloox-api/src/Skynet.cpp | ab21e19940b69a1f877fb3aa5353d8a15423d09b | [] | no_license | idwanglu2010/gloox_demo | 73717d101484312d388b87e6e210edd31f2231e8 | 5c518af74248652dcd462667c3ad89cd899702e0 | refs/heads/master | 2020-05-04T17:07:44.532240 | 2014-11-13T06:57:15 | 2014-11-13T06:57:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,256 | cpp | #include "../inc/Skynet.h"
#include "SkynetImpl.h"
#include "LogConfig.h"
#include <thread>
#define TAG "Skynet"
namespace skynet
{
Skynet::Skynet()
{
}
Skynet::~Skynet()
{
}
void Skynet::initialize(const InitializeInfo& info)
{
EnvironmentType type = info.type;
LOGD(TAG,"initialize begin, type: %d\n",type);
SkynetImpl *impl = SkynetImpl::getInstance(type);
impl->initialize(info.appid);
LOGD(TAG,"initialize end");
}
void Skynet::login(const LoginInfo& info, const LoginListener* loginListener)
{
SkynetImpl *impl = SkynetImpl::getInstance();
//impl->login(info,loginListener);
std::thread t(&SkynetImpl::login,impl,info,loginListener);
t.detach();
}
void Skynet::sendMessage(const SendMessageInfo& info, const SendMessageListener* sendMessageListener)
{
SkynetImpl *impl = SkynetImpl::getInstance();
//impl->sendMessage(info,sendMessageListener);
std::thread t(&SkynetImpl::sendMessage,impl,info,sendMessageListener);
t.detach();
}
void Skynet::joinChatRoom(const JoinChatRoomInfo& info, const JoinRoomListener* joinRoomListener)
{
SkynetImpl *impl = SkynetImpl::getInstance();
//impl->joinChatRoom(info,joinRoomListener);
std::thread t(&SkynetImpl::joinChatRoom,impl,info,joinRoomListener);
t.detach();
}
void Skynet::leaveChatRoom(const LeaveChatRoomInfo& info, const LeaveRoomListener* leaveRoomListener)
{
SkynetImpl *impl = SkynetImpl::getInstance();
//impl->leaveChatRoom(info,leaveRoomListener);
std::thread t(&SkynetImpl::leaveChatRoom,impl,info,leaveRoomListener);
t.detach();
}
bool Skynet::logout()
{
SkynetImpl *impl = SkynetImpl::getInstance();
std::thread t(&SkynetImpl::logout,impl);
t.detach();
//impl->logout();
return true;
}
void Skynet::registerMessageReceiverListener(const MessageReceiverListener* messageReceiverListener)
{
SkynetImpl *impl = SkynetImpl::getInstance();
impl->registerMessageReceiverListener(messageReceiverListener);
}
void Skynet::unregisterMessageReceiverListener(const MessageReceiverListener* messageReceiverListener)
{
SkynetImpl *impl = SkynetImpl::getInstance();
impl->unregisterMessageReceiverListener(messageReceiverListener);
}
}
| [
"idwanglu2010@gmail.com"
] | idwanglu2010@gmail.com |
73e5de3206c790419301186321a6dc543339a05f | c8bfd99efdacac5c2155f513144afed8237ec508 | /Syber Packets Defense/Simulator.h | 985e9b30e7b7ef7303d559bf7dc42766e2e913ed | [] | no_license | evyatarh/Cpp-projects | 298f479de5f337d91b05ff53166b52fdd2e49c53 | f34da032d8cb12316eebc89270f9a7a860c5818e | refs/heads/main | 2023-05-27T16:37:21.353286 | 2021-06-15T14:56:10 | 2021-06-15T14:56:10 | 377,184,462 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,574 | h |
#ifndef SIMULATOR_H_
#define SIMULATOR_H_
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include "Tackle.h"
#include "Cornerback.h"
#include "Linebacker.h"
using namespace std;
class Simulator {
private:
vector <DefensivePacket*> originalDefensivePacket;
vector <DefensivePacket*> updatedDefensivePacket;
vector <vector<bool>> attackVec;
int generationBeat;
int stringsDimension;
static const int MINPOPULATION = 2;
static const int MAXPOPULATION = 1000;
static const int MINSTRINGSDIMENSION = 3;
static const int MAXSTRINGSDIMENSION = 10000;
static const int MAXGENERATION = 1000000;
public:
Simulator(const char *arg1,const char *arg2,const int &arc);
Simulator(const Simulator &sim); //copy c'tor
Simulator& operator=(const Simulator &sim); //copy set operator
void startTheSimulator();
int powerOfDefense();
void flipBitInPropebuility();
void printTheUpdatedPacket();
void checkTheRc();
void printType(const DefensivePacket *a);
void printTheOriginalPacket();
void getConfigFromTheUser(const char* arg1);
void getOffenseFromTheUser(const char *arg2);
void switchStrings(DefensivePacket * a,DefensivePacket * b);
virtual ~Simulator();
/******************** class InputErrorException **************************/
//this class represent an exception from kind of Input Error exception
class InputErrorException{
private:
string str;
public:
//use default copy c'tor and copy set operator
InputErrorException(const string &s):str(s){};
virtual void printError()const{
cerr << "ERROR: "<< str << endl;
}
virtual~InputErrorException(){}
};
/******************** class ArcException **************************/
//this class represent an exception from kind of number of arguments exception
class ArcException{
private:
string str;
public:
//use default copy c'tor and copy set operator
ArcException(const string &s):str(s){};
virtual void printError()const{
cerr << "ERROR: "<< str << "The number of the arguments does not fit" << endl;
}
virtual~ArcException(){}
};
/******************** class IOException **************************/
//this class represent an exception from kind of Input Output exception
class IOException{
private:
string str;
public:
//use default copy c'tor and copy set operator
IOException(){}
IOException(const string &s):str(s){};
virtual void printError()const{
cerr << "ERROR: "<< str <<" does not exist or cannot be processed" << endl;
}
virtual~IOException(){}
};
};
#endif /* SIMULATOR_H_ */
| [
"noreply@github.com"
] | evyatarh.noreply@github.com |
340d6ca3d46a96048c00a165d0fe104d84832f4f | 95edf9e7bc17ed081d75bdd135c3adc4c3506bd0 | /second_term/vector_data_structure/vector.hpp | 7ce8ab5ea066f5731e0a189572729bfe2a8fffff | [] | no_license | t-weathers/introductory_computer_science | 3097e59379b2f99d3b379da5e473e79a0411564f | 7ee09a6136f893b65d61a8f20a70bcb26380fe3c | refs/heads/master | 2020-04-25T08:51:26.725647 | 2019-02-26T19:18:30 | 2019-02-26T19:18:30 | 172,660,062 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 945 | hpp | #include <stdlib.h>
#include<exception>
#include <stdexcept>
template <class T>
class vector {
private:
T *v;
int s;
public:
vector(){
s=0;
v=NULL;
}
~vector(){
delete [] v;
}
int size() {
return s;
}
void push_back(T ele) {
T *temp;
temp = new T[++s];
for(int i=0; i<s-1; i++)
temp[i]=v[i];
delete [] v;
v=temp;
v[s-1]=ele;
}
vector(vector<T> &other){
this->s = other.s;
v = new T[s];
for(int i = 0; i < other.s; i++){
this->v[i] = other.v[i];
}
}
void operator=(vector<T> &other){
if(v != NULL){
delete [] v;
}
s = other.s;
v = new T[s];
for(int i = 0; i < other.s; i++){
v[i] = other.v[i];
}
}
T operator [] (int a){
return v[a];
}
T at(int a){
if(a>=s || a <0){
throw std::out_of_range("out of vector bounds");
}
else
return v[a];
}
};
| [
"noreply@github.com"
] | t-weathers.noreply@github.com |
032faded2c09d0810a1110f7db79553aa56ac1c5 | 7b6e927d42ad155d8b827c345c2b2dffa7bd003b | /library/view/controls/tabbed_pane/native_tabbed_pane_win.h | 9a473d672ac56f704e779e31e63f487b79fdffcc | [] | no_license | wang70937/x-framework | d6b06a2910728bdfc219c9d1d166a71ce2c8233c | ccd772cfc28e724382800a30101e1f8c0e6bcde8 | refs/heads/master | 2021-01-24T09:18:01.883650 | 2016-09-29T01:47:20 | 2016-09-29T01:47:20 | 69,445,984 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,896 | h |
#ifndef __view_native_tabbed_pane_win_h__
#define __view_native_tabbed_pane_win_h__
#pragma once
#include <vector>
#include "native_tabbed_pane_wrapper.h"
#include "view/controls/native_control_win.h"
namespace view
{
class Widget;
class TabLayout;
class NativeTabbedPaneWin : public NativeControlWin,
public NativeTabbedPaneWrapper
{
public:
explicit NativeTabbedPaneWin(TabbedPane* tabbed_pane);
virtual ~NativeTabbedPaneWin();
// NativeTabbedPaneWrapper implementation:
virtual void AddTab(const std::wstring& title, View* contents);
virtual void AddTabAtIndex(int index,
const std::wstring& title,
View* contents,
bool select_if_first_tab);
virtual View* RemoveTabAtIndex(int index);
virtual void SelectTabAt(int index);
virtual int GetTabCount();
virtual int GetSelectedTabIndex();
virtual View* GetSelectedTab();
virtual View* GetView();
virtual void SetFocus();
virtual gfx::Size GetPreferredSize();
virtual HWND GetTestingHandle() const;
// NativeControlWin overrides.
virtual void CreateNativeControl();
virtual bool ProcessMessage(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result);
// View overrides:
virtual void Layout();
virtual FocusTraversable* GetFocusTraversable();
virtual void ViewHierarchyChanged(bool is_add, View* parent, View* child);
private:
// Called upon creation of native control to initialize tabs that are added
// before the native control is created.
void InitializeTabs();
// Adds a tab with the given content to native control at the given index.
void AddNativeTab(int index, const std::wstring& title);
// Changes the contents view to the view associated with the tab at |index|.
// |invoke_listener| controls if this methold should invoke the
// Listener::TabSelectedAt callback.
void DoSelectTabAt(int index, boolean invoke_listener);
// Resizes the HWND control to macth the size of the containing view.
void ResizeContents();
// The tabbed-pane we are bound to.
TabbedPane* tabbed_pane_;
// The layout manager we use for managing our tabs.
TabLayout* tab_layout_manager_;
// The views associated with the different tabs.
std::vector<View*> tab_views_;
// The tab's title strings.
std::vector<const std::wstring> tab_titles_;
// The index of the selected tab.
int selected_index_;
// The window displayed in the tab.
Widget* content_window_;
DISALLOW_COPY_AND_ASSIGN(NativeTabbedPaneWin);
};
} //namespace view
#endif //__view_native_tabbed_pane_win_h__ | [
"wang70937@163.com"
] | wang70937@163.com |
68b4d99d871428f47dfadce519bcd215f6a81a54 | 40dc3f774f264f3c2d41bbd0c9cf9e07459ee000 | /Code/C++/binary_tree_from_preorder_and_inorder.cpp | f324638bd58a883b25f4602c998108e5da9a9f1c | [
"LicenseRef-scancode-free-unknown",
"MIT"
] | permissive | krishna-NIT/Algo-Tree | 8a5f66b5baef0b7b38a22c41fe090cc9754d8a67 | 1cdb2c3682c6ab85ae8af0b57f42697c15a10554 | refs/heads/main | 2023-05-08T23:39:00.964136 | 2021-05-31T04:07:24 | 2021-05-31T04:07:24 | 371,605,115 | 3 | 0 | MIT | 2021-05-28T06:38:42 | 2021-05-28T06:38:42 | null | UTF-8 | C++ | false | false | 4,264 | cpp | /*
Construction of binary tree from inorder and preorder traversal
binary tree can be uniquely constructed if it's preorder and inorder traversals
are given.
The following steps need to be followed
1. From the preorder traversal , it is evident that the first element is the root node
2. In inorder traversal, all the nodes which are on the left side of root (from preorder)
belong to the left sub-tree and those which are on right side of the root (from preorder)
are on right side of root (from preorder) belong to right sub-tree
3. Now the problem reduces to form sub-trees and the same procedure can be applied
repeatedly.
*/
#include <iostream>
using namespace std;
//class for the binary tree
class TreeNode
{
public:
char data;
TreeNode *left;
TreeNode *right;
};
// search function searches the inorder traversal and returns the index if found
int search(char in[], int start, int end, char key)
{
for (int i = start; i <= end; i++)
{
if (in[i] == key)
{
return i;
}
}
}
// Build Tree Builds the tree from preorder and inorder traversals
TreeNode *BuildTree(char in[], char pre[], int start, int end)
{
//preindex is static as it should get incremented after each recursive calls
static int preindex = 0;
if (start > end)
{
return NULL;
}
//get New node and make left and right as null
TreeNode *node = new TreeNode();
node->data = pre[preindex];
node->left = NULL;
node->right = NULL;
preindex++;
//if there is only one node return that node
if (start == end)
{
return node;
}
// find the location of the root from the preorder traversal in the inorder
//traversal and store it in loc
int loc = search(in, start, end, node->data);
//the elements to the left of the inorder traversal forms the left subtree
node->left = BuildTree(in, pre, start, loc - 1);
// the elements to the right of the inorder traversal forms the right subtree
node->right = BuildTree(in, pre, loc + 1, end);
return node;
}
// inorder traversal for binary tree
void inorder(TreeNode *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%c ", root->data);
inorder(root->right);
}
}
// preorder traversal for binary tree
void preorder(TreeNode *root)
{
if (root != NULL)
{
printf("%c ", root->data);
preorder(root->left);
preorder(root->right);
}
}
// postorder traversal for binary tree
void postorder(TreeNode *root)
{
if (root != NULL)
{
postorder(root->left);
postorder(root->right);
printf("%c ", root->data);
}
}
// print the preorder inorder and postorder traversals of the resulting tree
void printTree(TreeNode *root)
{
printf("\nThe inorder traversal of the tree is\n");
inorder(root);
printf("\nThe preorder traversal of the tree is\n");
preorder(root);
printf("\nThe postorder traversal of the tree is\n");
postorder(root);
printf("\n");
}
int main()
{
printf("Enter the number of nodes in the binary tree \n");
int n;
cin >> n;
char *pre = (char *)malloc(sizeof(char) * (n + 1));
char *in = (char *)malloc(sizeof(char) * (n + 1));
printf("Enter the preorder traversal of the tree\n");
for (int i = 0; i < n; i++)
{
cin >> pre[i];
}
printf("Enter the inorder traversal of the tree \n");
for (int i = 0; i < n; i++)
{
cin >> in[i];
}
TreeNode *root = BuildTree(in, pre, 0, n - 1);
printTree(root);
return 0;
}
/*
Sample I/O :
1)
Enter the number of nodes in the binary tree
6
Enter the preorder traversal of the tree
A B D E C F
Enter the inorder traversal of the tree
D B E A F C
The inorder traversal of the tree is
D B E A F C
The preorder traversal of the tree is
A B D E C F
The postorder traversal of the tree is
D E B F C A
2)
Enter the number of nodes in the binary tree
4
Enter the preorder traversal of the tree
A B D C
Enter the inorder traversal of the tree
B D A C
The inorder traversal of the tree is
B D A C
The preorder traversal of the tree is
A B D C
The postorder traversal of the tree is
D B C A
Time complexity : O( n^2 )
Space complexity : O( n )
*/
| [
"noreply@github.com"
] | krishna-NIT.noreply@github.com |
87cfadc4c135e1b2430da5952fc6829f528f7e38 | c0f14a4ec245198916a377ae9fdd990f3c93b562 | /secondary/src/RootIO.cc | 1fbb330e44520492024f2247adaac0a9e673c483 | [] | no_license | Chriisbrown/persistance | 234d0fcd929e54efd18c32a75758173379704c5f | 044e33967149712966885e1b294a2e35854c9af5 | refs/heads/master | 2020-04-19T12:34:18.103114 | 2019-01-29T17:17:45 | 2019-01-29T17:17:45 | 168,195,130 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,357 | cc | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
/// \file persistency/P01/src/RootIO.cc
/// \brief Implementation of the RootIO class
//
// $Id: RootIO.cc 98770 2016-08-09 14:22:25Z gcosmo $
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#include <sstream>
#include "RootIO.hh"
//
#include "G4SDManager.hh"
#include "G4HCofThisEvent.hh"
#include "G4EventManager.hh"
#include "G4Event.hh"
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
static RootIO* instance = 0;
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
RootIO::RootIO():fNevents(0)
{
// initialize ROOT
TSystem ts;
gSystem->Load("libExP01ClassesDict");
//gDebug = 1;
fFile = new TFile("hits.root","RECREATE");
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
RootIO::~RootIO()
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
RootIO* RootIO::GetInstance()
{
if (instance == 0 )
{
instance = new RootIO();
}
return instance;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void RootIO::Write(std::vector<PhotonHit*>* hcont)
{
fNevents++;
std::ostringstream os;
os << fNevents;
std::string stevt = "Event_" + os.str();
const char* chevt = stevt.c_str();
G4cout << "writing " << stevt << G4endl;
fFile->WriteObject(hcont, chevt);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void RootIO::Close()
{
fFile->Close();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| [
"chris.brown@fpsl.net"
] | chris.brown@fpsl.net |
4482579e5dd0b7f86c3d66d5a2f5db3f04c07d37 | 91bb97c1f9ed275c8db4fb706e9370f2bb6e999a | /Camera/CameraInit.cpp | 5eb1f971d1de5cf85f38b1f10ced192ece583c89 | [] | no_license | icp3/Graphics | 39e70140113c326658cefca7221d440d975e3a6f | 86a49823278679c7334ce3d30917a9c6831ef81c | refs/heads/master | 2020-06-13T20:44:51.342123 | 2019-07-02T23:03:11 | 2019-07-02T23:03:11 | 194,782,680 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,363 | cpp | //
// Created by ian on 7/2/19.
//
#include <Camera.h>
//Sets camera values to defaults
void CameraInit(Camera* camera)
{
camera->Front = vec3(0.0f, 0.0f, -1.0f);
camera->MouseSensitivity = SENSITIVITY;
camera->MovementSpeed = SPEED;
camera->Zoom = ZOOM;
camera->Position = vec3(0.0f, 14.8f, 0.0f);
camera->WorldUp = vec3(0.0f, 1.0f, 0.0f);
camera->Yaw = YAW;
camera->Pitch = PITCH;
CameraUpdateVectors(camera);
}
// Constructor with vectors
void CameraInit(Camera* camera, vec3 position, vec3 up, float yaw = YAW, float pitch = PITCH)
{
camera->Front = vec3(0.0f, 0.0f, -1.0f);
camera->MovementSpeed = SPEED;
camera->MouseSensitivity = SENSITIVITY;
camera->Zoom = ZOOM;
camera->Position = position;
camera->WorldUp = up;
camera->Pitch = pitch;
camera->Yaw = yaw;
CameraUpdateVectors(camera);
}
// Constructor with scalar values
void CameraInit(Camera* camera, float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch)
{
camera->Front = vec3(0.0f, 0.0f, -1.0f);
camera->MovementSpeed = SPEED;
camera->MouseSensitivity = SENSITIVITY;
camera->Zoom = ZOOM;
camera->Position = vec3(posX, posY, posZ);
camera->WorldUp = vec3(upX, upY, upZ);
camera->Yaw = yaw;
camera->Pitch = pitch;
CameraUpdateVectors(camera);
} | [
"icp3@zips.uakron.edu"
] | icp3@zips.uakron.edu |
9a4efbcb38b890249f3b028b33a64962275969fb | 6397057f97b6aefc2d4c95db0f2815aa8b3ebca8 | /atcoder/abc145/A.cpp | e9e8e9fa8161d10084c35c06fd3320e6d75c10a7 | [] | no_license | masterace007/codeforces_harwest | 7a212012e437d7809753c12022698ee819516205 | 8d35a4e9fd200ebce33fd99f26ea93ea5d30f509 | refs/heads/master | 2023-04-28T17:23:59.157691 | 2021-02-06T12:05:00 | 2021-05-16T16:41:54 | 330,159,824 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 914 | cpp | #include<bits/stdc++.h>
#define endl '\n'
#define pb push_back
#define mod 1000000007
#define int long long int
#define hii cout<<"yes\n";
#define all(x) x.begin(),x.end()
#define deb(x) cout<<#x<<" : "<<x<<"\n";
#define FASTIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;
using namespace chrono;
void solve() {
int n;
cin >> n;
cout<<pow(n,2)<<endl;
}
int32_t main() {
FASTIO;
#ifndef ONLINE_JUDGE
freopen("Input.txt", "r", stdin);
freopen("Output.txt", "w", stdout);
freopen("Error.txt", "w", stderr);
#endif
auto start1 = high_resolution_clock::now();
int t = 1;
//cin >> t;
while (t--) {
solve();
}
auto stop1 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop1 - start1);
#ifndef ONLINE_JUDGE
cerr << "Time: " << duration.count() / 1000 << endl;
#endif
return 0;
} | [
"raghubanshi.shobhit24@gmail.com"
] | raghubanshi.shobhit24@gmail.com |
b6905498236ef8974c04c51752e65203e319af2a | 279736f0b43160f481efac9a8b409ccc0f42e530 | /Source/Main.cpp | 1eb096c76907ce5c8831265ea2e0939904d0841d | [] | no_license | maxwfreu/Chess | cddb399f502b0c2e54e0d76d97556fc9a2403ebe | d705e6f5ecbaa71462e91db603a6f2bf8d15bf9a | refs/heads/master | 2020-03-15T22:29:31.504227 | 2018-05-06T21:06:42 | 2018-05-06T21:06:42 | 132,374,674 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,228 | cpp | /*
==============================================================================
This file was auto-generated!
It contains the basic startup code for a JUCE application.
==============================================================================
*/
#include "../JuceLibraryCode/JuceHeader.h"
#include "MainComponent.h"
#include <iostream>
class ChessGUIApplication : public JUCEApplication
{
public:
//==============================================================================
ChessGUIApplication() {}
const String getApplicationName() override { return "ChessGUI"; }
const String getApplicationVersion() override { return "1.0.0"; }
void initialise (const String&) override { mainWindow.reset (new MainWindow ("Chess", new MainComponent(), *this)); }
void shutdown() override { mainWindow = nullptr; }
private:
class MainWindow : public DocumentWindow
{
public:
MainWindow (const String& name, Component* c, JUCEApplication& a)
: DocumentWindow (name, Desktop::getInstance().getDefaultLookAndFeel()
.findColour (ResizableWindow::backgroundColourId),
DocumentWindow::allButtons),
app (a)
{
setUsingNativeTitleBar (true);
setContentOwned (c, true);
#if JUCE_ANDROID || JUCE_IOS
setFullScreen (true);
#else
setResizable (true, false);
setResizeLimits (300, 250, 10000, 10000);
centreWithSize (getWidth(), getHeight());
#endif
setVisible (true);
// gameLoop.start();
}
void closeButtonPressed() override
{
app.systemRequestedQuit();
}
private:
JUCEApplication& app;
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
};
std::unique_ptr<MainWindow> mainWindow;
};
//==============================================================================
START_JUCE_APPLICATION (ChessGUIApplication)
| [
"maxwfreu@alumni.stanford.edu"
] | maxwfreu@alumni.stanford.edu |
3fb60e3cc85fbc94ee6ffcc46fff0ba3dc53a2e3 | b111b77f2729c030ce78096ea2273691b9b63749 | /perf-native-large/project806/src/testComponent971/cpp/main.cpp | 01a19f0ef7617bfc8b13128b6fce43f3acae8236 | [] | no_license | WeilerWebServices/Gradle | a1a55bdb0dd39240787adf9241289e52f593ccc1 | 6ab6192439f891256a10d9b60f3073cab110b2be | refs/heads/master | 2023-01-19T16:48:09.415529 | 2020-11-28T13:28:40 | 2020-11-28T13:28:40 | 256,249,773 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,337 | cpp | #include <stdio.h>
#include <component1074/lib1.h>
#include <component186/lib1.h>
#include <component133/lib1.h>
#include <component134/lib1.h>
#include <component135/lib1.h>
#include <component262/lib1.h>
#include <component260/lib1.h>
#include <externalComponent138/lib1.h>
#include <component139/lib1.h>
#include <component140/lib1.h>
#include <component141/lib1.h>
#include <component736/lib1.h>
#include <component445/lib1.h>
#include <component1070/lib1.h>
#include <component148/lib1.h>
#include <component149/lib1.h>
#include <externalComponent109/lib1.h>
#include <externalComponent150/lib1.h>
#include <component151/lib1.h>
#include <component162/lib1.h>
#include <component162/lib1.h>
#include <component680/lib1.h>
#include <component788/lib1.h>
#include <component145/lib1.h>
#include <component146/lib1.h>
#include <component169/lib1.h>
#include <component153/lib1.h>
#include <externalComponent23/lib1.h>
#include <component719/lib1.h>
#include <component652/lib1.h>
#include <externalComponent156/lib1.h>
#include <component785/lib1.h>
#include <component1079/lib1.h>
#include <component158/lib1.h>
#include <component783/lib1.h>
#include <component788/lib1.h>
#include <externalComponent9/lib1.h>
#include <externalComponent10/lib1.h>
#include <externalComponent11/lib1.h>
#include <externalComponent12/lib1.h>
#include <externalComponent13/lib1.h>
#include <externalComponent14/lib1.h>
#include <externalComponent15/lib1.h>
#include <externalComponent16/lib1.h>
#include <externalComponent17/lib1.h>
#include <externalComponent18/lib1.h>
#include <externalComponent19/lib1.h>
#include <externalComponent20/lib1.h>
#include <externalComponent21/lib1.h>
#include <externalComponent167/lib1.h>
#include <component169/lib1.h>
#include <externalComponent170/lib1.h>
#include <component265/lib1.h>
#include <externalComponent1/lib1.h>
#include <externalComponent2/lib1.h>
#include <externalComponent3/lib1.h>
#include <externalComponent4/lib1.h>
#include <externalComponent5/lib1.h>
#include <externalComponent6/lib1.h>
#include <externalComponent7/lib1.h>
#include <component172/lib1.h>
#include <externalComponent23/lib1.h>
#include <externalComponent24/lib1.h>
#include <externalComponent25/lib1.h>
#include <externalComponent26/lib1.h>
#include <externalComponent27/lib1.h>
#include <externalComponent28/lib1.h>
#include <externalComponent29/lib1.h>
#include <externalComponent30/lib1.h>
#include <externalComponent31/lib1.h>
#include <externalComponent32/lib1.h>
#include <externalComponent33/lib1.h>
#include <externalComponent34/lib1.h>
#include <externalComponent35/lib1.h>
#include <externalComponent36/lib1.h>
#include <externalComponent37/lib1.h>
#include <externalComponent38/lib1.h>
#include <externalComponent39/lib1.h>
#include <externalComponent40/lib1.h>
#include <externalComponent41/lib1.h>
#include <externalComponent42/lib1.h>
#include <externalComponent43/lib1.h>
#include <externalComponent44/lib1.h>
#include <externalComponent45/lib1.h>
#include <externalComponent46/lib1.h>
#include <externalComponent47/lib1.h>
#include <externalComponent48/lib1.h>
#include <externalComponent49/lib1.h>
#include <externalComponent50/lib1.h>
#include <externalComponent51/lib1.h>
#include <externalComponent111/lib1.h>
#include <externalComponent53/lib1.h>
#include <externalComponent54/lib1.h>
#include <externalComponent55/lib1.h>
#include <externalComponent56/lib1.h>
#include <externalComponent57/lib1.h>
#include <externalComponent58/lib1.h>
#include <externalComponent59/lib1.h>
#include <externalComponent60/lib1.h>
#include <externalComponent61/lib1.h>
#include <externalComponent62/lib1.h>
#include <externalComponent63/lib1.h>
#include <externalComponent64/lib1.h>
#include <externalComponent65/lib1.h>
#include <externalComponent66/lib1.h>
#include <externalComponent67/lib1.h>
#include <externalComponent68/lib1.h>
#include <externalComponent69/lib1.h>
#include <externalComponent70/lib1.h>
#include <externalComponent71/lib1.h>
#include <externalComponent72/lib1.h>
#include <externalComponent73/lib1.h>
#include <externalComponent74/lib1.h>
#include <externalComponent75/lib1.h>
#include <externalComponent174/lib1.h>
#include <component1077/lib1.h>
#include <component1078/lib1.h>
#include <component164/lib1.h>
#include <externalComponent204/lib1.h>
int main() {
printf("Hello from Main\n");
}
| [
"nateweiler84@gmail.com"
] | nateweiler84@gmail.com |
1cd1f6ebb7d9ac8bfe2e73d2882ed4d175d32e04 | d8e7a11322f6d1b514c85b0c713bacca8f743ff5 | /7.6.00.37/V76_00_37/MaxDB_ORG/sys/src/SAPDB/FileDirectory/FileDir_PageIndexPage.cpp | 60bcad2a3c131a83ae7325a591555d6ffff287f0 | [] | no_license | zhaonaiy/MaxDB_GPL_Releases | a224f86c0edf76e935d8951d1dd32f5376c04153 | 15821507c20bd1cd251cf4e7c60610ac9cabc06d | refs/heads/master | 2022-11-08T21:14:22.774394 | 2020-07-07T00:52:44 | 2020-07-07T00:52:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,683 | cpp | /*****************************************************************************/
/*!
@file FileDir_PageIndexPage.cpp
@author MartinKi
@ingroup FileDirectory_Files
@brief Implementation of class FileDir_PageIndexPage.
\if EMIT_LICENCE
========== licence begin GPL
Copyright (c) 2003-2005 SAP AG
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
========== licence end
\endif
*/
/*****************************************************************************/
/*===========================================================================*
* INCLUDES *
*===========================================================================*/
#include "FileDirectory/FileDir_PageIndexPage.hpp"
#include "FileDirectory/FileDir_Page.hpp"
// for Data_PageNo:
#include "DataAccess/Data_Types.hpp"
#include "DataAccess/Data_BasePage.hpp"
// to write page:
#include "IOManager/IOMan_IDataIO.hpp"
// PASCAL: GG_basic_constants_and_type
#include "ggg00.h"
// to init Data_BasePage:
#include "hbd01_1.h"
#include "hbd13.h"
#include "FrameControl/FrameCtrl_IFileDirectory.hpp"
// vgetpid():
#include "heo51.h"
#include "RunTime/RTE_Types.hpp"
#include "SAPDBCommon/Tracing/SAPDBTrace_Usage.hpp"
#include "SAPDBCommon/ErrorsAndMessages/SAPDBErr_Assertions.hpp"
#include "SAPDBCommon/ErrorsAndMessages/SAPDBErr_MessageList.hpp"
#include "SAPDBCommon/SAPDB_MemCopyMove.hpp"
#include "SAPDBCommon/SAPDB_Types.hpp"
/*===========================================================================*
* DEFINES *
*===========================================================================*/
/*===========================================================================*
* MACROS *
*===========================================================================*/
/*===========================================================================*
* LOCAL CLASSES, STRUCTURES, TYPES, UNIONS ... *
*===========================================================================*/
/*===========================================================================*
* STATIC/INLINE FUNCTIONS (PROTOTYPES) *
*===========================================================================*/
/*===========================================================================*
* METHODS *
*===========================================================================*/
FileDir_PageIndexPage::FileDir_PageIndexPage(
const Data_PageNo& pageNumber)
: m_anchor(0),
m_currentEntry(0),
m_isDirty(true),
m_initialized(false)
{
SAPDBTRACE_METHOD_DEBUG( "FileDir_PageIndexPage::FileDir_PageIndexPage",
FileDir_Trace, 5 );
RTE_TaskId taskId;
vgetpid( taskId );
m_Frame = FrameCtrl_IFileDirectory::GetInstance().NewFDirFrame( taskId );
if ( !m_Frame.IsAssigned() ) {
return;
}
m_anchor =
reinterpret_cast<char*>(m_Frame.GetPointer(0, m_Frame.GetLength()));
if (m_anchor != 0) {
// init header/trailer of Data_BasePage:
tgg00_FileId fileId;
tbd_node_ptrs np = { reinterpret_cast<tbd_nodeptr>(m_anchor),
0 };
fileId = b01niltree_id;
fileId.fileType_gg00().clear();
fileId.fileType_gg00().addElement(ftsPerm_egg00);
fileId.fileType_gg00().addElement(ftsConcurrent_egg00);
fileId.fileRoot_gg00() = pageNumber;
b13init_default_data_page(fileId,
0,
pageNumber,
np);
np.np_ptr()->nd_header().pageType_gg00().becomes( ptFileDir_egg00 );
np.np_ptr()->nd_trailer().pageType_gg00().becomes( ptFileDir_egg00 );
np.np_ptr()->nd_level() = FileDir_Common::FileDir_PageIndexPage;
// end init header
Data_PageNo invalidPage;
this->SetNextPage( invalidPage );
this->SetEntryCount( 0 );
m_currentEntry = reinterpret_cast<PageType*>(&m_anchor[HeaderSize]);
}
}
/*************************************************************************/
FileDir_PageIndexPage::~FileDir_PageIndexPage()
{
SAPDBTRACE_METHOD_DEBUG( "FileDir_PageIndexPage::~FileDir_PageIndexPage",
FileDir_Trace, 5 );
if ( m_Frame.IsAssigned() ) {
RTE_TaskId taskId;
vgetpid( taskId );
FrameCtrl_IFileDirectory::GetInstance().FreeFDirFrame(
taskId, m_Frame );
}
}
/*************************************************************************/
SAPDB_Bool FileDir_PageIndexPage::Initialize()
{
SAPDBTRACE_METHOD_DEBUG( "FileDir_PageIndexPage::Initialize",
FileDir_Trace, 5 );
m_initialized = ( m_Frame.IsAssigned() && (m_anchor != 0) );
return m_initialized;
}
/*************************************************************************/
SAPDB_Bool FileDir_PageIndexPage::ReinitializeFromContent()
{
SAPDBTRACE_METHOD_DEBUG( "FileDir_PageIndexPage::ReinitializeFromContent",
FileDir_Trace, 5 );
SAPDBERR_ASSERT_STATE( m_initialized );
m_currentEntry =
reinterpret_cast<PageType*>(&m_anchor[HeaderSize])
+ this->GetEntryCount();
return true;
}
/*************************************************************************/
SAPDB_Bool FileDir_PageIndexPage::AddPage(const FileDir_Page& page)
{
SAPDBTRACE_METHOD_DEBUG( "FileDir_PageIndexPage::AddPage",
FileDir_Trace, 5 );
SAPDBERR_ASSERT_STATE( m_initialized );
if ( IsFull() ) {
return false;
}
m_isDirty = true;
*m_currentEntry++ = page.PageNo();
this->ModifyEntryCount( 1 );
return true;
}
/*************************************************************************/
SAPDB_Bool FileDir_PageIndexPage::RemovePage(const FileDir_Page& page)
{
SAPDBTRACE_METHOD_DEBUG( "FileDir_PageIndexPage::RemovePage",
FileDir_Trace, 5 );
SAPDBERR_ASSERT_STATE( m_initialized );
PageType* curPage = FirstEntryPos();
SAPDBErr_MessageList messages;
while ( curPage <= m_currentEntry ) {
if ( *curPage == page.PageNo() ) {
if ( curPage < m_currentEntry ) {
SAPDB_MemMove(
curPage, curPage + 1,
(m_currentEntry - curPage) * sizeof(PageType),
"FileDirectory", __FILE__, __LINE__, messages );
}
m_isDirty = true;
--m_currentEntry;
this->ModifyEntryCount( -1 );
return true;
}
++curPage;
}
return false;
}
/*************************************************************************/
void FileDir_PageIndexPage::SetEntryCount(SAPDB_Int4 entryCount)
{
SAPDBTRACE_METHOD_DEBUG(
"FileDir_PageIndexPage::SetEntryCount", FileDir_Trace, 5 );
this->NodePtr()->nd_record_cnt() = entryCount;
}
/*************************************************************************/
void FileDir_PageIndexPage::ModifyEntryCount(SAPDB_Int4 delta)
{
SAPDBTRACE_METHOD_DEBUG(
"FileDir_PageIndexPage::ModifyEntryCount", FileDir_Trace, 5 );
this->NodePtr()->nd_record_cnt() += delta;
}
/*************************************************************************/
SAPDB_Int4 FileDir_PageIndexPage::GetEntryCount() const
{
SAPDBTRACE_METHOD_DEBUG(
"FileDir_PageIndexPage::ModifyEntryCount", FileDir_Trace, 5 );
return this->NodePtr()->nd_record_cnt();
}
/*************************************************************************/
void FileDir_PageIndexPage::SetNextPage(const Data_PageNo& nextPage)
{
SAPDBTRACE_METHOD_DEBUG(
"FileDir_PageIndexPage::SetNextPage", FileDir_Trace, 5 );
this->NodePtr()->nd_right() = nextPage;
m_isDirty = true;
}
/*************************************************************************/
Data_PageNo FileDir_PageIndexPage::GetNextPage() const
{
SAPDBTRACE_METHOD_DEBUG(
"FileDir_PageIndexPage::GetNextPage", FileDir_Trace, 5 );
SAPDBERR_ASSERT_STATE( m_initialized );
return Data_PageNo( this->NodePtr()->nd_right() );
}
/*************************************************************************/
SAPDB_Bool FileDir_PageIndexPage::IsFull() const
{
SAPDBTRACE_METHOD_DEBUG(
"FileDir_PageIndexPage::IsFull", FileDir_Trace, 5 );
SAPDBERR_ASSERT_STATE( m_initialized );
return
(m_currentEntry + 1)
>=
reinterpret_cast<PageType*>(&m_anchor[ PageSize - TrailerSize ]);
}
/*************************************************************************/
SAPDB_Bool FileDir_PageIndexPage::IsEmpty() const
{
SAPDBERR_ASSERT_STATE( m_initialized );
return
m_currentEntry
==
reinterpret_cast<PageType*>(&m_anchor[ HeaderSize ]);
}
/*************************************************************************/
SAPDB_Bool FileDir_PageIndexPage::MergeRecommended() const
{
SAPDBERR_ASSERT_STATE( m_initialized );
return
m_currentEntry
<
reinterpret_cast<PageType*>(
&m_anchor[ HeaderSize + PageDataSize / 2 ]);
}
/*************************************************************************/
SAPDB_UInt FileDir_PageIndexPage::Capacity() const
{
return PageDataSize / sizeof(PageType);
}
/*************************************************************************/
void FileDir_PageIndexPage::Flush(const RTE_TaskId taskId)
{
SAPDBERR_ASSERT_STATE( m_initialized );
IOMan_IDataIO::GetInstance().WriteDataPage( taskId, *this );
}
/*************************************************************************/
/*************************************************************************/
FileDir_PageIndexPage::Iterator&
FileDir_PageIndexPage::Iterator::operator++()
{
if ( ((m_current+1) == m_indexPage->m_currentEntry)
|| (m_current == 0) ) {
m_current = 0;
} else {
++m_current;
}
return *this;
}
/*************************************************************************/
FileDir_PageIndexPage::Iterator
FileDir_PageIndexPage::Iterator::operator++(int)
{
Iterator i = *this;
++(*this);
return i;
}
/*************************************************************************/
SAPDB_Bool
FileDir_PageIndexPage::Iterator::operator==(const Iterator& i) const
{
return
(m_indexPage == i.m_indexPage)
&&
(m_current == i.m_current);
}
/*************************************************************************/
FileDir_PageIndexPage::Iterator&
FileDir_PageIndexPage::Iterator::operator=(const Iterator& i)
{
if (*this == i)
return *this;
m_indexPage = i.m_indexPage;
m_current = i.m_current;
return *this;
}
/*************************************************************************/
FileDir_PageIndexPage::Iterator::Iterator(FileDir_PageIndexPage& indexPage)
: m_indexPage(&indexPage),
m_current(indexPage.FirstEntryPos())
{
if ( m_current == indexPage.m_currentEntry ) {
m_current = 0;
}
}
/*************************************************************************/
FileDir_PageIndexPage::Iterator::Iterator(
FileDir_PageIndexPage& indexPage,
bool)
: m_indexPage(&indexPage),
m_current(0)
{}
/**************************************************************************/
FileDir_ReturnCode FileDir_PageIndexPage::CheckData(RTE_TaskId taskId)
{
SAPDBTRACE_METHOD_DEBUG( "FileDir_PageIndexPage::CheckData",
FileDir_Trace, 5 );
// FIXME: verify page
return FileDir_Okay;
}
/*************************************************************************/
| [
"gunter.mueller@gmail.com"
] | gunter.mueller@gmail.com |
658bb087361eb9b615aef35fdc8cef98f26cd478 | 760b25ad34068cde2ae6921f560156305fc0455c | /NotThatGameEngine/NotThatGameEngine/Textures.cpp | 2f353306d8cb4b399de2cce3cd2c23e14752fb23 | [
"MIT",
"CC-BY-4.0",
"CC-BY-3.0"
] | permissive | HoduRe/NotThatGameEngine | 51dbbde0de91f12c5b81792fb4bcfc9df27f5e37 | e1a6bd073fbd34f3598b2c03f8d0d82cd8540ccc | refs/heads/master | 2023-06-09T20:32:50.503739 | 2021-06-18T10:14:34 | 2021-06-18T10:14:34 | 299,239,952 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,683 | cpp | #include "Application.h"
#include "Textures.h"
#include "Load.h"
#include "Devil/include/il.h"
#include "Devil/include/ilu.h"
#include "Devil/include/ilut.h"
#include "ManagerEvent.h"
Texture::Texture(Application* app, bool start_enabled) : Module(app, start_enabled), textureVec(), defaultTexture("Alex"), checkersTexture("Checker"), degenerateTexture("Degenerate") {}
Texture::~Texture() { textureVec.clear(); }
bool Texture::Init() { // OpenGL has not been initialized yet
bool ret = true;
ilInit();
iluInit();
ilutInit();
LOG("DevIL libraries initialized.\n");
ilEnable(IL_ORIGIN_SET);
ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
return ret;
}
bool Texture::Start() { return true; }
bool Texture::CleanUp() {
if (textureVec.size() != 0) { glDeleteTextures(textureVec.size(), &textureVec[0].textureId); }
return true;
}
update_status Texture::PreUpdate(float dt) {
for (int i = 0; i < textureVec.size(); i++) {
if (textureVec[i].reference <= 0 && textureVec[i].name != defaultTexture && textureVec[i].name != checkersTexture && textureVec[i].name != degenerateTexture) {
glDeleteTextures(1, (const GLuint*)&textureVec[i].id);
textureVec.erase(textureVec.begin() + i);
i--;
}
}
return update_status::UPDATE_CONTINUE;
}
update_status Texture::Update(float dt) { return update_status::UPDATE_CONTINUE; }
void Texture::AddTexture(TextureData* texture) { textureVec.push_back(*texture); }
uint Texture::IsTextureRepeated(GLuint id) {
for (int i = textureVec.size() - 1; i > -1; i--) {
if (textureVec[i].textureId == id) { return textureVec[i].textureId; }
}
return 0;
}
uint Texture::IsTextureRepeated(std::string _name) {
for (int i = textureVec.size() - 1; i > -1; i--) {
if (textureVec[i].name == _name) { return textureVec[i].textureId; }
}
return 0;
}
TextureData* Texture::GetTextureData(GLuint id) {
int size = textureVec.size();
for (int i = 0; i < size; i++) { if (textureVec[i].textureId == id) { return &textureVec[i]; } }
return nullptr;
}
TextureData* Texture::GetTextureData(std::string name) {
int size = textureVec.size();
for (int i = 0; i < size; i++) { if (textureVec[i].name == name) { return &textureVec[i]; } }
return nullptr;
}
std::vector<TextureData> Texture::GetTextureVector() { return textureVec; }
void Texture::IncreaseTextureCount(std::string textureName) {
TextureData* textureData = GetTextureData(textureName);
if (textureData != nullptr) { textureData->reference++; }
}
void Texture::DecreaseTextureCount(std::string textureName) {
TextureData* textureData = GetTextureData(textureName);
if (textureData != nullptr) { textureData->reference--; }
}
| [
"47557484+ferba93@users.noreply.github.com"
] | 47557484+ferba93@users.noreply.github.com |
f32cc15cd63834781de44937640e18dd129ed540 | c27e1686cb8163c32b8bd74b60cb8f5251c34e0c | /PRCDMP/include/UTILS/Config.h | f5a465f4e462209a0733cf19037251b6975bf9ab | [] | no_license | konsiritt/prcdmp | 3c013aa712518d57a4a446420e403a7804b9668a | caffbfb523ebba86af0c15bb866f058f28fe211a | refs/heads/master | 2020-06-18T07:15:33.000097 | 2019-07-10T16:59:36 | 2019-07-10T16:59:36 | 196,210,671 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,264 | h | #ifndef CONFIG_H
#define CONFIG_H
#include <string>
#include <fstream>
#include <iostream>
#include <jsoncpp/json/value.h>
#include <jsoncpp/json/json.h>
#include "UTILS/common.h"
class Config
{
public:
Config(std::string datasetPath);
// basePath_ ends in */data/
Config(std::string datasetPath, std::string basePath_);
void fillTrajectoryPath(int episodeNr);
// Getters
Json::Value getDmpJson();
Json::Value getDataJson();
std::string getwPath();
std::string getInitialWPath();
std::string getTrajectoryPath();
std::string getReplayTrajectoryPath();
std::string getReplayTrajectoryPathQ();
std::string getDmpConfPath();
std::string getDataConfPath();
std::string getConfBasePath();
private:
std::string datasetPath;
std::string basePath;
std::string confBasePath;
std::string dmpConfPath;
std::string dataConfPath;
std::string trajectoryPath;
std::string replayTrajectoryPath;
std::string replayTrajectoryPathQ;
std::string wPath;
std::string initialWPath;
std::ifstream dmpconf;
std::ifstream dataconf;
Json::Reader dmpConfReader;
Json::Reader dataConfReader;
Json::Value dmpJson;
Json::Value dataJson;
};
#endif // CONFIG_H
| [
"k.ritt@tum.de"
] | k.ritt@tum.de |
1b812be90d51b499b78628f748d3b749b184291a | 33c2839e77e490bb6bdc1b9ea5b4e76d3204bd2d | /Alpha/Sprite.cpp | de75e0ac85ac7ea457becf1bfbbee938c6dd5de2 | [] | no_license | higorbreno/Alpha | 2804f790f8fd1d7f9161ab3640f500f6e7bd3212 | 09b68547fdf46c4c48927c5c74cc6656fc45f092 | refs/heads/master | 2023-08-21T01:46:00.136956 | 2021-09-29T14:38:53 | 2021-09-29T14:38:53 | 411,711,140 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,179 | cpp | /**********************************************************************************
// Sprite (Código Fonte)
//
// Criação: 11 Jul 2007
// Atualização: 08 Set 2021
// Compilador: Visual C++ 2019
//
// Descrição: Define uma classe para representar um sprite
//
**********************************************************************************/
#include "Sprite.h"
#include "Engine.h"
#include "Scene.h"
// -------------------------------------------------------------------------------
// Inicialização de membros estáticos das classes
// valores de profundidade predefinidos
const float Layer::FRONT = 0.01f;
const float Layer::UPPER = 0.25f;
const float Layer::MIDDLE = 0.50f;
const float Layer::LOWER = 0.75f;
const float Layer::BACK = 0.99f;
// ---------------------------------------------------------------------------------
Sprite::Sprite(string filename)
{
// carrega imagem
image = new Image(filename);
localImage = true;
// configura registro sprite
sprite.texture = image->View();
}
// ---------------------------------------------------------------------------------
Sprite::Sprite(const Image * img)
{
// aponta para imagem externa
image = img;
localImage = false;
// configura registro sprite
sprite.texture = image->View();
}
// ---------------------------------------------------------------------------------
Sprite::~Sprite()
{
if (localImage)
delete image;
}
// ---------------------------------------------------------------------------------
void Sprite::Draw(float x, float y, float z, float scale, float rotation, Color color)
{
sprite.x = x - Scene::camera2d->X();
sprite.y = y - Scene::camera2d->Y();
sprite.scale = scale;
sprite.depth = z;
sprite.rotation = rotation;
sprite.width = image->Width();
sprite.height = image->Height();
sprite.texCoord.x = 0;
sprite.texCoord.y = 0;
sprite.texSize.x = 1;
sprite.texSize.y = 1;
sprite.color = color;
// adiciona o sprite na lista de desenho
Engine::renderer->Draw(sprite);
}
// --------------------------------------------------------------------------------- | [
"higor@LAPTOP-QJN44KV9"
] | higor@LAPTOP-QJN44KV9 |
2d13f8230b2aac0c6c476da3269b4affcb41b5e5 | ce9e8b427f1aea9a66989102ff67ea9ced0e5493 | /playwidget.cpp | 0165c4e73b50d6e41573b32601fa52e288e77581 | [] | no_license | Kutovvo/sudoku | e93a7f23a3b5e8ac9a4cde52dc5089710d73a87e | 26d7f48c58d48e3e03cc1d5bbc08f38ad8dbfd8f | refs/heads/master | 2021-01-11T23:42:03.542155 | 2017-01-11T09:44:16 | 2017-01-11T09:44:16 | 78,624,465 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,803 | cpp | #include "playwidget.h"
PlayWidget::PlayWidget(QStandardItemModel* showPazle_, QPushButton **btn_, QLCDNumber *lcd_, QWidget *obj = 0):
QWidget(obj),
showPazle(showPazle_),
setUserData(new QStandardItemModel(9,9,this)),
click_row(-1),
click_col(-1),
userNumber(0),
btn(btn_),
lcd(lcd_),
hint(false),
buttonHint(new bool[9]),
stepFinish(0),
createNewGame(false)
{
setFocusPolicy(Qt::StrongFocus);
buttonHint[0] = 0;
for(int row = 0; row < 9; row++){
buttonHint[row+1] = 0;
for(int col = 0; col < 9; col++){
if(showPazle->data(showPazle->index(row, col)).toInt() != 0){
setUserData->setData(setUserData->index(col,row),-1);
}
}
}
click_row = -1;
click_col = -1;
enableDisableButton(hint);
showFinish();
}
PlayWidget::~PlayWidget()
{
}
void PlayWidget::resetData()
{
for(int row = 0; row < 9; row++){
buttonHint[row+1] = 0;
for(int col = 0; col < 9; col++){
if(showPazle->data(showPazle->index(row, col)).toInt() != 0){
setUserData->setData(setUserData->index(col,row),-1);
}
else{
setUserData->setData(setUserData->index(col,row),0);
}
}
}
click_row = -1;
click_col = -1;
repaint();
enableDisableButton(hint);
showFinish();
}
bool PlayWidget::getStatusNewGame()
{
return createNewGame;
}
void PlayWidget::enableDisableButton(bool act)
{
if(click_row == -1 && click_col == -1){
for(int i = 0; i < 10; i++)
btn[i]->setEnabled(false);
}
else{
if(!hint){
for(int i = 0; i < 10; i++)
btn[i]->setDisabled(act);
}
else{
for(int i = 0; i < 9; i++)
buttonHint[i] = true;
for(int i = 0; i < 9; i++){
if(showPazle->data(showPazle->index(click_col, i)).toInt())
buttonHint[showPazle->data(showPazle->index(click_col, i)).toInt()-1] = false;
if(setUserData->data(setUserData->index(i, click_col)).toInt())
buttonHint[setUserData->data(setUserData->index(i, click_col)).toInt()-1] = false;
}
for(int i = 0; i < 9; i++){
if(showPazle->data(showPazle->index(i, click_row)).toInt())
buttonHint[showPazle->data(showPazle->index(i, click_row)).toInt()-1] = false;
if(setUserData->data(setUserData->index(click_row, i)).toInt())
buttonHint[setUserData->data(setUserData->index(click_row, i)).toInt()-1] = false;
}
int s_col, e_col, s_row, e_row;
if(click_col >= 0 && click_col <=2)
(s_col = 0, e_col =2);
else if(click_col >= 3 && click_col <=5)
(s_col = 3, e_col =5);
else
(s_col = 6, e_col =8);
if(click_row >= 0 && click_row <=2)
(s_row = 0, e_row =2);
else if(click_row >= 3 && click_row <=5)
(s_row = 3, e_row =5);
else
(s_row = 6, e_row =8);
for(int col = s_col; col <= e_col; col++)
for(int row = s_row; row <= e_row; row++){
if(showPazle->data(showPazle->index(col, row)).toInt())
buttonHint[showPazle->data(showPazle->index(col, row)).toInt()-1] = false;
if(setUserData->data(setUserData->index(row, col)).toInt())
buttonHint[setUserData->data(setUserData->index(row, col)).toInt()-1] = false;
}
for(int i = 1; i < 10; i++)
btn[i]->setEnabled(buttonHint[i-1]);
}
}
}
void PlayWidget::setHint(bool hint_)
{
hint = hint_;
if(click_row != -1 && click_col != -1)
enableDisableButton(hint);
}
void PlayWidget::showFinish()
{
stepFinish = 0;
for(int row = 0; row < 9; row++){
for(int col = 0; col < 9; col++){
if(setUserData->data(setUserData->index(col, row)).toInt() != -1 && setUserData->data(setUserData->index(col, row)).toInt() < 1)
stepFinish++;
}
}
lcd->display(stepFinish);
if(stepFinish == 0){
QStandardItemModel* finish = new QStandardItemModel(9,9,this);
for(int row = 0; row < 9; row++)
for(int col = 0; col < 9; col++)
finish->setData(finish->index(row,col),setUserData->data(setUserData->index(row, col)).toInt());
for(int row = 0; row < 9; row++)
for(int col = 0; col < 9; col++)
if(showPazle->data(showPazle->index(col, row)).toInt() != 0)
finish->setData(finish->index(row,col),showPazle->data(showPazle->index(col, row)).toInt());
LogicaSudoku *lS = new LogicaSudoku(this);
lS->setModel(finish);
// bool deside = lS->checkErrPuzzle();
QMessageBox* msgBox = new QMessageBox(this);
msgBox->setWindowTitle("Sudoku");
if(lS->checkErrPuzzle()){
msgBox->setText("Вітаємо судоку вирішено вірно!");
msgBox->setInformativeText("Створити ще гру?");
msgBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
}
else{
msgBox->setText("Нажаль у рішенні є помилка, перевірте!");
msgBox->setStandardButtons(QMessageBox::Close);
}
switch (msgBox->exec()) {
case QMessageBox::Ok:
createNewGame = true;
break;
case QMessageBox::Cancel:
createNewGame = false;
break;
default:
qDebug()<<"Close";
break;
}
delete lS;
// df->show();
// df->exec();
// qDebug()<<deside;
// QString tab = " | ";
// qDebug() << " \n\n finish \n\n";
// for(int k = 0; k < 9; k++)
// tab = tab + " " + QString::number(k+1);
// qDebug() << tab;
// qDebug() << "------------------------------------------------";
// tab = "";
// for(int k = 0; k < 9; k++){
// for(int k1 = 0; k1 < 9; k1++){
// int val = finish->data(finish->index(k1, k, QModelIndex()), Qt::DisplayRole).toInt();
// if(val == 0)
// tab = tab + " ";
// else
// tab = tab + " " + QString("%1").arg(val);
// }
// qDebug() << k+1<<"|"<<tab;
// tab = "";
// }
// qDebug() << "======================================";
}
}
void PlayWidget::mousePressEvent(QMouseEvent *event)
{
if(event->button() & Qt::LeftButton){
if((event->x() < width && event->x() > 0) && (event->y() < heigth && event->y() > 0)){
click_row = 0;
click_col = 0;
while (step_line*click_row < event->x()) {
click_row++;
}
while (step_line*click_col < event->y()) {
click_col++;
}
click_row -= 1;
click_col -= 1;
if(showPazle->data(showPazle->index(click_col, click_row)).toInt() != 0){
click_row = -1;
click_col = -1;
enableDisableButton(true);
}
else{
enableDisableButton(false);
}
}
else{
click_row = -1;
click_col = -1;
}
repaint();
}
}
void PlayWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QRect rect = this->geometry();
width = rect.width()*0.99;
heigth = rect.width()*0.99;
width > heigth?heigth = width:width =heigth;
if(heigth>rect.height()){
width=rect.height()*0.99;
heigth=rect.height()*0.99;
}
step_line = width/9;
QFont font = painter.font();
int sizeFont = step_line/2;
font.setPixelSize(sizeFont);
painter.setFont(font);
QRect boundingRect;
painter.setBrush(QBrush(QColor("#E6E6FA")));
for(int row = 0; row < 9; row++){
for(int col = 0; col < 9; col++){
if(showPazle->data(showPazle->index(row, col)).toInt() > 0){
painter.setPen(QPen(QColor("#778899"),0,Qt::NoPen));
painter.drawRect(QRect(step_line*col,step_line*row,step_line,step_line));
painter.setPen(QPen(QColor("#778899"),1,Qt::SolidLine));
painter.drawText(QRect( step_line*col+sizeFont*0.7, step_line*row+sizeFont/2, sizeFont, sizeFont), 0, QString::number(showPazle->data(showPazle->index(row, col)).toInt()), &boundingRect);
}
else{
if(setUserData->data(setUserData->index(col, row)).toInt() > 0)
painter.drawText(QRect( step_line*col+sizeFont*0.7, step_line*row+sizeFont/2, sizeFont, sizeFont), 0, QString::number(setUserData->data(setUserData->index(col, row)).toInt()), &boundingRect);
}
}
}
painter.setBrush(QBrush(Qt::NoBrush));
painter.setPen(QPen(QColor("#778899"),3,Qt::SolidLine));
painter.drawRect(QRect(0,0,width,heigth));
for(int i = 1; i <9; i++){
i == 0||i == 3||i == 6||i == 9?painter.setPen(QPen(QColor("#778899"),3,Qt::SolidLine)):painter.setPen(QPen(QColor("#778899"),1,Qt::SolidLine));
painter.drawLine(QPointF(step_line*i,0),QPointF(step_line*i,heigth));
painter.drawLine(QPointF(0,step_line*i),QPointF(heigth, step_line*i));
}
if( click_row > -1 && click_col > -1){
painter.setPen(QPen(QColor("#ff0000"),3,Qt::SolidLine));
painter.drawRect(QRect(step_line*click_row,step_line*click_col,step_line,step_line));
if(userNumber != 0){
painter.drawText(QRect( step_line*click_row+sizeFont*0.7, step_line*click_col+sizeFont/2, sizeFont, sizeFont), 0, QString::number(userNumber), &boundingRect);
userNumber = 0;
}
}
}
void PlayWidget::keyPressEvent(QKeyEvent *event)
{
if(event->key() > 16777233 || event->key() < 16777238 ){
if( click_row == -1 && click_col == -1){
switch (event->key()) {
case 16777234:
click_row = 9;
click_col = 8;
do {} while (showPazle->data(showPazle->index( 8, --click_row)).toInt());
break;
case 16777236:
click_row = -1;
click_col = 0;
do {} while (showPazle->data(showPazle->index(0, ++click_row)).toInt());
break;
case 16777235:
click_row = 8;
click_col = 9;
do {} while (showPazle->data(showPazle->index(--click_col, 8)).toInt());
break;
case 16777237:
click_row = 0;
click_col = -1;
do {} while (showPazle->data(showPazle->index(++click_col, 0)).toInt());
break;
}
}
else{
switch (event->key()) {
case 16777234:
do {
--click_row;
if(click_row < 0){
click_row = 8;
click_col -= 1;
if(click_col < 0)
click_col = 8;
}
} while (showPazle->data(showPazle->index(click_col, click_row)).toInt());
break;
case 16777236:
do {
++click_row;
if(click_row > 8){
click_row = 0;
click_col += 1;
if(click_col > 8)
click_col = 0;
}
} while (showPazle->data(showPazle->index(click_col, click_row)).toInt());
break;
case 16777235:
do {
--click_col;
if(click_col < 0){
click_col = 8;
click_row -= 1;
if(click_row < 0)
click_row = 8;
}
} while (showPazle->data(showPazle->index(click_col, click_row)).toInt());
break;
case 16777237:
do {
++click_col;
if(click_col > 8){
click_col = 0;
click_row += 1;
if(click_row > 8)
click_row = 0;
}
} while (showPazle->data(showPazle->index(click_col, click_row)).toInt());
break;
}
userNumber = setUserData->data(setUserData->index(click_row, click_col)).toInt();
}
}
if(event->key() > 47 && event->key() < 58){
userNumber = event->key() - 48;
}
if( click_row > -1 && click_col > -1){
setUserData->setData(setUserData->index(click_row,click_col),userNumber);
userNumber = 0;
}
enableDisableButton(false);
repaint();
showFinish();
}
| [
"kutovvo@mail.ru"
] | kutovvo@mail.ru |
0959024ed65c2b7c25e84822f064c37abae8d9bb | 52d1aeda3c62ab766e04bb70b71428c446f76d7a | /code practice/0403/0403/test1.cpp | c0a80c15949995fb29c3c1133594eaee858f2e52 | [] | no_license | tinalny/cpp_project | b886ef4e4b153f3b974f6f497e91981707181579 | 534dfd652e21477abb19bc150b68628f4c41234e | refs/heads/master | 2022-09-18T10:03:47.732216 | 2020-06-06T14:04:41 | 2020-06-06T14:04:41 | 183,779,280 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | cpp | #include <iostream>
using namespace std;
int main1()
{
int n;
long long arr[21];
arr[1] = 0;
arr[2] = 1;
for (int i = 3; i < 22; i++)
{
arr[i] = (i - 1)*(arr[i - 1] + arr[i - 2]);
}
while (cin >> n)
{
float rate = 0;
long long sum = 1;
for (int i = 1; i <= n; i++)
{
sum *= i;
}
rate = ((1.0*arr[n]) / sum) * 100;
printf("%.2f%\n", rate);
}
system("pause");
return 0;
} | [
"1157143244@qq.com"
] | 1157143244@qq.com |
d54248e0db53d45b50ac29957cf14e7e8b2f8167 | f5dc059a4311bc542af480aa8e8784965d78c6e7 | /casa/Quanta/QBase.cc | f1c7c83cf530fd3edddf36ec17840feb3a6771f4 | [] | no_license | astro-informatics/casacore-1.7.0_patched | ec166dc4a13a34ed433dd799393e407d077a8599 | 8a7cbf4aa79937fba132cf36fea98f448cc230ea | refs/heads/master | 2021-01-17T05:26:35.733411 | 2015-03-24T11:08:55 | 2015-03-24T11:08:55 | 32,793,738 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,147 | cc | //# QBase.cc: base class for Quantum
//# Copyright (C) 1994,1995,1996,1998,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: QBase.cc 20551 2009-03-25 00:11:33Z Malte.Marquarding $
//# Includes
#include <casa/Exceptions/Error.h>
#include <casa/Quanta/QBase.h>
namespace casa { //# NAMESPACE CASA - BEGIN
QBase::QBase()
: qUnit() {}
QBase::QBase(const QBase &other)
: qUnit(other.qUnit) {}
QBase::QBase(const Unit &s)
: qUnit(s) {}
QBase::~QBase() {}
//# QBase general member functions
const String &QBase::getUnit() const {
return qUnit.getName();
}
void QBase::setUnit(const Unit &s) {
qUnit = s;
}
void QBase::setUnit(const QBase &other) {
qUnit = other.qUnit;
}
Bool QBase::isConform(const Unit &s) const {
return (qUnit.getValue() == s.getValue());
}
Bool QBase::isConform(const QBase &other) const {
return (qUnit.getValue() == other.qUnit.getValue());
}
//# Global functions
ostream &operator<<(ostream &os, const QBase &meas) {
meas.print(os);
return os;
}
} //# NAMESPACE CASA - END
| [
"jason.mcewen@ucl.ac.uk"
] | jason.mcewen@ucl.ac.uk |
4e7fe795dd8336350b66ccfe6d6af5bae26393b0 | 5ea87760fbddc9ef0858b22a3849f0f40a467fdc | /lib/mbed-cloud-client/certificate-enrollment-client/TESTS/unity-tests/cec_tests/tests/TestCertificateEnrollmentClient.cpp | 08a69106479ba68716f02c9239f018369182f54d | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Jekaah/mbed-edge | 75a60b5511deb6f023c98e0ff1d641548b132601 | 414e623533459774401fbcc51e51de8d4b838d22 | refs/heads/master | 2020-04-13T15:45:01.932921 | 2018-12-27T16:06:37 | 2018-12-27T16:06:37 | 163,301,200 | 0 | 0 | Apache-2.0 | 2018-12-27T14:04:10 | 2018-12-27T14:04:09 | null | UTF-8 | C++ | false | false | 4,029 | cpp | // ----------------------------------------------------------------------------
// Copyright 2018 ARM Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------
#ifdef CERT_RENEWAL_TEST
#include "TestCertificateEnrollmentClient.h"
#include "mbed-client/m2mresource.h"
#include "mbed-cloud-client/MbedCloudClient.h"
#include "include/ServiceClient.h"
#include "eventOS_scheduler.h"
#include "eventOS_event.h"
#include "ce_tlv.h"
#include "unity_fixture.h"
#include "mbed-client/m2mvector.h"
// ID of the handler we register to the MbedCloudClient event loop
static int8_t test_handler_id = -1;
typedef Vector<M2MBase*> M2MBaseList;
MbedCloudClient *g_mcc;
static bool _test_is_initialized = false;
// This emulates the event handler of mbed cloud client
void TestCertificateEnrollmentClient::test_event_handler(arm_event_s* event)
{
printf("in test event handler\n\n");
switch (event->event_type) {
case TEST_EVENT_TYPE_INIT:
// Nothing to do
break;
case TEST_EVENT_TYPE_RENEWAL_RESOURCE:
// Call resource callback
CertificateEnrollmentClient::testonly_certificate_renewal_post((void *) &(((Test_M2MExecuteParameterWrapper *)(event->data_ptr))->exec_param) );
delete (Test_M2MExecuteParameterWrapper *)(event->data_ptr);
}
}
void TestCertificateEnrollmentClient::server_initiated_certificate_renewal(uint8_t *tlv_buff, size_t tlv_buff_length)
{
Test_M2MExecuteParameterWrapper *exec_param;
exec_param = new Test_M2MExecuteParameterWrapper();
exec_param->set_exec_param(tlv_buff, tlv_buff_length);
arm_event_s event = {
.receiver = test_handler_id, // ID we got when creating our handler
.sender = 0, // Which tasklet sent us the event is irrelevant to us
.event_type = TEST_EVENT_TYPE_RENEWAL_RESOURCE, // Indicate event type
.event_id = 0, // We currently do not need an ID for a specific event - event type is enough
.data_ptr = (void *)exec_param, // pointer to the M2MResource::M2MExecuteParameter object that will be used by the resource callback
.priority = ARM_LIB_HIGH_PRIORITY_EVENT, // Network level priority
.event_data = 0, // Not used
};
eventOS_event_send(&event);
}
void TestCertificateEnrollmentClient::test_init()
{
if (!_test_is_initialized) {
// Create MbedCloudClient object - this will start the event loop
g_mcc = new MbedCloudClient();
TEST_ASSERT_NOT_EQUAL(g_mcc, NULL);
// Create an object list and fill it.
// Also do other initializations
M2MBaseList obj_list;
CertificateEnrollmentClient::init(obj_list, NULL);
// Add the object so that g_mcc has access to them and may release their memory when done
g_mcc->add_objects(obj_list);
// Register test event handler
eventOS_scheduler_mutex_wait();
if (test_handler_id == -1) { // Register the handler only if it hadn't been registered before
test_handler_id = eventOS_event_handler_create(test_event_handler, TEST_EVENT_TYPE_INIT);
}
eventOS_scheduler_mutex_release();
_test_is_initialized = true;
}
}
void TestCertificateEnrollmentClient::test_finalize()
{
if (_test_is_initialized) {
delete g_mcc;
CertificateEnrollmentClient::finalize();
_test_is_initialized = false;
}
}
#endif // CERT_RENEWAL_TEST
| [
"geir.sande@arm.com"
] | geir.sande@arm.com |
a36b05c8454615fff5ce7e26030bc9e3e9ced8f6 | 8958cb892f7d5255c62a6080112bdc0fe161e39b | /code/decorator/pancake/main.cpp | 96933301875988424484669748b18edd6e3b1c74 | [] | no_license | linhaidong/design_pattern | 102a47a1b8004cc30de6a54dda78ce2f663bfca8 | f49cfaceab0d918b7826c0842af31abe8a351713 | refs/heads/master | 2021-11-30T08:09:27.644122 | 2021-08-16T01:52:24 | 2021-08-16T01:52:24 | 147,285,137 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,917 | cpp | /*************************************************************************
> File Name: main.cpp
> Author: linhaidong
> Mail: linhaidong@alibaba-inc.com
> Time: 三 7/28 18:46:08 2021
> Abstract:
************************************************************************/
#include <iostream>
#include <string>
using namespace std;
//公用方法的基类,定义了被装饰函数
class Pancake
{
public:
string description = "Basic Pancake";
virtual string getDescription() { return description; }
virtual double cost() = 0;
};
class CondimentDecorator : public Pancake //装饰器基类
{
public:
string getDescrition();
};
class MeatPancake : public Pancake //肉煎饼
{
public:
MeatPancake() { description = "MeatPancake"; }
double cost() { return 6; }
};
class EggPancake : public Pancake //鸡蛋煎饼
{
public:
EggPancake() { description = "EggPancake"; }
double cost() { return 5; }
};
class Egg : public CondimentDecorator //额外加鸡蛋
{
public:
Pancake *base;
string getDescription() { return base->getDescription() + ", Egg"; }
Egg(Pancake *d) { base = d; }
double cost() { return base->cost() + 1.5; }
};
class Potato : public CondimentDecorator //额外加土豆
{
public:
Pancake *base;
string getDescription() { return base->getDescription() + ", Potato"; }
Potato(Pancake *d) { base = d; }
double cost() { return base->cost() + 1; }
};
class Bacon : public CondimentDecorator //额外加培根
{
public:
Bacon(Pancake *d) { base = d; }
Pancake *base;
string getDescription() { return base->getDescription() + ", Bacon"; }
double cost() { return base->cost() + 2; }
};
int main()
{
EggPancake pan1 = EggPancake();
Potato pan2 = Potato(&pan1);
Bacon pan3 = Bacon(&pan2);
cout << pan3.getDescription() << " $ : " << pan3.cost() << endl;
return 0;
}
| [
"linengier@126.com"
] | linengier@126.com |
1e162635a6622a539c508172397fc423dd5693f3 | 6c1313416066d48842802b7b8eb696935c2dbde2 | /Heirloom/thirdparty/glm/glm/detail/_swizzle_func.hpp | 50353cf217f77de9682613dd82f69eef9251c1c1 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-happy-bunny"
] | permissive | MilanDierickGD/QBert | c242a22afca9af31180665992a231ce2189db2cd | c49a626de47179e248e80b9c24c2425adc216593 | refs/heads/master | 2023-05-14T01:37:49.376784 | 2021-06-06T23:20:33 | 2021-06-06T23:20:33 | 372,919,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,336 | hpp | #pragma once
#define GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, CONST, A, B) \
vec<2, T, Q> A ## B() CONST \
{ \
return vec<2, T, Q>(this->A, this->B); \
}
#define GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, CONST, A, B, C) \
vec<3, T, Q> A ## B ## C() CONST \
{ \
return vec<3, T, Q>(this->A, this->B, this->C); \
}
#define GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, CONST, A, B, C, D) \
vec<4, T, Q> A ## B ## C ## D() CONST \
{ \
return vec<4, T, Q>(this->A, this->B, this->C, this->D); \
}
#define GLM_SWIZZLE_GEN_VEC2_ENTRY_DEF(T, P, L, CONST, A, B) \
template<typename T> \
vec<L, T, Q> vec<L, T, Q>::A ## B() CONST \
{ \
return vec<2, T, Q>(this->A, this->B); \
}
#define GLM_SWIZZLE_GEN_VEC3_ENTRY_DEF(T, P, L, CONST, A, B, C) \
template<typename T> \
vec<3, T, Q> vec<L, T, Q>::A ## B ## C() CONST \
{ \
return vec<3, T, Q>(this->A, this->B, this->C); \
}
#define GLM_SWIZZLE_GEN_VEC4_ENTRY_DEF(T, P, L, CONST, A, B, C, D) \
template<typename T> \
vec<4, T, Q> vec<L, T, Q>::A ## B ## C ## D() CONST \
{ \
return vec<4, T, Q>(this->A, this->B, this->C, this->D); \
}
#define GLM_MUTABLE
#define GLM_SWIZZLE_GEN_REF2_FROM_VEC2_SWIZZLE(T, P, A, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, 2, GLM_MUTABLE, A, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, 2, GLM_MUTABLE, B, A)
#define GLM_SWIZZLE_GEN_REF_FROM_VEC2(T, P) \
GLM_SWIZZLE_GEN_REF2_FROM_VEC2_SWIZZLE(T, P, x, y) \
GLM_SWIZZLE_GEN_REF2_FROM_VEC2_SWIZZLE(T, P, r, g) \
GLM_SWIZZLE_GEN_REF2_FROM_VEC2_SWIZZLE(T, P, s, t)
#define GLM_SWIZZLE_GEN_REF2_FROM_VEC3_SWIZZLE(T, P, A, B, C) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, A, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, A, C) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, B, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, B, C) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, C, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, C, B)
#define GLM_SWIZZLE_GEN_REF3_FROM_VEC3_SWIZZLE(T, P, A, B, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, GLM_MUTABLE, A, B, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, GLM_MUTABLE, A, C, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, GLM_MUTABLE, B, A, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, GLM_MUTABLE, B, C, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, GLM_MUTABLE, C, A, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, GLM_MUTABLE, C, B, A)
#define GLM_SWIZZLE_GEN_REF_FROM_VEC3_COMP(T, P, A, B, C) \
GLM_SWIZZLE_GEN_REF3_FROM_VEC3_SWIZZLE(T, P, A, B, C) \
GLM_SWIZZLE_GEN_REF2_FROM_VEC3_SWIZZLE(T, P, A, B, C)
#define GLM_SWIZZLE_GEN_REF_FROM_VEC3(T, P) \
GLM_SWIZZLE_GEN_REF_FROM_VEC3_COMP(T, P, x, y, z) \
GLM_SWIZZLE_GEN_REF_FROM_VEC3_COMP(T, P, r, g, b) \
GLM_SWIZZLE_GEN_REF_FROM_VEC3_COMP(T, P, s, t, p)
#define GLM_SWIZZLE_GEN_REF2_FROM_VEC4_SWIZZLE(T, P, A, B, C, D) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, A, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, A, C) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, A, D) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, B, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, B, C) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, B, D) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, C, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, C, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, C, D) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, D, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, D, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, GLM_MUTABLE, D, C)
#define GLM_SWIZZLE_GEN_REF3_FROM_VEC4_SWIZZLE(T, P, A, B, C, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , A, B, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , A, B, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , A, C, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , A, C, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , A, D, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , A, D, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , B, A, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , B, A, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , B, C, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , B, C, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , B, D, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , B, D, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , C, A, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , C, A, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , C, B, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , C, B, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , C, D, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , C, D, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , D, A, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , D, A, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , D, B, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , D, B, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , D, C, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, , D, C, B)
#define GLM_SWIZZLE_GEN_REF4_FROM_VEC4_SWIZZLE(T, P, A, B, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , A, C, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , A, C, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , A, D, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , A, D, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , A, B, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , A, B, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , B, C, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , B, C, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , B, D, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , B, D, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , B, A, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , B, A, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , C, B, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , C, B, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , C, D, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , C, D, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , C, A, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , C, A, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , D, C, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , D, C, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , D, A, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , D, A, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , D, B, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, , D, B, C, A)
#define GLM_SWIZZLE_GEN_REF_FROM_VEC4_COMP(T, P, A, B, C, D) \
GLM_SWIZZLE_GEN_REF2_FROM_VEC4_SWIZZLE(T, P, A, B, C, D) \
GLM_SWIZZLE_GEN_REF3_FROM_VEC4_SWIZZLE(T, P, A, B, C, D) \
GLM_SWIZZLE_GEN_REF4_FROM_VEC4_SWIZZLE(T, P, A, B, C, D)
#define GLM_SWIZZLE_GEN_REF_FROM_VEC4(T, P) \
GLM_SWIZZLE_GEN_REF_FROM_VEC4_COMP(T, P, x, y, z, w) \
GLM_SWIZZLE_GEN_REF_FROM_VEC4_COMP(T, P, r, g, b, a) \
GLM_SWIZZLE_GEN_REF_FROM_VEC4_COMP(T, P, s, t, p, q)
#define GLM_SWIZZLE_GEN_VEC2_FROM_VEC2_SWIZZLE(T, P, A, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, A, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, A, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, B, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, B, B)
#define GLM_SWIZZLE_GEN_VEC3_FROM_VEC2_SWIZZLE(T, P, A, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, A, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, A, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, B, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, B, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, A, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, A, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, B, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, B, B)
#define GLM_SWIZZLE_GEN_VEC4_FROM_VEC2_SWIZZLE(T, P, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, B, B)
#define GLM_SWIZZLE_GEN_VEC_FROM_VEC2_COMP(T, P, A, B) \
GLM_SWIZZLE_GEN_VEC2_FROM_VEC2_SWIZZLE(T, P, A, B) \
GLM_SWIZZLE_GEN_VEC3_FROM_VEC2_SWIZZLE(T, P, A, B) \
GLM_SWIZZLE_GEN_VEC4_FROM_VEC2_SWIZZLE(T, P, A, B)
#define GLM_SWIZZLE_GEN_VEC_FROM_VEC2(T, P) \
GLM_SWIZZLE_GEN_VEC_FROM_VEC2_COMP(T, P, x, y) \
GLM_SWIZZLE_GEN_VEC_FROM_VEC2_COMP(T, P, r, g) \
GLM_SWIZZLE_GEN_VEC_FROM_VEC2_COMP(T, P, s, t)
#define GLM_SWIZZLE_GEN_VEC2_FROM_VEC3_SWIZZLE(T, P, A, B, C) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, A, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, A, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, A, C) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, B, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, B, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, B, C) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, C, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, C, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, C, C)
#define GLM_SWIZZLE_GEN_VEC3_FROM_VEC3_SWIZZLE(T, P, A, B, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, A, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, A, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, A, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, B, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, B, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, B, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, C, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, C, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, C, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, A, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, A, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, A, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, B, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, B, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, B, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, C, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, C, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, C, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, A, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, A, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, A, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, B, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, B, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, B, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, C, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, C, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, C, C)
#define GLM_SWIZZLE_GEN_VEC4_FROM_VEC3_SWIZZLE(T, P, A, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, C, C)
#define GLM_SWIZZLE_GEN_VEC_FROM_VEC3_COMP(T, P, A, B, C) \
GLM_SWIZZLE_GEN_VEC2_FROM_VEC3_SWIZZLE(T, P, A, B, C) \
GLM_SWIZZLE_GEN_VEC3_FROM_VEC3_SWIZZLE(T, P, A, B, C) \
GLM_SWIZZLE_GEN_VEC4_FROM_VEC3_SWIZZLE(T, P, A, B, C)
#define GLM_SWIZZLE_GEN_VEC_FROM_VEC3(T, P) \
GLM_SWIZZLE_GEN_VEC_FROM_VEC3_COMP(T, P, x, y, z) \
GLM_SWIZZLE_GEN_VEC_FROM_VEC3_COMP(T, P, r, g, b) \
GLM_SWIZZLE_GEN_VEC_FROM_VEC3_COMP(T, P, s, t, p)
#define GLM_SWIZZLE_GEN_VEC2_FROM_VEC4_SWIZZLE(T, P, A, B, C, D) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, A, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, A, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, A, C) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, A, D) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, B, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, B, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, B, C) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, B, D) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, C, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, C, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, C, C) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, C, D) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, D, A) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, D, B) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, D, C) \
GLM_SWIZZLE_GEN_VEC2_ENTRY(T, P, const, D, D)
#define GLM_SWIZZLE_GEN_VEC3_FROM_VEC4_SWIZZLE(T, P, A, B, C, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, A, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, A, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, A, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, A, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, B, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, B, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, B, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, B, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, C, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, C, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, C, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, C, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, D, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, D, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, D, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, A, D, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, A, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, A, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, A, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, A, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, B, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, B, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, B, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, B, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, C, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, C, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, C, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, C, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, D, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, D, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, D, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, B, D, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, A, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, A, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, A, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, A, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, B, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, B, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, B, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, B, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, C, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, C, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, C, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, C, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, D, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, D, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, D, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, C, D, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, A, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, A, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, A, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, A, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, B, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, B, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, B, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, B, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, C, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, C, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, C, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, C, D) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, D, A) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, D, B) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, D, C) \
GLM_SWIZZLE_GEN_VEC3_ENTRY(T, P, const, D, D, D)
#define GLM_SWIZZLE_GEN_VEC4_FROM_VEC4_SWIZZLE(T, P, A, B, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, A, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, B, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, C, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, A, D, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, A, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, B, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, C, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, B, D, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, A, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, B, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, C, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, C, D, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, A, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, B, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, C, D, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, A, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, A, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, A, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, A, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, B, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, B, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, B, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, B, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, C, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, C, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, C, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, C, D) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, D, A) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, D, B) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, D, C) \
GLM_SWIZZLE_GEN_VEC4_ENTRY(T, P, const, D, D, D, D)
#define GLM_SWIZZLE_GEN_VEC_FROM_VEC4_COMP(T, P, A, B, C, D) \
GLM_SWIZZLE_GEN_VEC2_FROM_VEC4_SWIZZLE(T, P, A, B, C, D) \
GLM_SWIZZLE_GEN_VEC3_FROM_VEC4_SWIZZLE(T, P, A, B, C, D) \
GLM_SWIZZLE_GEN_VEC4_FROM_VEC4_SWIZZLE(T, P, A, B, C, D)
#define GLM_SWIZZLE_GEN_VEC_FROM_VEC4(T, P) \
GLM_SWIZZLE_GEN_VEC_FROM_VEC4_COMP(T, P, x, y, z, w) \
GLM_SWIZZLE_GEN_VEC_FROM_VEC4_COMP(T, P, r, g, b, a) \
GLM_SWIZZLE_GEN_VEC_FROM_VEC4_COMP(T, P, s, t, p, q)
| [
"milan.dierick@gmail.com"
] | milan.dierick@gmail.com |
711f84f02b962521d8e616a1f1d4d66fee3f1dc0 | 2c832a85c709a712e3b9f321a311f5227cdf65b7 | /myana_dry.cc | 5c456a81410b33298a447330fe5ef2d921c2e8c5 | [] | no_license | chrisroedig/lcls-ana | af7301afbd77c711fe1bee449560c3e9f970379a | f5c764be8087ef7ee3e91a885d1c85a3db54c694 | refs/heads/master | 2016-09-06T16:47:36.158865 | 2013-01-25T19:04:48 | 2013-01-25T19:04:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,193 | cc | /* $Id: myana.cc,v 1.14 2010/07/22 22:26:57 caf Exp $ */
#include <TROOT.h>
#include <TH1F.h>
#include <TProfile.h>
#include <math.h>
#include "myana.hh"
#include "main.hh"
//misc Globals
static int n_event=0;
//ETOF DAQ GLOBAL VARS
static int numChannelsETof = 0; //should be 5 :)
static int numSamplesETof = 0;
static double sampleIntervalETof = 0;//total acquisition interval
// This function is called once at the beginning of the analysis job,
// You can ask for detector "configuration" information here.
void beginjob()
{
int i=0;
int fail = 0;
char name[32];
fail = getAcqConfig( AmoETof, numChannelsETof, numSamplesETof, sampleIntervalETof);
if ( fail != 0 )
printf( "-----ERROR-----> COULD NOT GRAB ETOF CONFIG!!!!!!");
printf("numsmaples:%d\n",numSamplesETof);
printf("sampint:%e\n",sampleIntervalETof);
}
// This function is called once for each run. You should check to see
// if detector configuration information has changed.
void beginrun()
{
int fail = 0;
printf("[ BEGIN RUN ]\n");
//grab etof config - check for changes sicne begin job
int numChannelsETof2 = 0;
int numSamplesETof2 = 0;
double sampleIntervalETof2 = 0;
fail = getAcqConfig( AmoETof, numChannelsETof2, numSamplesETof2, sampleIntervalETof2);
if ( fail != 0 || numChannelsETof2 != numChannelsETof || numSamplesETof2 != numSamplesETof ||
sampleIntervalETof2 != sampleIntervalETof )
printf( "-----WARNING---> ETof configuration has been changed between runs!\n" );
}
void begincalib()
{
}
// This is called once every shot. You can ask for
// the individual detector shot data here.
void event()
{
int i;
int fail = 0;
if(n_event%10000==0){
printf("\n[ %d events, ha ha ha ] \n",n_event);
}
if(n_event%1000==0){
printf("|");}
else if(n_event%100==0){printf(".");}
fflush(stdout);
n_event++;
return;
}//END EVENT
void endcalib()
{
}
void endrun()
{
printf("\n[ END RUN ]\n");
}
void endjob()
{
printf("\n[ END JOB %d EVENTS ]\n\n",n_event);
char outname[20];
printf("\n\n BYE BYE NOW!\n");
}//END:endjob()
| [
"chris@roedig.us"
] | chris@roedig.us |
0dd71a6821deb0801a10eb40e5da36bd62bead50 | a865775d3502224a2e9544ec3f2c1ac0db2e0868 | /application/helpers.cpp | 34b803be8192bc9621d2687ac84aeb0e7ec0577d | [] | no_license | webclinic017/ampanov | c3afcc08f9dae78dcfe385b9860d9bd5050a43e4 | 1d19051b975714f7a2b8b3c82a2906998a7493c5 | refs/heads/master | 2022-03-30T06:57:33.635946 | 2020-01-19T18:12:05 | 2020-01-19T18:12:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,006 | cpp | #include "helpers.h"
QString Helpers::atom_date() {
QDateTime now = QDateTime::currentDateTime();
now.setOffsetFromUtc(now.offsetFromUtc());
return now.toString(Qt::ISODate);
}
QString Helpers::iso_date() {
QDate now(QDate::currentDate());
return now.toString("yyyy-MM-dd");
}
QString Helpers::iso_datetime() {
QDateTime now(QDateTime::currentDateTime());
return now.toString("yyyy-MM-dd hh:mm:ss");
}
QDateTime Helpers::atom_to_datetime(QString value) {
QString parsed;
parsed = value.left(19);
int timeZoneOffset;
timeZoneOffset = value.right(6).left(3).toInt() * 3600;
QDateTime result;
result = QDateTime::fromString(parsed,"yyyy-MM-ddTHH:mm:ss");
result.setTimeSpec(Qt::OffsetFromUTC);
result.setUtcOffset(timeZoneOffset);
return result;
}
bool Helpers::isWeekday() {
QDateTime now = QDateTime::currentDateTime();
if (now.date().dayOfWeek() >= 1 && now.date().dayOfWeek() <= 5) return true;
return false;
}
| [
"mgladkowski@axyz.com"
] | mgladkowski@axyz.com |
8e290be7abf4ecedbe1c0e3ebd2c1b7f95029c3b | 3097b6088e50175d7e0361de509db21093c5cc60 | /tests/spec_tests/br_if_tests.cpp | 2fff698578b84d314836a63fc8090fcc9de15952 | [] | no_license | compumatrix/eos-vm | fd3d5b2f6f62ef7f2fd2e70c18808ae938de81a9 | 39a74ba50949cb554fd7d18496620b8f5068834c | refs/heads/master | 2020-06-01T05:49:00.363954 | 2019-06-06T13:37:54 | 2019-06-06T13:37:54 | 190,664,239 | 2 | 0 | null | 2019-06-06T23:44:20 | 2019-06-06T23:44:19 | null | UTF-8 | C++ | false | false | 10,711 | cpp | #include <catch2/catch.hpp>
#include <eosio/vm/backend.hpp>
#include <wasm_config.hpp>
extern eosio::vm::wasm_allocator wa;
using backend_t = eosio::vm::backend<nullptr_t>;
using namespace eosio::vm;
TEST_CASE( "Testing wasm <br_if_0_wasm>", "[br_if_0_wasm_tests]" ) {
auto code = backend_t::read_wasm( br_if_0_wasm );
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
CHECK(!bkend.call_with_return(nullptr, "env", "type-i32"));
CHECK(!bkend.call_with_return(nullptr, "env", "type-i64"));
CHECK(!bkend.call_with_return(nullptr, "env", "type-f32"));
CHECK(!bkend.call_with_return(nullptr, "env", "type-f64"));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "type-i32-value")) == static_cast<uint32_t>(1));
CHECK(to_i64(*bkend.call_with_return(nullptr, "env", "type-i64-value")) == static_cast<uint64_t>(2));
CHECK(to_f32(*bkend.call_with_return(nullptr, "env", "type-f32-value")) == static_cast<float>(3.0f));
CHECK(to_f64(*bkend.call_with_return(nullptr, "env", "type-f64-value")) == static_cast<double>(4.0));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-block-first", static_cast<uint32_t>(0))) == static_cast<uint32_t>(2));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-block-first", static_cast<uint32_t>(1))) == static_cast<uint32_t>(3));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-block-mid", static_cast<uint32_t>(0))) == static_cast<uint32_t>(2));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-block-mid", static_cast<uint32_t>(1))) == static_cast<uint32_t>(3));
CHECK(!bkend.call_with_return(nullptr, "env", "as-block-last", static_cast<uint32_t>(0)));
CHECK(!bkend.call_with_return(nullptr, "env", "as-block-last", static_cast<uint32_t>(1)));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-block-first-value", static_cast<uint32_t>(0))) == static_cast<uint32_t>(11));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-block-first-value", static_cast<uint32_t>(1))) == static_cast<uint32_t>(10));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-block-mid-value", static_cast<uint32_t>(0))) == static_cast<uint32_t>(21));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-block-mid-value", static_cast<uint32_t>(1))) == static_cast<uint32_t>(20));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-block-last-value", static_cast<uint32_t>(0))) == static_cast<uint32_t>(11));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-block-last-value", static_cast<uint32_t>(1))) == static_cast<uint32_t>(11));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-loop-first", static_cast<uint32_t>(0))) == static_cast<uint32_t>(2));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-loop-first", static_cast<uint32_t>(1))) == static_cast<uint32_t>(3));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-loop-mid", static_cast<uint32_t>(0))) == static_cast<uint32_t>(2));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-loop-mid", static_cast<uint32_t>(1))) == static_cast<uint32_t>(4));
CHECK(!bkend.call_with_return(nullptr, "env", "as-loop-last", static_cast<uint32_t>(0)));
//CHECK(!bkend.call_with_return(nullptr, "env", "as-loop-last", static_cast<uint32_t>(1)));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-br-value")) == static_cast<uint32_t>(1));
CHECK(!bkend.call_with_return(nullptr, "env", "as-br_if-cond"));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-br_if-value")) == static_cast<uint32_t>(1));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-br_if-value-cond", static_cast<uint32_t>(0))) == static_cast<uint32_t>(2));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-br_if-value-cond", static_cast<uint32_t>(1))) == static_cast<uint32_t>(1));
CHECK(!bkend.call_with_return(nullptr, "env", "as-br_table-index"));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-br_table-value")) == static_cast<uint32_t>(1));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-br_table-value-index")) == static_cast<uint32_t>(1));
CHECK(to_i64(*bkend.call_with_return(nullptr, "env", "as-return-value")) == static_cast<uint64_t>(1));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-if-cond", static_cast<uint32_t>(0))) == static_cast<uint32_t>(2));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-if-cond", static_cast<uint32_t>(1))) == static_cast<uint32_t>(1));
CHECK(!bkend.call_with_return(nullptr, "env", "as-if-then", static_cast<uint32_t>(0), static_cast<uint32_t>(0)));
CHECK(!bkend.call_with_return(nullptr, "env", "as-if-then", static_cast<uint32_t>(4), static_cast<uint32_t>(0)));
CHECK(!bkend.call_with_return(nullptr, "env", "as-if-then", static_cast<uint32_t>(0), static_cast<uint32_t>(1)));
CHECK(!bkend.call_with_return(nullptr, "env", "as-if-then", static_cast<uint32_t>(4), static_cast<uint32_t>(1)));
CHECK(!bkend.call_with_return(nullptr, "env", "as-if-else", static_cast<uint32_t>(0), static_cast<uint32_t>(0)));
CHECK(!bkend.call_with_return(nullptr, "env", "as-if-else", static_cast<uint32_t>(3), static_cast<uint32_t>(0)));
CHECK(!bkend.call_with_return(nullptr, "env", "as-if-else", static_cast<uint32_t>(0), static_cast<uint32_t>(1)));
CHECK(!bkend.call_with_return(nullptr, "env", "as-if-else", static_cast<uint32_t>(3), static_cast<uint32_t>(1)));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-select-first", static_cast<uint32_t>(0))) == static_cast<uint32_t>(3));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-select-first", static_cast<uint32_t>(1))) == static_cast<uint32_t>(3));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-select-second", static_cast<uint32_t>(0))) == static_cast<uint32_t>(3));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-select-second", static_cast<uint32_t>(1))) == static_cast<uint32_t>(3));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-select-cond")) == static_cast<uint32_t>(3));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-call-first")) == static_cast<uint32_t>(12));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-call-mid")) == static_cast<uint32_t>(13));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-call-last")) == static_cast<uint32_t>(14));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-call_indirect-func")) == static_cast<uint32_t>(4));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-call_indirect-first")) == static_cast<uint32_t>(4));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-call_indirect-mid")) == static_cast<uint32_t>(4));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-call_indirect-last")) == static_cast<uint32_t>(4));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-local.set-value", static_cast<uint32_t>(0))) == static_cast<uint32_t>(4294967295));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-local.set-value", static_cast<uint32_t>(1))) == static_cast<uint32_t>(17));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-local.tee-value", static_cast<uint32_t>(0))) == static_cast<uint32_t>(4294967295));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-local.tee-value", static_cast<uint32_t>(1))) == static_cast<uint32_t>(1));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-global.set-value", static_cast<uint32_t>(0))) == static_cast<uint32_t>(4294967295));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-global.set-value", static_cast<uint32_t>(1))) == static_cast<uint32_t>(1));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-load-address")) == static_cast<uint32_t>(1));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-loadN-address")) == static_cast<uint32_t>(30));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-store-address")) == static_cast<uint32_t>(30));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-store-value")) == static_cast<uint32_t>(31));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-storeN-address")) == static_cast<uint32_t>(32));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-storeN-value")) == static_cast<uint32_t>(33));
CHECK(to_f64(*bkend.call_with_return(nullptr, "env", "as-unary-operand")) == static_cast<double>(1.0));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-binary-left")) == static_cast<uint32_t>(1));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-binary-right")) == static_cast<uint32_t>(1));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-test-operand")) == static_cast<uint32_t>(0));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-compare-left")) == static_cast<uint32_t>(1));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-compare-right")) == static_cast<uint32_t>(1));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "as-memory.grow-size")) == static_cast<uint32_t>(1));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "nested-block-value", static_cast<uint32_t>(0))) == static_cast<uint32_t>(21));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "nested-block-value", static_cast<uint32_t>(1))) == static_cast<uint32_t>(9));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "nested-br-value", static_cast<uint32_t>(0))) == static_cast<uint32_t>(5));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "nested-br-value", static_cast<uint32_t>(1))) == static_cast<uint32_t>(9));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "nested-br_if-value", static_cast<uint32_t>(0))) == static_cast<uint32_t>(5));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "nested-br_if-value", static_cast<uint32_t>(1))) == static_cast<uint32_t>(9));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "nested-br_if-value-cond", static_cast<uint32_t>(0))) == static_cast<uint32_t>(5));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "nested-br_if-value-cond", static_cast<uint32_t>(1))) == static_cast<uint32_t>(9));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "nested-br_table-value", static_cast<uint32_t>(0))) == static_cast<uint32_t>(5));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "nested-br_table-value", static_cast<uint32_t>(1))) == static_cast<uint32_t>(9));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "nested-br_table-value-index", static_cast<uint32_t>(0))) == static_cast<uint32_t>(5));
CHECK(to_i32(*bkend.call_with_return(nullptr, "env", "nested-br_table-value-index", static_cast<uint32_t>(1))) == static_cast<uint32_t>(9));
}
| [
"larry.kittinger@block.one"
] | larry.kittinger@block.one |
ca7b7b4ee1397bd724506d218aa67c3a9ea1c3d8 | cd982e468c9493635816f8ca468e6de5e03ab5da | /DIKUgrafik/Src/glmutils/testglmutils2d.cpp | acdd7a13b8a9a9002c7929e5add36174696b630e | [] | no_license | gmnamra/Grafik | 5ee0625ee95779fbc67ab00ee6247880bb57c3c5 | a7bb9b0035091cce5d1261c775eb753dd15e76b8 | refs/heads/master | 2020-05-27T12:42:46.288013 | 2018-01-20T12:00:19 | 2018-01-20T12:00:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,585 | cpp | #include <iostream>
#include <iomanip>
#include <stdexcept>
#include <cmath>
#include <string>
#include <cctype>
#include "DIKUgrafik/glmutils.h"
int main()
{
glm::mat3x3 translatiommatrix1 = glm::translate(1.0f, 2.0f);
std::cout << "translate(1.0f, 2.0f):" << std::endl;
std::cout << translatiommatrix1 << std::endl;
glm::mat3x3 invtranslatiommatrix1 = glm::invtranslate(1.0f, 2.0f);
std::cout << "invtranslate(1.0f, 2.0f):" << std::endl;
std::cout << invtranslatiommatrix1 << std::endl;
glm::vec2 transvec(2.0f, 1.0f);
glm::mat3x3 translatiommatrix2 = glm::translate(transvec);
std::cout << "translate(transvec):" << std::endl;
std::cout << translatiommatrix2 << std::endl;
glm::mat3x3 invtranslatiommatrix2 = glm::invtranslate(transvec);
std::cout << "invtranslate(transvec):" << std::endl;
std::cout << invtranslatiommatrix2 << std::endl;
glm::mat3x3 scalematrix1 = glm::scale(3.0f, 4.0f);
std::cout << "scale(3.0f, 4.0f)" << std::endl;
std::cout << scalematrix1 << std::endl;
glm::mat3x3 invscalematrix1 = glm::invscale(3.0f, 4.0f);
std::cout << "invscale(3.0f, 4.0f)" << std::endl;
std::cout << invscalematrix1 << std::endl;
glm::vec2 scalevec(4.0f, 3.0f);
glm::mat3x3 scalematrix2 = glm::scale(scalevec);
std::cout << "scale(scalevec)" << std::endl;
std::cout << scalematrix2 << std::endl;
glm::mat3x3 invscalematrix2 = glm::invscale(scalevec);
std::cout << "invscale(scalevec)" << std::endl;
std::cout << invscalematrix2 << std::endl;
glm::mat3x3 rotationmatrix = glm::rotate(45.0f * glm::pi<float>() / 180.0f);
std::cout << "rotate(45.0f * glm::pi<float>() / 180.0f)" << std::endl;
std::cout << rotationmatrix << std::endl;
glm::mat3x3 invrotationmatrix = glm::invrotate(45.0f * glm::pi<float>() / 180.0f);
std::cout << "invrotate(45.0f * glm::pi<float>() / 180.0f)" << std::endl;
std::cout << invrotationmatrix << std::endl;
glm::mat3x3 shearXmatrix = glm::shearX(5.0f);
std::cout << "shearX(5.0f)" << std::endl;
std::cout << shearXmatrix << std::endl;
glm::mat3x3 invshearXmatrix = glm::invshearX(5.0f);
std::cout << "invshearX(5.0f)" << std::endl;
std::cout << invshearXmatrix << std::endl;
glm::mat3x3 shearYmatrix = glm::shearY(6.0f);
std::cout << "shearY(6.0f)" << std::endl;
std::cout << shearYmatrix << std::endl;
glm::mat3x3 invshearYmatrix = glm::invshearY(6.0f);
std::cout << "invshearY(6.0f)" << std::endl;
std::cout << invshearYmatrix << std::endl;
return 0;
}
| [
"jakobhl@hotmail.com"
] | jakobhl@hotmail.com |
9e0bd30c6f97dad935727ae59ecb88a9be134d58 | b2ffa4d7a4a24fadfee929d59a0caa89f0a784fd | /test/mytest.cpp | 965b771aa812e3319c9b1e4b30287b82c0777b39 | [
"Zlib"
] | permissive | yangshangde/zlib | 8bb15a5786aa55f087359bff876e7d5f710f1db4 | c4eae6d767b3c96975c3574201181c4eb0c96174 | refs/heads/master | 2020-12-28T20:43:44.145286 | 2015-11-26T11:41:43 | 2015-11-26T11:41:43 | 44,728,123 | 0 | 0 | null | 2015-10-22T07:05:24 | 2015-10-22T07:05:23 | null | UTF-8 | C++ | false | false | 1,782 | cpp | #include <iostream>
#include <fstream>
#include "zlib.h"
using namespace std;
#define CHECK_ERR(err, msg) { \
if (err != Z_OK) { \
fprintf(stderr, "%s error: %d\n", msg, err); \
exit(1); \
} \
}
string getDictFromFile()
{
ifstream dictFile;
dictFile.open("dict.data", ios_base::in);
if (!dictFile.is_open())
{
cerr << "Failed to open dictionary file" << endl;
return NULL;
}
string dictionary;
string line;
while (dictFile >> line)
{
dictionary += line;
}
return dictionary;
}
int testCompress()
{
string dictionary = getDictFromFile();
char destBuf[2048] = {0};
ifstream srcFile("src.json");
string line;
int err;
int destLen = 0;
string first;
srcFile >> first;
while (srcFile >> line)
{
z_stream d_stream;
d_stream.opaque = (voidpf)0;
err = deflateInit(&d_stream, Z_BEST_COMPRESSION);
CHECK_ERR(err, "deflateInit");
err = deflateSetDictionary(&d_stream, (const Bytef*)(dictionary.c_str()), dictionary.size());
//err = deflateSetDictionary(&d_stream, (const Bytef*)(first.c_str()), first.size());
CHECK_ERR(err, "deflateSetDictionary");
d_stream.next_in = (z_const unsigned char *)(line.c_str());
d_stream.avail_in = line.size();
d_stream.next_out = (Bytef *)destBuf;
d_stream.avail_out = 2048;
err = deflate(&d_stream, Z_FINISH);
if (Z_STREAM_END != err)
{
fprintf(stderr, "deflate should report Z_STERAM_END\n");
exit(1);
}
destLen = d_stream.total_out;
cout << "src len=" << line.size() << ", dest len=" << destLen << ", compress ratio=" << (int)((float) destLen / (float)line.size() * 100) << "%" << endl;
//deflateResetKeep(&d_stream) ;
err = deflateEnd(&d_stream);
CHECK_ERR(err, "deflateEnd");
}
return 0;
}
int main()
{
return testCompress();
}
| [
"yangshangde@163.com"
] | yangshangde@163.com |
68016639effcc0c9a3f3e2c92c574cfb27340ce6 | 3d4f69dba44f5e285c19c6762494073148011bbe | /solution/430. Flatten a Multilevel Doubly Linked List/430.cpp | 597c0fb9b3e983cda2c334cfc8b1cdec36257e5b | [] | no_license | cmeslo/leetcode | a0fd9826aaf77380c6cfb6bd24f26024345077be | 9b304046c2727364a3c9e5c513cb312fabdc729e | refs/heads/master | 2023-08-31T02:34:56.962597 | 2023-08-30T17:06:07 | 2023-08-30T17:06:07 | 96,622,859 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 609 | cpp | /*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
};
*/
class Solution {
public:
Node* tail;
Node* flatten(Node* head) {
auto p = head;
while (p) {
if (p->child) {
auto next = flatten(p->child);
next->prev = p;
tail->next = p->next;
if (p->next) p->next->prev = tail;
p->next = p->child;
p->child = nullptr;
}
tail = p;
p = p->next;
}
return head;
}
};
| [
"noreply@github.com"
] | cmeslo.noreply@github.com |
dd9d45bce71712bf309a2c61d4d1fe6557416e64 | ff83893bfc94fc84f0145e435615642374843239 | /2020_ICPC_Universidad_Nacional_de_Colombia_Programming_Contest/A.cpp | 48a4f3a72f66fe6a20fca389841a7ef6b7708354 | [] | no_license | IcecreamArtist/acm_icpc | f3d25949fb5ea34376f4e4820dfbfbb4d1c061e9 | 211490f5c341c9b3814843e072663e156da585a5 | refs/heads/master | 2023-05-06T05:37:47.193501 | 2021-05-30T04:10:41 | 2021-05-30T04:10:41 | 331,293,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,718 | cpp | #include<bits/stdc++.h>
using namespace std;
double ax,ay,bx,by,cx,cy,dx,dy,len1,len2;
const double eps = 1e-12; // 精度
/*
* 思路:三分
* 模拟过程,分两段,先是三分从A点走到B点(要使得前面的路径更短)。然后再站定在A点,三分另一个人继续走。
* 其实第一段可以直接判断(1)是否交叉=0(2)只考虑两个起点的连线与两个终点的连线。但由于这样也符合为一个抛物线。
* 为减少讨论,用三分处理。注意精度问题。
*/
double get_dis(double x1,double y1,double x2,double y2){return (x2-x1)*(x2-x1)+(y2-y1)*(y2-y1);}
double check(double dis){
// 计算长边上的点距离起点走了dis,两点的距离
double x1,y1,x2,y2; // 两点的坐标
if(dis>=len1-eps) x1=bx,y1=by;
else x1 = ax+(bx-ax)/len1*dis,y1 = ay+(by-ay)/len1*dis;
if(dis>=len2-eps) x2=dx,y2=dy;
else x2 = cx+(dx-cx)/len2*dis,y2 = cy+(dy-cy)/len2*dis;
return get_dis(x1,y1,x2,y2);
}
// 三分板子
double three_div(double left,double right){
// left and right represent the distance gone
double ans=1e25;
for(int i=1;i<=1e5;++i){
double lmid = (2*left+right)/3;
double rmid = (2*right+left)/3;
double resl = check(lmid),resr = check(rmid);
if(resl+eps<=resr) right = rmid;
else left = lmid;
ans = min({ans,resl,resr});
}
return ans;
}
int main(){
scanf("%lf%lf%lf%lf",&ax,&ay,&bx,&by);
scanf("%lf%lf%lf%lf",&cx,&cy,&dx,&dy);
len1 = sqrt(get_dis(ax,ay,bx,by)),len2 = sqrt(get_dis(cx,cy,dx,dy));
double ans = min(three_div(0,min(len1,len2)),three_div(min(len1,len2),max(len1,len2)));
printf("%.12lf\n",sqrt(ans));
} | [
"1443885711@qq.com"
] | 1443885711@qq.com |
292b49169f939abeb77c244dbcb885fec70854aa | 2797fa3565a3f293ade88e3544968d84a02b1460 | /mem_leak_detector/mem_leak_detector.cpp | f7b2089b05b7e94c26dd211fa6aba8fe5302d4f2 | [] | no_license | codercheng/CodeSnippet | b750a7b150443e19f019f81539922f7ed9b3240f | c141af1a8384a204f2fe529af524ebd53793ec6d | refs/heads/master | 2016-09-06T15:33:04.425128 | 2015-03-28T05:55:35 | 2015-03-28T05:55:35 | 24,602,907 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 253 | cpp | #include "mem_leak_detector.h"
void memoryLeakDetector() {
#ifdef _DEBUG
_CrtSetDbgFlag( _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
#endif
}
void setBreakPoint(int alloc_num) {
#ifdef _DEBUG
_CrtSetBreakAlloc(alloc_num);
#endif
} | [
"chengshuguang@qq.com"
] | chengshuguang@qq.com |
b955f0b442dde020a821fa505c29226e67212099 | ba73c355eaf88b2a4d984145e306b83cf53da9b8 | /controller/ironstack_types/openflow_queue_stats.h | 2908d592f4180b023de63abb92bd813873c53125 | [
"BSD-3-Clause"
] | permissive | zteo-phd-software/ironstack | cd0d10e2666fd0e829e8cfaea24fcd49cc2adaf0 | 649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0 | refs/heads/master | 2020-02-26T15:38:23.943187 | 2016-09-30T18:42:19 | 2016-09-30T18:42:19 | 69,498,904 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 738 | h | #pragma once
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <arpa/inet.h>
#include <inttypes.h>
#include "../../common/autobuf.h"
#include "../../common/openflow.h"
#include <string>
using namespace std;
// externally usable class
class openflow_queue_stats {
public:
// constructor
openflow_queue_stats();
// clears the object
void clear();
// generates debug string information
string to_string() const;
// serialization and deserialization
uint32_t serialize(autobuf& dest) const;
bool deserialize(const autobuf& input);
// publicly accessible fields
bool all_ports;
uint16_t port;
bool all_queues;
uint32_t queue_id;
uint64_t tx_bytes;
uint64_t tx_packets;
uint64_t tx_errors;
};
| [
"zhiyuan.teo@gmail.com"
] | zhiyuan.teo@gmail.com |
5e6a40eea7951d75da41130d1401932e3486a5af | 8087b720481b939198f0b6ac84bf7dc9b22fac93 | /libPr3/Signal/signalmast.h | 0b2f240a5ffebe8f5a2a884ea1b25cd46cef2a6a | [] | no_license | michaeloed/DecoderPro_app | 78e049090fc6c4d30dcc23ecb868d57b30361d8b | fb85623c205e88963e46ae49d9b244d20aa3c3c7 | refs/heads/master | 2022-02-15T07:03:23.797135 | 2022-01-29T06:47:26 | 2022-01-29T06:47:26 | 170,830,385 | 0 | 0 | null | 2019-02-15T08:37:44 | 2019-02-15T08:37:44 | null | UTF-8 | C++ | false | false | 5,317 | h | #ifndef SIGNALMAST_H
#define SIGNALMAST_H
#include "namedbean.h"
#include "signalsystem.h"
#include "signalappearancemap.h"
/**
* Represent a signal mast. A signal mast is one or more signal heads
* that are treated as a single signal. (Imagine several heads
* attached to a single mast, though other implementations are possible)
* <P>
* A mast presents an Aspect, as that's a composite of the appearance
* of the entire signal.
* <P>
* This class has three bound parameters:
*<DL>
*<DT>aspect<DD>The specific aspect being shown.
* <p>
* Aspects are named by a user defined QString name.
*
*<DT>lit<DD>Whether the head's lamps are lit or left dark.
*<P>
* This differs from the DARK color defined for the appearance
* parameter, in that it's independent of that. Lit is
* intended to allow you to extinquish a signal head for
* approach lighting, while still allowing it's color to be
* set to a definite value for e.g. display on a panel or
* evaluation in higher level logic.
*
*<DT>held<DD>Whether the head's lamps should be forced to the RED position
* in higher-level logic.
*<P>
* For use in signaling systems, this is a convenient
* way of storing whether a higher-level of control (e.g. non-vital
* system or dispatcher) has "held" the signal at stop. It does
* not effect how this signal head actually works; any appearance can
* be set and will be displayed even when "held" is set.
*</dl>
* The integer state (getState(), setState()) is the index of the
* current aspect in the list of all defined aspects.
* <hr>
* This file is part of JMRI.
* <P>
* JMRI is free software; you can redistribute it and/or modify it under
* the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation. See the "COPYING" file for a copy
* of this license.
* <P>
* JMRI 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.
* <P>
*
* @author Bob Jacobsen Copyright (C) 2002, 2008
* @author Pete Cressman Copyright (C) 2009
* @version $Revision: 20673 $
*/
/*public*/ /*interface*/ class LIBPR3SHARED_EXPORT SignalMast : public AbstractNamedBean
{
Q_OBJECT
public:
SignalMast(QString systemName, QString userName, QObject* parent) : AbstractNamedBean(systemName, userName, parent) {}
SignalMast(QString systemName, QObject* parent) : AbstractNamedBean(systemName, parent) {}
~SignalMast() {}
SignalMast(const SignalMast&) :AbstractNamedBean() {}
/**
* Set aspect to a valid name in the current
* signal system definition.
* @throws IllegalArgumentException if not a valid aspect name
*/
/*public*/ virtual void setAspect(QString /*aspect*/) {}
/**
* Get current aspect name. This is a bound property.
*
* @return null if not yet set
*/
/*public*/ virtual QString getAspect() {return"";}
/*public*/ virtual QVector<QString> getValidAspects() { return QVector<QString>();}
/*public*/ virtual SignalSystem* getSignalSystem() {return NULL;}
/*public*/ virtual SignalAppearanceMap* getAppearanceMap() {return NULL;}
/**
* Set the specific mast type for this mast.
* This is the
* type that appears in the SystemName and filename, i.e. "SL-3-high"
* for the
* <a href="http://jmri.org/xml/signals/AAR-1946/appearance-SL-3-high.xml">AAR-1946/appearance-SL-3-high.xml</a>
* definition.
*/
/*public*/ virtual void setMastType(/*@Nonnull*/ QString /*type*/) {}
/**
* Get the specific mast type for this mast.
* This is the
* type that appears in the SystemName and filename, i.e. "SL-3-high"
* for the
* <a href="http://jmri.org/xml/signals/AAR-1946/appearance-SL-3-high.xml">AAR-1946/appearance-SL-3-high.xml</a>
* definition.
*/
/*public*/ virtual QString getMastType() {return "";}
/**
* Lit is a bound parameter. It controls
* whether the signal head's lamps are lit or left dark.
*/
/*public*/ virtual bool getLit() {return false;}
/*public*/ virtual void setLit(bool /*newLit*/) {}
/**
* Held is a bound parameter. It controls
* what mechanisms can control the head's appearance.
* The actual semantics are defined by those external mechanisms.
*/
/*public*/ virtual bool getHeld() {return false;}
/*public*/ virtual void setHeld(bool /*newHeld*/) {}
/**
* Determine if the permissive SML logic should be disabled. The default will be
* false which means that automatic permissive processing is allowed. Prototypical
* CTC designs frequently require an additional action, such as Call-On, to enable permissive aspects.
* @return true if permissive SML is disabled.
*/
/*public*/ virtual bool isPermissiveSmlDisabled() {return false;}
/*public*/ virtual void setPermissiveSmlDisabled(bool /*disabled*/) {}
/*public*/ virtual bool isAspectDisabled(QString /*aspect*/) {return false;}
/*public*/ virtual QString className() =0;
friend class SignalMastIcon;
friend class DefaultSignalMastLogic;
friend class DestinationMast;
};
#endif // SIGNALMAST_H
| [
"allenck@windstream.net"
] | allenck@windstream.net |
cc0bd8e84150f13585dd6a26a830def96b2ccb3c | 65e3391b6afbef10ec9429ca4b43a26b5cf480af | /MUON/MUONmapping/AliMpDataStreams.cxx | 4393117f545d57a86665bce537dc4fc317c6e379 | [] | permissive | alisw/AliRoot | c0976f7105ae1e3d107dfe93578f819473b2b83f | d3f86386afbaac9f8b8658da6710eed2bdee977f | refs/heads/master | 2023-08-03T11:15:54.211198 | 2023-07-28T12:39:57 | 2023-07-28T12:39:57 | 53,312,169 | 61 | 299 | BSD-3-Clause | 2023-07-28T13:19:50 | 2016-03-07T09:20:12 | C++ | UTF-8 | C++ | false | false | 4,930 | cxx | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id$
// $MpId: AliMpDataStreams.cxx,v 1.12 2006/05/23 13:09:54 ivana Exp $
// Category: basic
//-----------------------------------------------------------------------------
// Class AliMpDataStreams
// ----------------------
// Class for providing mapping data streams
// See detailed description in the header file.
// Author: Ivana Hrivnacova; IPN Orsay
//-----------------------------------------------------------------------------
#include "AliMpDataStreams.h"
#include "AliMpDataMap.h"
#include "AliMpFiles.h"
#include "AliLog.h"
#include <TMap.h>
#include <TFile.h>
#include <TObjString.h>
#include <TString.h>
#include <Riostream.h>
#include <string>
/// \cond CLASSIMP
ClassImp(AliMpDataStreams)
/// \endcond
//______________________________________________________________________________
AliMpDataStreams::AliMpDataStreams(AliMpDataMap* map)
: TObject(),
fMap(map),
fReadFromFiles(kTRUE)
{
/// Standard and default constructor
if ( map ) fReadFromFiles = kFALSE;
}
//______________________________________________________________________________
AliMpDataStreams::AliMpDataStreams(TRootIOCtor* /*ioCtor*/)
: TObject(),
fMap(0),
fReadFromFiles()
{
/// Root IO constructor
}
//______________________________________________________________________________
AliMpDataStreams::~AliMpDataStreams()
{
/// Destructor
// delete fMap;
// Do not delete data map as it is a CDB object
// which is cached
}
//
// private methods
//
//______________________________________________________________________________
void AliMpDataStreams::CutDataPath(string& dataPath) const
{
/// Cut the path defined in AliMpFiles as Top() + one more directory
string top = AliMpFiles::GetTop().Data();
if ( dataPath.find(top) != string::npos ) dataPath.erase(0, top.size()+1);
dataPath.erase(0,dataPath.find('/')+1);
}
//
// public methods
//
//______________________________________________________________________________
istream& AliMpDataStreams::CreateDataStream(const TString& path) const
{
/// Return the string with data in the mapping file spcified with path.
/// Both full path in the file system and a short path (without
/// $LICE_ROOT/mapping/data string) can be used.
if ( fReadFromFiles ) {
AliDebugStream(2) << "Opening file " << path.Data() << endl;
ifstream* fileBuffer = new ifstream();
fileBuffer->open(path.Data());
if ( ! fileBuffer->good() ) {
AliErrorStream()
<< "Cannot open file " << path.Data() << endl;
}
return *fileBuffer;
}
else {
AliDebugStream(2) << "Opening stream " << path.Data() << endl;
// Cut top from the path
string dataPath = path.Data();
CutDataPath(dataPath);
istringstream* stringBuffer
= new istringstream(fMap->Get(dataPath).Data());
return *stringBuffer;
}
}
//______________________________________________________________________________
Bool_t AliMpDataStreams::IsDataStream(const TString& path) const
{
/// Return true, if data with given path exists
if ( fReadFromFiles ) {
ifstream fileBuffer(path.Data());
return fileBuffer.good();
}
else {
// Cut top from the path
string dataPath = path.Data();
CutDataPath(dataPath);
return ( fMap->Get(dataPath, kFALSE) != "" );
}
}
//______________________________________________________________________________
void AliMpDataStreams::SetReadFromFiles()
{
/// Set option to read data from files
fReadFromFiles = kTRUE;
}
//______________________________________________________________________________
Bool_t AliMpDataStreams::GetReadFromFiles() const
{
/// Return the info where the data are loaded from
return fReadFromFiles;
}
| [
"ivana@f7af4fe6-9843-0410-8265-dc069ae4e863"
] | ivana@f7af4fe6-9843-0410-8265-dc069ae4e863 |
d476bd073151bf5bd7f6d87cc40aedee93490e2a | c4414325871c4165a83afe1d0ba99d097929a18a | /qtcsv/sources/variantdata.cpp | aeb09412934c8576cbbdd94807c48a736fb60f3c | [
"MIT"
] | permissive | vakmancordero/BinaryTreeAVL-QT | 53a63df06466e9d27f80e462b6a6cc1e8a173461 | 630985a988ed084ac89c0563113689eb28c0cbff | refs/heads/master | 2021-01-21T07:00:51.550258 | 2017-02-27T12:58:26 | 2017-02-27T12:58:26 | 83,310,398 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,536 | cpp | #include "qtcsv/include/qtcsv/variantdata.h"
#include <QVariant>
#include <QStringList>
using namespace QtCSV;
class VariantData::VariantDataPrivate
{
public:
// Check if all values are convertable to strings
bool isConvertableToString(const QList<QVariant>& values) const;
// Transform QStringList to QList<QVariant>
QList<QVariant> toListOfVariants(const QStringList& values) const;
QList< QList<QVariant> > m_values;
};
// Check if all values are convertable to strings
// @input:
// - values - list of values
// @output:
// - bool - True if all values are convertable to strings, False otherwise
bool VariantData::VariantDataPrivate::isConvertableToString(
const QList<QVariant>& values) const
{
for ( QList<QVariant>::const_iterator iter = values.constBegin();
iter != values.constEnd(); ++iter)
{
if ( false == (*iter).canConvert<QString>() )
{
return false;
}
}
return true;
}
// Transform QStringList to QList<QVariant>
// @input:
// - values - list of strings
// @output:
// - QList<QVariant> - list of the same strings, but converted to QVariants
QList<QVariant> VariantData::VariantDataPrivate::toListOfVariants(
const QStringList& values) const
{
QList<QVariant> list;
for ( QStringList::const_iterator iter = values.constBegin();
iter != values.constEnd(); ++iter)
{
list << QVariant(*iter);
}
return list;
}
VariantData::VariantData() :
d_ptr(new VariantDataPrivate)
{
}
VariantData::VariantData(const VariantData& other) :
d_ptr(new VariantDataPrivate)
{
d_ptr->m_values = other.d_ptr->m_values;
}
VariantData::~VariantData()
{
delete d_ptr;
}
// Add new empty row
void VariantData::addEmptyRow()
{
d_ptr->m_values << QList<QVariant>();
}
// Add new row with one value
// @input:
// - value - value that is supposed to be written to the new row.
// If value is empty, empty row will be added. Value must be convertable to a
// QString!
// @output:
// - bool - True if new row was successfully added, else False
bool VariantData::addRow(const QVariant& value)
{
if ( false == value.canConvert<QString>() )
{
return false;
}
d_ptr->m_values << (QList<QVariant>() << value);
return true;
}
// Add new row with list of values
// @input:
// - values - list of values. If list is empty, empty row will be added.
// Values must be convertable to a QString!
// @output:
// - bool - True if new row was successfully added, else False
bool VariantData::addRow(const QList<QVariant> &values)
{
if ( false == d_ptr->isConvertableToString(values) )
{
return false;
}
d_ptr->m_values << values;
return true;
}
// Add new row with specified values (as strings)
// @input:
// - values - list of strings. If list is empty, empty row will be added.
void VariantData::addRow(const QStringList &values)
{
d_ptr->m_values << d_ptr->toListOfVariants(values);
}
// Clear all data
void VariantData::clear()
{
d_ptr->m_values.clear();
}
// Insert new row at index position 'row'.
// @input:
// - row - index of row. If 'row' is 0, the value will be set as first row.
// If 'row' is >= rowCount(), the value will be added as new last row.
// - value - value that is supposed to be written to the new row. Value must be
// convertable to a QString!
// @output:
// - bool - True if row was inserted, False otherwise
bool VariantData::insertRow(const int& row,
const QVariant& value)
{
return insertRow(row, (QList<QVariant>() << value));
}
// Insert new row at index position 'row'.
// @input:
// - row - index of row. If 'row' is 0, the value will be set as first row.
// If 'row' is >= rowCount(), the values will be added as new last row.
// - values - list of strings that are supposed to be written to the new row
// @output:
// - bool - True if row was inserted, False otherwise
bool VariantData::insertRow(const int& row,
const QStringList& values)
{
return insertRow(row, d_ptr->toListOfVariants(values));
}
// Insert new row at index position 'row'.
// @input:
// - row - index of row. If 'row' is 0, the value will be set as first row.
// If 'row' is >= rowCount(), the values will be added as new last row.
// - values - list of values that are supposed to be written to the new row.
// Values must be convertable to a QString!
// @output:
// - bool - True if row was inserted, False otherwise
bool VariantData::insertRow(const int& row,
const QList<QVariant>& values)
{
if ( false == d_ptr->isConvertableToString(values) )
{
return false;
}
d_ptr->m_values.insert(row, values);
return true;
}
// Check if there are any rows
// @output:
// - bool - True if there are any rows, else False
bool VariantData::isEmpty() const
{
return d_ptr->m_values.isEmpty();
}
// Remove the row at index position 'row'
// @input:
// - row - index of row to remove. 'row' must be a valid index position
// (i.e., 0 <= row < rowCount()). Otherwise function will do nothing.
void VariantData::removeRow(const int& row)
{
d_ptr->m_values.removeAt(row);
}
// Replace the row at index position 'row' with new row.
// @input:
// - row - index of row that should be replaced. 'row' must be
// a valid index position (i.e., 0 <= row < rowCount()).
// - value - value that is supposed to be written instead of the 'old' values.
// Value must be convertable to QString!
// @output:
// - bool - True if row was replaced, else False
bool VariantData::replaceRow(const int& row,
const QVariant& value)
{
return replaceRow(row, (QList<QVariant>() << value));
}
// Replace the row at index position 'row' with new row.
// @input:
// - row - index of row that should be replaced. 'row' must be
// a valid index position (i.e., 0 <= row < rowCount()).
// - values - values that are supposed to be written instead of the 'old'
// values.
// @output:
// - bool - True if row was replaced, else False
bool VariantData::replaceRow(const int& row,
const QStringList& values)
{
return replaceRow(row, d_ptr->toListOfVariants(values));
}
// Replace the row at index position 'row' with new row.
// @input:
// - row - index of row that should be replaced. 'row' must be
// a valid index position (i.e., 0 <= row < rowCount()).
// - values - values that are supposed to be written instead of the 'old'
// values. Values must be convertable to a QString!
// @output:
// - bool - True if row was replaced, else False
bool VariantData::replaceRow(const int& row,
const QList<QVariant>& values)
{
if ( false == d_ptr->isConvertableToString(values) )
{
return false;
}
d_ptr->m_values.replace(row, values);
return true;
}
// Reserve space for 'size' rows.
// @input:
// - size - number of rows to reserve in memory. If 'size' is smaller than the
// current number of rows, function will do nothing.
void VariantData::reserve(const int& size)
{
d_ptr->m_values.reserve(size);
}
// Get number of rows
// @output:
// - int - current number of rows
int VariantData::rowCount() const
{
return d_ptr->m_values.size();
}
// Get values (as list of strings) of specified row
// @input:
// - row - valid number of the row
// @output:
// - QStringList - values of the row. If row have invalid value, function will
// return empty QStringList.
QStringList VariantData::rowValues(const int& row) const
{
if ( row < 0 || rowCount() <= row )
{
return QStringList();
}
QStringList values;
for ( int i = 0; i < d_ptr->m_values.at(row).size(); ++i )
{
values << d_ptr->m_values.at(row).at(i).toString();
}
return values;
}
bool VariantData::operator==(const VariantData& other) const
{
return d_ptr->m_values == other.d_ptr->m_values;
}
VariantData& VariantData::operator=(const VariantData& other)
{
VariantData tmp(other);
std::swap(d_ptr, tmp.d_ptr);
return *this;
}
// Add new row that would contain one value
VariantData& VariantData::operator<<(const QVariant& value)
{
this->addRow(value);
return *this;
}
// Add new row with specified values
VariantData& VariantData::operator<<(const QList<QVariant>& values)
{
this->addRow(values);
return *this;
}
// Add new row with specified values
VariantData& VariantData::operator<<(const QStringList& values)
{
this->addRow(values);
return *this;
}
| [
"vakmancordero@gmail.com"
] | vakmancordero@gmail.com |
52aba8ce5359b8ed80eb539fbda11e6aa56fb582 | da3330ab9a5ec69c1f861b70b9bab4918555a3ac | /source/core/modules/assembler/assembler-ia32.h | a0b8e12f69a255c13c8dbf6dfb97d6805c130fa1 | [
"Apache-2.0"
] | permissive | wghub/Dobby | 65862300c3fb2cbafbe845581f0c095dc38af456 | 9790d119e0fe9b3e61fafab4f8d1bfebe45d562b | refs/heads/master | 2023-01-05T19:42:52.012669 | 2020-11-08T09:19:00 | 2020-11-08T09:19:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,517 | h | #ifndef CORE_ASSEMBLER_X86_H
#define CORE_ASSEMBLER_X86_H
#include "common/headers/common_header.h"
#include "core/arch/x86/registers-x86.h"
#include "core/modules/assembler/assembler.h"
#include "CodeBuffer/code-buffer-x86.h"
#include "xnucxx/LiteMutableArray.h"
#include "xnucxx/LiteIterator.h"
#define IsInt8(imm) (-128 <= imm && imm <= 127)
namespace zz {
namespace x86 {
constexpr Register VOLATILE_REGISTER = eax;
// ================================================================
// PseudoLabel
class PseudoLabel : public Label {
public:
enum PseudoLabelType { kDisp32_off_9 };
typedef struct _PseudoLabelInstruction {
int position_;
PseudoLabelType type_;
} PseudoLabelInstruction;
public:
PseudoLabel(void) {
instructions_.initWithCapacity(8);
}
~PseudoLabel(void) {
for (size_t i = 0; i < instructions_.getCount(); i++) {
PseudoLabelInstruction *item = (PseudoLabelInstruction *)instructions_.getObject(i);
delete item;
}
instructions_.release();
}
bool has_confused_instructions() {
return instructions_.getCount() > 0;
}
void link_confused_instructions(CodeBuffer *buffer = nullptr) {
if (!buffer)
UNREACHABLE();
CodeBuffer *_buffer = buffer;
for (size_t i = 0; i < instructions_.getCount(); i++) {
PseudoLabelInstruction *instruction = (PseudoLabelInstruction *)instructions_.getObject(i);
int32_t offset = pos() - instruction->position_;
switch (instruction->type_) {
case kDisp32_off_9: {
int disp32_fix_pos = instruction->position_ - sizeof(int32_t);
_buffer->FixBindLabel(disp32_fix_pos, offset + 9);
} break;
default:
UNREACHABLE();
break;
}
}
};
void link_to(int pos, PseudoLabelType type) {
PseudoLabelInstruction *instruction = new PseudoLabelInstruction;
instruction->position_ = pos;
instruction->type_ = type;
instructions_.pushObject((LiteObject *)instruction);
}
private:
LiteMutableArray instructions_;
};
class RelocLabelEntry : public PseudoLabel {
public:
explicit RelocLabelEntry(uint32_t data) : data_size_(0) {
data_ = data;
}
uint32_t data() {
return data_;
}
private:
uint32_t data_;
int data_size_;
};
#define ModRM_Mod(byte) ((byte & 0b11000000) >> 6)
#define ModRM_RegOpcode(byte) ((byte & 0b00111000) >> 3)
#define ModRM_RM(byte) (byte & 0b00000111)
typedef union _ModRM {
byte_t ModRM;
struct {
byte_t RM : 3;
byte_t RegOpcode : 3;
byte_t Mod : 2;
};
} ModRM;
// ================================================================
// Immediate
class Immediate {
public:
explicit Immediate(int32_t imm) : value_(imm), value_size_(32) {
if ((int32_t)(int8_t)imm == imm) {
value_size_ = 8;
} else if ((int32_t)(int16_t)imm == imm) {
value_size_ = 16;
} else {
value_size_ = 32;
}
}
explicit Immediate(int32_t imm, int size) : value_(imm), value_size_(size) {
}
int32_t value() const {
return value_;
}
int size() const {
return value_size_;
}
private:
const int32_t value_;
int value_size_;
};
// ================================================================
// Operand
class Operand {
public:
// [base]
Operand(Register base);
// [base + disp/r]
Operand(Register base, int32_t disp);
// [base + index*scale + disp/r]
Operand(Register base, Register index, ScaleFactor scale, int32_t disp);
// [index*scale + disp/r]
Operand(Register index, ScaleFactor scale, int32_t disp);
public: // Getter and Setter
uint8_t modrm() {
return (encoding_at(0));
}
uint8_t mod() const {
return (encoding_at(0) >> 6) & 3;
}
Register rm() const {
return Register::from_code(encoding_at(0) & 7);
}
ScaleFactor scale() const {
return static_cast<ScaleFactor>((encoding_at(1) >> 6) & 3);
}
Register index() const {
return Register::from_code((encoding_at(1) >> 3) & 7);
}
Register base() const {
return Register::from_code(encoding_at(1) & 7);
}
int8_t disp8() const {
ASSERT(length_ >= 2);
return static_cast<int8_t>(encoding_[length_ - 1]);
}
int32_t disp32() const {
ASSERT(length_ >= 5);
return static_cast<int32_t>(encoding_[length_ - 4]);
}
protected:
Operand() : length_(0) {
}
void SetModRM(int mod, Register rm) {
ASSERT((mod & ~3) == 0);
encoding_[0] = (mod << 6) | rm.code();
length_ = 1;
}
void SetSIB(ScaleFactor scale, Register index, Register base) {
ASSERT(length_ == 1);
ASSERT((scale & ~3) == 0);
encoding_[1] = (scale << 6) | (index.code() << 3) | base.code();
length_ = 2;
}
void SetDisp8(int8_t disp) {
ASSERT(length_ == 1 || length_ == 2);
encoding_[length_++] = static_cast<uint8_t>(disp);
}
void SetDisp32(int32_t disp) {
ASSERT(length_ == 1 || length_ == 2);
*(int32_t *)&encoding_[length_] = disp;
length_ += sizeof(disp);
}
private:
// explicit Operand(Register reg) : rex_(REX_NONE) { SetModRM(3, reg); }
// Get the operand encoding byte at the given index.
uint8_t encoding_at(intptr_t index) const {
ASSERT(index >= 0 && index < length_);
return encoding_[index];
}
public:
uint8_t length_;
uint8_t encoding_[6];
};
// ================================================================
// Address
class Address : public Operand {
public:
Address(Register base, int32_t disp) {
int base_ = base.code();
int ebp_ = ebp.code();
int esp_ = esp.code();
if ((disp == 0) && (base_ != ebp_)) {
SetModRM(0, base);
if (base_ == esp_)
SetSIB(TIMES_1, esp, base);
} else if (disp >= -128 && disp <= 127) {
SetModRM(1, base);
if (base_ == esp_)
SetSIB(TIMES_1, esp, base);
SetDisp8(disp);
} else {
SetModRM(2, base);
if (base_ == esp_)
SetSIB(TIMES_1, esp, base);
SetDisp32(disp);
}
}
// This addressing mode does not exist.
Address(Register base, Register r);
Address(Register index, ScaleFactor scale, int32_t disp) {
ASSERT(index.code() != rsp.code()); // Illegal addressing mode.
SetModRM(0, esp);
SetSIB(scale, index, ebp);
SetDisp32(disp);
}
// This addressing mode does not exist.
Address(Register index, ScaleFactor scale, Register r);
Address(Register base, Register index, ScaleFactor scale, int32_t disp) {
ASSERT(index.code() != rsp.code()); // Illegal addressing mode.
int rbp_ = ebp.code();
if ((disp == 0) && ((base.code() & 7) != rbp_)) {
SetModRM(0, esp);
SetSIB(scale, index, base);
} else if (disp >= -128 && disp <= 127) {
SetModRM(1, esp);
SetSIB(scale, index, base);
SetDisp8(disp);
} else {
SetModRM(2, esp);
SetSIB(scale, index, base);
SetDisp32(disp);
}
}
// This addressing mode does not exist.
Address(Register base, Register index, ScaleFactor scale, Register r);
};
// ================================================================
// Assembler
class Assembler : public AssemblerBase {
public:
Assembler(void *address) : AssemblerBase(address) {
buffer_ = new CodeBuffer(32);
DLOG(0, "Assembler buffer at %p", (CodeBufferBase *)buffer_->getRawBuffer());
}
~Assembler() {
if (buffer_)
delete buffer_;
}
public:
void Emit1(byte_t val) {
buffer_->Emit8(val);
}
void Emit(int32_t value) {
buffer_->Emit32(value);
}
// ================================================================
// Immediate
void EmitImmediate(Immediate imm, int imm_size) {
if (imm_size == 8) {
buffer_->Emit8((uint8_t)imm.value());
} else if (imm_size == 32) {
buffer_->Emit32((uint32_t)imm.value());
} else {
UNREACHABLE();
}
}
// ================================================================
// Operand Encoding
// ATTENTION:
// ModR/M == 8 registers and 24 addressing mode
// RM or MR
void Emit_OpEn_Register_Operand(Register dst, Address &operand) {
EmitModRM_Update_Register(operand.modrm(), dst);
buffer_->EmitBuffer(&operand.encoding_[1], operand.length_ - 1);
}
void Emit_OpEn_Register_RegisterOperand(Register dst, Register src) {
EmitModRM_Register_Register(dst, src);
}
void Emit_OpEn_Operand_Immediate(uint8_t extra_opcode, Address &operand, Immediate imm) {
}
void Emit_OpEn_RegisterOperand_Immediate(uint8_t extra_opcode, Register reg, Immediate imm) {
EmitModRM_ExtraOpcode_Register(extra_opcode, reg);
EmitImmediate(imm, imm.size());
}
void Emit_OpEn_Operand(uint8_t extra_opcode, Address &operand) {
EmitModRM_Update_ExtraOpcode(operand.modrm(), extra_opcode);
buffer_->EmitBuffer(&operand.encoding_[1], operand.length_ - 1);
}
void Emit_OpEn_RegisterOperand(uint8_t extra_opcode, Register reg) {
EmitModRM_ExtraOpcode_Register(extra_opcode, reg);
}
// Encoding: OI
void Emit_OpEn_OpcodeRegister_Immediate(uint8_t opcode, Register dst, Immediate imm) {
EmitOpcode_Register(opcode, dst);
EmitImmediate(imm, imm.size());
}
// ================================================================
// ModRM
inline void EmitModRM(uint8_t Mod, uint8_t RegOpcode, uint8_t RM) {
uint8_t ModRM = 0;
ModRM |= Mod << 6;
ModRM |= RegOpcode << 3;
ModRM |= RM;
Emit1(ModRM);
}
void EmitModRM_ExtraOpcode_Register(uint8_t extra_opcode, Register reg) {
EmitModRM(0b11, extra_opcode, reg.code());
}
void EmitModRM_Register_Register(Register reg1, Register reg2) {
EmitModRM(0b11, reg1.code(), reg2.code());
}
// update operand's ModRM
void EmitModRM_Update_Register(uint8_t modRM, Register reg) {
EmitModRM(ModRM_Mod(modRM), reg.code(), ModRM_RM(modRM));
}
// update operand's ModRM
void EmitModRM_Update_ExtraOpcode(uint8_t modRM, uint8_t extra_opcode) {
EmitModRM(ModRM_Mod(modRM), extra_opcode, ModRM_RM(modRM));
}
// ================================================================
// Opcode
void EmitOpcode(uint8_t opcode) {
Emit1(opcode);
}
void EmitOpcode_Register(uint8_t opcode, Register reg) {
EmitOpcode(opcode | reg.code());
}
// ================================================================
// Instruction
void pushfq() {
Emit1(0x9C);
}
void jmp(Immediate imm);
void sub(Register dst, Immediate imm) {
DCHECK_EQ(dst.size(), 32);
EmitOpcode(0x81);
Emit_OpEn_RegisterOperand_Immediate(0x5, dst, imm);
}
void add(Register dst, Immediate imm) {
DCHECK_EQ(dst.size(), 32);
EmitOpcode(0x81);
Emit_OpEn_RegisterOperand_Immediate(0x0, dst, imm);
}
// MOV RAX, 0x320
// 48 c7 c0 20 03 00 00 (MI encoding)
// 48 b8 20 03 00 00 00 00 00 00 (OI encoding)
void mov(Register dst, const Immediate imm) {
// OI encoding
Emit_OpEn_OpcodeRegister_Immediate(0xb8, dst, imm);
}
void mov(Register dst, Address src) {
EmitOpcode(0x8B);
Emit_OpEn_Register_Operand(dst, src);
}
void mov(Address dst, Register src) {
EmitOpcode(0x89);
Emit_OpEn_Register_Operand(src, dst);
}
void mov(Register dst, Register src) {
Emit1(0x8B);
Emit_OpEn_Register_RegisterOperand(dst, src);
}
void call(Address operand) {
EmitOpcode(0xFF);
Emit_OpEn_Operand(0x2, operand);
}
void call(Immediate imm) {
EmitOpcode(0xe8);
EmitImmediate(imm, imm.size());
}
void call(Register reg) {
EmitOpcode(0xFF);
Emit_OpEn_RegisterOperand(0x2, reg);
}
void pop(Register reg) {
EmitOpcode_Register(0x58, reg);
}
void push(Register reg) {
EmitOpcode_Register(0x50, reg);
}
void ret() {
EmitOpcode(0xc3);
}
void nop() {
EmitOpcode(0x90);
}
};
// ================================================================
// TurboAssembler
class TurboAssembler : public Assembler {
public:
TurboAssembler(void *address) : Assembler(address) {
data_labels_ = NULL;
}
addr32_t CurrentIP();
void CallFunction(ExternalReference function) {
nop();
MovRipToRegister(VOLATILE_REGISTER);
call(Address(VOLATILE_REGISTER, INT32_MAX));
{
RelocLabelEntry *addrLabel = new RelocLabelEntry((uint64_t)function.address());
addrLabel->link_to(ip_offset(), PseudoLabel::kDisp32_off_9);
this->AppendRelocLabelEntry(addrLabel);
}
nop();
}
void MovRipToRegister(Register dst) {
call(Immediate(0, 32));
pop(dst);
}
// ================================================================
// RelocLabelEntry
void PseudoBind(PseudoLabel *label) {
const addr_t bound_pc = buffer_->getSize();
label->bind_to(bound_pc);
// If some instructions have been wrote, before the label bound, we need link these `confused` instructions
if (label->has_confused_instructions()) {
label->link_confused_instructions(reinterpret_cast<CodeBuffer *>(this->GetCodeBuffer()));
}
}
void RelocBind() {
if (data_labels_ == NULL)
return;
for (size_t i = 0; i < data_labels_->getCount(); i++) {
RelocLabelEntry *label = (RelocLabelEntry *)data_labels_->getObject(i);
PseudoBind(label);
Emit(label->data());
}
}
void AppendRelocLabelEntry(RelocLabelEntry *label) {
if (data_labels_ == NULL) {
data_labels_ = new LiteMutableArray(8);
}
data_labels_->pushObject((LiteObject *)label);
}
private:
LiteMutableArray *data_labels_;
};
} // namespace x86
} // namespace zz
#endif
| [
"jmpews@gmail.com"
] | jmpews@gmail.com |
d71ca3d3a7205aa4deef0b0fa636d9d875ae273d | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/third_party/pdfium/core/fpdfapi/fpdf_page/cpdf_countedobject.h | e7f4ab6af0efe8375919264580d429a7a6185ae8 | [
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT"
] | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 1,275 | h | // Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#ifndef CORE_FPDFAPI_FPDF_PAGE_CPDF_COUNTEDOBJECT_H_
#define CORE_FPDFAPI_FPDF_PAGE_CPDF_COUNTEDOBJECT_H_
#include "core/fpdfapi/fpdf_page/cpdf_pattern.h"
#include "core/fpdfapi/fpdf_page/include/cpdf_colorspace.h"
#include "core/fxcrt/include/fx_system.h"
template <class T>
class CPDF_CountedObject {
public:
explicit CPDF_CountedObject(T* ptr) : m_nCount(1), m_pObj(ptr) {}
void reset(T* ptr) { // CAUTION: tosses prior ref counts.
m_nCount = 1;
m_pObj = ptr;
}
void clear() { // Now you're all weak ptrs ...
delete m_pObj;
m_pObj = nullptr;
}
T* get() const { return m_pObj; }
T* AddRef() {
ASSERT(m_pObj);
++m_nCount;
return m_pObj;
}
void RemoveRef() {
if (m_nCount)
--m_nCount;
}
size_t use_count() const { return m_nCount; }
protected:
size_t m_nCount;
T* m_pObj;
};
using CPDF_CountedColorSpace = CPDF_CountedObject<CPDF_ColorSpace>;
using CPDF_CountedPattern = CPDF_CountedObject<CPDF_Pattern>;
#endif // CORE_FPDFAPI_FPDF_PAGE_CPDF_COUNTEDOBJECT_H_
| [
"changhyeok.bae@lge.com"
] | changhyeok.bae@lge.com |
239b65ce88f261dbb685ef3325fc4fc57c9a8610 | 07cbe159795612509c2e7e59eb9c8ff6c6ed6b0d | /partitioned/RayleighBenard/consistencyTest/Ra_1e+05_turbExnerFoam_X1_Y50_adHocBC/tStep0.005_0.005/Exner.diff_initConds | d435181ad3aecf0ea4b3ef55c214d044df57a4e4 | [] | no_license | AtmosFOAM/danRun | aacaaf8a22e47d1eb6390190cb98fbe846001e7a | 94d19c4992053d7bd860923e9605c0cbb77ca8a2 | refs/heads/master | 2021-03-22T04:32:10.679600 | 2020-12-03T21:09:40 | 2020-12-03T21:09:40 | 118,792,506 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,212 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: dev
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.005";
object Exner.diff_initConds;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField nonuniform List<scalar>
52
(
3.36709999993e-07
3.56834000015e-07
3.80347999984e-07
4.04611000038e-07
4.28496999993e-07
4.52408999929e-07
4.76351999956e-07
4.99880999927e-07
5.24162000026e-07
5.49212999967e-07
5.73861000053e-07
5.98550000008e-07
6.23288999968e-07
6.47613999982e-07
6.72654000056e-07
6.98037999958e-07
7.24162000032e-07
7.49783999998e-07
7.74987999996e-07
8.01531999994e-07
8.27670999959e-07
8.53299000014e-07
8.79807000032e-07
9.07216999968e-07
9.34225000027e-07
9.61330000049e-07
9.88638000021e-07
1.01615699999e-06
1.04379099997e-06
1.07101400004e-06
1.09920400004e-06
1.12838300004e-06
1.15705399995e-06
1.18520000003e-06
1.21425200006e-06
1.24377900002e-06
1.274138e-06
1.30341300009e-06
1.33352500009e-06
1.36414200003e-06
1.39563699997e-06
1.42613600007e-06
1.45811399999e-06
1.489204e-06
1.52180599999e-06
1.5533990001e-06
1.58592099997e-06
1.61888299999e-06
1.65219000003e-06
1.68220300001e-06
3.37200000144e-07
1.68141000001e-06
)
;
boundaryField
{
ground
{
type fixedFluxBuoyantExner;
gradient uniform 0;
value uniform 3.07620624085e-07;
}
top
{
type fixedFluxBuoyantExner;
gradient uniform 0;
value uniform 1.64525742952e-06;
}
left
{
type cyclic;
}
right
{
type cyclic;
}
frontAndBack
{
type empty;
}
}
// ************************************************************************* //
| [
"d.shipley.1341@gmail.com"
] | d.shipley.1341@gmail.com | |
127af6c3280a4a5eb857baea86d74e7cb19cf1b1 | 85d43750332a8ca7252eacbfba252bb3bde8ec4c | /modbus-bbb-src/modbusmatildalsclient.h | bc623d0f922ce0c372f81a8add4a08f9fa253a13 | [] | no_license | KTS-Intek/modbus-bbb | 18b0cf7748bd6854b39c07865cd8b7f41866e82f | 81422349e434ddbe13b220dd27bd80819c724c47 | refs/heads/main | 2023-06-26T01:19:19.612589 | 2023-06-19T17:28:58 | 2023-06-19T17:28:58 | 339,476,418 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,076 | h | #ifndef MODBUSMATILDALSCLIENT_H
#define MODBUSMATILDALSCLIENT_H
///[!] ipc
#include "localsockets/regularlocalsocket.h"
#include <QObject>
#include <QtCore>
class ModbusMatildaLSClient : public RegularLocalSocket
{
Q_OBJECT
public:
explicit ModbusMatildaLSClient(bool verboseMode, QObject *parent = nullptr);
void decodeReadData(const QVariant &dataVar, const quint16 &command);
signals:
void onMatildaCommandReceived(QString messagetag, QString objecttag, bool isok, QString messageerror);
public slots:
//for client side
void sendCommand2zbyrator(quint16 pollCode, QString ni, QString messagetag, QString objecttag);
void sendCommand2firefly(quint16 pollCode, QString ni, QString messagetag, QString objecttag);
private:
bool sendCommand2zbyratorHash(QVariantHash hash , QString messagetag, QString objecttag);
bool sendCommand2fireflyHash(QVariantHash hash , QString messagetag, QString objecttag);
bool sendCommand2fireflyReloadSettHash(QString messagetag, QString objecttag);
};
#endif // MODBUSMATILDALSCLIENT_H
| [
"bohdanzikranets@gmail.com"
] | bohdanzikranets@gmail.com |
618fe81f930d020651ddf9d18a84f20c3532d53e | 6250f3343eff1638912510b66ed936c59796635a | /include/toolkit/thirdparty/stlsoft/STLSoft/include/stlsoft/shims/access/string.hpp | 94a56e7381058efbb723d6596d168d215e9da4b5 | [
"Apache-2.0"
] | permissive | nneesshh/mytoolkit | b4b242307a6603bc5785bc130de8f4d3b5ea9265 | 336ae9c7077c8687a8cf8a2ce4aec804c28ab90c | refs/heads/master | 2020-04-05T15:18:07.985547 | 2018-12-17T11:36:07 | 2018-12-17T11:36:07 | 156,961,652 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,640 | hpp | /* /////////////////////////////////////////////////////////////////////////
* File: stlsoft/shims/access/string.hpp
*
* Purpose: Primary include file for string access shims representing
* built-in and standard string types.
*
* Created: 16th January 2002
* Updated: 19th February 2017
*
* Home: http://stlsoft.org/
*
* Copyright (c) 2002-2017, Matthew Wilson and Synesis Software
* 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(s) of Matthew Wilson and Synesis Software nor the
* names of any 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.
*
* ////////////////////////////////////////////////////////////////////// */
/** \file stlsoft/shims/access/string.hpp
*
* \brief [C++] Primary include file for string access shims representing
* built-in and standard string types
* (\ref group__concept__Shim__string_access "String Access Shims" Concept).
*/
#ifndef STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_HPP_STRING
#define STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_HPP_STRING
#ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION
# define STLSOFT_VER_STLSOFT_SHIMS_ACCESS_HPP_STRING_MAJOR 4
# define STLSOFT_VER_STLSOFT_SHIMS_ACCESS_HPP_STRING_MINOR 3
# define STLSOFT_VER_STLSOFT_SHIMS_ACCESS_HPP_STRING_REVISION 2
# define STLSOFT_VER_STLSOFT_SHIMS_ACCESS_HPP_STRING_EDIT 96
#endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */
/* /////////////////////////////////////////////////////////////////////////
* includes
*/
#ifndef STLSOFT_INCL_STLSOFT_H_STLSOFT
# include <stlsoft/stlsoft.h>
#endif /* !STLSOFT_INCL_STLSOFT_H_STLSOFT */
#ifdef STLSOFT_TRACE_INCLUDE
# pragma message(__FILE__)
#endif /* STLSOFT_TRACE_INCLUDE */
#ifndef STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_STRING_H_FWD
# include <stlsoft/shims/access/string/fwd.h>
#endif /* !STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_STRING_H_FWD */
#ifndef STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_STRING_STD_H_C_STRING
# include <stlsoft/shims/access/string/std/c_string.h>
#endif /* !STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_STRING_STD_H_C_STRING */
#ifndef STLSOFT_MINIMUM_SAS_INCLUDES
# ifndef STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_STRING_STD_HPP_EXCEPTION
# include <stlsoft/shims/access/string/std/exception.hpp>
# endif /* !STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_STRING_STD_HPP_EXCEPTION */
# ifndef STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_STRING_STD_HPP_BASIC_STRING
# include <stlsoft/shims/access/string/std/basic_string.hpp>
# endif /* !STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_STRING_STD_HPP_BASIC_STRING */
# ifndef STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_STRING_STD_HPP_TIME
# include <stlsoft/shims/access/string/std/time.hpp>
# endif /* !STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_STRING_STD_HPP_TIME */
# ifndef STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_STRING_STD_HPP_TYPE_INFO
# include <stlsoft/shims/access/string/std/type_info.hpp>
# endif /* !STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_STRING_STD_HPP_TYPE_INFO */
#endif /* !STLSOFT_MINIMUM_SAS_INCLUDES */
/* /////////////////////////////////////////////////////////////////////////
* inclusion control
*/
#ifdef STLSOFT_CF_PRAGMA_ONCE_SUPPORT
# pragma once
#endif /* STLSOFT_CF_PRAGMA_ONCE_SUPPORT */
#endif /* !STLSOFT_INCL_STLSOFT_SHIMS_ACCESS_HPP_STRING */
/* ///////////////////////////// end of file //////////////////////////// */
| [
"nneesshh@163.com"
] | nneesshh@163.com |
57fd5359c9c4f6253ac8b6698e3541c5035a9a71 | 9da88ab805303c25bd9654ad45287a62a6c4710f | /Cpp/LeetCode/acwing35_3.cpp | 63f7961b4295da71a5c6ba198cfc3256abd5b993 | [] | no_license | ms303956362/myexercise | 7bb7be1ac0b8f40aeee8ca2df19255024c6d9bdc | 4730c438354f0c7fc3bce54f8c1ade6e627586c9 | refs/heads/master | 2023-04-13T01:15:01.882780 | 2023-04-03T15:03:22 | 2023-04-03T15:03:22 | 232,984,051 | 2 | 0 | null | 2022-12-02T06:55:19 | 2020-01-10T06:47:00 | C | UTF-8 | C++ | false | false | 1,824 | cpp | // IO
#include <iostream>
#include <sstream>
// ordered container
#include <vector>
#include <deque>
#include <list>
#include <forward_list>
#include <string>
#include <stack>
#include <queue>
// associative-container
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
// algorithm
#include <algorithm>
#include <cmath>
// utility
#include <initializer_list>
#include <iterator>
#include <memory>
#include <utility>
// c
#include <cstdio>
#include <cstdlib>
#include <cstring>
// functional
#include <functional>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
int main(int argc, char const *argv[])
{
int n;
cin >> n;
vector<int> s(n), c(n);
for (int i = 0; i < n; ++i) {
cin >> s[i];
}
for (int i = 0; i < n; ++i) {
cin >> c[i];
}
int ans = 1e9;
for (int i = 1; i < n - 1; ++i) {
int c1 = 1e9, c2 = 1e9;
for (int j = 0; j < i; ++j) {
if (s[j] < s[i]) {
c1 = min(c1, c[j]);
}
}
for (int j = n - 1; j > i; --j) {
if (s[i] < s[j]) {
c2 = min(c2, c[j]);
}
}
if (c1 != 1e9 && c2 != 1e9) {
ans = min(ans, c1 + c2 + c[i]);
}
}
if (ans != 1e9)
cout << ans << endl;
else
cout << -1 << endl;
return 0;
}
| [
"ms303956362@163.com"
] | ms303956362@163.com |
51677d499f1969435d9bc3751088c436dfbe2ea8 | 78e2c512ca819c2dddb72ced9f48b35f430daba1 | /Europa v6s/Europa v6/depricated/CGauge.cpp | da8c2d80dc1a16e51b23d74f9f4d04716ed2d650 | [] | no_license | thedarkprincedc/Europa | 5bd0225d3b14c8e46b9f24b3531ef7b9b4fe4e7c | 67d8b871485668ec014bec0ac4f734543956ad09 | refs/heads/master | 2021-01-18T13:58:34.223954 | 2014-12-04T04:52:31 | 2014-12-04T04:52:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,519 | cpp | #include "../PHNX_CORE/Core_Global.h"
#include "cdxmesh.h"
class TestGame : public CApplication{
private:
CGraphics m_CGraphics;
CDXMesh *m_mesh;
CCamera *m_pFlexCamera;
public:
TestGame(){
m_Width = 640;
m_Height = 480;
m_Style = WS_BORDER | WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU;
strcpy(m_Class, "TestGameClass");
strcpy(m_Caption, "Test Game Class");
}
BOOL Init(){
m_CGraphics.Init();
m_CGraphics.SetMode(GethWnd(), TRUE, TRUE, 640, 480, 16);
//m_CGraphics.SetMode(GethWnd(), FALSE, FALSE);
m_CGraphics.EnableAlphaBlending(FALSE);
m_CGraphics.EnableAlphaTesting(FALSE);
m_CGraphics.SetPerspective(D3DX_PI/4, 1.3333f, 1.0f, 10000.0f);
m_mesh = new CDXMesh(m_CGraphics.GetD3DDevice());
m_mesh->LoadMesh("./strider/lkj.x","./strider/");
m_pFlexCamera = new CCamera();
return TRUE;
}
BOOL Shutdown(){
return TRUE;
}
void CameraControls(IDirect3DDevice9 *pDevice){
D3DXMATRIX view;
pDevice->GetTransform(D3DTS_VIEW, &view);
m_pFlexCamera->GetViewMatrix(&view);
if(GetAsyncKeyState(VK_UP)) m_pFlexCamera->Walk(+1);
if(GetAsyncKeyState(VK_DOWN)) m_pFlexCamera->Walk(-1);
if(GetAsyncKeyState(VK_LEFT)) m_pFlexCamera->Strafe(-1);
if(GetAsyncKeyState(VK_RIGHT)) m_pFlexCamera->Strafe(+1);
if(GetAsyncKeyState(0x005A)) m_pFlexCamera->Fly(+1);
if(GetAsyncKeyState(0x0058)) m_pFlexCamera->Fly(-1);
if(GetAsyncKeyState(0x0041)) m_pFlexCamera->Pitch(+.15);
if(GetAsyncKeyState(0x0053)) m_pFlexCamera->Pitch(-.15);
if(GetAsyncKeyState(0x0051)) m_pFlexCamera->Roll(-.15);
if(GetAsyncKeyState(0x0057)) m_pFlexCamera->Roll(+.15);
if(GetAsyncKeyState(0x0045)) m_pFlexCamera->Yaw(-.15);
if(GetAsyncKeyState(0x0052)) m_pFlexCamera->Yaw(+.15);
pDevice->SetTransform(D3DTS_VIEW, &view);
}
BOOL Frame(){
m_CGraphics.Clear(0xffffffff);
m_CGraphics.BeginScene();
CameraControls(m_CGraphics.GetD3DDevice());
m_mesh->Render(30);
m_CGraphics.EndScene();
m_CGraphics.BeginSprite();
m_CGraphics.EndSprite();
m_CGraphics.Display();
return TRUE;
}
int FAR PASCAL MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg){
case WM_KEYDOWN:{
switch(wParam)
{ case VK_SPACE:
PostQuitMessage(0);
}
return 0;
}
}
return (int)DefWindowProc(hWnd, uMsg, wParam, lParam);
}
};
int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow){
TestGame TestGame;
return TestGame.Run();
} | [
"brettmosley@hotmail.com"
] | brettmosley@hotmail.com |
86f9eeb88a44951460f931aabff6c25f1a9ae2b1 | 304ea2162378f3d7bbdb5a95898bf6a4fdbbb9e3 | /athena/examples/LCM/Singlecar/obu/src/fam/msg/nad_lcm/ou_route_respond.hpp | d0fa18cc57abe1217a91428f1dbefd3b1274edc3 | [] | no_license | Tubbxl/Athena_Src | 5ad65686fd9fe5baed0dbda19f31c536f33e253d | 53d2c0a4829b6eff0443546da37a6461166cb6c7 | refs/heads/master | 2022-01-29T23:58:42.551053 | 2018-12-04T09:56:01 | 2018-12-04T09:56:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,440 | hpp | /** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT MODIFY
* BY HAND!!
*
* Generated by lcm-gen
**/
#include <lcm/lcm_coretypes.h>
#ifndef __nad_lcm_ou_route_respond_hpp__
#define __nad_lcm_ou_route_respond_hpp__
#include <string>
#include "nad_lcm/route_planning.hpp"
namespace nad_lcm
{
/// obu->vui:返回路径规划结果
class ou_route_respond
{
public:
std::string obu_name;
int32_t retcode;
nad_lcm::route_planning route;
public:
/**
* Encode a message into binary form.
*
* @param buf The output buffer.
* @param offset Encoding starts at thie byte offset into @p buf.
* @param maxlen Maximum number of bytes to write. This should generally be
* equal to getEncodedSize().
* @return The number of bytes encoded, or <0 on error.
*/
inline int encode(void *buf, int offset, int maxlen) const;
/**
* Check how many bytes are required to encode this message.
*/
inline int getEncodedSize() const;
/**
* Decode a message from binary form into this instance.
*
* @param buf The buffer containing the encoded message.
* @param offset The byte offset into @p buf where the encoded message starts.
* @param maxlen The maximum number of bytes to reqad while decoding.
* @return The number of bytes decoded, or <0 if an error occured.
*/
inline int decode(const void *buf, int offset, int maxlen);
/**
* Retrieve the 64-bit fingerprint identifying the structure of the message.
* Note that the fingerprint is the same for all instances of the same
* message type, and is a fingerprint on the message type definition, not on
* the message contents.
*/
inline static int64_t getHash();
/**
* Returns "ou_route_respond"
*/
inline static const char* getTypeName();
// LCM support functions. Users should not call these
inline int _encodeNoHash(void *buf, int offset, int maxlen) const;
inline int _getEncodedSizeNoHash() const;
inline int _decodeNoHash(const void *buf, int offset, int maxlen);
inline static uint64_t _computeHash(const __lcm_hash_ptr *p);
};
int ou_route_respond::encode(void *buf, int offset, int maxlen) const
{
int pos = 0, tlen;
int64_t hash = (int64_t)getHash();
tlen = __int64_t_encode_array(buf, offset + pos, maxlen - pos, &hash, 1);
if(tlen < 0) return tlen; else pos += tlen;
tlen = this->_encodeNoHash(buf, offset + pos, maxlen - pos);
if (tlen < 0) return tlen; else pos += tlen;
return pos;
}
int ou_route_respond::decode(const void *buf, int offset, int maxlen)
{
int pos = 0, thislen;
int64_t msg_hash;
thislen = __int64_t_decode_array(buf, offset + pos, maxlen - pos, &msg_hash, 1);
if (thislen < 0) return thislen; else pos += thislen;
if (msg_hash != getHash()) return -1;
thislen = this->_decodeNoHash(buf, offset + pos, maxlen - pos);
if (thislen < 0) return thislen; else pos += thislen;
return pos;
}
int ou_route_respond::getEncodedSize() const
{
return 8 + _getEncodedSizeNoHash();
}
int64_t ou_route_respond::getHash()
{
static int64_t hash = _computeHash(NULL);
return hash;
}
const char* ou_route_respond::getTypeName()
{
return "ou_route_respond";
}
int ou_route_respond::_encodeNoHash(void *buf, int offset, int maxlen) const
{
int pos = 0, tlen;
char* obu_name_cstr = (char*) this->obu_name.c_str();
tlen = __string_encode_array(buf, offset + pos, maxlen - pos, &obu_name_cstr, 1);
if(tlen < 0) return tlen; else pos += tlen;
tlen = __int32_t_encode_array(buf, offset + pos, maxlen - pos, &this->retcode, 1);
if(tlen < 0) return tlen; else pos += tlen;
tlen = this->route._encodeNoHash(buf, offset + pos, maxlen - pos);
if(tlen < 0) return tlen; else pos += tlen;
return pos;
}
int ou_route_respond::_decodeNoHash(const void *buf, int offset, int maxlen)
{
int pos = 0, tlen;
int32_t __obu_name_len__;
tlen = __int32_t_decode_array(buf, offset + pos, maxlen - pos, &__obu_name_len__, 1);
if(tlen < 0) return tlen; else pos += tlen;
if(__obu_name_len__ > maxlen - pos) return -1;
this->obu_name.assign(((const char*)buf) + offset + pos, __obu_name_len__ - 1);
pos += __obu_name_len__;
tlen = __int32_t_decode_array(buf, offset + pos, maxlen - pos, &this->retcode, 1);
if(tlen < 0) return tlen; else pos += tlen;
tlen = this->route._decodeNoHash(buf, offset + pos, maxlen - pos);
if(tlen < 0) return tlen; else pos += tlen;
return pos;
}
int ou_route_respond::_getEncodedSizeNoHash() const
{
int enc_size = 0;
enc_size += this->obu_name.size() + 4 + 1;
enc_size += __int32_t_encoded_array_size(NULL, 1);
enc_size += this->route._getEncodedSizeNoHash();
return enc_size;
}
uint64_t ou_route_respond::_computeHash(const __lcm_hash_ptr *p)
{
const __lcm_hash_ptr *fp;
for(fp = p; fp != NULL; fp = fp->parent)
if(fp->v == ou_route_respond::getHash)
return 0;
const __lcm_hash_ptr cp = { p, (void*)ou_route_respond::getHash };
uint64_t hash = 0x50291f88b3890b2aLL +
nad_lcm::route_planning::_computeHash(&cp);
return (hash<<1) + ((hash>>63)&1);
}
}
#endif
| [
"297285508@qq.com"
] | 297285508@qq.com |
5fe28532888314b896fa06f52955d10f2e96dc5f | 4da63548a099bd3024234221caee799329935221 | /include/hermes/Parser/JSLexer.h | a1a4e0920e18af1d22889cf4dea8fca58047fb9a | [
"MIT"
] | permissive | Pengchengxiang/hermes | e31fb16b176d6270ed14670bb25e1c01508b2ca5 | 35da03ff3cd5c7c5391e809d8d1d99d8f227be0b | refs/heads/master | 2022-11-10T05:47:18.880627 | 2020-06-27T03:30:49 | 2020-06-27T03:34:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,676 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifndef HERMES_PARSER_JSLEXER_H
#define HERMES_PARSER_JSLEXER_H
#include "hermes/Parser/Config.h"
#include "hermes/Support/Allocator.h"
#include "hermes/Support/OptValue.h"
#include "hermes/Support/SourceErrorManager.h"
#include "hermes/Support/StringTable.h"
#include "hermes/Support/UTF8.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallString.h"
#include <functional>
#include <utility>
namespace hermes {
namespace parser {
using llvm::SMLoc;
using llvm::SMRange;
class Token;
class JSLexer;
enum class TokenKind {
#define TOK(name, str) name,
#include "TokenKinds.def"
};
inline constexpr int ord(TokenKind kind) {
return static_cast<int>(kind);
}
#ifndef NDEBUG
/// \return true if \p kind is a punctuator token.
inline bool isPunctuatorDbg(TokenKind kind) {
switch (kind) {
#define PUNCTUATOR(name, str) \
case TokenKind::name: \
return true;
#include "TokenKinds.def"
default:
return false;
}
}
#endif
const unsigned NUM_JS_TOKENS = ord(TokenKind::_last_token) + 1;
const char *tokenKindStr(TokenKind kind);
class RegExpLiteral {
UniqueString *body_;
UniqueString *flags_;
public:
RegExpLiteral(UniqueString *body, UniqueString *flags)
: body_(body), flags_(flags) {}
UniqueString *getBody() const {
return body_;
}
UniqueString *getFlags() const {
return flags_;
}
};
/// Encapsulates the information contained in the current token.
/// We only ever create one of these, but it is cleaner to keep the data
/// in a separate class.
class Token {
TokenKind kind_{TokenKind::none};
SMRange range_{};
double numeric_{};
UniqueString *ident_{nullptr};
/// Representation of the string literal for tokens that are strings.
/// If the current token is part of a template literal, this is null
/// when it contains a NotEscapeSequence. This is necessary for syntax errors
/// for NotEscapeSequence in untagged string literals.
UniqueString *stringLiteral_{nullptr};
RegExpLiteral *regExpLiteral_{nullptr};
/// Representation of one these depending on the TokenKind:
/// - The Template Raw Value (TRV) associated with the token if it represents
/// a part or whole of a template literal.
/// - The raw string of a JSXText.
UniqueString *rawString_{nullptr};
/// If the current token is a string literal, this flag indicates whether it
/// contains any escapes or new line continuations. We need this in order to
/// detect directives.
bool stringLiteralContainsEscapes_ = false;
Token(const Token &) = delete;
const Token &operator=(const Token &) = delete;
public:
Token() = default;
~Token() = default;
TokenKind getKind() const {
return kind_;
}
bool isResWord() const {
return kind_ > TokenKind::_first_resword &&
kind_ < TokenKind::_last_resword;
}
bool isTemplateLiteral() const {
return getKind() == TokenKind::no_substitution_template ||
getKind() == TokenKind::template_head ||
getKind() == TokenKind::template_middle ||
getKind() == TokenKind::template_tail;
}
SMLoc getStartLoc() const {
return range_.Start;
}
SMLoc getEndLoc() const {
return range_.End;
}
SMRange getSourceRange() const {
return range_;
}
StringRef inputStr() const {
return StringRef(
range_.Start.getPointer(),
range_.End.getPointer() - range_.Start.getPointer());
}
double getNumericLiteral() const {
assert(getKind() == TokenKind::numeric_literal);
return numeric_;
}
UniqueString *getIdentifier() const {
assert(getKind() == TokenKind::identifier);
return ident_;
}
UniqueString *getResWordIdentifier() const {
assert(isResWord());
return ident_;
}
UniqueString *getResWordOrIdentifier() const {
assert(getKind() == TokenKind::identifier || isResWord());
return ident_;
}
UniqueString *getStringLiteral() const {
assert(getKind() == TokenKind::string_literal);
return stringLiteral_;
}
bool getStringLiteralContainsEscapes() const {
assert(getKind() == TokenKind::string_literal);
return stringLiteralContainsEscapes_;
}
/// \return whether the template literal token contains a NotEscapeSequence,
/// as defined in the ES9.0 spec:
/// http://ecma-international.org/ecma-262/9.0/#prod-NotEscapeSequence
bool getTemplateLiteralContainsNotEscapes() const {
assert(isTemplateLiteral());
return stringLiteral_ == nullptr;
}
UniqueString *getTemplateValue() const {
assert(isTemplateLiteral());
return stringLiteral_;
}
UniqueString *getTemplateRawValue() const {
assert(isTemplateLiteral());
return rawString_;
}
RegExpLiteral *getRegExpLiteral() const {
assert(getKind() == TokenKind::regexp_literal);
return regExpLiteral_;
}
UniqueString *getJSXTextValue() const {
assert(getKind() == TokenKind::jsx_text);
return stringLiteral_;
}
UniqueString *getJSXTextRaw() const {
assert(getKind() == TokenKind::jsx_text);
return rawString_;
}
private:
void setStart(const char *start) {
range_.Start = SMLoc::getFromPointer(start);
}
void setEnd(const char *end) {
range_.End = SMLoc::getFromPointer(end);
}
void setPunctuator(TokenKind kind) {
kind_ = kind;
}
void setEof() {
kind_ = TokenKind::eof;
}
void setNumericLiteral(double literal) {
kind_ = TokenKind::numeric_literal;
numeric_ = literal;
}
void setIdentifier(UniqueString *ident) {
kind_ = TokenKind::identifier;
ident_ = ident;
}
void setStringLiteral(UniqueString *literal, bool containsEscapes) {
kind_ = TokenKind::string_literal;
stringLiteral_ = literal;
stringLiteralContainsEscapes_ = containsEscapes;
}
void setRegExpLiteral(RegExpLiteral *literal) {
kind_ = TokenKind::regexp_literal;
regExpLiteral_ = literal;
}
void setResWord(TokenKind kind, UniqueString *ident) {
assert(kind > TokenKind::_first_resword && kind < TokenKind::_last_resword);
kind_ = kind;
ident_ = ident;
}
void
setTemplateLiteral(TokenKind kind, UniqueString *cooked, UniqueString *raw) {
assert(
kind == TokenKind::no_substitution_template ||
kind == TokenKind::template_head ||
kind == TokenKind::template_middle || kind == TokenKind::template_tail);
kind_ = kind;
stringLiteral_ = cooked;
rawString_ = raw;
}
void setJSXText(UniqueString *value, UniqueString *raw) {
kind_ = TokenKind::jsx_text;
stringLiteral_ = value;
rawString_ = raw;
}
friend class JSLexer;
};
class JSLexer {
public:
using Allocator = hermes::BumpPtrAllocator;
private:
SourceErrorManager &sm_;
Allocator &allocator_;
/// ID of the buffer in the SourceErrorManager.
uint32_t bufId_;
/// When operating without an external StringTable, store own own copy
/// here.
std::unique_ptr<StringTable> ownStrTab_;
StringTable &strTab_;
bool strictMode_;
/// If true, when a surrogate pair sequence is encountered in a string literal
/// in the source, convert that string literal to its canonical UTF-8
/// sequence.
bool convertSurrogates_;
Token token_;
const char *bufferStart_;
const char *curCharPtr_;
const char *bufferEnd_;
bool newLineBeforeCurrentToken_ = false;
llvm::SmallString<256> tmpStorage_;
/// Storage used for the Template Raw Value when scanning template literals.
llvm::SmallString<256> rawStorage_;
/// Pre-allocated identifiers for all reserved words.
UniqueString *resWordIdent_
[ord(TokenKind::_last_resword) - ord(TokenKind::_first_resword) + 1];
UniqueString *&resWordIdent(TokenKind kind) {
assert(
kind >= TokenKind::_first_resword && kind <= TokenKind::_last_resword);
return resWordIdent_[ord(kind) - ord(TokenKind::_first_resword)];
}
public:
/// \param convertSurrogates See member variable \p convertSurrogates_.
explicit JSLexer(
std::unique_ptr<llvm::MemoryBuffer> input,
SourceErrorManager &sm,
Allocator &allocator,
StringTable *strTab = nullptr,
bool strictMode = true,
bool convertSurrogates = false);
/// \param convertSurrogates See member variable \p convertSurrogates_.
explicit JSLexer(
uint32_t bufId,
SourceErrorManager &sm,
Allocator &allocator,
StringTable *strTab = nullptr,
bool strictMode = true,
bool convertSurrogates = false);
/// \param convertSurrogates See member variable \p convertSurrogates_.
JSLexer(
StringRef input,
SourceErrorManager &sm,
Allocator &allocator,
StringTable *strTab = nullptr,
bool strictMode = true,
bool convertSurrogates = false)
: JSLexer(
llvm::MemoryBuffer::getMemBuffer(input, "JavaScript"),
sm,
allocator,
strTab,
strictMode,
convertSurrogates) {}
/// \param convertSurrogates See member variable \p convertSurrogates_.
JSLexer(
llvm::MemoryBufferRef input,
SourceErrorManager &sm,
Allocator &allocator,
StringTable *strTab = nullptr,
bool strictMode = true,
bool convertSurrogates = false)
: JSLexer(
llvm::MemoryBuffer::getMemBuffer(input),
sm,
allocator,
strTab,
strictMode,
convertSurrogates) {}
SourceErrorManager &getSourceMgr() {
return sm_;
}
Allocator &getAllocator() {
return allocator_;
}
StringTable &getStringTable() {
return strTab_;
}
bool isStrictMode() const {
return strictMode_;
}
void setStrictMode(bool strictMode) {
strictMode_ = strictMode;
}
/// \return true if a line terminator was consumed before the current token.
///
/// The caller can use that information to make decisions about inserting
/// missing semicolons.
bool isNewLineBeforeCurrentToken() const {
return newLineBeforeCurrentToken_;
}
/// \return the current token.
const Token *getCurToken() const {
return &token_;
}
/// \return the current char pointer location.
SMLoc getCurLoc() const {
return SMLoc::getFromPointer(curCharPtr_);
}
/// Force an EOF at the next token.
void forceEOF() {
curCharPtr_ = bufferEnd_;
}
/// Grammar context to be passed to advance().
/// - AllowRegExp: RegExp can follow
/// - AllowDiv: "/" can follow
/// - AllowJSXIdentifier: "/" can follow, "-" is part of identifiers,
/// ">" is scanned as its own token.
/// - Flow: "/" can follow and ">>" scans as two separate ">" tokens.
enum GrammarContext { AllowRegExp, AllowDiv, AllowJSXIdentifier, Flow };
/// Consume the current token and scan the next one, which becomes the new
/// current token. All whitespace is skipped befire the new token and if
/// a line terminator was encountered, the newLineBefireCurrentToken_ flag is
/// set.
/// \param grammarContext determines "/", "/=", regexp, and JSX identifiers.
const Token *advance(GrammarContext grammarContext = AllowRegExp);
/// Consume the current token and scan a new one inside a JSX child.
/// This scans JSXText or one of the punctuators: {, <, >, }.
const Token *advanceInJSXChild();
/// Check whether the current token is a directive, in other words is it a
/// string literal without escapes or new line continuations, followed by
/// either new line, semicolon or right brace.
/// This doesn't move the input pointer, so the optional semicolon, brace
/// or the new line will be consumed normally by the next \c advance() call.
///
/// \return true if the token can be interpreted as a directive.
bool isCurrentTokenADirective();
/// Rescan the } token as a TemplateMiddle or TemplateTail.
/// Should be called in the middle of parsing a template literal.
const Token *rescanRBraceInTemplateLiteral();
/// Skip over any non-line-terminator whitespace and return the kind of
/// the next token if there was no LineTerminator before it.
/// Does not report any error messages during lookahead.
/// For example, this is used to determine whether we're in the
/// async [no LineTerminator here] function
/// ^
/// or the
/// async [no LineTerminator here] ArrowFormalParameters
/// ^
/// case for parsing async functions and arrow functions.
/// \pre current token is an identifier or reserved word.
/// \param expectedToken if not None, then if the next token is expectedToken,
/// the next token is scanned and the curCharPtr_ isn't reset.
/// \return the kind of next token if there was no LineTerminator,
/// otherwise return None.
OptValue<TokenKind> lookahead1(OptValue<TokenKind> expectedToken);
UniqueString *getIdentifier(StringRef name) {
return strTab_.getString(name);
}
UniqueString *getStringLiteral(StringRef str) {
if (LLVM_UNLIKELY(convertSurrogates_)) {
return convertSurrogatesInString(str);
}
return strTab_.getString(str);
}
/// Move the lexer to the specific spot. Any future \p advance calls
/// will start from this position (the current token is not updated until
/// such a call).
void seek(SMLoc loc) {
curCharPtr_ = loc.getPointer();
}
/// Get the source buffer id we're currently parsing.
uint32_t getBufferId() {
return bufId_;
}
/// \return a pointer to the beginning of the buffer.
const char *getBufferStart() const {
return bufferStart_;
}
/// \return a pointer to the end of the buffer.
const char *getBufferEnd() const {
return bufferEnd_;
}
/// Store state of the lexer and allow rescanning from that point.
/// Can only save state when the current token is a punctuator or
/// TokenKind::identifier.
class SavePoint {
JSLexer *const lexer_;
/// Saved token kind, must be a punctuator.
TokenKind kind_;
/// Saved identifier, nullptr if kind_ != identifier.
UniqueString *ident_;
/// Saved curCharPtr_ from the lexer.
SMLoc loc_;
public:
SavePoint(JSLexer *lexer)
: lexer_(lexer),
kind_(lexer_->getCurToken()->getKind()),
ident_(
kind_ == TokenKind::identifier
? lexer_->getCurToken()->getIdentifier()
: nullptr),
loc_(lexer_->getCurLoc()) {
assert(
(isPunctuatorDbg(kind_) || kind_ == TokenKind::identifier) &&
"SavePoint can only be used for punctuators");
}
/// Restore the state of the lexer to the originally saved state.
void restore() {
if (kind_ == TokenKind::identifier) {
lexer_->unsafeSetIdentifier(ident_, loc_);
} else {
lexer_->unsafeSetPunctuator(kind_, loc_);
}
}
};
private:
/// Initialize the storage with the characters between \p begin and \p end.
inline void initStorageWith(const char *begin, const char *end);
/// Encode a Unicode codepoint into a UTF8 sequence and append it to \p
/// storage. Code points above 0xFFFF are encoded into UTF16, and the
/// resulting surrogate pair values are encoded individually into UTF8.
static inline void appendUnicodeToStorage(
uint32_t cp,
llvm::SmallVectorImpl<char> &storage);
/// Encode a Unicode codepoint into a UTF8 sequence and append it to \ref
/// tmpStorage_. Code points above 0xFFFF are encoded into UTF16, and the
/// resulting surrogate pair values are encoded individually into UTF8.
inline void appendUnicodeToStorage(uint32_t cp) {
appendUnicodeToStorage(cp, tmpStorage_);
}
/// Decode a UTF8 sequence, advancing the current pointer and reporting
/// errors.
inline uint32_t decodeUTF8();
/// Decode a UTF8 sequence when it is already known that it is not ASCII.
/// In other words, isUTF8Start(*at) == true
/// \param at points to the sequence and is incremented past it.
inline uint32_t _decodeUTF8SlowPath(const char *&at);
/// Decode a UTF8 sequence at the specified address \p at without
/// reporting errors.
///
/// The caller must have already ensured that the first byte is not ASCII.
/// The caller can verify the decoded value and optionally update the current
/// pointer.
///
/// \return the decoded value and the incremented pointer
inline std::pair<uint32_t, const char *> _peekUTF8(const char *at) const;
/// Decode a UTF8 sequence without advancing the current pointer and without
/// reporting errors.
///
/// The caller must have already ensured that the first byte is not ASCII.
/// The caller can verify the decoded value and optionally update the current
/// pointer.
///
/// \return the decoded value and the incremented current pointer
inline std::pair<uint32_t, const char *> _peekUTF8() const;
static inline bool isUnicodeIdentifierStart(uint32_t ch);
static inline bool isUnicodeIdentifierPart(uint32_t ch);
/// Decode a unicode escape sequence in the form "\uXXXX".
///
/// \ref curCharPtr_ must point to the backslash of the escape. It will be
/// updated to point to the first character after the escape.
uint32_t consumeUnicodeEscape();
/// Decode a unicode escape sequence in the form "\uXXXX".
/// Does not report any errors.
///
/// \ref curCharPtr_ must point to the backslash of the escape. It will be
/// updated to point to the first character after the escape.
/// On failure, curCharPtr_ will be reset to where it was when the function
/// was called.
/// \return the resultant code point on success, None on error.
llvm::Optional<uint32_t> consumeUnicodeEscapeOptional();
/// Specify the types of identifiers which should be allowed when consuming
/// identifiers.
enum class IdentifierMode {
/// Standard JavaScript identifiers only.
JS,
/// JavaScript identifiers and '-'.
JSX,
/// JavaScript identifiers and identifiers which begin with '@'.
Flow,
};
/// Decode an IdentifierStart production per ES5.1 7.6.
/// \return whether an IdentifierStart was successfully decoded.
bool consumeIdentifierStart();
/// Decode a sequence (possibly empty) of IdentifierPart.
template <IdentifierMode Mode>
void consumeIdentifierParts();
/// Decode an IdentifierPart per ES5.1 7.6 that does not begin with a
/// backslash.
/// \return true if an IdentifierPart was decoded, false if the current
/// character was a backslash or not an IdentifierPart.
template <IdentifierMode Mode>
bool consumeOneIdentifierPartNoEscape();
/// Scan an octal number after the first character has been recognized
/// (but not consumed yet). \p maxLen is the maximum length including the
/// first character.
unsigned char consumeOctal(unsigned maxLen);
/// Scan a hex number after the first character has been recognized but not
/// consumed.
/// \param requiredLen is the number of digits in the hex literal.
/// \param errorOnFail if true, report an error on failing to recognize a hex
/// number.
llvm::Optional<uint32_t> consumeHex(
unsigned requiredLen,
bool errorOnFail = true);
/// Scan a hex number inside the braces in \u{CodePoint}.
/// \param errorOnFail whether to report error on failure.
/// \ref curCharPtr_ must point to the opening { of the escape, and will
/// be updated to point after the closing }.
/// \return the resultant number on success, None on failure.
llvm::Optional<uint32_t> consumeBracedCodePoint(bool errorOnFail = true);
/// Skip until after the end of the line terminaing the block comment.
/// \return the updated source pointer.
const char *skipLineComment(const char *start);
/// Skip until after the end of the block comment.
/// \return the updated source pointer.
const char *skipBlockComment(const char *start);
/// Try to read a "magic comment" of the form `//# name=value` at \p ptr.
/// \return the value encoded in the comment if found, None otherwise.
llvm::Optional<StringRef> tryReadMagicComment(
llvm::StringRef name,
const char *ptr);
void scanNumber();
/// Recognise a reserved word depending on the mode (strict vs non-strict).
/// \return \c TokenKind::identifier if the word wasn't recognized, or the
/// \c TokenKind of the word otherwise.
TokenKind scanReservedWord(const char *start, unsigned length);
/// Attempt to scan an identifier with the assumption that there are no
/// Unicode escapes or UTF-8 characters, meaning that there is no neet to copy
/// it into a temporary buffer. If an escape or UTF-8 character is
/// encountered, add the currently scanned part to the storage and continue by
/// invoking the slow path scanIdentifierParts().
template <IdentifierMode Mode>
void scanIdentifierFastPath(const char *start);
void scanIdentifierFastPathInContext(
const char *start,
GrammarContext grammarContext) {
if (HERMES_PARSE_JSX &&
LLVM_UNLIKELY(grammarContext == GrammarContext::AllowJSXIdentifier)) {
scanIdentifierFastPath<IdentifierMode::JSX>(start);
} else if (
HERMES_PARSE_FLOW &&
LLVM_UNLIKELY(grammarContext == GrammarContext::Flow)) {
scanIdentifierFastPath<IdentifierMode::Flow>(start);
} else {
scanIdentifierFastPath<IdentifierMode::JS>(start);
}
}
template <IdentifierMode Mode>
void scanIdentifierParts();
void scanIdentifierPartsInContext(GrammarContext grammarContext) {
if (HERMES_PARSE_JSX &&
LLVM_UNLIKELY(grammarContext == GrammarContext::AllowJSXIdentifier)) {
scanIdentifierParts<IdentifierMode::JSX>();
} else if (
HERMES_PARSE_FLOW &&
LLVM_UNLIKELY(grammarContext == GrammarContext::Flow)) {
scanIdentifierParts<IdentifierMode::Flow>();
} else {
scanIdentifierParts<IdentifierMode::JS>();
}
}
template <bool JSX>
void scanString();
void scanStringInContext(GrammarContext grammarContext) {
#if HERMES_PARSE_JSX
LLVM_UNLIKELY(grammarContext == GrammarContext::AllowJSXIdentifier)
? scanString<true>() :
#endif
scanString<false>();
}
void scanRegExp();
/// Attempt to scan a template literal starting at ` or at }.
void scanTemplateLiteral();
/// Convert the surrogates into \p str into a valid UTF-8 sequence, and unique
/// it into the string table.
UniqueString *convertSurrogatesInString(StringRef str);
/// Set the current token kind to \p kind without any checks and seek to
/// \p loc.
/// Should only be used for save point use-cases.
void unsafeSetPunctuator(TokenKind kind, SMLoc loc) {
assert(isPunctuatorDbg(kind) && "must set a punctuator");
token_.setPunctuator(kind);
seek(loc);
}
/// Set the current token kind to \p kind without any checks and seek to
/// \p loc.
/// Should only be used for save point use-cases.
void unsafeSetIdentifier(UniqueString *ident, SMLoc loc) {
token_.setIdentifier(ident);
seek(loc);
}
/// Initialize the parser for a given source buffer id.
void initializeWithBufferId(uint32_t bufId);
/// Create/lookup identifiers for all reserved words used during parsing.
void initializeReservedIdentifiers();
/// Report an error for the range from startLoc to curCharPtr.
bool errorRange(SMLoc startLoc, const llvm::Twine &msg) {
return error({startLoc, SMLoc::getFromPointer(curCharPtr_)}, msg);
}
/// Report an error using the current token's location.
bool error(const llvm::Twine &msg) {
return error(token_.getSourceRange(), msg);
}
/// Emit an error at the specified source location. If the maximum number of
/// errors has been reached, return false and move the scanning pointer to
/// EOF.
/// \return false if too many errors have been emitted and we need to abort.
bool error(SMLoc loc, const llvm::Twine &msg);
/// Emit an error at the specified source range. If the maximum number of
/// errors has been reached, return false and move the scanning pointer to
/// EOF.
/// \return false if too many errors have been emitted and we need to abort.
bool error(SMRange range, const llvm::Twine &msg);
/// Emit an error at the specified source location and range. If the maximum
/// number of errors has been reached, return false and move the scanning
/// pointer to EOF.
/// \return false if too many errors have been emitted and we need to abort.
bool error(SMLoc loc, SMRange range, const llvm::Twine &msg);
};
inline void JSLexer::initStorageWith(const char *begin, const char *end) {
tmpStorage_.clear();
tmpStorage_.append(begin, end);
}
inline void JSLexer::appendUnicodeToStorage(
uint32_t cp,
llvm::SmallVectorImpl<char> &storage) {
// Sized to allow for two 16-bit values to be encoded.
// A 16-bit value takes up to three bytes encoded in UTF-8.
char buf[8];
char *d = buf;
// We need to normalize code points which would be encoded with a surrogate
// pair. Note that this produces technically invalid UTF-8.
if (LLVM_LIKELY(cp < 0x10000)) {
hermes::encodeUTF8(d, cp);
} else {
assert(cp <= UNICODE_MAX_VALUE && "invalid Unicode value");
cp -= 0x10000;
hermes::encodeUTF8(d, UTF16_HIGH_SURROGATE + ((cp >> 10) & 0x3FF));
hermes::encodeUTF8(d, UTF16_LOW_SURROGATE + (cp & 0x3FF));
}
storage.append(buf, d);
}
inline uint32_t JSLexer::decodeUTF8() {
const char *saveStart = curCharPtr_;
return hermes::decodeUTF8<false>(curCharPtr_, [=](const Twine &msg) {
error(SMLoc::getFromPointer(saveStart), msg);
});
}
inline uint32_t JSLexer::_decodeUTF8SlowPath(const char *&at) {
return hermes::_decodeUTF8SlowPath<false>(
at, [=](const Twine &msg) { error(SMLoc::getFromPointer(at), msg); });
}
inline std::pair<uint32_t, const char *> JSLexer::_peekUTF8(
const char *at) const {
uint32_t ch =
hermes::_decodeUTF8SlowPath<false>(at, [](const llvm::Twine &) {});
return std::make_pair(ch, at);
}
inline std::pair<uint32_t, const char *> JSLexer::_peekUTF8() const {
return _peekUTF8(curCharPtr_);
}
inline bool JSLexer::isUnicodeIdentifierStart(uint32_t ch) {
return ch == '_' || ch == '$' || ((ch | 32) >= 'a' && (ch | 32) <= 'z') ||
isUnicodeOnlyLetter(ch);
}
inline bool JSLexer::isUnicodeIdentifierPart(uint32_t ch) {
// TODO: clearly this has to be optimized somehow
return isUnicodeIdentifierStart(ch) || isUnicodeCombiningMark(ch) ||
isUnicodeDigit(ch) || isUnicodeConnectorPunctuation(ch) ||
ch == UNICODE_ZWNJ || ch == UNICODE_ZWJ;
}
} // namespace parser
} // namespace hermes
#endif // HERMES_PARSER_JSLEXER_H
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
7d7996c12d51bc081bf103b5bc0faa69fe403d1b | 42ba73134eeca961230044e4cef29a5fc35e3529 | /TktkDirectX12GameLib/_Test3DActionGame/src/GameObject/MainSceneObjects/PlayerObjects/Player/Scripts/Act3D_PlayerController.h | d78d584e9663203306c8cacc3d8de3df2fb09abe | [] | no_license | tktk2104/TktkDirectX12GameLib | 5b9ef672ce0a99bbce8a156751b423ef840729b3 | 4d037ec603d9f30d8c4ed3fb4474cfaea49c8ac9 | refs/heads/master | 2023-02-22T14:38:10.101382 | 2020-12-03T04:55:05 | 2020-12-03T04:55:05 | 287,092,170 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 844 | h | #ifndef ACT_3D_PLAYER_CONTROLLER_H_
#define ACT_3D_PLAYER_CONTROLLER_H_
#include <TktkDX12GameLib.h>
// プレイヤーを移動、回転させるコンポーネント
class Act3D_PlayerController
: public tktk::ComponentBase
{
public:
Act3D_PlayerController(float moveSpeedPerSec, float rotateDegSpeedPerSec);
public:
void start();
void update();
void handleMessage(tktk::MessageTypeCarrier type, const tktk::MessageAttachment& attachment);
private:
// 移動処理
void move();
// 回転処理
void rotate();
// 最も近い敵の方に向く
void lookMostNearEnemy();
private:
// 毎秒の移動速度
float m_moveSpeedPerSec;
// 毎秒の回転速度
float m_rotateDegSpeedPerSec;
// 座標管理コンポーネント
tktk::ComponentPtr<tktk::Transform3D> m_transform;
};
#endif // !ACT_3D_PLAYER_CONTROLLER_H_ | [
"taka.lalpedhuez@2104.gmail.com"
] | taka.lalpedhuez@2104.gmail.com |
39b3aa165e3daf5a3d5e0915bf333fc24eb93b44 | 52f86e1b8e082405bb501341abf6b98ccceb5701 | /src/lib/core/container/dict.h | 396f43d8a485ea26ac56ba0d5c2114a77e77f324 | [] | no_license | esrever/pagan | 367dcce63df9e4ca73d018f24783776df0693bb4 | eb8dfeeeaa127114b79d41b72855d6e7fcbf463b | refs/heads/master | 2020-03-31T09:11:32.566241 | 2014-04-01T15:12:20 | 2014-04-01T15:12:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,715 | h | #pragma once
#include <iostream>
#include <functional>
#include <map>
#include <string>
#include <typeinfo>
#include <typeindex>
#include <cassert>
namespace pgn
{
//! stores functions for allocation/deletion of arbitrary objects
struct cObjectMemoryMan
{
typedef std::function<void( void *&)> func_del;
typedef std::function< void* (const void *)> func_alloc;
template<class T>
static cObjectMemoryMan Create()
{
cObjectMemoryMan outp;
outp.mAllocator = [](const void* p){ return (void *)(new T(*(T *)p)); };
outp.mDeleter = [](void *& p){ delete (T *&)p; p = nullptr; };
return outp;
}
func_del mDeleter;
func_alloc mAllocator;
};
struct cObjectMap
{
typedef std::string key_type;
typedef void * value_type;
typedef std::map< key_type, value_type> map_type;
typedef std::pair<map_type, cObjectMemoryMan> map_and_man_type;
cObjectMap(){}
cObjectMap(const cObjectMap&){ assert(mData.first.empty()); }
~cObjectMap()
{
for (auto& v : mData.first)
mData.second.mDeleter(v.second);
}
template<class T>
T * Get(const std::string& name)
{
auto iter = mData.first.find(name);
return (iter == mData.first.end()) ? nullptr : (T *)iter->second;
}
map_and_man_type mData;
private:
cObjectMap& operator = (const cObjectMap&) {}
};
//! TODO: how to copy/clone dicts around? allow it or not? if yes, the logic should clearly be in ObjectMap
class cDict
{
public:
typedef std::string key_type;
typedef void * value_type;
typedef std::map< key_type, value_type> map_type;
typedef std::pair<map_type, cObjectMemoryMan> map_and_man_type;
cDict(){}
cDict(const cDict& d){}
cDict& operator = (const cDict& d){ return *this; }
/**
* Gets a value of the given type, if not found return nullptr
* @name key key name
*/
template<class T>
T * Get(const std::string& name)
{
const auto& ti = typeid(T);
auto iter = mPerTypeData.find(ti);
if (iter == mPerTypeData.end())
return nullptr;
else
return iter->second.Get<T>(name);
}
/**
* Inserts a new value at the given key
* @name key key name
* @name value value
*/
template<class T>
void Insert(const std::string& name, const T& value)
{
const auto& ti = typeid(value);
auto iter = mPerTypeData.find(ti);
map_and_man_type * valp;
if (iter == mPerTypeData.end())
{
auto& ref = mPerTypeData[ti];
ref.mData.second = cObjectMemoryMan::Create<T>();
valp = &ref.mData;
}
else
valp = &iter->second.mData;
// get map/man pair
auto& val = *valp;
void * vptr = (void *)&value;
void * newobj = val.second.mAllocator(vptr);
val.first.insert(std::make_pair(name, newobj));
}
/**
* Erases a value in a given key
* @name key key name
*/
template<class T>
void Erase(const std::string& name)
{
const auto& ti = typeid(T);
auto iter = mPerTypeData.find(ti);
if (iter != mPerTypeData.end())
{
auto& submap = iter->second.mData;
auto iter2 = submap.first.find(name);
if (iter2 != submap.first.end())
{
submap.second.mDeleter(iter2->second);
submap.first.erase(iter2);
}
}
}
/**
* Applies a function to the key-value pairs of a given type
* @name func a function with the signature void(const string&, const T&)
*/
template<class T>
void Visit(std::function<void(const std::string& key, const T& val)> func)
{
const auto& submap = mPerTypeData[typeid(T)];
for (const auto& kv : submap.mData.first)
{
func(kv.first, *(T *)kv.second);
}
}
private:
std::map<std::type_index, cObjectMap> mPerTypeData;
};
}
| [
"esrever2357@gmail.com"
] | esrever2357@gmail.com |
43533f8f5cce31cc8bf0c265c0a851b364745189 | 6c6d806b7d432d3763b5da6ef76075d738abb35a | /apps/cafeteria/supplierform.cpp | dfb0eb3cad1e74ca5df5e00a00a22abde42398f1 | [] | no_license | lpxxn/mytestmc | bdf27fd7c4586483d6e7c79802f71bb01ed01712 | 6d4deb25ac0c51d37bf7247d85c31ad32173be44 | refs/heads/master | 2020-08-28T11:31:40.592124 | 2019-11-11T08:49:08 | 2019-11-11T08:49:08 | 217,686,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,073 | cpp | #include "supplierform.h"
#include "ui_supplierform.h"
#include <QLabel>
#include <QDockWidget>
#include <QPushButton>
#include <QVBoxLayout>
void SupplierForm::addButtons(FlowLayout &layout) {
QPushButton *pb2 = new QPushButton("b");
pb2->setMinimumWidth(100);
pb2->setMinimumHeight(80);
layout.addWidget(pb2);
}
SupplierForm::SupplierForm(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::SupplierForm)
{
ui->setupUi(this);
this->setWindowFlag(Qt::Window);
this->setWindowModality(Qt::WindowModal);
if (parent == nullptr) {
this->setAttribute(Qt::WA_DeleteOnClose, true);
}
//this->centralWidget()->hide();
this->setCentralWidget(nullptr);
this->setDockNestingEnabled(true);
leftDock = new QDockWidget(QLatin1String("Left"), this);
QWidget* multiWidget = new QWidget(this);
//multiWidget->setMaximumWidth(110);
FlowLayout* layout = new FlowLayout;
QPushButton *pb = new QPushButton("a");
pb->setMinimumWidth(100);
pb->setMinimumHeight(80);
connect(pb, &QPushButton::clicked, this, &SupplierForm::leftDockWidgetReset);
layout->addWidget(pb);
addButtons(*layout);
addButtons(*layout);
addButtons(*layout);
multiWidget->setLayout(layout);
leftDock->setWidget(multiWidget);
//dock->setFeatures(QDockWidget::NoDockWidgetFeatures);
//dock->setAllowedAreas(Qt::NoDockWidgetArea);
//leftDock->setAllowedAreas(Qt::LeftDockWidgetArea);
addDockWidget(Qt::LeftDockWidgetArea, leftDock);
addNewDock();
addNewDock();
addNewDock();
}
SupplierForm::~SupplierForm()
{
delete ui;
}
void SupplierForm::on_btnAddDock_clicked()
{
addNewDock();
}
void SupplierForm::leftDockWidgetReset()
{
this->leftDock->setFloating(false);
//this->restoreDockWidget(this->leftDock);
}
void SupplierForm::addNewDock()
{
QDockWidget *dock = new QDockWidget(QLatin1String("Last filters"), this);
QWidget* multiWidget = new QWidget();
QVBoxLayout* layout = new QVBoxLayout();
QPushButton* filter1 = new QPushButton(QLatin1String("Filter number 1"));
QPushButton* filter2 = new QPushButton(QLatin1String("Filter number 2"));
QPushButton* filter3 = new QPushButton(QLatin1String("Filter number 3"));
QPushButton* filter4 = new QPushButton(QLatin1String("Filter number 4"));
QPushButton* filter5 = new QPushButton(QLatin1String("Filter number 5"));
QLabel* label = new QLabel(QLatin1String("QPushButtons"));
layout->addWidget(filter1);
layout->addWidget(filter2);
layout->addWidget(filter3);
layout->addWidget(filter4);
layout->addWidget(filter5);
layout->addWidget(label);
multiWidget->setLayout(layout);
dock->setWidget(multiWidget);
//dock->setFeatures(QDockWidget::AllDockWidgetFeatures);//设置此窗体所有特性--可关闭,可移动,可浮动
dock->setAllowedAreas(Qt::AllDockWidgetAreas);
//dock->setAllowedAreas(Qt::TopDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
addDockWidget(Qt::RightDockWidgetArea, dock);
}
| [
"mi_duo@live.com"
] | mi_duo@live.com |
dfc6af6a0d39408d8b460a1ad565d978c3dc90c2 | 5403de3ab2a43726326d000b6d9000a422b5b243 | /a2/a2test/BigQ.h | 202b3681ff693982c1d324a02435bf3f25dcf925 | [] | no_license | daniellu789/Database_System_Implementation | 529b4a249f1e22773ed5e1a238ccda9caf9c91bc | 3e249e11a6362d975e739f6e0df8c12c5b1b7ff2 | refs/heads/master | 2021-01-10T22:05:26.170913 | 2014-04-14T23:07:35 | 2014-04-14T23:07:35 | 18,341,838 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,541 | h | #ifndef BIGQ_H
#define BIGQ_H
#include <pthread.h>
#include <iostream>
#include "Pipe.h"
#include "File.h"
#include "Record.h"
#include "Comparison.h"
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
class BigQ {
private:
char *tmpFile;
File tempFile;
vector<int> runIndex;
int pageNum;
public:
BigQ(Pipe &in, Pipe &out, OrderMaker &sortorder, int runlength);
~BigQ();
};
struct mergePQRec
{
Record mRec;
int noofrun;
};
class myComp
{
private:
OrderMaker* sortOrder;
public:
myComp(OrderMaker *sortorder)
{
sortOrder = sortorder;
}
bool operator()(Record* left,Record* right)
{
ComparisonEngine comparisonEngine;
if(comparisonEngine.Compare(left,right,sortOrder)<0)
return false;
else
return true;
}
};
class myCompPQ
{
private:
OrderMaker* sortOrder;
public:
myCompPQ(OrderMaker *sortorder)
{
sortOrder = sortorder;
}
bool operator()(mergePQRec *leftRecord, mergePQRec *rightRecord)
{
ComparisonEngine comparisonEngine;
if(comparisonEngine.Compare(&(leftRecord->mRec), &(rightRecord->mRec), sortOrder)<=0)
return false;
else
return true;
}
};
#endif
| [
"daniellu789@gmail.com"
] | daniellu789@gmail.com |
2805e16f5f31e82c3c26ae8e934b8fcada26e54a | cea06455dfda7ec875232eeac68b4c27af7b3e2f | /rosplan_tiago_active_human_fall_prevention/src/RPHumanApproachDetect.cpp | 5130b6f9f53a580da2666d32f52d2aeaf5d8e689 | [
"MIT"
] | permissive | RCPRG-ros-pkg/rosplan_interface_tiago | 33682259e525180383748f31a20e64db6cea228f | 380dee7019c35902133061bd2e049cde0afe7c6d | refs/heads/master | 2020-09-20T06:34:17.580904 | 2019-09-19T02:26:42 | 2019-09-19T02:26:42 | 224,400,688 | 0 | 0 | MIT | 2019-11-27T10:05:17 | 2019-11-27T10:05:17 | null | UTF-8 | C++ | false | false | 1,710 | cpp | #include "RPHumanApproachDetect.h"
/* The implementation of RPTutorial.h */
namespace KCL_rosplan {
/* constructor */
RPHumanApproachDetect::RPHumanApproachDetect(ros::NodeHandle &nh) {
// perform setup
node_name = ros::this_node::getName();
node_name_pretty = '(' + node_name + ')';
}
/* action dispatch callback */
bool RPHumanApproachDetect::concreteCallback(const rosplan_dispatch_msgs::ActionDispatch::ConstPtr& msg) {
// The action implementation goes here.
// Get action parameters
auto action_parameters = msg.get()->parameters;
auto action_duration_s = msg.get()->duration;
auto action_real_duration_s = action_duration_s + ACTION_ADDITION_TIME_S;
action_client.waitForServer();
rosplan_tiago_active_human_fall_prevention::HumanApproachDetectGoal goal;
// Fill in goal here
goal.dummy_goal = 500;
action_client.sendGoal(goal);
action_client.waitForResult(ros::Duration(action_real_duration_s));
if (action_client.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) {
}
// complete the action
ROS_INFO("%s: HUMANAPPROACHDETECT Action completing", node_name_pretty.c_str());
return true;
}
} // close namespace
/*-------------*/
/* Main method */
/*-------------*/
int main(int argc, char **argv) {
ros::init(argc, argv, "rosplan_human_approach_detect_action_client", ros::init_options::AnonymousName);
ros::NodeHandle nh("~");
// create action client here?
// create PDDL action subscriber
KCL_rosplan::RPHumanApproachDetect rpti(nh);
rpti.runActionInterface();
return 0;
}
| [
"lzielinski66@gmail.com"
] | lzielinski66@gmail.com |
ebc219eab6155090f4ca4d1a19d585106cc5f4c3 | 25f8a4d8841af2b6b5107cc1d1488a99d02dea86 | /Jungol/555-array1.cpp | bda47905323fec42759a77df1c29fbe79e91402c | [] | no_license | SooDevv/Algorithm_Training | 3a5b771a68c7ccd06487cb157a94ea2bf2b2a049 | a7d19604af0c1d8594210236e10a2c1ad1110521 | refs/heads/master | 2021-06-20T09:21:13.672098 | 2019-07-20T06:32:16 | 2019-07-20T06:32:16 | 138,552,790 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 164 | cpp | #include <iostream>
using namespace std;
int main(){
char s[10];
for(int i=0; i<10; i++){
cin >> s[i];
}
for(int i=0; i<10; i++){
cout << s[i];
}
}
| [
"julieline@naver.com"
] | julieline@naver.com |
97fc047fa3311fc060cfd82b3908df2d81ec9411 | 9218887dd7a67815d927c18ee8106f52199e50aa | /iOS_app/Classes/Native/mscorlib_System_Collections_Generic_Dictionary_2_E3250803816.h | b869217d8a315e09b5066a545120fbd38df39099 | [
"Apache-2.0"
] | permissive | Bersaelor/D2 | 63cd10f47ec468000d299775dbfbdcfb02632add | 630297a7f634b2a5fe5c8fba007d587b948d36f6 | refs/heads/master | 2021-05-04T08:19:47.072397 | 2019-07-09T18:55:00 | 2019-07-09T18:55:00 | 70,339,035 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,867 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.Collections.Generic.Dictionary`2<System.String,UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager/VirtualButton>
struct Dictionary_2_t1933480424;
#include "mscorlib_System_ValueType1744280289.h"
#include "mscorlib_System_Collections_Generic_KeyValuePair_21832261130.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.Dictionary`2/Enumerator<System.String,UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager/VirtualButton>
struct Enumerator_t3250803816
{
public:
// System.Collections.Generic.Dictionary`2<TKey,TValue> System.Collections.Generic.Dictionary`2/Enumerator::dictionary
Dictionary_2_t1933480424 * ___dictionary_0;
// System.Int32 System.Collections.Generic.Dictionary`2/Enumerator::next
int32_t ___next_1;
// System.Int32 System.Collections.Generic.Dictionary`2/Enumerator::stamp
int32_t ___stamp_2;
// System.Collections.Generic.KeyValuePair`2<TKey,TValue> System.Collections.Generic.Dictionary`2/Enumerator::current
KeyValuePair_2_t1832261130 ___current_3;
public:
inline static int32_t get_offset_of_dictionary_0() { return static_cast<int32_t>(offsetof(Enumerator_t3250803816, ___dictionary_0)); }
inline Dictionary_2_t1933480424 * get_dictionary_0() const { return ___dictionary_0; }
inline Dictionary_2_t1933480424 ** get_address_of_dictionary_0() { return &___dictionary_0; }
inline void set_dictionary_0(Dictionary_2_t1933480424 * value)
{
___dictionary_0 = value;
Il2CppCodeGenWriteBarrier(&___dictionary_0, value);
}
inline static int32_t get_offset_of_next_1() { return static_cast<int32_t>(offsetof(Enumerator_t3250803816, ___next_1)); }
inline int32_t get_next_1() const { return ___next_1; }
inline int32_t* get_address_of_next_1() { return &___next_1; }
inline void set_next_1(int32_t value)
{
___next_1 = value;
}
inline static int32_t get_offset_of_stamp_2() { return static_cast<int32_t>(offsetof(Enumerator_t3250803816, ___stamp_2)); }
inline int32_t get_stamp_2() const { return ___stamp_2; }
inline int32_t* get_address_of_stamp_2() { return &___stamp_2; }
inline void set_stamp_2(int32_t value)
{
___stamp_2 = value;
}
inline static int32_t get_offset_of_current_3() { return static_cast<int32_t>(offsetof(Enumerator_t3250803816, ___current_3)); }
inline KeyValuePair_2_t1832261130 get_current_3() const { return ___current_3; }
inline KeyValuePair_2_t1832261130 * get_address_of_current_3() { return &___current_3; }
inline void set_current_3(KeyValuePair_2_t1832261130 value)
{
___current_3 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"K_W_F@web.de"
] | K_W_F@web.de |
24095484de7335875f9f8bf9b9c64462b65d0aac | f23fea7b41150cc5037ddf86cd7a83a4a225b68b | /SDK/BP_PromptActor_EmissaryRank2_MA_parameters.h | fd06233214f96ff7d797b16b22650e6bbbd44728 | [] | no_license | zH4x/SoT-SDK-2.2.0.1 | 36e1cf7f23ece6e6b45e5885f01ec7e9cd50625e | f2464e2e733637b9fa0075cde6adb5ed2be8cdbd | refs/heads/main | 2023-06-06T04:21:06.057614 | 2021-06-27T22:12:34 | 2021-06-27T22:12:34 | 380,845,087 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,462 | h | #pragma once
// Name: SoT, Version: 2.2.0b
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function BP_PromptActor_EmissaryRank2_MA.BP_PromptActor_EmissaryRank2_MA_C.UserConstructionScript
struct ABP_PromptActor_EmissaryRank2_MA_C_UserConstructionScript_Params
{
};
// Function BP_PromptActor_EmissaryRank2_MA.BP_PromptActor_EmissaryRank2_MA_C.ReceiveBeginPlay
struct ABP_PromptActor_EmissaryRank2_MA_C_ReceiveBeginPlay_Params
{
};
// Function BP_PromptActor_EmissaryRank2_MA.BP_PromptActor_EmissaryRank2_MA_C.ReceiveEndPlay
struct ABP_PromptActor_EmissaryRank2_MA_C_ReceiveEndPlay_Params
{
TEnumAsByte<Engine_EEndPlayReason> EndPlayReason; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function BP_PromptActor_EmissaryRank2_MA.BP_PromptActor_EmissaryRank2_MA_C.ExecuteUbergraph_BP_PromptActor_EmissaryRank2_MA
struct ABP_PromptActor_EmissaryRank2_MA_C_ExecuteUbergraph_BP_PromptActor_EmissaryRank2_MA_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"Massimo.linker@gmail.com"
] | Massimo.linker@gmail.com |
4b48e04d5380229434598d2fd2b5848ee1a47f49 | 5350528f269892758a014a3235d93532b9a2b801 | /3rd/protobuf/include/google/protobuf/stubs/substitute.h | 7a4d579ed7acb0e95f8bf9a68062923d1648c41c | [] | no_license | shwetak16/Pocker-1 | ff3c035024ef19a74215af000169c8edbdf843bc | bc7fafaa1e1420f238f2ac67732dad55bbcee1e3 | refs/heads/master | 2020-07-01T20:53:13.440269 | 2019-08-08T18:39:46 | 2019-08-08T18:39:46 | 201,297,346 | 0 | 0 | null | 2019-08-08T16:32:02 | 2019-08-08T16:32:01 | null | UTF-8 | C++ | false | false | 7,621 | h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the 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.
// Author: kenton@google.com (Kenton Varda)
// from google3/strings/substitute.h
#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/strutil.h>
#ifndef GOOGLE_PROTOBUF_STUBS_SUBSTITUTE_H_
#define GOOGLE_PROTOBUF_STUBS_SUBSTITUTE_H_
namespace google_public {
namespace protobuf {
namespace strings {
// ----------------------------------------------------------------------
// strings::Substitute()
// strings::SubstituteAndAppend()
// Kind of like StringPrintf, but different.
//
// Example:
// string GetMessage(string first_name, string last_name, int age) {
// return strings::Substitute("My name is $0 $1 and I am $2 years old.",
// first_name, last_name, age);
// }
//
// Differences from StringPrintf:
// * The format string does not identify the types of arguments.
// Instead, the magic of C++ deals with this for us. See below
// for a list of accepted types.
// * Substitutions in the format string are identified by a '$'
// followed by a digit. So, you can use arguments out-of-order and
// use the same argument multiple times.
// * It's much faster than StringPrintf.
//
// Supported types:
// * Strings (const char*, const string&)
// * Note that this means you do not have to add .c_str() to all of
// your strings. In fact, you shouldn't; it will be slower.
// * int32, int64, uint32, uint64: Formatted using SimpleItoa().
// * float, double: Formatted using SimpleFtoa() and SimpleDtoa().
// * bool: Printed as "true" or "false".
//
// SubstituteAndAppend() is like Substitute() but appends the result to
// *output. Example:
//
// string str;
// strings::SubstituteAndAppend(&str,
// "My name is $0 $1 and I am $2 years old.",
// first_name, last_name, age);
//
// Substitute() is significantly faster than StringPrintf(). For very
// large strings, it may be orders of magnitude faster.
// ----------------------------------------------------------------------
namespace internal { // Implementation details.
class SubstituteArg {
public:
inline SubstituteArg(const char* value)
: text_(value), size_(strlen(text_)) {}
inline SubstituteArg(const string& value)
: text_(value.data()), size_(value.size()) {}
// Indicates that no argument was given.
inline explicit SubstituteArg()
: text_(NULL), size_(-1) {}
// Primitives
// We don't overload for signed and unsigned char because if people are
// explicitly declaring their chars as signed or unsigned then they are
// probably actually using them as 8-bit integers and would probably
// prefer an integer representation. But, we don't really know. So, we
// make the caller decide what to do.
inline SubstituteArg(char value)
: text_(scratch_), size_(1) { scratch_[0] = value; }
inline SubstituteArg(short value)
: text_(FastInt32ToBuffer(value, scratch_)), size_(strlen(text_)) {}
inline SubstituteArg(unsigned short value)
: text_(FastUInt32ToBuffer(value, scratch_)), size_(strlen(text_)) {}
inline SubstituteArg(int value)
: text_(FastInt32ToBuffer(value, scratch_)), size_(strlen(text_)) {}
inline SubstituteArg(unsigned int value)
: text_(FastUInt32ToBuffer(value, scratch_)), size_(strlen(text_)) {}
inline SubstituteArg(long value)
: text_(FastLongToBuffer(value, scratch_)), size_(strlen(text_)) {}
inline SubstituteArg(unsigned long value)
: text_(FastULongToBuffer(value, scratch_)), size_(strlen(text_)) {}
inline SubstituteArg(long long value)
: text_(FastInt64ToBuffer(value, scratch_)), size_(strlen(text_)) {}
inline SubstituteArg(unsigned long long value)
: text_(FastUInt64ToBuffer(value, scratch_)), size_(strlen(text_)) {}
inline SubstituteArg(float value)
: text_(FloatToBuffer(value, scratch_)), size_(strlen(text_)) {}
inline SubstituteArg(double value)
: text_(DoubleToBuffer(value, scratch_)), size_(strlen(text_)) {}
inline SubstituteArg(bool value)
: text_(value ? "true" : "false"), size_(strlen(text_)) {}
inline const char* data() const { return text_; }
inline int size() const { return size_; }
private:
const char* text_;
int size_;
char scratch_[kFastToBufferSize];
};
} // namespace internal
LIBPROTOBUF_EXPORT string Substitute(
const char* format,
const internal::SubstituteArg& arg0 = internal::SubstituteArg(),
const internal::SubstituteArg& arg1 = internal::SubstituteArg(),
const internal::SubstituteArg& arg2 = internal::SubstituteArg(),
const internal::SubstituteArg& arg3 = internal::SubstituteArg(),
const internal::SubstituteArg& arg4 = internal::SubstituteArg(),
const internal::SubstituteArg& arg5 = internal::SubstituteArg(),
const internal::SubstituteArg& arg6 = internal::SubstituteArg(),
const internal::SubstituteArg& arg7 = internal::SubstituteArg(),
const internal::SubstituteArg& arg8 = internal::SubstituteArg(),
const internal::SubstituteArg& arg9 = internal::SubstituteArg());
LIBPROTOBUF_EXPORT void SubstituteAndAppend(
string* output, const char* format,
const internal::SubstituteArg& arg0 = internal::SubstituteArg(),
const internal::SubstituteArg& arg1 = internal::SubstituteArg(),
const internal::SubstituteArg& arg2 = internal::SubstituteArg(),
const internal::SubstituteArg& arg3 = internal::SubstituteArg(),
const internal::SubstituteArg& arg4 = internal::SubstituteArg(),
const internal::SubstituteArg& arg5 = internal::SubstituteArg(),
const internal::SubstituteArg& arg6 = internal::SubstituteArg(),
const internal::SubstituteArg& arg7 = internal::SubstituteArg(),
const internal::SubstituteArg& arg8 = internal::SubstituteArg(),
const internal::SubstituteArg& arg9 = internal::SubstituteArg());
} // namespace strings
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_STUBS_SUBSTITUTE_H_
| [
"panyumiao@panyumiaodeMacBook-Pro.local"
] | panyumiao@panyumiaodeMacBook-Pro.local |
33ad47eefef78e42afa1bf1da4a183445f245e23 | 404667ffb2026b5a805c7fe40597b390f6fa1cfd | /downloaddialog.cpp | 05f3737b69bf6d6da32d67a6e80e18fd8718f8d8 | [] | no_license | ElJeffe/FlickrPhotos | 701e51cdfef6d75edd6700dedd0f302f105d4002 | d5ec8046ce6394ce941e523ced45372c80f1da2c | refs/heads/master | 2021-01-10T21:08:02.815975 | 2010-01-17T10:56:27 | 2010-01-17T10:56:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,864 | cpp | #include "downloaddialog.h"
#include "ui_downloaddialog.h"
#include "collectioninfo.h"
#include <QTimer>
#include <QDebug>
DownloadDialog::DownloadDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::DownloadDialog)
{
ui->setupUi(this);
connect(this, SIGNAL(currentPhotoChanged(int)), this, SLOT(changeCurrentPhoto(int)));
}
DownloadDialog::~DownloadDialog()
{
delete ui;
}
void DownloadDialog::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void DownloadDialog::setPhotos(QList<PhotoData*> photos)
{
m_photos = photos;
ui->totalProgress->setMaximum(photos.size());
}
int DownloadDialog::exec()
{
QTimer::singleShot(0, this, SLOT(startDownload()));
return QDialog::exec();
}
void DownloadDialog::changeCurrentPhoto(int pos)
{
PhotoData* photo = m_photos[pos];
QImage* thumbImage = photo->GetThumbImage();
ui->thumbImage->setMinimumSize(thumbImage->size());
ui->thumbImage->setMaximumSize(thumbImage->size());
ui->thumbImage->setPixmap(QPixmap::fromImage(*thumbImage, Qt::AutoColor));
ui->statusLabel->setText(QString(tr("Downloading image %1")).arg(photo->GetName()));
ui->totalProgress->setValue(pos);
//connect(photo, SIGNAL(downloadProgress(qint64,qint64)), ui->photoProgress, SLOT(setValue(int)));
connect(photo, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(progress(qint64,qint64)));
}
void DownloadDialog::progress(qint64 one, qint64 two)
{
ui->photoProgress->setMaximum(two);
ui->photoProgress->setValue(one);
}
void DownloadDialog::startDownload()
{
for (int i = 0; i < m_photos.size() && this->isVisible(); ++i)
{
currentPhotoChanged(i);
m_photos[i]->downloadPhoto(m_quality);
}
close();
}
| [
"jef@steelant.be"
] | jef@steelant.be |
3eb1de573ebc8139fb8180988bae0499b056aec7 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /third_party/blink/renderer/platform/scheduler/common/thread_load_tracker.h | 6bf13f311467f0802ae0037032d653e17c3acc04 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 2,452 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_THREAD_LOAD_TRACKER_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_THREAD_LOAD_TRACKER_H_
#include "base/callback.h"
#include "base/macros.h"
#include "base/time/time.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
namespace scheduler {
// This class tracks thread load level, i.e. percentage of wall time spent
// running tasks.
// In order to avoid bias it reports load level at regular intervals.
// Every |reporting_interval_| time units, it reports the average thread load
// level computed using a sliding window of width |reporting_interval_|.
class PLATFORM_EXPORT ThreadLoadTracker {
DISALLOW_NEW();
public:
// Callback is called with (current_time, load_level) parameters.
using Callback = base::RepeatingCallback<void(base::TimeTicks, double)>;
ThreadLoadTracker(base::TimeTicks now,
const Callback& callback,
base::TimeDelta reporting_interval);
~ThreadLoadTracker();
void Pause(base::TimeTicks now);
void Resume(base::TimeTicks now);
// Note: this does not change |thread_state_|.
void Reset(base::TimeTicks now);
void RecordTaskTime(base::TimeTicks start_time, base::TimeTicks end_time);
void RecordIdle(base::TimeTicks now);
// TODO(altimin): Count wake-ups.
private:
enum class ThreadState { kActive, kPaused };
enum class TaskState { kTaskRunning, kIdle };
// This function advances |time_| to |now|, calling |callback_|
// in the process (multiple times if needed).
void Advance(base::TimeTicks now, TaskState task_state);
double Load();
// |time_| is the last timestamp LoadTracker knows about.
base::TimeTicks time_;
base::TimeTicks next_reporting_time_;
ThreadState thread_state_;
base::TimeTicks last_state_change_time_;
base::TimeDelta reporting_interval_;
// Recorded run time in window
// [next_reporting_time - reporting_interval, next_reporting_time].
base::TimeDelta run_time_inside_window_;
Callback callback_;
};
} // namespace scheduler
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_SCHEDULER_COMMON_THREAD_LOAD_TRACKER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
9621b9cb5d6699e12e69cf1f2ce6009c4e35538e | 258aa598158623f18693b78be765d767c782b282 | /src/config.hpp | aa81a687ec9c2d112b75aa802616aa0f62df0dc2 | [] | no_license | Piotr-Skorupa/air-quality-sensor | 410adfc1913ca72daec2ecce541d82e0d5b93ee3 | 88fe41c4f9d01e02e3436b6a7a71fefb65d261ed | refs/heads/master | 2023-06-04T21:22:24.657445 | 2021-06-26T09:27:48 | 2021-06-26T09:28:39 | 266,328,370 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | hpp | #pragma once
// Your Signomix account data
constexpr auto SIGNOMIX_LOGIN = "";
constexpr auto SIGNOMIX_PASSWORD = "";
constexpr auto SIGNOMIX_EUI = "";
constexpr auto SIGNOMIX_SECRET = "";
// Air quality measuremnt frequency
constexpr auto MEASUREMENT_PERIOD_SEC = 30 * 60; // 30 minutes
| [
"piotr94skorupa94@gmail.com"
] | piotr94skorupa94@gmail.com |
2c7325ac7453cfefe530d06f3d5cbadfa0fc3dc1 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/inetcore/outlookexpress/inetcomm/dll/defguid.cpp | 236e70169d7905861fad9c205343478499d90d7d | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 828 | cpp | // Copyright (c)1993-1995 Microsoft Corporation, All Rights Reserved
#include "pch.hxx"
#include <initguid.h>
#include <ole2.h>
#include <shlguidp.h>
#define INITGUID
#include "mimeole.h"
#ifdef SMIME_V3
#include "smimepol.h"
#endif // SMIME_V3
#include "mimeolep.h"
#include "mimeedit.h"
#ifndef MAC
#include "imnxport.h"
#endif // !MAC
#include "stmlock.h"
#ifndef WIN16
#include "ibdylock.h"
#endif // !WIN16
#include "ibdystm.h"
#ifndef MAC
#include "ixpurl.h"
#endif // !MAC
#include <xmlparser.h>
#include <booktree.h>
#ifdef WIN16
// The BINDNODESTATE type was defined in "booktree.h" file - only for WATCOMC.
#include "ibdylock.h"
#include <olectlid.h> // IID_IPersistStreamInit
#endif // WIN16
#include <containx.h>
#include <bookbody.h>
#ifndef MAC
#include <mlang.h>
#endif // !MAC
#include <msoert.h>
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
494cd1550ea86d965aaeb3b19306725f4c016791 | 3e737ee4064eb2d47fea04fedac9b41bf58820ad | /Rhombus.h | 33c4ac52758fb73329dc6c1e4405478312be0e1b | [] | no_license | pavelprach/Figure | 04d73f44b67be23c3eea1aa811eb16289c9111fa | 65a68c44d32a985720cd1a9e49c9b283f1483544 | refs/heads/master | 2022-04-13T13:07:27.551968 | 2020-04-10T17:54:05 | 2020-04-10T17:54:05 | 254,700,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 547 | h | #pragma once
#include "Figure.h"
class Rhombus : public Figure
{
int side;
int height;
public:
Rhombus() {}
Rhombus(int side,int height)
{
SetSide(side);
SetHeight(height);
}
void SetSide(int side)
{
this->side = side;
}
void SetHeight(int height)
{
this->height = height;
}
void Perimetr() override
{
int tempPerimetr;
tempPerimetr = side * 4;
SetPerimetr(tempPerimetr);
}
void Square() override
{
double tempSquare;
tempSquare = side * height;
SetSquare(tempSquare);
}
};
| [
"noreply@github.com"
] | pavelprach.noreply@github.com |
4e3dfcfbb262eae002788ff68eb38a1b539d2ddc | 947e8b3a0133dd4d06736b4728ffad296aac88b6 | /contest/greedy/388_DONE.cpp | a3b5f6b09326be816469bcaf9105e1ebce95c719 | [] | no_license | sngvahmed/problem-solving-code | 41427007d49d1b74ec90d15670e6ec1db617400f | 3b2714c87e93506b0d5a4ae3cc471d16c4d6ab1b | refs/heads/master | 2021-06-01T11:54:58.350875 | 2018-02-27T18:43:47 | 2018-02-27T18:43:47 | 39,954,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 920 | cpp | #include <sstream>
#include <deque>
#include <vector>
#include <list>
#include <string>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#define EPS 1.0E-13
#define EQL(x,y) (abs((x)-(y)) < EPS)
#define LT(x,y) (((y)-(x)) >= EPS)
#define GT(x,y) (((x)-(y)) >= EPS)
#define SZ(x) ((int)(x).size())
using namespace std;
class MonotoneSequence {
public:
//{10, 20, 30, 25, 20, 19, 20, 18, 23}
int longestMonotoneSequence(vector<int> seq) {
int q = 0;
for (int i = 0; i < seq.size(); i++) {
int counter = i;
int count = 0;
for (int q = i + 1; q < seq.size(); q++) {
if (seq[counter] < seq[q])
count++;
else
break;
counter++;
}
for (int q = i + 1; q < seq.size(); q++) {
if (seq[counter] < seq[q])
count++;
else
break;
counter++;
}
if (count > q)
q = count;
}
return q;
}
};
| [
"ahmednasser1993@gmail.com"
] | ahmednasser1993@gmail.com |
ff2a51e7654fda9efa2d73057908c0789cb54ad4 | 9c99641d20454681792481c25cd93503449b174d | /WEBGL_lesson7/src/testApp.h | 05ec2e26c864f3e8f6cf45cee925c5fefb43d660 | [] | no_license | fazeaction/OF_LearningWebGL_Examples | a8befc8c65dd2f9ffc0c45a3c54548f5a05295aa | b608e252b58129bab844c32cc6a7929f3643e145 | refs/heads/master | 2021-03-12T23:58:57.355788 | 2010-05-17T22:35:15 | 2010-05-17T22:35:15 | 665,483 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,529 | h | #ifndef _TEST_APP
#define _TEST_APP
#include "ofMain.h"
#include "ofxShader.h"
#include "ofxVectorMath.h"
class testApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed (int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void setupScreenForLesson();
void setMatrixUniforms();
void checkForKeys();
void setAmbientLightColor();
void setDirectLightColor();
void setPositionLight();
GLuint vboId[2];
GLint locationID[6];
GLfloat pMatrix[16];
GLfloat mvMatrix[16];
float xRot;
float xSpeed;
float yRot;
float ySpeed;
float xRotLight;
float yRotLight;
float z;
//AMBIENT COLOR VALUES
float ambient_red_value;
float ambient_green_value;
float ambient_blue_value;
//DIRECT LIGHT COLOR VALUES
float direct_red_value;
float direct_green_value;
float direct_blue_value;
//POSITION LIGTH
float xpos;
float ypos;
float zpos;
bool of_key_backspace_pressed;
bool of_key_page_up_pressed;
bool of_key_page_down_pressed;
bool of_key_left_pressed;
bool of_key_right_pressed;
bool of_key_up_pressed;
bool of_key_down_pressed;
bool use_lighting;
ofImage neheTexture;
ofTrueTypeFont verdana;
ofxShader shader;
ofxVec3f lightDirection;
};
#endif
| [
"tribadelics@gmail.com"
] | tribadelics@gmail.com |
52dd9543a70e213cf7003a686233ab4003484553 | c7aac55da99b0c2fbaa67d86b6a7be604c69dc4e | /hw2-starterCode/.history/hw2_core_code/hw2_20200321022111.cpp | 3da1348d6e40f75bc465043e063f0ed289394378 | [] | no_license | RealZiangLiu/usc_csci420_sp20 | 76733daa3ec84d9c3283330b65ca37fda416a350 | c3a7e38d32cf1f14100512a6da23aa34673f682d | refs/heads/master | 2023-02-19T09:33:39.379731 | 2020-04-23T01:29:34 | 2020-04-23T01:29:34 | 242,432,725 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,214 | cpp | /*
CSCI 420 Computer Graphics, USC
Assignment 2: Roller Coaster
C++ starter code
Student username: ziangliu
ID: 9114346039
*/
#include "basicPipelineProgram.h"
#include "openGLMatrix.h"
#include "imageIO.h"
#include "openGLHeader.h"
#include "glutHeader.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#if defined(WIN32) || defined(_WIN32)
#ifdef _DEBUG
#pragma comment(lib, "glew32d.lib")
#else
#pragma comment(lib, "glew32.lib")
#endif
#endif
#if defined(WIN32) || defined(_WIN32)
char shaderBasePath[1024] = SHADER_BASE_PATH;
#else
char shaderBasePath[1024] = "../openGLHelper-starterCode";
#endif
using namespace std;
// Constant parameters
const double param_s = 0.5;
const double param_u_step = 0.001;
const int param_speed = 5;
const double param_rail_scale = 0.1;
// represents one control point along the spline
struct Point
{
double x;
double y;
double z;
Point () {};
Point (double x_, double y_, double z_)
: x(x_), y(y_), z(z_) {}
Point operator- (Point other) {
return Point(x - other.x, y - other.y, z - other.z);
}
Point operator+ (Point other) {
return Point(x + other.x, y + other.y, z + other.z);
}
Point operator* (double mult) {
return Point(x * mult, y * mult, z * mult);
}
Point operator/ (double div) {
return Point(x / div, y / div, z / div);
}
void normalize () {
double norm = sqrt(x * x + y * y + z * z);
x /= norm;
y /= norm;
z /= norm;
}
Point cross (Point& other) {
Point res(y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x);
return res;
}
};
Point normalize (Point pt) {
double norm = sqrt(pt.x * pt.x + pt.y * pt.y + pt.z * pt.z);
return pt / norm;
}
// spline struct
// contains how many control points the spline has, and an array of control points
struct Spline
{
int numControlPoints;
Point * points;
};
struct CatmullMatrix
{
const vector< vector<double> > basis = { {-param_s, 2 - param_s, param_s - 2, param_s },
{2 * param_s, param_s - 3, 3 - 2 * param_s, -param_s},
{-param_s, 0, param_s, 0 },
{0, 1, 0, 0}};
Point computePosition (double u_, Point& p_1, Point& p_2, Point& p_3, Point& p_4) {
vector<double> first_res(4, 0.0);
vector<double> final_res(3, 0.0);
vector<double> design = {pow(u_, 3), pow(u_, 2), u_, 1.0};
vector<Point> control = {p_1, p_2, p_3, p_4};
// Multiply design matrix with basis
for (int i=0; i<4; ++i) {
for (int j=0; j<4; ++j) {
first_res[i] += (design[j] * basis[j][i]);
}
}
// Multiply previous result with control matrix
for (int i=0; i<4; ++i) {
final_res[0] += (first_res[i] * control[i].x);
final_res[1] += (first_res[i] * control[i].y);
final_res[2] += (first_res[i] * control[i].z);
}
return Point(final_res[0], final_res[1], final_res[2]);
}
Point computeTangent (double u_, Point& p_1, Point& p_2, Point& p_3, Point& p_4) {
vector<double> first_res(4, 0.0);
vector<double> final_res(3, 0.0);
vector<double> design = {3 * pow(u_, 2), 2 * u_, 1.0, 0.0};
vector<Point> control = {p_1, p_2, p_3, p_4};
// Multiply design matrix with basis
for (int i=0; i<4; ++i) {
for (int j=0; j<4; ++j) {
first_res[i] += (design[j] * basis[j][i]);
}
}
// Multiply previous result with control matrix
for (int i=0; i<4; ++i) {
final_res[0] += (first_res[i] * control[i].x);
final_res[1] += (first_res[i] * control[i].y);
final_res[2] += (first_res[i] * control[i].z);
}
Point res(final_res[0], final_res[1], final_res[2]);
return normalize(res);
}
};
CatmullMatrix computeMatrix;
// the spline array
Spline * splines;
// total number of splines
int numSplines;
int mousePos[2]; // x,y coordinate of the mouse position
int leftMouseButton = 0; // 1 if pressed, 0 if not
int middleMouseButton = 0; // 1 if pressed, 0 if not
int rightMouseButton = 0; // 1 if pressed, 0 if not
typedef enum { ROTATE, TRANSLATE, SCALE } CONTROL_STATE;
CONTROL_STATE controlState = ROTATE;
// state of the world
float landRotate[3] = { 0.0f, 0.0f, 0.0f };
float landTranslate[3] = { 0.0f, 0.0f, 0.0f };
float landScale[3] = { 1.0f, 1.0f, 1.0f };
int windowWidth = 1280;
int windowHeight = 720;
char windowTitle[512] = "CSCI 420 homework II";
int mode = 1;
int record_animation = 0;
int camera_on_rail = 0;
int roller_frame_count = 0;
GLuint VBO;
GLuint VAO;
GLuint EBO;
vector<GLuint> splineVBOs;
vector<GLuint> splineVAOs;
vector<int> splineVertexCnt;
// store point positions along spline
vector< vector<Point> > splinePointCoords;
vector< vector<Point> > splineTangents;
vector< vector<Point> > splineNormals;
vector< vector<Point> > splineBinormals;
OpenGLMatrix matrix;
BasicPipelineProgram * pipelineProgram;
int frame_cnt = 0;
// void renderWireframe();
void renderSplines();
int loadSplines(char * argv)
{
char * cName = (char *) malloc(128 * sizeof(char));
FILE * fileList;
FILE * fileSpline;
int iType, i = 0, j, iLength;
// load the track file
fileList = fopen(argv, "r");
if (fileList == NULL)
{
printf ("can't open file\n");
exit(1);
}
// stores the number of splines in a global variable
fscanf(fileList, "%d", &numSplines);
splines = (Spline*) malloc(numSplines * sizeof(Spline));
// reads through the spline files
for (j = 0; j < numSplines; j++)
{
i = 0;
fscanf(fileList, "%s", cName);
fileSpline = fopen(cName, "r");
if (fileSpline == NULL)
{
printf ("can't open file\n");
exit(1);
}
// gets length for spline file
fscanf(fileSpline, "%d %d", &iLength, &iType);
// allocate memory for all the points
splines[j].points = (Point *)malloc(iLength * sizeof(Point));
splines[j].numControlPoints = iLength;
// saves the data to the struct
while (fscanf(fileSpline, "%lf %lf %lf",
&splines[j].points[i].x,
&splines[j].points[i].y,
&splines[j].points[i].z) != EOF)
{
i++;
}
}
free(cName);
return 0;
}
int initTexture(const char * imageFilename, GLuint textureHandle)
{
// read the texture image
ImageIO img;
ImageIO::fileFormatType imgFormat;
ImageIO::errorType err = img.load(imageFilename, &imgFormat);
if (err != ImageIO::OK)
{
printf("Loading texture from %s failed.\n", imageFilename);
return -1;
}
// check that the number of bytes is a multiple of 4
if (img.getWidth() * img.getBytesPerPixel() % 4)
{
printf("Error (%s): The width*numChannels in the loaded image must be a multiple of 4.\n", imageFilename);
return -1;
}
// allocate space for an array of pixels
int width = img.getWidth();
int height = img.getHeight();
unsigned char * pixelsRGBA = new unsigned char[4 * width * height]; // we will use 4 bytes per pixel, i.e., RGBA
// fill the pixelsRGBA array with the image pixels
memset(pixelsRGBA, 0, 4 * width * height); // set all bytes to 0
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++)
{
// assign some default byte values (for the case where img.getBytesPerPixel() < 4)
pixelsRGBA[4 * (h * width + w) + 0] = 0; // red
pixelsRGBA[4 * (h * width + w) + 1] = 0; // green
pixelsRGBA[4 * (h * width + w) + 2] = 0; // blue
pixelsRGBA[4 * (h * width + w) + 3] = 255; // alpha channel; fully opaque
// set the RGBA channels, based on the loaded image
int numChannels = img.getBytesPerPixel();
for (int c = 0; c < numChannels; c++) // only set as many channels as are available in the loaded image; the rest get the default value
pixelsRGBA[4 * (h * width + w) + c] = img.getPixel(w, h, c);
}
// bind the texture
glBindTexture(GL_TEXTURE_2D, textureHandle);
// initialize the texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixelsRGBA);
// generate the mipmaps for this texture
glGenerateMipmap(GL_TEXTURE_2D);
// set the texture parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// query support for anisotropic texture filtering
GLfloat fLargest;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest);
printf("Max available anisotropic samples: %f\n", fLargest);
// set anisotropic texture filtering
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 0.5f * fLargest);
// query for any errors
GLenum errCode = glGetError();
if (errCode != 0)
{
printf("Texture initialization error. Error code: %d.\n", errCode);
return -1;
}
// de-allocate the pixel array -- it is no longer needed
delete [] pixelsRGBA;
return 0;
}
// write a screenshot to the specified filename
void saveScreenshot(const char * filename)
{
unsigned char * screenshotData = new unsigned char[windowWidth * windowHeight * 3];
glReadPixels(0, 0, windowWidth, windowHeight, GL_RGB, GL_UNSIGNED_BYTE, screenshotData);
ImageIO screenshotImg(windowWidth, windowHeight, 3, screenshotData);
if (screenshotImg.save(filename, ImageIO::FORMAT_JPEG) == ImageIO::OK)
std::cout << "File " << filename << " saved successfully." << endl;
else std::cout << "Failed to save file " << filename << '.' << endl;
delete [] screenshotData;
}
// write a screenshot to the specified filename
/*
void saveScreenshot(const char * filename)
{
int scale = 2;
int ww = windowWidth * scale;
int hh = windowHeight * scale;
unsigned char * screenshotData = new unsigned char[ww * hh * 3];
glReadPixels(0, 0, ww, hh, GL_RGB, GL_UNSIGNED_BYTE, screenshotData);
unsigned char * screenshotData1 = new unsigned char[windowWidth * windowHeight * 3];
for (int h = 0; h < windowHeight; h++) {
for (int w = 0; w < windowWidth; w++) {
int h1 = h * scale;
int w1 = w * scale;
screenshotData1[(h * windowWidth + w) * 3] = screenshotData[(h1 * ww + w1) * 3];
screenshotData1[(h * windowWidth + w) * 3 + 1] = screenshotData[(h1 * ww + w1) * 3 + 1];
screenshotData1[(h * windowWidth + w) * 3 + 2] = screenshotData[(h1 * ww + w1) * 3 + 2];
}
}
ImageIO screenshotImg(windowWidth, windowHeight, 3, screenshotData1);
if (screenshotImg.save(filename, ImageIO::FORMAT_JPEG) == ImageIO::OK)
cout << "File " << filename << " saved successfully." << endl;
else cout << "Failed to save file " << filename << '.' << endl;
delete [] screenshotData;
delete [] screenshotData1;
}*/
void displayFunc()
{
// render some stuff...
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Reset roller coaster frame counter
roller_frame_count %= splineVertexCnt[0];
float m[16], p[16]; // Column-major
if (!camera_on_rail) {
matrix.SetMatrixMode(OpenGLMatrix::ModelView);
matrix.LoadIdentity();
matrix.LookAt(0, 0, 5, 0, 0, 0, 0, 1, 0);
// matrix.SetMatrixMode(OpenGLMatrix::ModelView);
matrix.Translate(landTranslate[0], landTranslate[1], landTranslate[2]);
matrix.Rotate(landRotate[0], 1, 0, 0);
matrix.Rotate(landRotate[1], 0, 1, 0);
matrix.Rotate(landRotate[2], 0, 0, 1);
matrix.Scale(landScale[0], landScale[1], landScale[2]);
matrix.GetMatrix(m);
matrix.SetMatrixMode(OpenGLMatrix::Projection);
matrix.GetMatrix(p);
} else {
matrix.SetMatrixMode(OpenGLMatrix::ModelView);
matrix.LoadIdentity();
int focusIdx = (roller_frame_count+1) % splineVertexCnt[0];
matrix.LookAt(splinePointCoords[0][roller_frame_count].x + 0.01 * splineNormals[0][roller_frame_count].x,
splinePointCoords[0][roller_frame_count].y + 0.01 * splineNormals[0][roller_frame_count].y,
splinePointCoords[0][roller_frame_count].z + 0.01 * splineNormals[0][roller_frame_count].z, // eye point
splinePointCoords[0][focusIdx].x + 0.01 * splineNormals[0][focusIdx].x,
splinePointCoords[0][focusIdx].y + 0.01 * splineNormals[0][focusIdx].y,
splinePointCoords[0][focusIdx].z + 0.01 * splineNormals[0][focusIdx].z, // focus point
splineNormals[0][roller_frame_count].x,
splineNormals[0][roller_frame_count].y,
splineNormals[0][roller_frame_count].z);
matrix.Translate(landTranslate[0], landTranslate[1], landTranslate[2]);
matrix.Rotate(landRotate[0], 1, 0, 0);
matrix.Rotate(landRotate[1], 0, 1, 0);
matrix.Rotate(landRotate[2], 0, 0, 1);
matrix.Scale(landScale[0], landScale[1], landScale[2]);
matrix.GetMatrix(m);
matrix.SetMatrixMode(OpenGLMatrix::Projection);
matrix.GetMatrix(p);
}
// ++roller_frame_count;
roller_frame_count += param_speed;
// DEBUG print
cout << "Coord: " << splineTangents[0][roller_frame_count].x << " " << splineTangents[0][roller_frame_count].y << " " << splineTangents[0][roller_frame_count].z << endl;
// get a handle to the program
GLuint program = pipelineProgram->GetProgramHandle();
// get a handle to the modelViewMatrix shader variable
GLint h_modelViewMatrix = glGetUniformLocation(program, "modelViewMatrix");
// get a handle to the projectionMatrix shader variable
GLint h_projectionMatrix = glGetUniformLocation(program, "projectionMatrix");
// Get handle to mode shader variable
GLint h_mode = glGetUniformLocation(program, "mode");
// bind shader
pipelineProgram->Bind();
// Upload matrices to GPU
GLboolean isRowMajor = GL_FALSE;
glUniformMatrix4fv(h_modelViewMatrix, 1, isRowMajor, m);
glUniformMatrix4fv(h_projectionMatrix, 1, isRowMajor, p);
// set variable
pipelineProgram->SetModelViewMatrix(m);
pipelineProgram->SetProjectionMatrix(p);
// renderWireframe();
renderSplines();
glutSwapBuffers();
}
void idleFunc()
{
if (record_animation == 1) {
// Save screenshots for animation
if (frame_cnt % 4 == 0 && frame_cnt < 1200) {
string file_path = "../screenshots/";
string id;
int t = frame_cnt / 4;
for (int i=0; i<3; ++i) {
id += to_string(t % 10);
t /= 10;
}
reverse(id.begin(), id.end());
file_path += (id + ".jpg");
saveScreenshot(file_path.c_str());
}
++frame_cnt;
}
// make the screen update
glutPostRedisplay();
}
void reshapeFunc(int w, int h)
{
glViewport(0, 0, w, h);
matrix.SetMatrixMode(OpenGLMatrix::Projection);
matrix.LoadIdentity();
matrix.Perspective(54.0f, (float)w / (float)h, 0.01f, 100.0f);
matrix.SetMatrixMode(OpenGLMatrix::ModelView);
}
void mouseMotionDragFunc(int x, int y)
{
// mouse has moved and one of the mouse buttons is pressed (dragging)
// the change in mouse position since the last invocation of this function
int mousePosDelta[2] = { x - mousePos[0], y - mousePos[1] };
switch (controlState)
{
// translate the landscape
case TRANSLATE:
if (leftMouseButton)
{
// control x,y translation via the left mouse button
landTranslate[0] += mousePosDelta[0] * 0.01f;
landTranslate[1] -= mousePosDelta[1] * 0.01f;
}
if (middleMouseButton)
{
// control z translation via the middle mouse button
landTranslate[2] += mousePosDelta[1] * 0.01f;
}
break;
// rotate the landscape
case ROTATE:
if (leftMouseButton)
{
// control x,y rotation via the left mouse button
landRotate[0] += mousePosDelta[1];
landRotate[1] += mousePosDelta[0];
}
if (middleMouseButton)
{
// control z rotation via the middle mouse button
landRotate[2] += mousePosDelta[1];
}
break;
// scale the landscape
case SCALE:
if (leftMouseButton)
{
// control x,y scaling via the left mouse button
landScale[0] *= 1.0f + mousePosDelta[0] * 0.01f;
landScale[1] *= 1.0f - mousePosDelta[1] * 0.01f;
}
if (middleMouseButton)
{
// control z scaling via the middle mouse button
landScale[2] *= 1.0f - mousePosDelta[1] * 0.01f;
}
break;
}
// store the new mouse position
mousePos[0] = x;
mousePos[1] = y;
}
void mouseMotionFunc(int x, int y)
{
// mouse has moved
// store the new mouse position
mousePos[0] = x;
mousePos[1] = y;
}
void mouseButtonFunc(int button, int state, int x, int y)
{
// a mouse button has has been pressed or depressed
// keep track of the mouse button state, in leftMouseButton, middleMouseButton, rightMouseButton variables
switch (button)
{
case GLUT_LEFT_BUTTON:
leftMouseButton = (state == GLUT_DOWN);
break;
case GLUT_MIDDLE_BUTTON:
middleMouseButton = (state == GLUT_DOWN);
break;
case GLUT_RIGHT_BUTTON:
rightMouseButton = (state == GLUT_DOWN);
break;
}
// keep track of whether CTRL and SHIFT keys are pressed
switch (glutGetModifiers())
{
case GLUT_ACTIVE_CTRL:
controlState = TRANSLATE;
break;
case GLUT_ACTIVE_SHIFT:
controlState = SCALE;
break;
// if CTRL and SHIFT are not pressed, we are in rotate mode
default:
controlState = ROTATE;
break;
}
// store the new mouse position
mousePos[0] = x;
mousePos[1] = y;
}
void keyboardFunc(unsigned char key, int x, int y)
{
switch (key)
{
case 27: // ESC key
exit(0); // exit the program
break;
case ' ':
std::cout << "You pressed the spacebar." << endl;
break;
case 't': // Translate
controlState = TRANSLATE;
break;
case 'x':
// take a screenshot
saveScreenshot("screenshot.jpg");
break;
case 's':
// Start capture animation
record_animation = (1 - record_animation);
break;
case 'r':
// Run the roller coaster
camera_on_rail = 1 - camera_on_rail;
if (camera_on_rail) {
cout << "Placing camera on rail. Press 'r' again to change." << endl;
} else {
cout << "Camera free move mode. Press 'r' again to change." << endl;
}
break;
}
}
// void renderPoints() {
// glBindVertexArray(pointVAO);
// glDrawArrays(GL_POINTS, 0, pointNumVertex);
// glBindVertexArray(0);
// }
// void renderWireframe() {
// glBindVertexArray(wireVAO);
// glDrawElements(GL_LINES, wireIdxCnt, GL_UNSIGNED_INT, (void*)0);
// glBindVertexArray(0);
// }
void renderSplines () {
for (size_t i=0; i<numSplines; ++i) {
glBindVertexArray(splineVAOs[i]);
glDrawArrays(GL_LINE_STRIP, 0, splineVertexCnt[i]);
glBindVertexArray(0);
}
}
void add_square_rail_points (glm::vec3* pointPositions, glm::vec3* squarePositions, int splineIdx, int pointCnt) {
int squarePointCnt = 0;
for (int i=0; i<pointCnt; ++i) {
Point p_0 = splinePointCoords[splineIdx][i];
Point n_0 = splineNormals[splineIdx][i];
Point b_0 = splineBinormals[splineIdx][i];
Point v_0, v_1, v_2, v_3, v_4;
v_0 = p_0 + (b_0 - n_0) * param_rail_scale;
v_1 = p_0 + (n_0 + b_0) * param_rail_scale;
v_2 = p_0 + (n_0 - b_0) * param_rail_scale;
v_3 = p_0 + (Point(0,0,0) - n_0 - b_0) * param_rail_scale;
squarePositions[squarePointCnt] = glm::vec3(v_0.x, v_0.y, v_0.z);
squarePositions[squarePointCnt+1] = glm::vec3(v_1.x, v_1.y, v_1.z);
squarePositions[squarePointCnt+2] = glm::vec3(v_2.x, v_2.y, v_2.z);
squarePositions[squarePointCnt+3] = glm::vec3(v_3.x, v_3.y, v_3.z);
squarePointCnt += 4;
}
}
void compute_square_rail_idx (glm::vec3* squareIdx, glm::vec3* squarePositions, int splineIdx, int pointCnt) {
}
void compute_store_points_tangents (glm::vec3* pointPositions, int splineIdx, int pointCnt, int u_cnt, Point& p_1, Point& p_2, Point& p_3, Point& p_4) {
Point res = computeMatrix.computePosition(u_cnt * param_u_step, p_1, p_2, p_3, p_4);
// Position vector to put into VBO
pointPositions[pointCnt] = glm::vec3(res.x, res.y, res.z);
// Global position vector to track point locations
splinePointCoords[splineIdx].push_back(res);
Point tangent = computeMatrix.computeTangent(u_cnt * param_u_step, p_1, p_2, p_3, p_4);
// Global tangent vector to track tangent of spline at this point
splineTangents[splineIdx].push_back(tangent);
}
void compute_catmull_rom_point (glm::vec3* pointPositions, glm::vec3* squarePositions, Point* points, int currNumCtrlPts, int splineIdx, Point& prev_1, Point& prev_2, Point& next_1, bool connect_prev = false, bool connect_next = false) {
pointCnt = 0;
if (connect_prev) {
// First segment to connect with previous spline
for (int u_cnt=0; u_cnt < (int)(1.0 / param_u_step); ++u_cnt) {
compute_store_points_tangents(pointPositions, splineIdx, pointCnt, u_cnt, prev_2, prev_1, points[1], points[2]);
++pointCnt;
}
// Second segment to connect with previous spline
for (int u_cnt=0; u_cnt < (int)(1.0 / param_u_step); ++u_cnt) {
compute_store_points_tangents(pointPositions, splineIdx, pointCnt, u_cnt, prev_1, points[1], points[2], points[3]);
++pointCnt;
}
}
int start = connect_prev ? 2 : 1;
int end = connect_next ? (currNumCtrlPts-3) : (currNumCtrlPts-2);
for (int i=start; i<end; ++i) {
for (int u_cnt=0; u_cnt < (int)(1.0 / param_u_step); ++u_cnt) {
compute_store_points_tangents(pointPositions, splineIdx, pointCnt, u_cnt, points[i-1], points[i], points[i+1], points[i+2]);
++pointCnt;
}
}
// last point
if (connect_next) {
for (int u_cnt=0; u_cnt <= (int)(1.0 / param_u_step); ++u_cnt) {
compute_store_points_tangents(pointPositions, splineIdx, pointCnt, u_cnt, points[currNumCtrlPts-4], points[currNumCtrlPts-3], points[currNumCtrlPts-2], next_1);
++pointCnt;
}
} else {
compute_store_points_tangents(pointPositions, splineIdx, pointCnt, (int)(1.0 / param_u_step), points[currNumCtrlPts-4], points[currNumCtrlPts-3], points[currNumCtrlPts-2], points[currNumCtrlPts-1]);
++pointCnt;
}
// Compute initial Frenet Frame vectors
Point initial_V(0.0, 0.0, 1.0);
Point T_0 = splineTangents[splineIdx][0];
Point N_0 = normalize(T_0.cross(initial_V));
Point B_0 = normalize(T_0.cross(N_0));
splineNormals[splineIdx].push_back(N_0);
splineBinormals[splineIdx].push_back(B_0);
for (int i=1; i<pointCnt; ++i) {
splineNormals[splineIdx].push_back(normalize(splineBinormals[splineIdx][i-1].cross(splineTangents[splineIdx][i])));
splineBinormals[splineIdx].push_back(normalize(splineTangents[splineIdx][i].cross(splineNormals[splineIdx][i])));
}
// TODO: check this
add_square_rail_points(pointPositions, squarePositions, splineIdx, pointCnt);
}
void initScene(int argc, char *argv[])
{
// load the splines from the provided filename
loadSplines(argv[1]);
printf("Loaded %d spline(s).\n", numSplines);
for(int i=0; i<numSplines; i++)
printf("Num control points in spline %d: %d.\n", i, splines[i].numControlPoints);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
/*
Initialize pipelineProgram
*/
pipelineProgram = new BasicPipelineProgram;
int ret = pipelineProgram->Init(shaderBasePath);
if (ret != 0) abort();
Point prev_1_point;
Point prev_2_point;
Point next_1_point;
// Intialize global coord and tangent vectors
splinePointCoords.resize(numSplines);
splineTangents.resize(numSplines);
splineNormals.resize(numSplines);
splineBinormals.resize(numSplines);
for (int i=0; i<numSplines; ++i) {
// cout << "[DEBUG] Control points: " << splines[i].numControlPoints << endl;
int currNumCtrlPts = splines[i].numControlPoints;
// currNumCtrlPts - 3 segments, +1 for endpoint
int uNumPoints = ((int)(1.0 / param_u_step)) * (currNumCtrlPts - 3) + 1;
GLuint currVBO, currVAO;
bool connect_prev = false;
if (i > 0) {
connect_prev = true;
prev_1_point = splines[i-1].points[splines[i-1].numControlPoints-2];
prev_2_point = splines[i-1].points[splines[i-1].numControlPoints-3];
}
bool connect_next = false;
if (i < numSplines - 1) {
connect_next = true;
next_1_point = splines[i+1].points[1];
}
if (connect_prev) {
uNumPoints += ((int)(1.0 / param_u_step) * 2);
}
if (connect_next) {
uNumPoints += (int)(1.0 / param_u_step);
}
int squareIdxCnt = 24 * (uNumPoints - 1);
// TODO: only keep one of these two
glm::vec3* pointPositions = new glm::vec3[uNumPoints];
glm::vec3* squarePositions = new glm::vec3[uNumPoints*4];
unsigned int* squareIndex = new unsigned int[squareIdxCnt];
// TODO: move color computation to vertex shader
glm::vec4* pointColors = new glm::vec4[uNumPoints];
// Disable multiple curve connection
// connect_prev = false;
// connect_next = false;
int realPointCnt = 0;
compute_catmull_rom_point(pointPositions, squarePositions, splines[i].points, currNumCtrlPts, i, prev_1_point, prev_2_point, next_1_point, connect_prev, connect_next);
// Set colors
for (int i=0; i<realPointCnt; ++i) {
pointColors[i] = glm::vec4(1.0, 1.0, 1.0, 1.0);
}
// DEBUG output
// for (int i=0; i<uNumPoints; ++i) {
// cout << pointPositions[i][0] << ", " << pointPositions[i][1] << ", " << pointPositions[i][2] << endl;
// }
// TODO: add function to compute eight points for cross-section for every two points on rail
// Set positions VBO
glGenBuffers(1, &currVBO);
glBindBuffer(GL_ARRAY_BUFFER, currVBO);
// glBufferData(GL_ARRAY_BUFFER, sizeof(pointPositions) + sizeof(pointColors), nullptr, GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * realPointCnt + sizeof(glm::vec4) * realPointCnt, nullptr, GL_STATIC_DRAW);
// Upload position data
// glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(pointPositions), pointPositions);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::vec3) * realPointCnt, pointPositions);
// Upload color data
// glBufferSubData(GL_ARRAY_BUFFER, sizeof(pointPositions), sizeof(pointColors), pointColors);
glBufferSubData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * realPointCnt, sizeof(glm::vec4) * realPointCnt, pointColors);
glGenVertexArrays(1, &currVAO);
glBindVertexArray(currVAO);
// Bind pointVBO
glBindBuffer(GL_ARRAY_BUFFER, currVBO);
// Set "position" layout
GLuint loc = glGetAttribLocation(pipelineProgram->GetProgramHandle(), "position");
glEnableVertexAttribArray(loc);
const void * offset = (const void*) 0;
GLsizei stride = 0;
glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, stride, offset);
// Set "color" layout
loc = glGetAttribLocation(pipelineProgram->GetProgramHandle(), "color");
glEnableVertexAttribArray(loc);
// offset = (const void*) sizeof(pointPositions);
offset = (const void*) (sizeof(glm::vec3) * realPointCnt);
glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, stride, offset);
glBindVertexArray(0); // Unbind the VAO
glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind the VBO
splineVBOs.push_back(currVBO);
splineVAOs.push_back(currVAO);
splineVertexCnt.push_back(realPointCnt);
delete [] pointColors;
delete [] pointPositions;
// delete [] tangentPoints;
}
/*
{
// glm::vec3 pointPositions[pointNumVertex];
glm::vec3* pointPositions = new glm::vec3[pointNumVertex];
// glm::vec4 pointColors[pointNumVertex];
glm::vec4* pointColors = new glm::vec4[pointNumVertex];
for (int x=0; x<imageWidth; ++x) {
for (int y=0; y<imageHeight; ++y) {
double color_R = heightmapImage->getPixel(x, y, channels[0]) / 255.0;
double color_G = heightmapImage->getPixel(x, y, channels[1]) / 255.0;
double color_B = heightmapImage->getPixel(x, y, channels[2]) / 255.0;
double color_height = (color_R / 3.0 + color_G / 3.0 + color_B / 3.0);
pointPositions[y * imageWidth + x] = glm::vec3((double)(x - imageWidth/2.0) / imageWidth * 4, color_height, (double)(y - imageHeight/2.0) / imageHeight * 4);
pointColors[y * imageWidth + x] = glm::vec4(color_R, color_G, color_B, 1);
}
}
// Set positions VBO
glGenBuffers(1, &pointVBO);
glBindBuffer(GL_ARRAY_BUFFER, pointVBO);
// glBufferData(GL_ARRAY_BUFFER, sizeof(pointPositions) + sizeof(pointColors), nullptr, GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * pointNumVertex + sizeof(glm::vec4) * pointNumVertex, nullptr, GL_STATIC_DRAW);
// Upload position data
// glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(pointPositions), pointPositions);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::vec3) * pointNumVertex, pointPositions);
// Upload color data
// glBufferSubData(GL_ARRAY_BUFFER, sizeof(pointPositions), sizeof(pointColors), pointColors);
glBufferSubData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * pointNumVertex, sizeof(glm::vec4) * pointNumVertex, pointColors);
glGenVertexArrays(1, &pointVAO);
glBindVertexArray(pointVAO);
// Bind pointVBO
glBindBuffer(GL_ARRAY_BUFFER, pointVBO);
// Set "position" layout
GLuint loc = glGetAttribLocation(pipelineProgram->GetProgramHandle(), "position");
glEnableVertexAttribArray(loc);
const void * offset = (const void*) 0;
GLsizei stride = 0;
glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, stride, offset);
// Set "color" layout
loc = glGetAttribLocation(pipelineProgram->GetProgramHandle(), "color");
glEnableVertexAttribArray(loc);
// offset = (const void*) sizeof(pointPositions);
offset = (const void*) (sizeof(glm::vec3) * pointNumVertex);
glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, stride, offset);
glBindVertexArray(0); // Unbind the VAO
glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind the VBO
delete [] pointPositions;
delete [] pointColors;
}
*/
glEnable(GL_DEPTH_TEST);
std::cout << "GL error: " << glGetError() << std::endl;
}
int main(int argc, char *argv[])
{
if (argc<2)
{
printf ("usage: %s <trackfile>\n", argv[0]);
exit(0);
}
std::cout << "Initializing GLUT..." << endl;
glutInit(&argc,argv);
std::cout << "Initializing OpenGL..." << endl;
#ifdef __APPLE__
glutInitDisplayMode(GLUT_3_2_CORE_PROFILE | GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL);
#else
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STENCIL);
#endif
glutInitWindowSize(windowWidth, windowHeight);
glutInitWindowPosition(0, 0);
glutCreateWindow(windowTitle);
std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << endl;
std::cout << "OpenGL Renderer: " << glGetString(GL_RENDERER) << endl;
std::cout << "Shading Language Version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl;
#ifdef __APPLE__
// This is needed on recent Mac OS X versions to correctly display the window.
glutReshapeWindow(windowWidth - 1, windowHeight - 1);
#endif
// tells glut to use a particular display function to redraw
glutDisplayFunc(displayFunc);
// perform animation inside idleFunc
glutIdleFunc(idleFunc);
// callback for mouse drags
glutMotionFunc(mouseMotionDragFunc);
// callback for idle mouse movement
glutPassiveMotionFunc(mouseMotionFunc);
// callback for mouse button changes
glutMouseFunc(mouseButtonFunc);
// callback for resizing the window
glutReshapeFunc(reshapeFunc);
// callback for pressing the keys on the keyboard
glutKeyboardFunc(keyboardFunc);
// init glew
#ifdef __APPLE__
// nothing is needed on Apple
#else
// Windows, Linux
GLint result = glewInit();
if (result != GLEW_OK)
{
std::cout << "error: " << glewGetErrorString(result) << endl;
exit(EXIT_FAILURE);
}
#endif
// do initialization
initScene(argc, argv);
// sink forever into the glut loop
glutMainLoop();
}
| [
"ziangliu@usc.edu"
] | ziangliu@usc.edu |
f9168f57090a523d26cd9f969e2661282f287a17 | eb1ab8e2a2799d321c89805ca3b7958dc8414763 | /fon/FormantGrid.cpp | b8f2c7bd1421c4322733fb19d53616d7623fa9aa | [] | no_license | imnorobot/upraat | 401aa2f8ad95dcd1c420298eca1770f0896de23b | 8a1f44b02ad363813be1240d7c22d4a0c36c9be8 | refs/heads/master | 2016-09-06T11:13:52.795830 | 2012-10-03T07:56:47 | 2012-10-03T07:56:47 | 6,055,912 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,034 | cpp | /* FormantGrid.cpp
*
* Copyright (C) 2008-2011 Paul Boersma & David Weenink
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "FormantGrid.h"
#include "PitchTier_to_Sound.h"
#include "Formula.h"
#include "oo_DESTROY.h"
#include "FormantGrid_def.h"
#include "oo_COPY.h"
#include "FormantGrid_def.h"
#include "oo_EQUAL.h"
#include "FormantGrid_def.h"
#include "oo_CAN_WRITE_AS_ENCODING.h"
#include "FormantGrid_def.h"
#include "oo_WRITE_TEXT.h"
#include "FormantGrid_def.h"
#include "oo_READ_TEXT.h"
#include "FormantGrid_def.h"
#include "oo_WRITE_BINARY.h"
#include "FormantGrid_def.h"
#include "oo_READ_BINARY.h"
#include "FormantGrid_def.h"
#include "oo_DESCRIPTION.h"
#include "FormantGrid_def.h"
Thing_implement (FormantGrid, Function, 0);
double structFormantGrid :: v_getVector (long irow, long icol) {
RealTier tier = (RealTier) formants -> item [irow];
return RealTier_getValueAtIndex (tier, icol);
}
double structFormantGrid :: v_getFunction1 (long irow, double x) {
RealTier tier = (RealTier) formants -> item [irow];
return RealTier_getValueAtTime (tier, x);
}
void structFormantGrid :: v_shiftX (double xfrom, double xto) {
FormantGrid_Parent :: v_shiftX (xfrom, xto);
for (long i = 1; i <= formants -> size; i ++) {
RealTier tier = (RealTier) formants -> item [i];
tier -> v_shiftX (xfrom, xto);
}
for (long i = 1; i <= bandwidths -> size; i ++) {
RealTier tier = (RealTier) bandwidths -> item [i];
tier -> v_shiftX (xfrom, xto);
}
}
void structFormantGrid :: v_scaleX (double xminfrom, double xmaxfrom, double xminto, double xmaxto) {
FormantGrid_Parent :: v_scaleX (xminfrom, xmaxfrom, xminto, xmaxto);
for (long i = 1; i <= formants -> size; i ++) {
RealTier tier = (RealTier) formants -> item [i];
tier -> v_scaleX (xminfrom, xmaxfrom, xminto, xmaxto);
}
for (long i = 1; i <= bandwidths -> size; i ++) {
RealTier tier = (RealTier) bandwidths -> item [i];
tier -> v_scaleX (xminfrom, xmaxfrom, xminto, xmaxto);
}
}
void FormantGrid_init (I, double tmin, double tmax, long numberOfFormants) {
iam (FormantGrid);
my formants = Ordered_create ();
my bandwidths = Ordered_create ();
for (long iformant = 1; iformant <= numberOfFormants; iformant ++) {
RealTier formant = RealTier_create (tmin, tmax);
Collection_addItem (my formants, formant);
RealTier bandwidth = RealTier_create (tmin, tmax);
Collection_addItem (my bandwidths, bandwidth);
}
my xmin = tmin;
my xmax = tmax;
}
FormantGrid FormantGrid_createEmpty (double tmin, double tmax, long numberOfFormants) {
try {
autoFormantGrid me = Thing_new (FormantGrid);
FormantGrid_init (me.peek(), tmin, tmax, numberOfFormants);
return me.transfer();
} catch (MelderError) {
Melder_throw ("Empty FormantGrid not created.");
}
}
FormantGrid FormantGrid_create (double tmin, double tmax, long numberOfFormants,
double initialFirstFormant, double initialFormantSpacing,
double initialFirstBandwidth, double initialBandwidthSpacing)
{
try {
autoFormantGrid me = FormantGrid_createEmpty (tmin, tmax, numberOfFormants);
for (long iformant = 1; iformant <= numberOfFormants; iformant ++) {
FormantGrid_addFormantPoint (me.peek(), iformant, 0.5 * (tmin + tmax),
initialFirstFormant + (iformant - 1) * initialFormantSpacing);
FormantGrid_addBandwidthPoint (me.peek(), iformant, 0.5 * (tmin + tmax),
initialFirstBandwidth + (iformant - 1) * initialBandwidthSpacing);
}
return me.transfer();
} catch (MelderError) {
Melder_throw ("FormantGrid not created.");
}
}
void FormantGrid_addFormantPoint (FormantGrid me, long iformant, double t, double value) {
try {
if (iformant < 1 || iformant > my formants -> size)
Melder_throw ("No such formant number.");
RealTier formantTier = (RealTier) my formants -> item [iformant];
RealTier_addPoint (formantTier, t, value);
} catch (MelderError) {
Melder_throw (me, ": formant point not added.");
}
}
void FormantGrid_addBandwidthPoint (FormantGrid me, long iformant, double t, double value) {
try {
if (iformant < 1 || iformant > my formants -> size)
Melder_throw ("No such formant number.");
RealTier bandwidthTier = (RealTier) my bandwidths -> item [iformant];
RealTier_addPoint (bandwidthTier, t, value);
} catch (MelderError) {
Melder_throw (me, ": bandwidth point not added.");
}
}
double FormantGrid_getFormantAtTime (FormantGrid me, long iformant, double t) {
if (iformant < 1 || iformant > my formants -> size) return NUMundefined;
return RealTier_getValueAtTime ((RealTier) my formants -> item [iformant], t);
}
double FormantGrid_getBandwidthAtTime (FormantGrid me, long iformant, double t) {
if (iformant < 1 || iformant > my bandwidths -> size) return NUMundefined;
return RealTier_getValueAtTime ((RealTier) my bandwidths -> item [iformant], t);
}
void FormantGrid_removeFormantPointsBetween (FormantGrid me, long iformant, double tmin, double tmax) {
if (iformant < 1 || iformant > my formants -> size) return;
AnyTier_removePointsBetween (my formants -> item [iformant], tmin, tmax);
}
void FormantGrid_removeBandwidthPointsBetween (FormantGrid me, long iformant, double tmin, double tmax) {
if (iformant < 1 || iformant > my bandwidths -> size) return;
AnyTier_removePointsBetween (my bandwidths -> item [iformant], tmin, tmax);
}
void Sound_FormantGrid_filter_inline (Sound me, FormantGrid formantGrid) {
double dt = my dx;
if (formantGrid -> formants -> size && formantGrid -> bandwidths -> size)
for (long iformant = 1; iformant <= formantGrid -> formants -> size; iformant ++) {
RealTier formantTier = (RealTier) formantGrid -> formants -> item [iformant];
RealTier bandwidthTier = (RealTier) formantGrid -> bandwidths -> item [iformant];
for (long isamp = 1; isamp <= my nx; isamp ++) {
double t = my x1 + (isamp - 1) * my dx;
/*
* Compute LP coefficients.
*/
double formant, bandwidth;
formant = RealTier_getValueAtTime (formantTier, t);
bandwidth = RealTier_getValueAtTime (bandwidthTier, t);
if (NUMdefined (formant) && NUMdefined (bandwidth)) {
double cosomdt = cos (2 * NUMpi * formant * dt);
double r = exp (- NUMpi * bandwidth * dt);
/* Formants at 0 Hz or the Nyquist are single poles, others are double poles. */
if (fabs (cosomdt) > 0.999999) { /* Allow for round-off errors. */
/* single pole: D(z) = 1 - r z^-1 */
for (long channel = 1; channel <= my ny; channel ++) {
if (isamp > 1) my z [channel] [isamp] += r * my z [channel] [isamp - 1];
}
} else {
/* double pole: D(z) = 1 + p z^-1 + q z^-2 */
double p = - 2 * r * cosomdt;
double q = r * r;
for (long channel = 1; channel <= my ny; channel ++) {
if (isamp > 1) my z [channel] [isamp] -= p * my z [channel] [isamp - 1];
if (isamp > 2) my z [channel] [isamp] -= q * my z [channel] [isamp - 2];
}
}
}
}
}
}
Sound Sound_FormantGrid_filter (Sound me, FormantGrid formantGrid) {
try {
autoSound thee = Data_copy (me);
Sound_FormantGrid_filter_inline (thee.peek(), formantGrid);
Vector_scale (thee.peek(), 0.99);
return thee.transfer();
} catch (MelderError) {
Melder_throw (me, ": not filtered with ", formantGrid, ".");
}
}
Sound Sound_FormantGrid_filter_noscale (Sound me, FormantGrid formantGrid) {
try {
autoSound thee = Data_copy (me);
Sound_FormantGrid_filter_inline (thee.peek(), formantGrid);
return thee.transfer();
} catch (MelderError) {
Melder_throw (me, ": not filtered with ", formantGrid, ".");
}
}
Sound FormantGrid_to_Sound (FormantGrid me, double samplingFrequency,
double tStart, double f0Start, double tMid, double f0Mid, double tEnd, double f0End,
double adaptFactor, double maximumPeriod, double openPhase, double collisionPhase, double power1, double power2)
{
try {
autoPitchTier pitch = PitchTier_create (my xmin, my xmax);
RealTier_addPoint (pitch.peek(), my xmin + tStart * (my xmax - my xmin), f0Start);
RealTier_addPoint (pitch.peek(), my xmin + tMid * (my xmax - my xmin), f0Mid);
RealTier_addPoint (pitch.peek(), my xmax - (1.0 - tEnd) * (my xmax - my xmin), f0End);
autoSound thee = PitchTier_to_Sound_phonation (pitch.peek(), samplingFrequency,
adaptFactor, maximumPeriod, openPhase, collisionPhase, power1, power2, false);
Sound_FormantGrid_filter_inline (thee.peek(), me);
return thee.transfer();
} catch (MelderError) {
Melder_throw (me, ": not converted to Sound.");
}
}
void FormantGrid_playPart (FormantGrid me, double tmin, double tmax, double samplingFrequency,
double tStart, double f0Start, double tMid, double f0Mid, double tEnd, double f0End,
double adaptFactor, double maximumPeriod, double openPhase, double collisionPhase, double power1, double power2,
int (*playCallback) (void *playClosure, int phase, double tmin, double tmax, double t), void *playClosure)
{
try {
autoSound sound = FormantGrid_to_Sound (me, samplingFrequency,
tStart, f0Start, tMid, f0Mid, tEnd, f0End,
adaptFactor, maximumPeriod, openPhase, collisionPhase, power1, power2);
Vector_scale (sound.peek(), 0.99);
Sound_playPart (sound.peek(), tmin, tmax, playCallback, playClosure);
} catch (MelderError) {
Melder_throw (me, ": not played.");
}
}
void FormantGrid_formula_bandwidths (FormantGrid me, const wchar_t *expression, Interpreter interpreter, FormantGrid thee) {
try {
Formula_compile (interpreter, me, expression, kFormula_EXPRESSION_TYPE_NUMERIC, TRUE);
if (thee == NULL) thee = me;
for (long irow = 1; irow <= my formants -> size; irow ++) {
RealTier bandwidth = (RealTier) thy bandwidths -> item [irow];
for (long icol = 1; icol <= bandwidth -> points -> size; icol ++) {
struct Formula_Result result;
Formula_run (irow, icol, & result);
if (result. result.numericResult == NUMundefined)
Melder_throw ("Cannot put an undefined value into the tier.\nFormula not finished.");
((RealPoint) bandwidth -> points -> item [icol]) -> value = result. result.numericResult;
}
}
} catch (MelderError) {
Melder_throw (me, ": bandwidth formula not completed.");
}
}
void FormantGrid_formula_frequencies (FormantGrid me, const wchar_t *expression, Interpreter interpreter, FormantGrid thee) {
try {
Formula_compile (interpreter, me, expression, kFormula_EXPRESSION_TYPE_NUMERIC, TRUE);
if (thee == NULL) thee = me;
for (long irow = 1; irow <= my formants -> size; irow ++) {
RealTier formant = (RealTier) thy formants -> item [irow];
for (long icol = 1; icol <= formant -> points -> size; icol ++) {
struct Formula_Result result;
Formula_run (irow, icol, & result);
if (result. result.numericResult == NUMundefined)
Melder_throw ("Cannot put an undefined value into the tier.\nFormula not finished.");
((RealPoint) formant -> points -> item [icol]) -> value = result. result.numericResult;
}
}
} catch (MelderError) {
Melder_throw (me, ": frequency formula not completed.");
}
}
FormantGrid Formant_downto_FormantGrid (Formant me) {
try {
autoFormantGrid thee = FormantGrid_createEmpty (my xmin, my xmax, my maxnFormants);
for (long iframe = 1; iframe <= my nx; iframe ++) {
Formant_Frame frame = & my d_frames [iframe];
double t = Sampled_indexToX (me, iframe);
for (long iformant = 1; iformant <= frame -> nFormants; iformant ++) {
Formant_Formant pair = & frame -> formant [iformant];
FormantGrid_addFormantPoint (thee.peek(), iformant, t, pair -> frequency);
FormantGrid_addBandwidthPoint (thee.peek(), iformant, t, pair -> bandwidth);
}
}
return thee.transfer();
} catch (MelderError) {
Melder_throw (me, ": not converted to FormantGrid.");
}
}
Formant FormantGrid_to_Formant (FormantGrid me, double dt, double intensity) {
try {
Melder_assert (dt > 0.0);
Melder_assert (intensity >= 0.0);
long nt = (long) floor ((my xmax - my xmin) / dt) + 1;
double t1 = 0.5 * (my xmin + my xmax - (nt - 1) * dt);
autoFormant thee = Formant_create (my xmin, my xmax, nt, dt, t1, my formants -> size);
for (long iframe = 1; iframe <= nt; iframe ++) {
Formant_Frame frame = & thy d_frames [iframe];
frame -> intensity = intensity;
frame -> nFormants = my formants -> size;
frame -> formant = NUMvector <structFormant_Formant> (1, my formants -> size);
double t = t1 + (iframe - 1) * dt;
for (long iformant = 1; iformant <= my formants -> size; iformant ++) {
Formant_Formant formant = & frame -> formant [iformant];
formant -> frequency = RealTier_getValueAtTime ((RealTier) my formants -> item [iformant], t);
formant -> bandwidth = RealTier_getValueAtTime ((RealTier) my bandwidths -> item [iformant], t);
}
}
return thee.transfer();
} catch (MelderError) {
Melder_throw (me, ": not converted to Formant.");
}
}
Sound Sound_Formant_filter (Sound me, Formant formant) {
try {
autoFormantGrid grid = Formant_downto_FormantGrid (formant);
autoSound thee = Sound_FormantGrid_filter (me, grid.peek());
return thee.transfer();
} catch (MelderError) {
Melder_throw (me, ": not filtered with ", formant, ".");
}
}
Sound Sound_Formant_filter_noscale (Sound me, Formant formant) {
try {
autoFormantGrid grid = Formant_downto_FormantGrid (formant);
autoSound thee = Sound_FormantGrid_filter_noscale (me, grid.peek());
return thee.transfer();
} catch (MelderError) {
Melder_throw (me, ": not filtered with ", formant, ".");
}
}
/* End of file FormantGrid.cpp */
| [
"dellison@email.arizona.edu"
] | dellison@email.arizona.edu |
cfb406910eb7983db24775c9d7883cff9fb69869 | 1d0a4511fecf241bc422aada22f24b4af16dd32d | /PWG/FLOW/Tasks/AliAnalysisTaskCMWESE.h | e6b869b3ac974a40daaecf7a1d6a4b2cdd0a7c44 | [] | permissive | gskorodu/AliPhysics | d119d0bfc09da5e63af6e27bd669569197a7afac | cee15828f9c460d93d67a7ddd505f0eec4db5c35 | refs/heads/master | 2021-11-10T20:23:31.492946 | 2021-11-10T11:37:30 | 2021-11-10T11:37:30 | 173,935,052 | 0 | 0 | BSD-3-Clause | 2019-03-05T11:36:31 | 2019-03-05T11:36:30 | null | UTF-8 | C++ | false | false | 10,234 | h | #ifndef AliAnalysisTaskCMWESE_cxx
#define AliAnalysisTaskCMWESE_cxx
#include "AliAnalysisTaskSE.h"
#include "AliEventCuts.h"
#include "AliAODTrack.h"
#include "TProfile3D.h"
#include "TProfile2D.h"
#include "TProfile.h"
#include "TComplex.h"
#include "TList.h"
#include "TFile.h"
#include "TSpline.h"
#include "TProfile.h"
#include "TH1.h"
#include "TH2.h"
//class AliAnalysisUtils;
#include "AliAnalysisTaskSE.h"
#include "AliEventCuts.h"
class AliAnalysisTaskCMWESE : public AliAnalysisTaskSE
{
public:
AliAnalysisTaskCMWESE();
AliAnalysisTaskCMWESE(const char *name);
AliAnalysisTaskCMWESE(const char *name, TString PR, bool NUE, bool NUA, bool V0Calib);
virtual ~AliAnalysisTaskCMWESE();
virtual void UserCreateOutputObjects();
virtual void UserExec(Option_t *option);
virtual void Terminate(Option_t *);
int GetDebug(){return fDebug;}
void SetDebug(int x){fDebug = x;}
int GerHarmonic(){return fHarmonic;}
void SetHarmonic(double x) {fHarmonic = x;}
int GetTrigger(){return fTrigger;}
void SetTrigger(int x){fTrigger = x;}
int GetFilterBit(){return fFltbit;}
void SetFilterBit(int x){fFltbit = x;}
int GetNclsCut(){return fNclsCut;}
void SetNclsCut(int x){fNclsCut = x;}
float GetChi2High(){return fChi2Hg;}
void SetChi2High(float x){fChi2Hg = x;}
float GetChi2Low(){return fChi2Lo;}
void SetChi2Low(float x){fChi2Lo = x;}
float GetDCAcutZ(){return fDcaCutz;}
void SetDCAcutZ(float x){fDcaCutz = x;}
float GetDCAcutXY(){return fDcaCutxy;}
void SetDCAcutXY(float x){fDcaCutxy = x;}
float GetPtMin(){return fPtMin;}
void SetPtMin(float x){fPtMin = x;}
float GetPtMax(){return fPtMax;}
void SetPtMax(float x){fPtMax = x;}
int GetCentBinLow(){return fCbinLo;}
void SetCentBinLow(int x){fCbinLo = x;}
int GetCentBinHigh(){return fCbinHg;}
void SetCentBinHigh(int x){fCbinHg = x;}
TString GetPeriod(){return fPeriod;}
void SetPeriod(TString x) { fPeriod = x; }
TString GetMultComp(){return fMultComp;}
void SetMultComp(TString x) { fMultComp = x; }
float GetEtaGap(){return fEtaGap;}
void SetEtaGap(float x) { fEtaGap = x; }
bool GetV0CalibOn(){return fV0CalibOn;}
void SetV0CalibOn(bool x){fV0CalibOn = x;}
bool GetTPCCalibOn(){return fTPCCalibOn;}
void SetTPCCalibOn(bool x){fTPCCalibOn = x;}
bool GetV0QAOn(){return fQAV0;}
void SetV0QAOn(bool x){fQAV0 = x;}
bool GetTPCQAOn(){return fQATPC;}
void SetTPCQAOn(bool x){fQATPC = x;}
bool GetNUEOn(){return fDoNUE;}
void SetNUEOn(bool x){fDoNUE = x;}
bool GetNUAOn(){return fDoNUA;}
void SetNUAOn(bool x){fDoNUA = x;}
float GetCentCut(){return fCentCut;}
void SetCentCut(float x){fCentCut = x;}
private:
static const int NCENTBINS = 10;
static const int NPOIBINS = 2;
static const int NQNBINS = 10;
void ResetHists();
bool DoCumulants();
void CalcRefFlow();
void CalcIntCov();
double GetNUECor(int charge, double pt);
double GetNUACor(int charge, double phi, double eta, double vz);
int GetRunNumBin(int runNum);
// pile-up
bool RejectEvtMultComp (AliAODEvent* fAOD);
bool RejectEvtTFFit(AliAODEvent* fAOD);
bool RejectEvtTPCITSfb32TOF (AliAODEvent* fAOD);
bool AODPileupCheck (AliAODEvent* fAOD);
bool PileUpMultiVertex (AliAODEvent* fAOD);
double GetWDist(const AliVVertex* v0, const AliVVertex* v1);
bool RemovalForLHC18 (AliAODEvent* fAOD);
bool RemovalForRun1 (AliAODEvent* fAOD, AliAnalysisUtils* fUtils);
bool RemovalForpPb (AliAODEvent* fAOD);
bool AcceptAODTrack(AliAODEvent* fAOD, AliAODTrack *track, AliAODVertex* fVtx);
bool AnalyzeAOD(AliAODEvent* fAOD, AliAODVertex* fVtx);
bool CalcQnVectorV0(AliAODEvent* fAOD, AliAODVertex* fVtx, double mAch, double Mult);
bool CalcQnVectorTPC(AliAODEvent* fAOD);
int GetQnPercV0(double qn_thtsEvt, double mAch, double Mult);
bool GetV0CalibHisto(AliAODEvent* fAOD, AliAODVertex* fVtx);
int GetQnPercTPC(AliAODEvent* fAOD);
double GetEventPlane(double qx, double qy);
int GetPercCode(double perc);
// Cuts and options
int fDebug; // debug level controls amount of output statements
double fHarmonic; // value of harmonic
int fTrigger; // flag of trigger; 0 = kINT7; 1 = kMB; 2 = kMB+kCentral+kSemiCentral
int fFltbit; // AOD filter bit selection
int fNclsCut; // ncls cut for all tracks
float fChi2Hg; // upper limmit for chi2
float fChi2Lo; // lower limmit for chi2
float fDcaCutz; // dcaz cut for all tracks
float fDcaCutxy; // dcaxy cut for all tracks
float fPtMin; // minimum pt for Q-vector components
float fPtMax; // maximum pt for Q-vector components
int fCbinHg; // higher centrality bin for histogram array
int fCbinLo; // lower centrality bin for histogram array
TString fPeriod; // period
TString fMultComp; // Multiplicity Comparison pile-up
double fEtaGap; // value for the Eta Gap in c2 calculation
bool fV0CalibOn; // switch for v0 qn calib
bool fTPCCalibOn; // switch for tpc qn calib
bool fQAV0; // flag for V0 qn QA
bool fQATPC; // flag for TPC qn QA
bool fDoNUE; // switch for NUE
bool fDoNUA; // switch for NUA
float fCentCut; // centrality restriction for V0M and TRK
// Global Variables Unchanged in an Evt
int fRunNum; // runnumber
int fRunNumBin; // runnumer bin; 10:139510...; 11:170387...; 15HIR:246994...
int fVzBin; // vertex z bin
int fCentBin; // centrality bin: 0-10
double fCent; // value of centrality
int fQnBin; // qn bin: 0-10
const float fEtaCut; // eta cut
const float fDedxCut; //dedx cut
const float fZvtxCut; // z-vertex selection for collision
// Weight List
TList* fListNUE; // read list for NUE
TList* fListNUA1; // read lists for NUA
TList* fListNUA2; // read lists for NUA
TList* fListNUA3; // read lists for NUA
TList* fListVZEROCALIB; // read list fpr V0 Calib
// Q QStar event-wise
TComplex fNegEtaQ;
TComplex fNegEtaQStar;
TComplex fPosEtaQ;
TComplex fPosEtaQStar;
double fNegEtaMQ;
double fPosEtaMQ;
// Read Files for NUA/NUE/VoCalib
TH1D* hNUEweightPlus;
TH1D* hNUEweightMinus;
TH2D* hNUAweightPlus;
TH2D* hNUAweightMinus;
TH3F* hCorrectNUAPos; // Protty
TH3F* hCorrectNUANeg; // Protty
TH2D* hMultV0Read;
TH2D* hQnPercentile;
TH1D* hQnPercentile_centThisEvt;
TSpline3* sp;
TF1* fSPDCutPU;
TF1* fV0CutPU;
TF1* fCenCutLowPU;
TF1* fCenCutHighPU;
TF1* fMultCutPU;
// Output QA
TList* fOutputList;
TH1D* hEvtCount;
TH1I* hRunNumBin;
TH1D* hPt;
TH2D* hPDedx;
// Update Evt-by-Evt, will not be saved
TH2D* hReQ_thisEvt;
TH2D* hImQ_thisEvt;
TH2D* hReQ2_thisEvt;
TH2D* hImQ2_thisEvt;
TH2D* hMQ_thisEvt;
TH2D* hMQ_weight_thisEvt;
TH2D* hReQPos_thisEvt;
TH2D* hImQPos_thisEvt;
TH2D* hMQPos_thisEvt;
TH2D* hMQPos_weight_thisEvt;
TH2D* hReQNeg_thisEvt;
TH2D* hImQNeg_thisEvt;
TH2D* hMQNeg_thisEvt;
TH2D* hMQNeg_weight_thisEvt;
TProfile* pRefFlow_thisEvt;
TProfile* pIntd2_thisEvt;
// Read Files for V0Calib
TProfile3D* pV0XMeanRead[3];
TProfile3D* pV0YMeanRead[3];
// Run2 A.Dorbin
TH1D* hMultV0[138]; //Dobrin
TH1D* hQxnmV0[138][2];
TH1D* hQynmV0[138][2];
TH1D* hQxnsV0[138][2];
TH1D* hQynsV0[138][2];
double fMultV0Ch[64];
double fV0XMean[3];
double fV0YMean[3];
double fV0XSigma[3];
double fV0YSigma[3];
TSpline3* splQ2c[90]; //A.Dobrin
// Output QA
TH1D* hCent[2];
TH1D* hVz[2];
TH2D* hCentQA[8];
TH2D* hMultCentQA[2];
TH2D* hMultMultQA[6];
TProfile* pV2pT[NCENTBINS];
// track-wise QA
TH1D* hEta[2];
TH1D* hPhi[2];
TH2D* hEtaPhi[2];
TH1D* hDcaXy[2];
TH1D* hDcaZ[2];
TH1D* hNhits[2];
// Qn & psi QA
TH2D* hQxCentRecenter[3];
TH2D* hQxVtxRecenter[3];
TH2D* hQyCentRecenter[3];
TH2D* hQyVtxRecenter[3];
TH2D* hQnCentRecenter[3];
TH1D* hPsiV0Recenter[NCENTBINS][3];
// physics
TProfile* pRefFlow[NCENTBINS];
TProfile* pIntd2[NCENTBINS];
TProfile* pIntd2Ach[NCENTBINS];
TProfile* pAch[NCENTBINS];
TH1D* hMult[NCENTBINS+1][NQNBINS];
TH1D* hAch[NCENTBINS+1][NQNBINS];
AliAnalysisTaskCMWESE(const AliAnalysisTaskCMWESE&);
AliAnalysisTaskCMWESE& operator=(const AliAnalysisTaskCMWESE&);
ClassDef(AliAnalysisTaskCMWESE, 1);
};
#endif | [
"2487640463@qq.com"
] | 2487640463@qq.com |
30149b02a4e7f77367ebb0eccb57a44ebf6055c9 | ad3bc509c4f61424492b2949e03c60628f631a31 | /test/posix_captures/other/09_stadfa.re | e1cdb1033c03491d9b0c29237f69bdb57a40b057 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] | permissive | sergeyklay/re2c | 0b1cdbfe40b4514be33320b2e1d263cf5d6426d6 | 88ff1e5a2ad57d424fe999e17960c564886d36f4 | refs/heads/master | 2021-12-23T22:24:30.716697 | 2021-06-26T22:56:00 | 2021-06-27T15:23:28 | 299,206,360 | 0 | 0 | NOASSERTION | 2021-06-19T10:49:05 | 2020-09-28T06:10:35 | C | UTF-8 | C++ | false | false | 132 | re | // re2c $INPUT -o $OUTPUT -i --flex-syntax --stadfa
/*!re2c
re2c:flags:posix-captures = 1;
(aa*|aaa*)*
{}
"" {}
*/
| [
"skvadrik@gmail.com"
] | skvadrik@gmail.com |
932f0d5ebac069f7ee5c241c35d9c7f98317cc8d | 98cf264eeab058754c55aeae5c0bb6c55516d49a | /Oculus/OculusCompassTest/ClientSocketTest/TmpSocketTest.cpp | f8071e5a15a83d6171a8e3972f7fdc3e16c77761 | [] | no_license | JMilleson/tredjepersonsvy | 2c417f7cb3469d99932c6a9a1d33698ae5dd81c9 | 7340537f6570f47a5ba2733d1f09a3fba563b8f5 | refs/heads/master | 2020-04-16T00:33:10.666768 | 2016-03-30T11:47:43 | 2016-03-30T11:47:43 | 50,998,747 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,878 | cpp |
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <stdio.h>
#include <OVR_CAPI.h>
#include <OVR_Math.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "8888"
#define DEFAULT_ADDRES "192.168.42.1"
#define TARGET_HEIGHT 200
#define STX '\002'
#define ETX '\003'
void readCompass(ovrSession session, SOCKET ConnectSocket)
{
using namespace OVR;
int iResult;
char sendbuf[10];
OVR::Posef pose;
while (1)
{
//Change ovr time to predict future
ovrTrackingState ts = ovr_GetTrackingState(session, ovr_GetTimeInSeconds(), ovrFalse);
float yaw, pitch, roll;
if (ts.StatusFlags & (ovrStatus_OrientationTracked | ovrStatus_PositionTracked))
{
pose = ts.HeadPose.ThePose;
pose.Rotation.GetEulerAngles<Axis_Y, Axis_X, Axis_Z>(&yaw, &roll, &pitch);
yaw = yaw * 180 / 3.1416;
yaw += 200;
printf("compass: %f\n", yaw);
printf("target height: %d\n", TARGET_HEIGHT);
//sprintf_s(sendbuf, "%6.1f", yaw);
sendbuf[0] = STX;
sendbuf[1] = '0' + (((int)(yaw / 100)) % 10);
sendbuf[2] = '0' + (((int)(yaw / 10)) % 10);
sendbuf[3] = '0' + (((int)yaw) % 10);
sendbuf[4] = '0' + (((int)(TARGET_HEIGHT / 1000)) % 10);
sendbuf[5] = '0' + (((int)(TARGET_HEIGHT / 100)) % 10);
sendbuf[6] = '0' + (((int)(TARGET_HEIGHT / 10)) % 10);
sendbuf[7] = '0' + (((int)TARGET_HEIGHT) % 10);
sendbuf[8] = ETX;
sendbuf[9] = '\0';
iResult = send(ConnectSocket, sendbuf, 10, 0);
if (iResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
}
}
Sleep(500);
}
}
// Include the OculusVR SDK
void Application()
{
ovrResult ovrResult = ovr_Initialize(nullptr);
if (OVR_FAILURE(ovrResult))
return;
ovrSession session;
ovrGraphicsLuid luid;
ovrResult = ovr_Create(&session, &luid);
if (OVR_FAILURE(ovrResult))
{
ovr_Shutdown();
return;
}
ovrHmdDesc desc = ovr_GetHmdDesc(session);
ovrSizei resolution = desc.Resolution;
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
//char *sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo("192.168.42.1", DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return;
}
readCompass(session, ConnectSocket);
ovr_Destroy(session);
ovr_Shutdown();
}
int __cdecl main(int argc, char **argv)
{
Application();
return 0;
}
/*int __cdecl main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
//char *sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN;
// Validate the parameters
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo("192.168.42.1", DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
char sendbuf[5];
sendbuf[0] = '|';
sendbuf[1] = '1';
sendbuf[2] = '2';
sendbuf[3] = '3';
sendbuf[4] = '|';
while (1) {
iResult = send(ConnectSocket, sendbuf, 5, 0);
if (iResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
}
Sleep(1000);
}
printf("Bytes Sent: %ld\n", iResult);
// cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
*/ | [
"jacob@gideflod.se"
] | jacob@gideflod.se |
470f12c486aa7f5babaf74c3788605ba46c4919c | 8c4110620598955e79bafcc343de86f7bbc02eed | /src/main.cpp | 00d480c0e4365596de4d822886d5a53549e92b42 | [] | no_license | nuocoin/nuocoin | aebe78b71531b28160bd910aa9dd77a32718d2b2 | ccf4c17fba78a4ae14d61d57c3ace08e1263bf7e | refs/heads/master | 2021-01-18T10:52:52.951628 | 2016-05-19T09:14:20 | 2016-05-19T09:14:20 | 58,093,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 172,498 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Copyright (c) 2013 The Sifcoin developers
// Copyright (c) 2013 The NuoCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <math.h>
#include "alert.h"
#include "checkpoints.h"
#include "db.h"
#include "txdb.h"
#include "net.h"
#include "init.h"
#include "ui_interface.h"
#include "checkqueue.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace std;
using namespace boost;
//
// Global state
//
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
unsigned int nTransactionsUpdated = 0;
map<uint256, CBlockIndex*> mapBlockIndex;
uint256 hashGenesisBlock("0x0000095af3910afca63c7bb31e9750902284309def5afdf6164577894f07b2b3");
static const unsigned int timeGenesisBlock = 1462524673;
static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // joy joy
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
uint256 nBestChainWork = 0;
uint256 nBestInvalidWork = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed
int64 nTimeBestReceived = 0;
int nScriptCheckThreads = 0;
bool fImporting = false;
bool fReindex = false;
bool fBenchmark = false;
bool fTxIndex = false;
unsigned int nCoinCacheSize = 5000;
/** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */
int64 CTransaction::nMinTxFee = 10; // Override with -mintxfee
/** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */
int64 CTransaction::nMinRelayTxFee = 100;
CMedianFilter<int> cPeerBlockCounts(8, 0); // Amount of blocks that other nodes claim to have
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
map<uint256, CDataStream*> mapOrphanTransactions;
map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "NuoCoin Signed Message:\n";
double dHashesPerSec = 0.0;
int64 nHPSTimerStart = 0;
// Settings
int64 nTransactionFee = 0;
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
void RegisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.insert(pwalletIn);
}
}
void UnregisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.erase(pwalletIn);
}
}
// get the wallet transaction with the given hash (if it exists)
bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->GetTransaction(hashTx,wtx))
return true;
return false;
}
// erases transaction with the given hash from all wallets
void static EraseFromWallets(uint256 hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->EraseFromWallet(hash);
}
// make sure all wallets know about the given transaction, in the given block
void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
}
// notify wallets about a new best chain
void static SetBestChain(const CBlockLocator& loc)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->SetBestChain(loc);
}
// notify wallets about an updated transaction
void static UpdatedTransaction(const uint256& hashTx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->UpdatedTransaction(hashTx);
}
// dump all wallets
void static PrintWallets(const CBlock& block)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->PrintWallet(block);
}
// notify wallets about an incoming inventory (for request counts)
void static Inventory(const uint256& hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->Inventory(hash);
}
// ask wallets to resend their transactions
void static ResendWalletTransactions()
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->ResendWalletTransactions();
}
//////////////////////////////////////////////////////////////////////////////
//
// CCoinsView implementations
//
bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) { return false; }
bool CCoinsView::SetCoins(const uint256 &txid, const CCoins &coins) { return false; }
bool CCoinsView::HaveCoins(const uint256 &txid) { return false; }
CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
bool CCoinsView::GetStats(CCoinsStats &stats) { return false; }
CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) { return base->GetCoins(txid, coins); }
bool CCoinsViewBacked::SetCoins(const uint256 &txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
bool CCoinsViewBacked::HaveCoins(const uint256 &txid) { return base->HaveCoins(txid); }
CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
bool CCoinsViewBacked::GetStats(CCoinsStats &stats) { return base->GetStats(stats); }
CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) {
if (cacheCoins.count(txid)) {
coins = cacheCoins[txid];
return true;
}
if (base->GetCoins(txid, coins)) {
cacheCoins[txid] = coins;
return true;
}
return false;
}
std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(const uint256 &txid) {
std::map<uint256,CCoins>::iterator it = cacheCoins.lower_bound(txid);
if (it != cacheCoins.end() && it->first == txid)
return it;
CCoins tmp;
if (!base->GetCoins(txid,tmp))
return cacheCoins.end();
std::map<uint256,CCoins>::iterator ret = cacheCoins.insert(it, std::make_pair(txid, CCoins()));
tmp.swap(ret->second);
return ret;
}
CCoins &CCoinsViewCache::GetCoins(const uint256 &txid) {
std::map<uint256,CCoins>::iterator it = FetchCoins(txid);
assert(it != cacheCoins.end());
return it->second;
}
bool CCoinsViewCache::SetCoins(const uint256 &txid, const CCoins &coins) {
cacheCoins[txid] = coins;
return true;
}
bool CCoinsViewCache::HaveCoins(const uint256 &txid) {
return FetchCoins(txid) != cacheCoins.end();
}
CBlockIndex *CCoinsViewCache::GetBestBlock() {
if (pindexTip == NULL)
pindexTip = base->GetBestBlock();
return pindexTip;
}
bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
pindexTip = pindex;
return true;
}
bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
cacheCoins[it->first] = it->second;
pindexTip = pindex;
return true;
}
bool CCoinsViewCache::Flush() {
bool fOk = base->BatchWrite(cacheCoins, pindexTip);
if (fOk)
cacheCoins.clear();
return fOk;
}
unsigned int CCoinsViewCache::GetCacheSize() {
return cacheCoins.size();
}
/** CCoinsView that brings transactions from a memorypool into view.
It does not check for spendings by memory pool transactions. */
CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) {
if (base->GetCoins(txid, coins))
return true;
if (mempool.exists(txid)) {
const CTransaction &tx = mempool.lookup(txid);
coins = CCoins(tx, MEMPOOL_HEIGHT);
return true;
}
return false;
}
bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) {
return mempool.exists(txid) || base->HaveCoins(txid);
}
CCoinsViewCache *pcoinsTip = NULL;
CBlockTreeDB *pblocktree = NULL;
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CDataStream& vMsg)
{
CTransaction tx;
CDataStream(vMsg) >> tx;
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
CDataStream* pvMsg = new CDataStream(vMsg);
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
if (pvMsg->size() > 5000)
{
printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().c_str());
delete pvMsg;
return false;
}
mapOrphanTransactions[hash] = pvMsg;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().c_str(),
mapOrphanTransactions.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
if (!mapOrphanTransactions.count(hash))
return;
const CDataStream* pvMsg = mapOrphanTransactions[hash];
CTransaction tx;
CDataStream(*pvMsg) >> tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
}
delete pvMsg;
mapOrphanTransactions.erase(hash);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
//////////////////////////////////////////////////////////////////////////////
//
// CTransaction / CTxOut
//
bool CTxOut::IsDust() const
{
// "Dust" is defined in terms of CTransaction::nMinRelayTxFee,
// which has units satoshis-per-kilobyte.
// If you'd pay more than 1/3 in fees
// to spend something, then we consider it dust.
// A typical txout is 33 bytes big, and will
// need a CTxIn of at least 148 bytes to spend,
// so dust is a txout less than 54 uBTC
// (5430 satoshis) with default nMinRelayTxFee
return ((nValue*1000)/(3*((int)GetSerializeSize(SER_DISK,0)+148)) < CTransaction::nMinRelayTxFee);
}
bool CTransaction::IsStandard() const
{
if (nVersion > CTransaction::TXCOMMENT_VERSION)
return false;
if (!IsFinal())
return false;
// Disallow large transaction comments
if (strTxComment.length() > MAX_TX_COMMENT_LEN)
return false;
// Extremely large transactions with lots of inputs can cost the network
// almost as much to process as they cost the sender in fees, because
// computing signature hashes is O(ninputs*txsize). Limiting transactions
// to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
unsigned int sz = this->GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (sz >= MAX_STANDARD_TX_SIZE)
return false;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
// pay-to-script-hash, which is 3 ~80-byte signatures, 3
// ~65-byte public keys, plus a few script ops.
if (txin.scriptSig.size() > 500)
return false;
if (!txin.scriptSig.IsPushOnly())
return false;
}
BOOST_FOREACH(const CTxOut& txout, vout) {
if (!::IsStandard(txout.scriptPubKey))
return false;
if (txout.IsDust())
return false;
}
return true;
}
//
// Check transaction inputs, and make sure any
// pay-to-script-hash transactions are evaluating IsStandard scripts
//
// Why bother? To avoid denial-of-service attacks; an attacker
// can submit a standard HASH... OP_EQUAL transaction,
// which will get accepted into blocks. The redemption
// script can be anything; an attacker could use a very
// expensive-to-check-upon-redemption script like:
// DUP CHECKSIG DROP ... repeated 100 times... OP_1
//
bool CTransaction::AreInputsStandard(CCoinsViewCache& mapInputs) const
{
if (IsCoinBase())
return true; // Coinbases don't use vin normally
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
vector<vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions))
return false;
int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
if (nArgsExpected < 0)
return false;
// Transactions with extra stuff in their scriptSigs are
// non-standard. Note that this EvalScript() call will
// be quick, because if there are any operations
// beside "push data" in the scriptSig the
// IsStandard() call returns false
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
return false;
if (whichType == TX_SCRIPTHASH)
{
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (!Solver(subscript, whichType2, vSolutions2))
return false;
if (whichType2 == TX_SCRIPTHASH)
return false;
int tmpExpected;
tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int CTransaction::GetLegacySigOpCount() const
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
{
CBlock blockTmp;
if (pblock == NULL) {
CCoins coins;
if (pcoinsTip->GetCoins(GetHash(), coins)) {
CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
if (pindex) {
if (!blockTmp.ReadFromDisk(pindex))
return 0;
pblock = &blockTmp;
}
}
}
if (pblock) {
// Update the tx's hashBlock
hashBlock = pblock->GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
if (pblock->vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)pblock->vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = pblock->GetMerkleBranch(nIndex);
}
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
bool CTransaction::CheckTransaction(CValidationState &state) const
{
// Basic checks that don't depend on any context
if (vin.empty())
return state.DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
if (vout.empty())
return state.DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
// Size limits
if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return state.DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
// Check for negative or overflow output values
int64 nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
if (txout.nValue < 0)
return state.DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
if (txout.nValue > MAX_MONEY)
return state.DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return state.DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, vin)
{
if (vInOutPoints.count(txin.prevout))
return state.DoS(100, error("CTransaction::CheckTransaction() : duplicate inputs"));
vInOutPoints.insert(txin.prevout);
}
if (IsCoinBase())
{
if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
return state.DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
}
else
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull())
return state.DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
}
return true;
}
int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
enum GetMinFee_mode mode) const
{
// Base fee is either nMinTxFee or nMinRelayTxFee
int64 nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
unsigned int nNewBlockSize = nBlockSize + nBytes;
int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
if (fAllowFree)
{
if (nBlockSize == 1)
{
// Transactions under 10K are free
// (about 4500 BTC if made of 50 BTC inputs)
if (nBytes < 10000)
nMinFee = 0;
}
else
{
// Free transaction area
if (nNewBlockSize < 27000)
nMinFee = 0;
}
}
// To limit dust spam, require base fee if any output is less than 0.01
if (nMinFee < nBaseFee)
{
BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.nValue < CENT)
nMinFee = nBaseFee;
}
// Raise the price as the block approaches full
if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
{
if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
return uint64(-1);
nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
}
if (!MoneyRange(nMinFee))
nMinFee = uint64(-1);
return nMinFee;
}
void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
{
LOCK(cs);
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
// iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
while (it != mapNextTx.end() && it->first.hash == hashTx) {
coins.Spend(it->first.n); // and remove those outputs from coins
it++;
}
}
bool CTxMemPool::accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree,
bool* pfMissingInputs)
{
if (pfMissingInputs)
*pfMissingInputs = false;
if (!tx.CheckTransaction(state))
return error("CTxMemPool::accept() : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return state.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
// To help v0.1.5 clients who would see it as a negative number
if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
// Rather not work on nonstandard transactions (unless -testnet)
if (!fTestNet && !tx.IsStandard())
return error("CTxMemPool::accept() : nonstandard transaction type");
// is it already in the memory pool?
uint256 hash = tx.GetHash();
{
LOCK(cs);
if (mapTx.count(hash))
return false;
}
// Check for conflicts with in-memory transactions
CTransaction* ptxOld = NULL;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (mapNextTx.count(outpoint))
{
// Disable replacement feature for now
return false;
// Allow replacing with a newer version of the same transaction
if (i != 0)
return false;
ptxOld = mapNextTx[outpoint].ptx;
if (ptxOld->IsFinal())
return false;
if (!tx.IsNewerThan(*ptxOld))
return false;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
return false;
}
break;
}
}
if (fCheckInputs)
{
CCoinsView dummy;
CCoinsViewCache view(dummy);
{
LOCK(cs);
CCoinsViewMemPool viewMemPool(*pcoinsTip, *this);
view.SetBackend(viewMemPool);
// do we already have it?
if (view.HaveCoins(hash))
return false;
// do all inputs exist?
// Note that this does not check for the presence of actual outputs (see the next check for that),
// only helps filling in pfMissingInputs (to determine missing vs spent).
BOOST_FOREACH(const CTxIn txin, tx.vin) {
if (!view.HaveCoins(txin.prevout.hash)) {
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
}
// are the actual inputs available?
if (!tx.HaveInputs(view))
return state.Invalid(error("CTxMemPool::accept() : inputs already spent"));
// Bring the best block into scope
view.GetBestBlock();
// we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
view.SetBackend(dummy);
}
// Check for non-standard pay-to-script-hash in inputs
if (!tx.AreInputsStandard(view) && !fTestNet)
return error("CTxMemPool::accept() : nonstandard transaction input");
// Note: if you modify this code to accept non-standard transactions, then
// you should add code here to check that the transaction does a
// reasonable number of ECDSA signature verifications.
int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
// Don't accept it if it can't get into a block
int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY);
if (fLimitFree && nFees < txMinFee)
return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
hash.ToString().c_str(),
nFees, txMinFee);
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (fLimitFree && nFees < CTransaction::nMinRelayTxFee)
{
static double dFreeCount;
static int64 nLastTime;
int64 nNow = GetTime();
LOCK(cs);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
if (fDebug)
printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!tx.CheckInputs(state, view, true, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC))
{
return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().c_str());
}
}
// Store transaction in memory
{
LOCK(cs);
if (ptxOld)
{
printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
remove(*ptxOld);
}
addUnchecked(hash, tx);
}
///// are we sure this is ok when loading transactions or restoring block txes
// If updated, erase old tx from wallet
if (ptxOld)
EraseFromWallets(ptxOld->GetHash());
SyncWithWallets(hash, tx, NULL, true);
printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
hash.ToString().c_str(),
mapTx.size());
return true;
}
bool CTransaction::AcceptToMemoryPool(CValidationState &state, bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs)
{
try {
return mempool.accept(state, *this, fCheckInputs, fLimitFree, pfMissingInputs);
} catch(std::runtime_error &e) {
return state.Abort(_("System error: ") + e.what());
}
}
bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
{
// Add to memory pool without checking anything. Don't call this directly,
// call CTxMemPool::accept to properly check the transaction first.
{
mapTx[hash] = tx;
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
nTransactionsUpdated++;
}
return true;
}
bool CTxMemPool::remove(const CTransaction &tx, bool fRecursive)
{
// Remove transaction from memory pool
{
LOCK(cs);
uint256 hash = tx.GetHash();
if (mapTx.count(hash))
{
if (fRecursive) {
for (unsigned int i = 0; i < tx.vout.size(); i++) {
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
if (it != mapNextTx.end())
remove(*it->second.ptx, true);
}
}
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapNextTx.erase(txin.prevout);
mapTx.erase(hash);
nTransactionsUpdated++;
}
}
return true;
}
bool CTxMemPool::removeConflicts(const CTransaction &tx)
{
// Remove transactions which depend on inputs of tx, recursively
LOCK(cs);
BOOST_FOREACH(const CTxIn &txin, tx.vin) {
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
if (it != mapNextTx.end()) {
const CTransaction &txConflict = *it->second.ptx;
if (txConflict != tx)
remove(txConflict, true);
}
}
return true;
}
void CTxMemPool::clear()
{
LOCK(cs);
mapTx.clear();
mapNextTx.clear();
++nTransactionsUpdated;
}
void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{
vtxid.clear();
LOCK(cs);
vtxid.reserve(mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back((*mi).first);
}
int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified)
{
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return pindexBest->nHeight - pindex->nHeight + 1;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!IsCoinBase())
return 0;
return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs, bool fLimitFree)
{
CValidationState state;
return CTransaction::AcceptToMemoryPool(state, fCheckInputs, fLimitFree);
}
bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs)
{
{
LOCK(mempool.cs);
// Add previous supporting transactions first
BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{
if (!tx.IsCoinBase())
{
uint256 hash = tx.GetHash();
if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
tx.AcceptToMemoryPool(fCheckInputs, false);
}
}
return AcceptToMemoryPool(fCheckInputs, false);
}
return false;
}
int CTxIndex::GetDepthInMainChain() const
{
// Read block header
CDiskBlockPos blockpos(pos.nFile, pos.nPos);
CBlock block;
if (!block.ReadFromDisk(blockpos))
return 0;
// Find the block in the index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return 1 + nBestHeight - pindex->nHeight;
}
// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
{
CBlockIndex *pindexSlow = NULL;
{
LOCK(cs_main);
{
LOCK(mempool.cs);
if (mempool.exists(hash))
{
txOut = mempool.lookup(hash);
return true;
}
}
if (fTxIndex) {
CDiskTxPos postx;
if (pblocktree->ReadTxIndex(hash, postx)) {
CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
CBlockHeader header;
try {
file >> header;
fseek(file, postx.nTxOffset, SEEK_CUR);
file >> txOut;
} catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
hashBlock = header.GetHash();
if (txOut.GetHash() != hash)
return error("%s() : txid mismatch", __PRETTY_FUNCTION__);
return true;
}
}
if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
int nHeight = -1;
{
CCoinsViewCache &view = *pcoinsTip;
CCoins coins;
if (view.GetCoins(hash, coins))
nHeight = coins.nHeight;
}
if (nHeight > 0)
pindexSlow = FindBlockByHeight(nHeight);
}
}
if (pindexSlow) {
CBlock block;
if (block.ReadFromDisk(pindexSlow)) {
BOOST_FOREACH(const CTransaction &tx, block.vtx) {
if (tx.GetHash() == hash) {
txOut = tx;
hashBlock = pindexSlow->GetBlockHash();
return true;
}
}
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
static CBlockIndex* pblockindexFBBHLast;
CBlockIndex* FindBlockByHeight(int nHeight)
{
CBlockIndex *pblockindex;
if (nHeight < nBestHeight / 2)
pblockindex = pindexGenesisBlock;
else
pblockindex = pindexBest;
if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
pblockindex = pblockindexFBBHLast;
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
while (pblockindex->nHeight < nHeight)
pblockindex = pblockindex->pnext;
pblockindexFBBHLast = pblockindex;
return pblockindex;
}
bool CBlock::ReadFromDisk(const CBlockIndex* pindex)
{
if (!ReadFromDisk(pindex->GetBlockPos()))
return false;
if (GetHash() != pindex->GetBlockHash())
return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
return true;
}
uint256 static GetOrphanRoot(const CBlockHeader* pblock)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblock->hashPrevBlock))
pblock = mapOrphanBlocks[pblock->hashPrevBlock];
return pblock->GetHash();
}
static const int64 nTargetTimespan = 40 * 60; // readjust difficulty once per hour
static const int64 nTargetSpacing = 60; // 30 seconds one block
static const int64 nInterval = nTargetTimespan / nTargetSpacing; // 10 blocks
int64 static GetBlockValue(int nHeight, int64 nFees, unsigned int nBits)
{
/* 2880 blocks/day , 3153600 blocks/year */
int64 nSubsidy = 0;
if (nHeight == 1)
{
nSubsidy = 460000000 * COIN;
}
else if (nHeight > 1 )
{
nSubsidy = 0 * COIN;
}
return nSubsidy + nFees;
}
//
// minimum amount of work that could possibly be required nTime after
// minimum work required was nBase
//
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
{
// Testnet has min-difficulty blocks
// after nTargetSpacing*2 time between blocks:
if (fTestNet && nTime > nTargetSpacing*2)
return bnProofOfWorkLimit.GetCompact();
CBigNum bnResult;
bnResult.SetCompact(nBase);
while (nTime > 0 && bnResult < bnProofOfWorkLimit)
{
// Maximum 200% adjustment...
bnResult *= 2;
// ... per timespan
nTime -= nTargetTimespan;
}
if (bnResult > bnProofOfWorkLimit)
bnResult = bnProofOfWorkLimit;
return bnResult.GetCompact();
}
unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
{
unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// Only change once per interval
if ((pindexLast->nHeight+1) % nInterval != 0)
{
// Special difficulty rule for testnet:
if (fTestNet)
{
// If the new block's timestamp is more than 2 * nTargetSpacing
// then allow mining of a min-difficulty block.
if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
return nProofOfWorkLimit;
else
{
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Go back by what we want to be nInterval blocks
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < nInterval-1; i++)
pindexFirst = pindexFirst->pprev;
assert(pindexFirst);
// Limit adjustment step
int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
//int64 LimUp = nTargetTimespan * 100 / 110; // 110% up
//int64 LimDown = nTargetTimespan * 2; // 200% down
//if (nActualTimespan < LimUp)
// nActualTimespan = LimUp;
//if (nActualTimespan > LimDown)
// nActualTimespan = LimDown;
int nActualTimespanLong = (pindexLast->GetBlockTime() - pindexFirst->GetBlockTime())/4;
int nActualTimespanAvg = (nActualTimespan + nActualTimespanLong)/2; // Average between short and long windows
nActualTimespan = nActualTimespanAvg + 3*nTargetTimespan;
nActualTimespan /= 4;
printf("RETARGET: nActualTimespanLong = %d, nActualTimeSpanAvg = %d, nActualTimespan (with funk) = %"PRI64d"\n", nActualTimespanLong, nActualTimespanAvg, nActualTimespan);
int nActualTimespanMax = nTargetTimespan*98/77; // add crack
int nActualTimespanMin = nTargetTimespan*77/98;
if(nActualTimespan < nActualTimespanMin) nActualTimespan = nActualTimespanMin;
if(nActualTimespan > nActualTimespanMax) nActualTimespan = nActualTimespanMax;
// Retarget
CBigNum bnNew;
bnNew.SetCompact(pindexLast->nBits);
bnNew *= nActualTimespan;
bnNew /= nTargetTimespan;
if (bnNew > bnProofOfWorkLimit)
bnNew = bnProofOfWorkLimit;
/// debug print
printf("GetNextWorkRequired RETARGET\n");
printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
// Check range
if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget.getuint256())
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
// Return maximum amount of blocks that other nodes claim to have
int GetNumBlocksOfPeers()
{
return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
}
bool IsInitialBlockDownload()
{
if (pindexBest == NULL || fImporting || fReindex || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
return true;
static int64 nLastUpdate;
static CBlockIndex* pindexLastBest;
if (pindexBest != pindexLastBest)
{
pindexLastBest = pindexBest;
nLastUpdate = GetTime();
}
return (GetTime() - nLastUpdate < 10 &&
pindexBest->GetBlockTime() < GetTime() - 96 * 60 * 60);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (pindexNew->nChainWork > nBestInvalidWork)
{
nBestInvalidWork = pindexNew->nChainWork;
pblocktree->WriteBestInvalidWork(CBigNum(nBestInvalidWork));
uiInterface.NotifyBlocksChanged();
}
printf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
pindexNew->GetBlockHash().ToString().c_str(), pindexNew->nHeight,
log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
pindexNew->GetBlockTime()).c_str());
printf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
hashBestChain.ToString().c_str(), nBestHeight, log(nBestChainWork.getdouble())/log(2.0),
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
if (pindexBest && nBestInvalidWork > nBestChainWork + (pindexBest->GetBlockWork() * 6).getuint256())
printf("InvalidChainFound: Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
}
void static InvalidBlockFound(CBlockIndex *pindex) {
pindex->nStatus |= BLOCK_FAILED_VALID;
pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
setBlockIndexValid.erase(pindex);
InvalidChainFound(pindex);
if (pindex->pnext) {
CValidationState stateDummy;
ConnectBestBlock(stateDummy); // reorganise away from the failed block
}
}
bool ConnectBestBlock(CValidationState &state) {
do {
CBlockIndex *pindexNewBest;
{
std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
if (it == setBlockIndexValid.rend())
return true;
pindexNewBest = *it;
}
if (pindexNewBest == pindexBest || (pindexBest && pindexNewBest->nChainWork == pindexBest->nChainWork))
return true; // nothing to do
// check ancestry
CBlockIndex *pindexTest = pindexNewBest;
std::vector<CBlockIndex*> vAttach;
do {
if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
// mark descendants failed
CBlockIndex *pindexFailed = pindexNewBest;
while (pindexTest != pindexFailed) {
pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
setBlockIndexValid.erase(pindexFailed);
pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed));
pindexFailed = pindexFailed->pprev;
}
InvalidChainFound(pindexNewBest);
break;
}
if (pindexBest == NULL || pindexTest->nChainWork > pindexBest->nChainWork)
vAttach.push_back(pindexTest);
if (pindexTest->pprev == NULL || pindexTest->pnext != NULL) {
reverse(vAttach.begin(), vAttach.end());
BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach) {
boost::this_thread::interruption_point();
try {
if (!SetBestChain(state, pindexSwitch))
return false;
} catch(std::runtime_error &e) {
return state.Abort(_("System error: ") + e.what());
}
}
return true;
}
pindexTest = pindexTest->pprev;
} while(true);
} while(true);
}
void CBlockHeader::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
// Updating time can change work required on testnet:
// if (fTestNet)
// nBits = GetNextWorkRequired(pindexPrev, this);
}
const CTxOut &CTransaction::GetOutputFor(const CTxIn& input, CCoinsViewCache& view)
{
const CCoins &coins = view.GetCoins(input.prevout.hash);
assert(coins.IsAvailable(input.prevout.n));
return coins.vout[input.prevout.n];
}
int64 CTransaction::GetValueIn(CCoinsViewCache& inputs) const
{
if (IsCoinBase())
return 0;
int64 nResult = 0;
for (unsigned int i = 0; i < vin.size(); i++)
nResult += GetOutputFor(vin[i], inputs).nValue;
return nResult;
}
unsigned int CTransaction::GetP2SHSigOpCount(CCoinsViewCache& inputs) const
{
if (IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut &prevout = GetOutputFor(vin[i], inputs);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
}
return nSigOps;
}
void CTransaction::UpdateCoins(CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash) const
{
// mark inputs spent
if (!IsCoinBase()) {
BOOST_FOREACH(const CTxIn &txin, vin) {
CCoins &coins = inputs.GetCoins(txin.prevout.hash);
CTxInUndo undo;
assert(coins.Spend(txin.prevout, undo));
txundo.vprevout.push_back(undo);
}
}
// add outputs
assert(inputs.SetCoins(txhash, CCoins(*this, nHeight)));
}
bool CTransaction::HaveInputs(CCoinsViewCache &inputs) const
{
if (!IsCoinBase()) {
// first check whether information about the prevout hash is available
for (unsigned int i = 0; i < vin.size(); i++) {
const COutPoint &prevout = vin[i].prevout;
if (!inputs.HaveCoins(prevout.hash))
return false;
}
// then check whether the actual outputs are available
for (unsigned int i = 0; i < vin.size(); i++) {
const COutPoint &prevout = vin[i].prevout;
const CCoins &coins = inputs.GetCoins(prevout.hash);
if (!coins.IsAvailable(prevout.n))
return false;
}
}
return true;
}
bool CScriptCheck::operator()() const {
const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().c_str());
return true;
}
bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
{
return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
}
bool CTransaction::CheckInputs(CValidationState &state, CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks) const
{
if (!IsCoinBase())
{
if (pvChecks)
pvChecks->reserve(vin.size());
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!HaveInputs(inputs))
return state.Invalid(error("CheckInputs() : %s inputs unavailable", GetHash().ToString().c_str()));
// While checking, GetBestBlock() refers to the parent block.
// This is also true for mempool checks.
int nSpendHeight = inputs.GetBestBlock()->nHeight + 1;
int64 nValueIn = 0;
int64 nFees = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
const COutPoint &prevout = vin[i].prevout;
const CCoins &coins = inputs.GetCoins(prevout.hash);
// If prev is coinbase, check that it's matured
if (coins.IsCoinBase()) {
if (nSpendHeight - coins.nHeight < COINBASE_MATURITY)
return state.Invalid(error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight));
}
// Check for negative or overflow input values
nValueIn += coins.vout[prevout.n].nValue;
if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return state.DoS(100, error("CheckInputs() : txin values out of range"));
}
if (nValueIn < GetValueOut())
return state.DoS(100, error("CheckInputs() : %s value in < value out", GetHash().ToString().c_str()));
// Tally transaction fees
int64 nTxFee = nValueIn - GetValueOut();
if (nTxFee < 0)
return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().c_str()));
nFees += nTxFee;
if (!MoneyRange(nFees))
return state.DoS(100, error("CheckInputs() : nFees out of range"));
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
// Skip ECDSA signature verification when connecting blocks
// before the last block chain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (fScriptChecks) {
for (unsigned int i = 0; i < vin.size(); i++) {
const COutPoint &prevout = vin[i].prevout;
const CCoins &coins = inputs.GetCoins(prevout.hash);
// Verify signature
CScriptCheck check(coins, *this, i, flags, 0);
if (pvChecks) {
pvChecks->push_back(CScriptCheck());
check.swap(pvChecks->back());
} else if (!check()) {
if (flags & SCRIPT_VERIFY_STRICTENC) {
// For now, check whether the failure was caused by non-canonical
// encodings or not; if so, don't trigger DoS protection.
CScriptCheck check(coins, *this, i, flags & (~SCRIPT_VERIFY_STRICTENC), 0);
if (check())
return state.Invalid();
}
return state.DoS(100,false);
}
}
}
}
return true;
}
bool CBlock::DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool *pfClean)
{
assert(pindex == view.GetBestBlock());
if (pfClean)
*pfClean = false;
bool fClean = true;
CBlockUndo blockUndo;
CDiskBlockPos pos = pindex->GetUndoPos();
if (pos.IsNull())
return error("DisconnectBlock() : no undo data available");
if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
return error("DisconnectBlock() : failure reading undo data");
if (blockUndo.vtxundo.size() + 1 != vtx.size())
return error("DisconnectBlock() : block and undo data inconsistent");
// undo transactions in reverse order
for (int i = vtx.size() - 1; i >= 0; i--) {
const CTransaction &tx = vtx[i];
uint256 hash = tx.GetHash();
// check that all outputs are available
if (!view.HaveCoins(hash)) {
fClean = fClean && error("DisconnectBlock() : outputs still spent? database corrupted");
view.SetCoins(hash, CCoins());
}
CCoins &outs = view.GetCoins(hash);
CCoins outsBlock = CCoins(tx, pindex->nHeight);
if (outs != outsBlock)
fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
// remove outputs
outs = CCoins();
// restore inputs
if (i > 0) { // not coinbases
const CTxUndo &txundo = blockUndo.vtxundo[i-1];
if (txundo.vprevout.size() != tx.vin.size())
return error("DisconnectBlock() : transaction and undo data inconsistent");
for (unsigned int j = tx.vin.size(); j-- > 0;) {
const COutPoint &out = tx.vin[j].prevout;
const CTxInUndo &undo = txundo.vprevout[j];
CCoins coins;
view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
if (undo.nHeight != 0) {
// undo data contains height: this is the last output of the prevout tx being spent
if (!coins.IsPruned())
fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
coins = CCoins();
coins.fCoinBase = undo.fCoinBase;
coins.nHeight = undo.nHeight;
coins.nVersion = undo.nVersion;
} else {
if (coins.IsPruned())
fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
}
if (coins.IsAvailable(out.n))
fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
if (coins.vout.size() < out.n+1)
coins.vout.resize(out.n+1);
coins.vout[out.n] = undo.txout;
if (!view.SetCoins(out.hash, coins))
return error("DisconnectBlock() : cannot restore coin inputs");
}
}
}
// move best block pointer to prevout block
view.SetBestBlock(pindex->pprev);
if (pfClean) {
*pfClean = fClean;
return true;
} else {
return fClean;
}
}
void static FlushBlockFile(bool fFinalize = false)
{
LOCK(cs_LastBlockFile);
CDiskBlockPos posOld(nLastBlockFile, 0);
FILE *fileOld = OpenBlockFile(posOld);
if (fileOld) {
if (fFinalize)
TruncateFile(fileOld, infoLastBlockFile.nSize);
FileCommit(fileOld);
fclose(fileOld);
}
fileOld = OpenUndoFile(posOld);
if (fileOld) {
if (fFinalize)
TruncateFile(fileOld, infoLastBlockFile.nUndoSize);
FileCommit(fileOld);
fclose(fileOld);
}
}
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
void ThreadScriptCheck() {
RenameThread("bitcoin-scriptch");
scriptcheckqueue.Thread();
}
bool CBlock::ConnectBlock(CValidationState &state, CBlockIndex* pindex, CCoinsViewCache &view, bool fJustCheck)
{
// Check it again in case a previous version let a bad block in
if (!CheckBlock(state, !fJustCheck, !fJustCheck))
return false;
// verify that the view's current state corresponds to the previous block
assert(pindex->pprev == view.GetBestBlock());
// Special case for the genesis block, skipping connection of its transactions
// (its coinbase is unspendable)
if (GetHash() == hashGenesisBlock) {
view.SetBestBlock(pindex);
pindexGenesisBlock = pindex;
return true;
}
bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction ids entirely.
// This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
// Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
// two in the chain that violate it. This prevents exploiting the issue against nodes in their
// initial block download.
bool fEnforceBIP30 = !pindex->phashBlock;
// bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
// !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
// (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
if (fEnforceBIP30) {
for (unsigned int i=0; i<vtx.size(); i++) {
uint256 hash = GetTxHash(i);
if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction"));
}
}
// BIP16 didn't become active until Apr 1 2012
int64 nBIP16SwitchTime = 1333238400;
bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
unsigned int flags = SCRIPT_VERIFY_NOCACHE |
(fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE);
CBlockUndo blockundo;
CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
int64 nStart = GetTimeMicros();
int64 nFees = 0;
int nInputs = 0;
unsigned int nSigOps = 0;
CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(vtx.size()));
std::vector<std::pair<uint256, CDiskTxPos> > vPos;
vPos.reserve(vtx.size());
for (unsigned int i=0; i<vtx.size(); i++)
{
const CTransaction &tx = vtx[i];
nInputs += tx.vin.size();
nSigOps += tx.GetLegacySigOpCount();
if (nSigOps > MAX_BLOCK_SIGOPS)
return state.DoS(100, error("ConnectBlock() : too many sigops"));
if (!tx.IsCoinBase())
{
if (!tx.HaveInputs(view))
return state.DoS(100, error("ConnectBlock() : inputs missing/spent"));
if (fStrictPayToScriptHash)
{
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += tx.GetP2SHSigOpCount(view);
if (nSigOps > MAX_BLOCK_SIGOPS)
return state.DoS(100, error("ConnectBlock() : too many sigops"));
}
nFees += tx.GetValueIn(view)-tx.GetValueOut();
std::vector<CScriptCheck> vChecks;
if (!tx.CheckInputs(state, view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL))
return false;
control.Add(vChecks);
}
CTxUndo txundo;
tx.UpdateCoins(state, view, txundo, pindex->nHeight, GetTxHash(i));
if (!tx.IsCoinBase())
blockundo.vtxundo.push_back(txundo);
vPos.push_back(std::make_pair(GetTxHash(i), pos));
pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
}
int64 nTime = GetTimeMicros() - nStart;
if (fBenchmark)
printf("- Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin)\n", (unsigned)vtx.size(), 0.001 * nTime, 0.001 * nTime / vtx.size(), nInputs <= 1 ? 0 : 0.001 * nTime / (nInputs-1));
if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees, pindex->nBits))
return state.DoS(100, error("ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")", vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees, pindex->nBits)));
if (!control.Wait())
return state.DoS(100, false);
int64 nTime2 = GetTimeMicros() - nStart;
if (fBenchmark)
printf("- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1));
if (fJustCheck)
return true;
// Write undo information to disk
if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
{
if (pindex->GetUndoPos().IsNull()) {
CDiskBlockPos pos;
if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
return error("ConnectBlock() : FindUndoPos failed");
if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
return state.Abort(_("Failed to write undo data"));
// update nUndoPos in block index
pindex->nUndoPos = pos.nPos;
pindex->nStatus |= BLOCK_HAVE_UNDO;
}
pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;
CDiskBlockIndex blockindex(pindex);
if (!pblocktree->WriteBlockIndex(blockindex))
return state.Abort(_("Failed to write block index"));
}
if (fTxIndex)
if (!pblocktree->WriteTxIndex(vPos))
return state.Abort(_("Failed to write transaction index"));
// add this block to the view's block chain
assert(view.SetBestBlock(pindex));
// Watch for transactions paying to me
for (unsigned int i=0; i<vtx.size(); i++)
SyncWithWallets(GetTxHash(i), vtx[i], this, true);
return true;
}
bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew)
{
// All modifications to the coin state will be done in this cache.
// Only when all have succeeded, we push it to pcoinsTip.
CCoinsViewCache view(*pcoinsTip, true);
// Find the fork (typically, there is none)
CBlockIndex* pfork = view.GetBestBlock();
CBlockIndex* plonger = pindexNew;
while (pfork && pfork != plonger)
{
while (plonger->nHeight > pfork->nHeight) {
plonger = plonger->pprev;
assert(plonger != NULL);
}
if (pfork == plonger)
break;
pfork = pfork->pprev;
assert(pfork != NULL);
}
// List of what to disconnect (typically nothing)
vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect (typically only pindexNew)
vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
if (vDisconnect.size() > 0) {
printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..\n", vDisconnect.size(), pfork->GetBlockHash().ToString().c_str());
printf("REORGANIZE: Connect %"PRIszu" blocks; ..%s\n", vConnect.size(), pindexNew->GetBlockHash().ToString().c_str());
}
// Disconnect shorter branch
vector<CTransaction> vResurrect;
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
CBlock block;
if (!block.ReadFromDisk(pindex))
return state.Abort(_("Failed to read block"));
int64 nStart = GetTimeMicros();
if (!block.DisconnectBlock(state, pindex, view))
return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
if (fBenchmark)
printf("- Disconnect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
// Queue memory transactions to resurrect.
// We only do this for blocks after the last checkpoint (reorganisation before that
// point should only happen with -reindex/-loadblock, or a misbehaving peer.
BOOST_FOREACH(const CTransaction& tx, block.vtx)
if (!tx.IsCoinBase() && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
vResurrect.push_back(tx);
}
// Connect longer branch
vector<CTransaction> vDelete;
BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
CBlock block;
if (!block.ReadFromDisk(pindex))
return state.Abort(_("Failed to read block"));
int64 nStart = GetTimeMicros();
if (!block.ConnectBlock(state, pindex, view)) {
if (state.IsInvalid()) {
InvalidChainFound(pindexNew);
InvalidBlockFound(pindex);
}
return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
}
if (fBenchmark)
printf("- Connect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
// Queue memory transactions to delete
BOOST_FOREACH(const CTransaction& tx, block.vtx)
vDelete.push_back(tx);
}
// Flush changes to global coin state
int64 nStart = GetTimeMicros();
int nModified = view.GetCacheSize();
assert(view.Flush());
int64 nTime = GetTimeMicros() - nStart;
if (fBenchmark)
printf("- Flush %i transactions: %.2fms (%.4fms/tx)\n", nModified, 0.001 * nTime, 0.001 * nTime / nModified);
// Make sure it's successfully written to disk before changing memory structure
bool fIsInitialDownload = IsInitialBlockDownload();
if (!fIsInitialDownload || pcoinsTip->GetCacheSize() > nCoinCacheSize) {
// Typical CCoins structures on disk are around 100 bytes in size.
// Pushing a new one to the database can cause it to be written
// twice (once in the log, and once in the tables). This is already
// an overestimation, as most will delete an existing entry or
// overwrite one. Still, use a conservative safety factor of 2.
if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
return state.Error();
FlushBlockFile();
pblocktree->Sync();
if (!pcoinsTip->Flush())
return state.Abort(_("Failed to write to coin database"));
}
// At this point, all changes have been done to the database.
// Proceed by updating the memory structures.
// Disconnect shorter branch
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
if (pindex->pprev)
pindex->pprev->pnext = NULL;
// Connect longer branch
BOOST_FOREACH(CBlockIndex* pindex, vConnect)
if (pindex->pprev)
pindex->pprev->pnext = pindex;
// Resurrect memory transactions that were in the disconnected branch
BOOST_FOREACH(CTransaction& tx, vResurrect) {
// ignore validation errors in resurrected transactions
CValidationState stateDummy;
tx.AcceptToMemoryPool(stateDummy, true, false);
}
// Delete redundant memory transactions that are in the connected branch
BOOST_FOREACH(CTransaction& tx, vDelete) {
mempool.remove(tx);
mempool.removeConflicts(tx);
}
// Update best block in wallet (so we can detect restored wallets)
if ((pindexNew->nHeight % 9600) == 0 || (!fIsInitialDownload && (pindexNew->nHeight % 240) == 0))
{
const CBlockLocator locator(pindexNew);
::SetBestChain(locator);
}
// New best block
hashBestChain = pindexNew->GetBlockHash();
pindexBest = pindexNew;
pblockindexFBBHLast = NULL;
nBestHeight = pindexBest->nHeight;
nBestChainWork = pindexNew->nChainWork;
nTimeBestReceived = GetTime();
nTransactionsUpdated++;
printf("SetBestChain: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f\n",
hashBestChain.ToString().c_str(), nBestHeight, log(nBestChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str(),
Checkpoints::GuessVerificationProgress(pindexBest));
// Check the version of the last 100 blocks to see if we need to upgrade:
if (!fIsInitialDownload)
{
int nUpgraded = 0;
const CBlockIndex* pindex = pindexBest;
for (int i = 0; i < 100 && pindex != NULL; i++)
{
if (pindex->nVersion > CBlock::CURRENT_VERSION)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
if (nUpgraded > 100/2)
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
}
if (!Checkpoints::IsSyncCheckpointEnforced()) // checkpoint advisory mode
{
if (pindexBest->pprev && !Checkpoints::CheckSyncCheckpoint(pindexBest->GetBlockHash(), pindexBest->pprev))
Checkpoints::strCheckpointWarning = _("Warning: checkpoint on different blockchain fork, contact developers to resolve the issue");
else
Checkpoints::strCheckpointWarning = "";
}
std::string strCmd = GetArg("-blocknotify", "");
if (!fIsInitialDownload && !strCmd.empty())
{
boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
bool CBlock::AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos)
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return state.Invalid(error("AddToBlockIndex() : %s already exists", hash.ToString().c_str()));
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(*this);
assert(pindexNew);
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
pindexNew->nTx = vtx.size();
pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + pindexNew->GetBlockWork().getuint256();
pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
pindexNew->nFile = pos.nFile;
pindexNew->nDataPos = pos.nPos;
pindexNew->nUndoPos = 0;
pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA;
setBlockIndexValid.insert(pindexNew);
if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew)))
return state.Abort(_("Failed to write block index"));
// New best?
if (!ConnectBestBlock(state))
return false;
if (pindexNew == pindexBest)
{
// Notify UI to display prev block's coinbase if it was ours
static uint256 hashPrevBestCoinBase;
UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = GetTxHash(0);
}
if (!pblocktree->Flush())
return state.Abort(_("Failed to sync block index"));
uiInterface.NotifyBlocksChanged();
return true;
}
bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown = false)
{
bool fUpdatedLast = false;
LOCK(cs_LastBlockFile);
if (fKnown) {
if (nLastBlockFile != pos.nFile) {
nLastBlockFile = pos.nFile;
infoLastBlockFile.SetNull();
pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile);
fUpdatedLast = true;
}
} else {
while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
FlushBlockFile(true);
nLastBlockFile++;
infoLastBlockFile.SetNull();
pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
fUpdatedLast = true;
}
pos.nFile = nLastBlockFile;
pos.nPos = infoLastBlockFile.nSize;
}
infoLastBlockFile.nSize += nAddSize;
infoLastBlockFile.AddBlock(nHeight, nTime);
if (!fKnown) {
unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
FILE *file = OpenBlockFile(pos);
if (file) {
printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
fclose(file);
}
}
else
return state.Error();
}
}
if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
return state.Abort(_("Failed to write file info"));
if (fUpdatedLast)
pblocktree->WriteLastBlockFile(nLastBlockFile);
return true;
}
bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
{
pos.nFile = nFile;
LOCK(cs_LastBlockFile);
unsigned int nNewSize;
if (nFile == nLastBlockFile) {
pos.nPos = infoLastBlockFile.nUndoSize;
nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
return state.Abort(_("Failed to write block info"));
} else {
CBlockFileInfo info;
if (!pblocktree->ReadBlockFileInfo(nFile, info))
return state.Abort(_("Failed to read block info"));
pos.nPos = info.nUndoSize;
nNewSize = (info.nUndoSize += nAddSize);
if (!pblocktree->WriteBlockFileInfo(nFile, info))
return state.Abort(_("Failed to write block info"));
}
unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
FILE *file = OpenUndoFile(pos);
if (file) {
printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
fclose(file);
}
}
else
return state.Error();
}
return true;
}
bool CBlock::CheckBlock(CValidationState &state, bool fCheckPOW, bool fCheckMerkleRoot) const
{
// These are checks that are independent of context
// that can be verified before saving an orphan block.
// Size limits
if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return state.DoS(100, error("CheckBlock() : size limits failed"));
// Special short-term limits to avoid 10,000 BDB lock limit:
/* if (GetBlockTime() >= 1363867200 && // start enforcing 21 March 2013, noon GMT
GetBlockTime() < 1368576000) // stop enforcing 15 May 2013 00:00:00
{
// Rule is: #unique txids referenced <= 4,500
// ... to prevent 10,000 BDB lock exhaustion on old clients
set<uint256> setTxIn;
for (size_t i = 0; i < vtx.size(); i++)
{
setTxIn.insert(vtx[i].GetHash());
if (i == 0) continue; // skip coinbase txin
BOOST_FOREACH(const CTxIn& txin, vtx[i].vin)
setTxIn.insert(txin.prevout.hash);
}
size_t nTxids = setTxIn.size();
if (nTxids > 4500)
return error("CheckBlock() : 15 May maxlocks violation");
}
*/
// Check proof of work matches claimed amount
if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
return state.DoS(50, error("CheckBlock() : proof of work failed"));
// Check timestamp
if (GetBlockTime() > GetAdjustedTime() + 1 * 60 * 60)
return state.Invalid(error("CheckBlock() : block timestamp too far in the future"));
// First transaction must be coinbase, the rest must not be
if (vtx.empty() || !vtx[0].IsCoinBase())
return state.DoS(100, error("CheckBlock() : first tx is not coinbase"));
for (unsigned int i = 1; i < vtx.size(); i++)
if (vtx[i].IsCoinBase())
return state.DoS(100, error("CheckBlock() : more than one coinbase"));
// Check transactions
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.CheckTransaction(state))
return error("CheckBlock() : CheckTransaction failed");
// Build the merkle tree already. We need it anyway later, and it makes the
// block cache the transaction hashes, which means they don't need to be
// recalculated many times during this block's validation.
BuildMerkleTree();
// Check for duplicate txids. This is caught by ConnectInputs(),
// but catching it earlier avoids a potential DoS attack:
set<uint256> uniqueTx;
for (unsigned int i=0; i<vtx.size(); i++) {
uniqueTx.insert(GetTxHash(i));
}
if (uniqueTx.size() != vtx.size())
return state.DoS(100, error("CheckBlock() : duplicate transaction"));
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
nSigOps += tx.GetLegacySigOpCount();
}
if (nSigOps > MAX_BLOCK_SIGOPS)
return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
// Check merkle root
if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
return true;
}
bool CBlock::AcceptBlock(CValidationState &state, CDiskBlockPos *dbp)
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return state.Invalid(error("AcceptBlock() : block already in mapBlockIndex"));
// Get prev block index
CBlockIndex* pindexPrev = NULL;
int nHeight = 0;
if (hash != hashGenesisBlock) {
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi == mapBlockIndex.end())
return state.DoS(10, error("AcceptBlock() : prev block not found"));
pindexPrev = (*mi).second;
nHeight = pindexPrev->nHeight+1;
// Check proof of work
if (nBits != GetNextWorkRequired(pindexPrev, this))
return state.DoS(100, error("AcceptBlock() : incorrect proof of work"));
// Check timestamp against prev
if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
return state.Invalid(error("AcceptBlock() : block's timestamp is too early"));
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.IsFinal(nHeight, GetBlockTime()))
return state.DoS(10, error("AcceptBlock() : contains a non-final transaction"));
// Check that the block chain matches the known block chain up to a checkpoint
if (!Checkpoints::CheckBlock(nHeight, hash))
return state.DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight));
// ppcoin: check that the block satisfies synchronized checkpoint
if (Checkpoints::IsSyncCheckpointEnforced() // checkpoint enforce mode
&& !Checkpoints::CheckSyncCheckpoint(hash, pindexPrev))
return error("AcceptBlock() : rejected by synchronized checkpoint");
// Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
// if (nVersion < 2)
// {
// if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) ||
// (fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100)))
// {
// return state.Invalid(error("AcceptBlock() : rejected nVersion=1 block"));
// }
// }
// Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
if (nVersion >= 2)
{
// if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
if ((!fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) ||
(fTestNet && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100)))
{
CScript expect = CScript() << nHeight;
if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
return state.DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
}
}
}
// Write block to history file
try {
unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
CDiskBlockPos blockPos;
if (dbp != NULL)
blockPos = *dbp;
if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, nTime, dbp != NULL))
return error("AcceptBlock() : FindBlockPos failed");
if (dbp == NULL)
if (!WriteToDisk(blockPos))
return state.Abort(_("Failed to write block"));
if (!AddToBlockIndex(state, blockPos))
return error("AcceptBlock() : AddToBlockIndex failed");
} catch(std::runtime_error &e) {
return state.Abort(_("System error: ") + e.what());
}
// Relay inventory, but don't relay old inventory during initial block download
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
if (hashBestChain == hash)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hash));
}
// ppcoin: check pending sync-checkpoint
Checkpoints::AcceptPendingSyncCheckpoint();
return true;
}
bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
{
unsigned int nFound = 0;
for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
return (nFound >= nRequired);
}
bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
{
// Check for duplicate
uint256 hash = pblock->GetHash();
if (mapBlockIndex.count(hash))
return state.Invalid(error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().c_str()));
if (mapOrphanBlocks.count(hash))
return state.Invalid(error("ProcessBlock() : already have block (orphan) %s", hash.ToString().c_str()));
// Preliminary checks
if (!pblock->CheckBlock(state))
return error("ProcessBlock() : CheckBlock FAILED");
CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
{
// Extra checks to prevent "fill up memory by spamming with bogus blocks"
int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
if (deltaTime < 0)
{
return state.DoS(100, error("ProcessBlock() : block with timestamp before last checkpoint"));
}
CBigNum bnNewBlock;
bnNewBlock.SetCompact(pblock->nBits);
CBigNum bnRequired;
bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
if (bnNewBlock > bnRequired)
{
return state.DoS(100, error("ProcessBlock() : block with too little proof-of-work"));
}
}
// ppcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
// If we don't already have its previous block, shunt it off to holding area until we get it
if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock))
{
printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().c_str());
// Accept orphans as long as there is a node to request its parents from
if (pfrom) {
CBlock* pblock2 = new CBlock(*pblock);
mapOrphanBlocks.insert(make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
// Ask this guy to fill in what we're missing
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
}
return true;
}
// Store to disk
if (!pblock->AcceptBlock(state, dbp))
return error("ProcessBlock() : AcceptBlock FAILED");
// Recursively process any orphan blocks that depended on this one
vector<uint256> vWorkQueue;
vWorkQueue.push_back(hash);
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
++mi)
{
CBlock* pblockOrphan = (*mi).second;
// Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan resolution (that is, feeding people an invalid block based on LegitBlockX in order to get anyone relaying LegitBlockX banned)
CValidationState stateDummy;
if (pblockOrphan->AcceptBlock(stateDummy))
vWorkQueue.push_back(pblockOrphan->GetHash());
mapOrphanBlocks.erase(pblockOrphan->GetHash());
delete pblockOrphan;
}
mapOrphanBlocksByPrev.erase(hashPrev);
}
printf("ProcessBlock: ACCEPTED\n");
// ppcoin: if responsible for sync-checkpoint send it
if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty() &&
(int)GetArg("-checkpointdepth", -1) >= 0)
Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
return true;
}
CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
{
header = block.GetBlockHeader();
vector<bool> vMatch;
vector<uint256> vHashes;
vMatch.reserve(block.vtx.size());
vHashes.reserve(block.vtx.size());
for (unsigned int i = 0; i < block.vtx.size(); i++)
{
uint256 hash = block.vtx[i].GetHash();
if (filter.IsRelevantAndUpdate(block.vtx[i], hash))
{
vMatch.push_back(true);
vMatchedTxn.push_back(make_pair(i, hash));
}
else
vMatch.push_back(false);
vHashes.push_back(hash);
}
txn = CPartialMerkleTree(vHashes, vMatch);
}
uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
if (height == 0) {
// hash at height 0 is the txids themself
return vTxid[pos];
} else {
// calculate left hash
uint256 left = CalcHash(height-1, pos*2, vTxid), right;
// calculate right hash if not beyong the end of the array - copy left hash otherwise1
if (pos*2+1 < CalcTreeWidth(height-1))
right = CalcHash(height-1, pos*2+1, vTxid);
else
right = left;
// combine subhashes
return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
}
}
void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
// determine whether this node is the parent of at least one matched txid
bool fParentOfMatch = false;
for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
fParentOfMatch |= vMatch[p];
// store as flag bit
vBits.push_back(fParentOfMatch);
if (height==0 || !fParentOfMatch) {
// if at height 0, or nothing interesting below, store hash and stop
vHash.push_back(CalcHash(height, pos, vTxid));
} else {
// otherwise, don't store any hash, but descend into the subtrees
TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
if (pos*2+1 < CalcTreeWidth(height-1))
TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
}
}
uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) {
if (nBitsUsed >= vBits.size()) {
// overflowed the bits array - failure
fBad = true;
return 0;
}
bool fParentOfMatch = vBits[nBitsUsed++];
if (height==0 || !fParentOfMatch) {
// if at height 0, or nothing interesting below, use stored hash and do not descend
if (nHashUsed >= vHash.size()) {
// overflowed the hash array - failure
fBad = true;
return 0;
}
const uint256 &hash = vHash[nHashUsed++];
if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid
vMatch.push_back(hash);
return hash;
} else {
// otherwise, descend into the subtrees to extract matched txids and hashes
uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
if (pos*2+1 < CalcTreeWidth(height-1))
right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
else
right = left;
// and combine them before returning
return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
}
}
CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
// reset state
vBits.clear();
vHash.clear();
// calculate height of tree
int nHeight = 0;
while (CalcTreeWidth(nHeight) > 1)
nHeight++;
// traverse the partial tree
TraverseAndBuild(nHeight, 0, vTxid, vMatch);
}
CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
vMatch.clear();
// An empty set will not work
if (nTransactions == 0)
return 0;
// check for excessively high numbers of transactions
if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
return 0;
// there can never be more hashes provided than one for every txid
if (vHash.size() > nTransactions)
return 0;
// there must be at least one bit per node in the partial tree, and at least one node per hash
if (vBits.size() < vHash.size())
return 0;
// calculate height of tree
int nHeight = 0;
while (CalcTreeWidth(nHeight) > 1)
nHeight++;
// traverse the partial tree
unsigned int nBitsUsed = 0, nHashUsed = 0;
uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
// verify that no problems occured during the tree traversal
if (fBad)
return 0;
// verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
return 0;
// verify that all hashes were consumed
if (nHashUsed != vHash.size())
return 0;
return hashMerkleRoot;
}
bool AbortNode(const std::string &strMessage) {
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return false;
}
bool CheckDiskSpace(uint64 nAdditionalBytes)
{
uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
return AbortNode(_("Error: Disk space is low!"));
return true;
}
CCriticalSection cs_LastBlockFile;
CBlockFileInfo infoLastBlockFile;
int nLastBlockFile = 0;
FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
{
if (pos.IsNull())
return NULL;
boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
boost::filesystem::create_directories(path.parent_path());
FILE* file = fopen(path.string().c_str(), "rb+");
if (!file && !fReadOnly)
file = fopen(path.string().c_str(), "wb+");
if (!file) {
printf("Unable to open file %s\n", path.string().c_str());
return NULL;
}
if (pos.nPos) {
if (fseek(file, pos.nPos, SEEK_SET)) {
printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
fclose(file);
return NULL;
}
}
return file;
}
FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
return OpenDiskFile(pos, "blk", fReadOnly);
}
FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
return OpenDiskFile(pos, "rev", fReadOnly);
}
CBlockIndex * InsertBlockIndex(uint256 hash)
{
if (hash == 0)
return NULL;
// Return existing
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
return (*mi).second;
// Create new
CBlockIndex* pindexNew = new CBlockIndex();
if (!pindexNew)
throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
return pindexNew;
}
bool static LoadBlockIndexDB()
{
if (!pblocktree->LoadBlockIndexGuts())
return false;
boost::this_thread::interruption_point();
// Calculate nChainWork
vector<pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size());
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
{
CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
}
sort(vSortedByHeight.begin(), vSortedByHeight.end());
BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
{
CBlockIndex* pindex = item.second;
pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + pindex->GetBlockWork().getuint256();
pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
setBlockIndexValid.insert(pindex);
}
// Load block file info
pblocktree->ReadLastBlockFile(nLastBlockFile);
printf("LoadBlockIndexDB(): last block file = %i\n", nLastBlockFile);
if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
printf("LoadBlockIndexDB(): last block file info: %s\n", infoLastBlockFile.ToString().c_str());
// Load nBestInvalidWork, OK if it doesn't exist
CBigNum bnBestInvalidWork;
pblocktree->ReadBestInvalidWork(bnBestInvalidWork);
nBestInvalidWork = bnBestInvalidWork.getuint256();
// Check whether we need to continue reindexing
bool fReindexing = false;
pblocktree->ReadReindexing(fReindexing);
fReindex |= fReindexing;
// Check whether we have a transaction index
pblocktree->ReadFlag("txindex", fTxIndex);
printf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
// Load hashBestChain pointer to end of best chain
pindexBest = pcoinsTip->GetBestBlock();
if (pindexBest == NULL)
return true;
hashBestChain = pindexBest->GetBlockHash();
nBestHeight = pindexBest->nHeight;
nBestChainWork = pindexBest->nChainWork;
// set 'next' pointers in best chain
CBlockIndex *pindex = pindexBest;
while(pindex != NULL && pindex->pprev != NULL) {
CBlockIndex *pindexPrev = pindex->pprev;
pindexPrev->pnext = pindex;
pindex = pindexPrev;
}
printf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s\n",
hashBestChain.ToString().c_str(), nBestHeight,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
return true;
}
bool VerifyDB() {
if (pindexBest == NULL || pindexBest->pprev == NULL)
return true;
// Verify blocks in the best chain
int nCheckLevel = GetArg("-checklevel", 3);
int nCheckDepth = GetArg( "-checkblocks", 288);
if (nCheckDepth == 0)
nCheckDepth = 1000000000; // suffices until the year 19000
if (nCheckDepth > nBestHeight)
nCheckDepth = nBestHeight;
nCheckLevel = std::max(0, std::min(4, nCheckLevel));
printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CCoinsViewCache coins(*pcoinsTip, true);
CBlockIndex* pindexState = pindexBest;
CBlockIndex* pindexFailure = NULL;
int nGoodTransactions = 0;
CValidationState state;
for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
{
boost::this_thread::interruption_point();
if (pindex->nHeight < nBestHeight-nCheckDepth)
break;
CBlock block;
// check level 0: read from disk
if (!block.ReadFromDisk(pindex))
return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
// check level 1: verify block validity
if (nCheckLevel >= 1 && !block.CheckBlock(state))
return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
// check level 2: verify undo validity
if (nCheckLevel >= 2 && pindex) {
CBlockUndo undo;
CDiskBlockPos pos = pindex->GetUndoPos();
if (!pos.IsNull()) {
if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
}
}
// check level 3: check for inconsistencies during memory-only disconnect of tip blocks
if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= 2*nCoinCacheSize + 32000) {
bool fClean = true;
if (!block.DisconnectBlock(state, pindex, coins, &fClean))
return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
pindexState = pindex->pprev;
if (!fClean) {
nGoodTransactions = 0;
pindexFailure = pindex;
} else
nGoodTransactions += block.vtx.size();
}
}
if (pindexFailure)
return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", pindexBest->nHeight - pindexFailure->nHeight + 1, nGoodTransactions);
// check level 4: try reconnecting blocks
if (nCheckLevel >= 4) {
CBlockIndex *pindex = pindexState;
while (pindex != pindexBest) {
boost::this_thread::interruption_point();
pindex = pindex->pnext;
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
if (!block.ConnectBlock(state, pindex, coins))
return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
}
}
printf("No coin database inconsistencies in last %i blocks (%i transactions)\n", pindexBest->nHeight - pindexState->nHeight, nGoodTransactions);
return true;
}
void UnloadBlockIndex()
{
mapBlockIndex.clear();
setBlockIndexValid.clear();
pindexGenesisBlock = NULL;
nBestHeight = 0;
nBestChainWork = 0;
nBestInvalidWork = 0;
hashBestChain = 0;
pindexBest = NULL;
}
bool LoadBlockIndex()
{
if (fTestNet)
{
pchMessageStart[0] = 0xFE;
pchMessageStart[1] = 0xEE;
pchMessageStart[2] = 0xA9;
pchMessageStart[3] = 0xF7;
hashGenesisBlock = uint256("0x0000028542fd4edd1fae38410e16afbfe6edbb0155d7d71ed56330926c3933fc");
}
//
// Load block index from databases
//
if (!fReindex && !LoadBlockIndexDB())
return false;
return true;
}
bool InitBlockIndex() {
// Check whether we're already initialized
if (pindexGenesisBlock != NULL)
return true;
// Use the provided setting for -txindex in the new database
fTxIndex = GetBoolArg("-txindex", false);
pblocktree->WriteFlag("txindex", fTxIndex);
printf("Initializing databases...\n");
// Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
if (!fReindex) {
// Genesis block
const char* pszTimestamp = "already in already databases we NuoCoinpark from USA with Transactions.";
CTransaction txNew;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = 0;
txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
CBlock block;
block.vtx.push_back(txNew);
block.hashPrevBlock = 0;
block.hashMerkleRoot = block.BuildMerkleTree();
block.nVersion = 112;
block.nTime = timeGenesisBlock;
block.nBits = bnProofOfWorkLimit.GetCompact();
block.nNonce = 3349253;
if (fTestNet)
{
block.nTime = 1392184910;
block.nNonce = 655598;
}
//// debug print
uint256 hash = block.GetHash();
while (hash > bnProofOfWorkLimit.getuint256()){
if (++block.nNonce==0) break;
hash = block.GetHash();
}
printf("%s\n", hash.ToString().c_str());
printf("%s\n", hashGenesisBlock.ToString().c_str());
printf("%s\n", block.hashMerkleRoot.ToString().c_str());
block.print();
assert(block.hashMerkleRoot == uint256("0xd77d20c12fe3761006b9e9e409e3dfa6c0cc8d2da67722b68ccc33eeb8f8caf5"));
assert(hash == hashGenesisBlock);
// Start new block file
try {
unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
CDiskBlockPos blockPos;
CValidationState state;
if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.nTime))
return error("LoadBlockIndex() : FindBlockPos failed");
if (!block.WriteToDisk(blockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
if (!block.AddToBlockIndex(state, blockPos))
return error("LoadBlockIndex() : genesis block not accepted");
// ppcoin: initialize synchronized checkpoint
printf("InitBlockIndex\n");
if (!Checkpoints::WriteSyncCheckpoint(hashGenesisBlock))
return error("LoadBlockIndex() : failed to init sync checkpoint");
printf("InitBlockIndex_Pass\n");
} catch(std::runtime_error &e) {
return error("LoadBlockIndex() : failed to initialize block database: %s", e.what());
}
}
// ppcoin: if checkpoint master key changed must reset sync-checkpoint
printf("InitBlockIndex_CheckCheckpointPubKey\n");
if (!Checkpoints::CheckCheckpointPubKey())
return error("LoadBlockIndex() : failed to reset checkpoint master pubkey");
return true;
}
void PrintBlockTree()
{
// pre-compute tree structure
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
CBlockIndex* pindex = (*mi).second;
mapNext[pindex->pprev].push_back(pindex);
// test
//while (rand() % 3 == 0)
// mapNext[pindex->pprev].push_back(pindex);
}
vector<pair<int, CBlockIndex*> > vStack;
vStack.push_back(make_pair(0, pindexGenesisBlock));
int nPrevCol = 0;
while (!vStack.empty())
{
int nCol = vStack.back().first;
CBlockIndex* pindex = vStack.back().second;
vStack.pop_back();
// print split or gap
if (nCol > nPrevCol)
{
for (int i = 0; i < nCol-1; i++)
printf("| ");
printf("|\\\n");
}
else if (nCol < nPrevCol)
{
for (int i = 0; i < nCol; i++)
printf("| ");
printf("|\n");
}
nPrevCol = nCol;
// print columns
for (int i = 0; i < nCol; i++)
printf("| ");
// print item
CBlock block;
block.ReadFromDisk(pindex);
printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
pindex->nHeight,
pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()).c_str(),
block.vtx.size());
PrintWallets(block);
// put the main time-chain first
vector<CBlockIndex*>& vNext = mapNext[pindex];
for (unsigned int i = 0; i < vNext.size(); i++)
{
if (vNext[i]->pnext)
{
swap(vNext[0], vNext[i]);
break;
}
}
// iterate children
for (unsigned int i = 0; i < vNext.size(); i++)
vStack.push_back(make_pair(nCol+i, vNext[i]));
}
}
bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
{
int64 nStart = GetTimeMillis();
int nLoaded = 0;
try {
CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
uint64 nStartByte = 0;
if (dbp) {
// (try to) skip already indexed part
CBlockFileInfo info;
if (pblocktree->ReadBlockFileInfo(dbp->nFile, info)) {
nStartByte = info.nSize;
blkdat.Seek(info.nSize);
}
}
uint64 nRewind = blkdat.GetPos();
while (blkdat.good() && !blkdat.eof()) {
boost::this_thread::interruption_point();
blkdat.SetPos(nRewind);
nRewind++; // start one byte further next time, in case of failure
blkdat.SetLimit(); // remove former limit
unsigned int nSize = 0;
try {
// locate a header
unsigned char buf[4];
blkdat.FindByte(pchMessageStart[0]);
nRewind = blkdat.GetPos()+1;
blkdat >> FLATDATA(buf);
if (memcmp(buf, pchMessageStart, 4))
continue;
// read size
blkdat >> nSize;
if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
continue;
} catch (std::exception &e) {
// no valid block header found; don't complain
break;
}
try {
// read block
uint64 nBlockPos = blkdat.GetPos();
blkdat.SetLimit(nBlockPos + nSize);
CBlock block;
blkdat >> block;
nRewind = blkdat.GetPos();
// process block
if (nBlockPos >= nStartByte) {
LOCK(cs_main);
if (dbp)
dbp->nPos = nBlockPos;
CValidationState state;
if (ProcessBlock(state, NULL, &block, dbp))
nLoaded++;
if (state.IsError())
break;
}
} catch (std::exception &e) {
printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__);
}
}
fclose(fileIn);
} catch(std::runtime_error &e) {
AbortNode(_("Error: system error: ") + e.what());
}
if (nLoaded > 0)
printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
extern map<uint256, CAlert> mapAlerts;
extern CCriticalSection cs_mapAlerts;
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (GetBoolArg("-testsafemode"))
strRPC = "test";
if (!CLIENT_VERSION_IS_RELEASE)
strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
// Checkpoint warning
if (Checkpoints::strCheckpointWarning != "")
{
nPriority = 900;
strStatusBar = Checkpoints::strCheckpointWarning;
}
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
nPriority = 1000;
strStatusBar = strMiscWarning;
}
// Longer invalid proof-of-work chain
if (pindexBest && nBestInvalidWork > nBestChainWork + (pindexBest->GetBlockWork() * 6).getuint256())
{
nPriority = 2000;
strStatusBar = strRPC = _("Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.");
}
// ppcoin: if detected invalid checkpoint enter safe mode
if (Checkpoints::hashInvalidCheckpoint != 0)
{
nPriority = 3000;
strStatusBar = strRPC = "WARNING: Inconsistent checkpoint found! Stop enforcing checkpoints and notify developers to resolve the issue.";
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority)
{
nPriority = alert.nPriority;
strStatusBar = alert.strStatusBar;
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(const CInv& inv)
{
switch (inv.type)
{
case MSG_TX:
{
bool txInMap = false;
{
LOCK(mempool.cs);
txInMap = mempool.exists(inv.hash);
}
return txInMap || mapOrphanTransactions.count(inv.hash) ||
pcoinsTip->HaveCoins(inv.hash);
}
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash) ||
mapOrphanBlocks.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
unsigned char pchMessageStart[4] = { 0xea, 0xe5, 0x3d, 0xde };
void static ProcessGetData(CNode* pfrom)
{
std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
vector<CInv> vNotFound;
while (it != pfrom->vRecvGetData.end()) {
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize())
break;
const CInv &inv = *it;
{
boost::this_thread::interruption_point();
it++;
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
{
// Send block from disk
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
CBlock block;
block.ReadFromDisk((*mi).second);
if (inv.type == MSG_BLOCK)
pfrom->PushMessage("block", block);
else // MSG_FILTERED_BLOCK)
{
LOCK(pfrom->cs_filter);
if (pfrom->pfilter)
{
CMerkleBlock merkleBlock(block, *pfrom->pfilter);
pfrom->PushMessage("merkleblock", merkleBlock);
// CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
// This avoids hurting performance by pointlessly requiring a round-trip
// Note that there is currently no way for a node to request any single transactions we didnt send here -
// they must either disconnect and retry or request the full block.
// Thus, the protocol spec specified allows for us to provide duplicate txn here,
// however we MUST always provide at least what the remote peer needs
typedef std::pair<unsigned int, uint256> PairType;
BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
pfrom->PushMessage("tx", block.vtx[pair.first]);
}
// else
// no response
}
// Trigger them to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// Bypass PushInventory, this must send even if redundant,
// and we want it right after the last block so they don't
// wait for other stuff first.
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
}
else if (inv.IsKnownType())
{
// Send stream from relay memory
bool pushed = false;
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end()) {
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TX) {
LOCK(mempool.cs);
if (mempool.exists(inv.hash)) {
CTransaction tx = mempool.lookup(inv.hash);
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << tx;
pfrom->PushMessage("tx", ss);
pushed = true;
}
}
if (!pushed) {
vNotFound.push_back(inv);
}
}
// Track requests for our stuff.
Inventory(inv.hash);
}
}
pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
if (!vNotFound.empty()) {
// Let the peer know that we didn't find what it asked for, so it doesn't
// have to wait around forever. Currently only SPV clients actually care
// about this message: it's needed when they are recursively walking the
// dependencies of relevant unconfirmed transactions. SPV clients want to
// do that because they want to know about (and store and rebroadcast and
// risk analyze) the dependencies of transactions relevant to them, without
// having to download the entire memory pool.
pfrom->PushMessage("notfound", vNotFound);
}
}
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
RandAddSeedPerfmon();
if (fDebug)
printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
printf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (strCommand == "version")
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
pfrom->Misbehaving(1);
return false;
}
int64 nTime;
CAddress addrMe;
CAddress addrFrom;
uint64 nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PROTO_VERSION)
{
// Since February 20, 2012, the protocol is initiated at version 209,
// and earlier versions are no longer supported
printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
pfrom->fDisconnect = true;
return false;
}
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty())
vRecv >> pfrom->strSubVer;
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
if (!vRecv.empty())
vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
else
pfrom->fRelayTxes = true;
if (pfrom->fInbound && addrMe.IsRoutable())
{
pfrom->addrLocal = addrMe;
SeenLocal(addrMe);
}
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
pfrom->fDisconnect = true;
return true;
}
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
AddTimeData(pfrom->addr, nTime);
// Change version
pfrom->PushMessage("verack");
pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
// Advertise our address
if (!fNoListen && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable())
pfrom->PushAddress(addr);
}
// Get recent addresses
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
{
pfrom->PushMessage("getaddr");
pfrom->fGetAddr = true;
}
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
{
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
cPeerBlockCounts.input(pfrom->nStartingHeight);
// ppcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
pfrom->Misbehaving(1);
return false;
}
else if (strCommand == "verack")
{
pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
}
else if (strCommand == "addr")
{
vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
return true;
if (vAddr.size() > 1000)
{
pfrom->Misbehaving(20);
return error("message addr size() = %"PRIszu"", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64 nNow = GetAdjustedTime();
int64 nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
{
boost::this_thread::interruption_point();
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint64 hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
hashRand = Hash2(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = hashRand ^ nPointer;
hashKey = Hash2(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == "inv")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message inv size() = %"PRIszu"", vInv.size());
}
// find last block in inv vector
unsigned int nLastBlock = (unsigned int)(-1);
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
nLastBlock = vInv.size() - 1 - nInv;
break;
}
}
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
boost::this_thread::interruption_point();
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(inv);
if (fDebug)
printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
if (!fAlreadyHave) {
if (!fImporting && !fReindex)
pfrom->AskFor(inv);
} else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
} else if (nInv == nLastBlock) {
// In case we are on a very long side-chain, it is possible that we already have
// the last block in an inv bundle sent in response to getblocks. Try to detect
// this situation and push another getblocks to continue.
pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
if (fDebug)
printf("force request: %s\n", inv.ToString().c_str());
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getdata")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %"PRIszu"", vInv.size());
}
if (fDebugNet || (vInv.size() != 1))
printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
if ((fDebugNet && vInv.size() > 0) || (vInv.size() == 1))
printf("received getdata for: %s\n", vInv[0].ToString().c_str());
pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
ProcessGetData(pfrom);
}
else if (strCommand == "getblocks")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
// Find the last block the caller has in the main chain
CBlockIndex* pindex = locator.GetBlockIndex();
// Send the rest of the chain
if (pindex)
pindex = pindex->pnext;
int nLimit = 500;
printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str(), nLimit);
for (; pindex; pindex = pindex->pnext)
{
if (pindex->GetBlockHash() == hashStop)
{
printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "getheaders")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
}
else
{
// Find the last block the caller has in the main chain
pindex = locator.GetBlockIndex();
if (pindex)
pindex = pindex->pnext;
}
// we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
vector<CBlock> vHeaders;
int nLimit = 2000;
printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str());
for (; pindex; pindex = pindex->pnext)
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx")
{
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CDataStream vMsg(vRecv);
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
// Truncate messages to the size of the tx in them
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
unsigned int oldSize = vMsg.size();
if (nSize < oldSize) {
vMsg.resize(nSize);
printf("truncating oversized TX %s (%u -> %u)\n",
tx.GetHash().ToString().c_str(),
oldSize, nSize);
}
bool fMissingInputs = false;
CValidationState state;
if (tx.AcceptToMemoryPool(state, true, true, &fMissingInputs))
{
RelayTransaction(tx, inv.hash, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
// Recursively process any orphan transactions that depended on this one
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
mi != mapOrphanTransactionsByPrev[hashPrev].end();
++mi)
{
const CDataStream& vMsg = *((*mi).second);
CTransaction tx;
CDataStream(vMsg) >> tx;
CInv inv(MSG_TX, tx.GetHash());
bool fMissingInputs2 = false;
// Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get anyone relaying LegitTxX banned)
CValidationState stateDummy;
if (tx.AcceptToMemoryPool(stateDummy, true, true, &fMissingInputs2))
{
printf(" accepted orphan tx %s\n", inv.hash.ToString().c_str());
RelayTransaction(tx, inv.hash, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
}
else if (!fMissingInputs2)
{
// invalid or too-little-fee orphan
vEraseQueue.push_back(inv.hash);
printf(" removed orphan tx %s\n", inv.hash.ToString().c_str());
}
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(vMsg);
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
if (nEvicted > 0)
printf("mapOrphan overflow, removed %u tx\n", nEvicted);
}
int nDoS;
if (state.IsInvalid(nDoS))
pfrom->Misbehaving(nDoS);
}
else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
{
CBlock block;
vRecv >> block;
printf("received block %s\n", block.GetHash().ToString().c_str());
// block.print();
CInv inv(MSG_BLOCK, block.GetHash());
pfrom->AddInventoryKnown(inv);
CValidationState state;
if (ProcessBlock(state, pfrom, &block))
mapAlreadyAskedFor.erase(inv);
int nDoS;
if (state.IsInvalid(nDoS))
pfrom->Misbehaving(nDoS);
}
else if (strCommand == "getaddr")
{
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
pfrom->PushAddress(addr);
}
else if (strCommand == "mempool")
{
std::vector<uint256> vtxid;
LOCK2(mempool.cs, pfrom->cs_filter);
mempool.queryHashes(vtxid);
vector<CInv> vInv;
BOOST_FOREACH(uint256& hash, vtxid) {
CInv inv(MSG_TX, hash);
if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(mempool.lookup(hash), hash)) ||
(!pfrom->pfilter))
vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ)
break;
}
if (vInv.size() > 0)
pfrom->PushMessage("inv", vInv);
}
else if (strCommand == "ping")
{
if (pfrom->nVersion > BIP0031_VERSION)
{
uint64 nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage("pong", nonce);
}
}
else if (strCommand == "alert")
{
CAlert alert;
vRecv >> alert;
uint256 alertHash = alert.GetHash();
if (pfrom->setKnown.count(alertHash) == 0)
{
if (alert.ProcessAlert())
{
// Relay
pfrom->setKnown.insert(alertHash);
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
else {
// Small DoS penalty so peers that send us lots of
// duplicate/expired/invalid-signature/whatever alerts
// eventually get banned.
// This isn't a Misbehaving(100) (immediate ban) because the
// peer might be an older or different implementation with
// a different signature key, etc.
pfrom->Misbehaving(10);
}
}
}
else if (strCommand == "filterload")
{
CBloomFilter filter;
vRecv >> filter;
if (!filter.IsWithinSizeConstraints())
// There is no excuse for sending a too-large filter
pfrom->Misbehaving(100);
else
{
LOCK(pfrom->cs_filter);
delete pfrom->pfilter;
pfrom->pfilter = new CBloomFilter(filter);
}
pfrom->fRelayTxes = true;
}
else if (strCommand == "filteradd")
{
vector<unsigned char> vData;
vRecv >> vData;
// Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
// and thus, the maximum size any matched object can have) in a filteradd message
if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
{
pfrom->Misbehaving(100);
} else {
LOCK(pfrom->cs_filter);
if (pfrom->pfilter)
pfrom->pfilter->insert(vData);
else
pfrom->Misbehaving(100);
}
}
else if (strCommand == "filterclear")
{
LOCK(pfrom->cs_filter);
delete pfrom->pfilter;
pfrom->pfilter = NULL;
pfrom->fRelayTxes = true;
}
else if (strCommand == "checkpoint") // ppcoin synchronized checkpoint
{
CSyncCheckpoint checkpoint;
vRecv >> checkpoint;
if (checkpoint.ProcessSyncCheckpoint(pfrom))
{
// Relay
pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
checkpoint.RelayTo(pnode);
}
}
else
{
// Ignore unknown commands for extensibility
}
// Update the last seen time for this node's address
if (pfrom->fNetworkNode)
if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
AddressCurrentlyConnected(pfrom->addr);
return true;
}
// requires LOCK(cs_vRecvMsg)
bool ProcessMessages(CNode* pfrom)
{
//if (fDebug)
// printf("ProcessMessages(%zu messages)\n", pfrom->vRecvMsg.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
bool fOk = true;
if (!pfrom->vRecvGetData.empty())
ProcessGetData(pfrom);
std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize())
break;
// get next message
CNetMessage& msg = *it;
//if (fDebug)
// printf("ProcessMessages(message %u msgsz, %zu bytes, complete:%s)\n",
// msg.hdr.nMessageSize, msg.vRecv.size(),
// msg.complete() ? "Y" : "N");
// end, if an incomplete message is found
if (!msg.complete())
break;
// at this point, any failure means we can delete the current message
it++;
// Scan for message start
if (memcmp(msg.hdr.pchMessageStart, pchMessageStart, sizeof(pchMessageStart)) != 0) {
printf("\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n");
fOk = false;
break;
}
// Read header
CMessageHeader& hdr = msg.hdr;
if (!hdr.IsValid())
{
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
// Checksum
CDataStream& vRecv = msg.vRecv;
uint256 hash = Hash2(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum)
{
printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Process message
bool fRet = false;
try
{
{
LOCK(cs_main);
fRet = ProcessMessage(pfrom, strCommand, vRecv);
}
boost::this_thread::interruption_point();
}
catch (std::ios_base::failure& e)
{
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from over-long size
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
}
// In case the connection got shut down, its receive buffer was wiped
if (!pfrom->fDisconnect)
pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
return fOk;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
// Keep-alive ping. We send a nonce of zero because we don't use it anywhere
// right now.
if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSendMsg.empty()) {
uint64 nonce = 0;
if (pto->nVersion > BIP0031_VERSION)
pto->PushMessage("ping", nonce);
else
pto->PushMessage("ping");
}
// Start block sync
if (pto->fStartSync && !fImporting && !fReindex) {
pto->fStartSync = false;
pto->PushGetBlocks(pindexBest, uint256(0));
}
// Resend wallet transactions that haven't gotten in a block yet
// Except during reindex, importing and IBD, when old wallet
// transactions become unconfirmed and spams other nodes.
if (!fReindex && !fImporting && !IsInitialBlockDownload())
{
ResendWalletTransactions();
}
// Address refresh broadcast
static int64 nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pnode->setAddrKnown.clear();
// Rebroadcast our address
if (!fNoListen)
{
CAddress addr = GetLocalAddress(&pnode->addr);
if (addr.IsRoutable())
pnode->PushAddress(addr);
}
}
}
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle)
{
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
// returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second)
{
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
pto->PushMessage("addr", vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage("addr", vAddr);
}
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size());
BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
{
if (pto->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle)
{
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint256 hashRand = inv.hash ^ hashSalt;
hashRand = Hash2(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((hashRand & 3) != 0);
// always trickle our own transactions
if (!fTrickleWait)
{
CWalletTx wtx;
if (GetTransaction(inv.hash, wtx))
if (wtx.fFromMe)
fTrickleWait = true;
}
if (fTrickleWait)
{
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pto->setInventoryKnown.insert(inv).second)
{
vInv.push_back(inv);
if (vInv.size() >= 1000)
{
pto->PushMessage("inv", vInv);
vInv.clear();
}
}
}
pto->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pto->PushMessage("inv", vInv);
//
// Message: getdata
//
vector<CInv> vGetData;
int64 nNow = GetTime() * 1000000;
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(inv))
{
if (fDebugNet)
printf("sending getdata: %s\n", inv.ToString().c_str());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
unsigned char* pdata = (unsigned char*)pbuffer;
unsigned int blocks = 1 + ((len + 8) / 64);
unsigned char* pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
unsigned int bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
pend[-2] = (bits >> 8) & 0xff;
pend[-3] = (bits >> 16) & 0xff;
pend[-4] = (bits >> 24) & 0xff;
return blocks;
}
static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
void SHA256Transform(void* pstate, void* pinput, const void* pinit)
{
SHA256_CTX ctx;
unsigned char data[64];
SHA256_Init(&ctx);
for (int i = 0; i < 16; i++)
((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
for (int i = 0; i < 8; i++)
ctx.h[i] = ((uint32_t*)pinit)[i];
SHA256_Update(&ctx, data, sizeof(data));
for (int i = 0; i < 8; i++)
((uint32_t*)pstate)[i] = ctx.h[i];
}
//
// ScanHash scans nonces looking for a hash with at least some zero bits.
// It operates on big endian data. Caller does the byte reversing.
// All input buffers are 16-byte aligned. nNonce is usually preserved
// between calls, but periodically or if nNonce is 0xffff0000 or above,
// the block is rebuilt and nNonce starts over at zero.
//
/*
unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
{
unsigned int& nNonce = *(unsigned int*)(pdata + 12);
for (;;)
{
// Crypto++ SHA256
// Hash pdata using pmidstate as the starting state into
// pre-formatted buffer phash1, then hash phash1 into phash
nNonce++;
SHA256Transform(phash1, pdata, pmidstate);
SHA256Transform(phash, phash1, pSHA256InitState);
// Return the nonce if the hash has at least some zero bits,
// caller will check if it has enough to reach the target
if (((unsigned short*)phash)[14] == 0)
return nNonce;
// If nothing found after trying for a while, return -1
if ((nNonce & 0xffff) == 0)
{
nHashesDone = 0xffff+1;
return (unsigned int) -1;
}
if ((nNonce & 0xfff) == 0)
boost::this_thread::interruption_point();
}
}
*/
// Some explaining would be appreciated
class COrphan
{
public:
CTransaction* ptx;
set<uint256> setDependsOn;
double dPriority;
double dFeePerKb;
COrphan(CTransaction* ptxIn)
{
ptx = ptxIn;
dPriority = dFeePerKb = 0;
}
void print() const
{
printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
ptx->GetHash().ToString().c_str(), dPriority, dFeePerKb);
BOOST_FOREACH(uint256 hash, setDependsOn)
printf(" setDependsOn %s\n", hash.ToString().c_str());
}
};
uint64 nLastBlockTx = 0;
uint64 nLastBlockSize = 0;
// We want to sort transactions by priority and fee, so:
typedef boost::tuple<double, double, CTransaction*> TxPriority;
class TxPriorityCompare
{
bool byFee;
public:
TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
bool operator()(const TxPriority& a, const TxPriority& b)
{
if (byFee)
{
if (a.get<1>() == b.get<1>())
return a.get<0>() < b.get<0>();
return a.get<1>() < b.get<1>();
}
else
{
if (a.get<0>() == b.get<0>())
return a.get<1>() < b.get<1>();
return a.get<0>() < b.get<0>();
}
}
};
CBlockTemplate* CreateNewBlock(CReserveKey& reservekey)
{
// Create new block
auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
if(!pblocktemplate.get())
return NULL;
CBlock *pblock = &pblocktemplate->block; // pointer for convenience
// Create coinbase tx
CTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
CPubKey pubkey;
if (!reservekey.GetReservedKey(pubkey))
return NULL;
txNew.vout[0].scriptPubKey << pubkey << OP_CHECKSIG;
// Add our coinbase tx as first transaction
pblock->vtx.push_back(txNew);
pblocktemplate->vTxFees.push_back(-1); // updated at end
pblocktemplate->vTxSigOps.push_back(-1); // updated at end
// Largest block you're willing to create:
unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
// Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
// Special compatibility rule before 15 May: limit size to 500,000 bytes:
// if (GetAdjustedTime() < 1368576000)
// nBlockMaxSize = std::min(nBlockMaxSize, (unsigned int)(MAX_BLOCK_SIZE_GEN));
// How much of the block should be dedicated to high-priority transactions,
// included regardless of the fees they pay
unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
// Minimum block size you want to create; block will be filled with free transactions
// until there are no more or the block reaches this size:
unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
// Collect memory pool transactions into the block
int64 nFees = 0;
{
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = pindexBest;
CCoinsViewCache view(*pcoinsTip, true);
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
bool fPrintPriority = GetBoolArg("-printpriority");
// This vector will be sorted into a priority queue:
vector<TxPriority> vecPriority;
vecPriority.reserve(mempool.mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
CTransaction& tx = (*mi).second;
if (tx.IsCoinBase() || !tx.IsFinal())
continue;
COrphan* porphan = NULL;
double dPriority = 0;
int64 nTotalIn = 0;
bool fMissingInputs = false;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Read prev transaction
if (!view.HaveCoins(txin.prevout.hash))
{
// This should never happen; all transactions in the memory
// pool should connect to either transactions in the chain
// or other transactions in the memory pool.
if (!mempool.mapTx.count(txin.prevout.hash))
{
printf("ERROR: mempool transaction missing input\n");
if (fDebug) assert("mempool transaction missing input" == 0);
fMissingInputs = true;
if (porphan)
vOrphan.pop_back();
break;
}
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
continue;
}
const CCoins &coins = view.GetCoins(txin.prevout.hash);
int64 nValueIn = coins.vout[txin.prevout.n].nValue;
nTotalIn += nValueIn;
int nConf = pindexPrev->nHeight - coins.nHeight + 1;
dPriority += (double)nValueIn * nConf;
}
if (fMissingInputs) continue;
// Priority is sum(valuein * age) / txsize
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
dPriority /= nTxSize;
// This is a more accurate fee-per-kilobyte than is used by the client code, because the
// client code rounds up the size to the nearest 1K. That's good, because it gives an
// incentive to create smaller transactions.
double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
if (porphan)
{
porphan->dPriority = dPriority;
porphan->dFeePerKb = dFeePerKb;
}
else
vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
}
// Collect transactions into block
uint64 nBlockSize = 1000;
uint64 nBlockTx = 0;
int nBlockSigOps = 100;
bool fSortedByFee = (nBlockPrioritySize <= 0);
TxPriorityCompare comparer(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
while (!vecPriority.empty())
{
// Take highest priority transaction off the priority queue:
double dPriority = vecPriority.front().get<0>();
double dFeePerKb = vecPriority.front().get<1>();
CTransaction& tx = *(vecPriority.front().get<2>());
std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
vecPriority.pop_back();
// Size limits
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= nBlockMaxSize)
continue;
// Legacy limits on sigOps:
unsigned int nTxSigOps = tx.GetLegacySigOpCount();
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
// Skip free transactions if we're past the minimum block size:
if (fSortedByFee && (dFeePerKb < CTransaction::nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
continue;
// Prioritize by fee once past the priority size or we run out of high-priority
// transactions:
if (!fSortedByFee &&
((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
{
fSortedByFee = true;
comparer = TxPriorityCompare(fSortedByFee);
std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
if (!tx.HaveInputs(view))
continue;
int64 nTxFees = tx.GetValueIn(view)-tx.GetValueOut();
nTxSigOps += tx.GetP2SHSigOpCount(view);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
CValidationState state;
if (!tx.CheckInputs(state, view, true, SCRIPT_VERIFY_P2SH))
continue;
CTxUndo txundo;
uint256 hash = tx.GetHash();
tx.UpdateCoins(state, view, txundo, pindexPrev->nHeight+1, hash);
// Added
pblock->vtx.push_back(tx);
pblocktemplate->vTxFees.push_back(nTxFees);
pblocktemplate->vTxSigOps.push_back(nTxSigOps);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
if (fPrintPriority)
{
printf("priority %.1f feeperkb %.1f txid %s\n",
dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
}
// Add transactions that depend on this one to the priority queue
if (mapDependers.count(hash))
{
BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
porphan->setDependsOn.erase(hash);
if (porphan->setDependsOn.empty())
{
vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
}
}
}
}
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
pblock->UpdateTime(pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
pblock->nNonce = 0;
// Calculate nVvalue dependet nBits
pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees, pblock->nBits);
pblocktemplate->vTxFees[0] = -nFees;
pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
pblocktemplate->vTxSigOps[0] = pblock->vtx[0].GetLegacySigOpCount();
CBlockIndex indexDummy(*pblock);
indexDummy.pprev = pindexPrev;
indexDummy.nHeight = pindexPrev->nHeight + 1;
CCoinsViewCache viewNew(*pcoinsTip, true);
CValidationState state;
if (!pblock->ConnectBlock(state, &indexDummy, viewNew, true))
throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
}
return pblocktemplate.release();
}
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
//
// Pre-build hash buffers
//
struct
{
struct unnamed2
{
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
}
block;
unsigned char pchPadding0[64];
uint256 hash1;
unsigned char pchPadding1[64];
}
tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.block.nVersion = pblock->nVersion;
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
tmp.block.nTime = pblock->nTime;
tmp.block.nBits = pblock->nBits;
tmp.block.nNonce = pblock->nNonce;
FormatHashBlocks(&tmp.block, sizeof(tmp.block));
FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
// Byte swap all the input buffer
for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
// Precalc the first half of the first hash, which stays constant
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
memcpy(pdata, &tmp.block, 128);
memcpy(phash1, &tmp.hash1, 64);
}
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
uint256 hash = pblock->GetHash();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
if (hash > hashTarget)
return false;
//// debug print
printf("NuoCoinMiner:\n");
printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("NuoCoinMiner : generated block is stale");
// Remove key from key pool
reservekey.KeepKey();
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[pblock->GetHash()] = 0;
}
// Process this block the same as if we had received it from another node
CValidationState state;
if (!ProcessBlock(state, NULL, pblock))
return error("NuoCoinMiner : ProcessBlock, block not accepted");
}
return true;
}
void static BitcoinMiner(CWallet *pwallet)
{
printf("NuoCoinMiner started\n");
SetThreadPriority(THREAD_PRIORITY_LOWEST);
RenameThread("NuoCoin-miner");
// Each thread has its own key and counter
CReserveKey reservekey(pwallet);
unsigned int nExtraNonce = 0;
try { loop {
// disable in testing
while (vNodes.empty())
MilliSleep(1000);
printf("Step after sleep\n");
//
// Create new block
//
unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrev = pindexBest;
auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlock(reservekey));
if (!pblocktemplate.get())
return;
CBlock *pblock = &pblocktemplate->block;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
printf("Running NuoCoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
//
// Pre-build hash buffers
//
/*
char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
*/
//
// Search
//
/*
int64 nStart = GetTime();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
uint256 hashbuf[2];
uint256& hash = *alignup<16>(hashbuf);
*/
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
int64 nStart = GetTime();
uint256 hash;
// unsigned int nHashesDone = 0;
loop
{
// unsigned int nNonceFound;
hash = pblock->GetHash();
if (hash <= hashTarget){
// nHashesDone += pblock->nNonce;
SetThreadPriority(THREAD_PRIORITY_NORMAL);
printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
CheckWork(pblock, *pwalletMain, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
break;
}
++pblock->nNonce;
// Meter hashes/sec
static int64 nHashCounter;
if (nHPSTimerStart == 0)
{
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
}
else
// nHashCounter += nHashesDone;
nHashCounter += 1;
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
static CCriticalSection cs;
{
LOCK(cs);
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
//static int64 nLogTime;
//if (GetTime() - nLogTime > 30 * 60)
//{
// nLogTime = GetTime();
printf("hashmeter %6.0f khash/s\n", dHashesPerSec/1000.0);
//}
}
}
}
// Check for stop or if block needs to be rebuilt
boost::this_thread::interruption_point();
// disable in testing
if (vNodes.empty())
break;
if (++pblock->nNonce >= 0xffff0000)
break;
if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
break;
if (pindexPrev != pindexBest)
break;
// Update nTime every few seconds
pblock->UpdateTime(pindexPrev);
//nBlockTime = ByteReverse(pblock->nTime);
if (fTestNet)
{
// Changing pblock->nTime can change work required on testnet:
//nBlockBits = ByteReverse(pblock->nBits);
hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
}
}
} }
catch (boost::thread_interrupted)
{
printf("NuoCoinMiner terminated\n");
throw;
}
}
void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
{
static boost::thread_group* minerThreads = NULL;
int nThreads = GetArg("-genproclimit", -1);
if (nThreads < 0)
nThreads = boost::thread::hardware_concurrency();
if (minerThreads != NULL)
{
minerThreads->interrupt_all();
delete minerThreads;
minerThreads = NULL;
}
if (nThreads == 0 || !fGenerate)
return;
minerThreads = new boost::thread_group();
for (int i = 0; i < nThreads; i++)
minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet));
}
// Amount compression:
// * If the amount is 0, output 0
// * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
// * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
// * call the result n
// * output 1 + 10*(9*n + d - 1) + e
// * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
// (this is decodable, as d is in [1-9] and e is in [0-9])
uint64 CTxOutCompressor::CompressAmount(uint64 n)
{
if (n == 0)
return 0;
int e = 0;
while (((n % 10) == 0) && e < 9) {
n /= 10;
e++;
}
if (e < 9) {
int d = (n % 10);
assert(d >= 1 && d <= 9);
n /= 10;
return 1 + (n*9 + d - 1)*10 + e;
} else {
return 1 + (n - 1)*10 + 9;
}
}
uint64 CTxOutCompressor::DecompressAmount(uint64 x)
{
// x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
if (x == 0)
return 0;
x--;
// x = 10*(9*n + d - 1) + e
int e = x % 10;
x /= 10;
uint64 n = 0;
if (e < 9) {
// x = 9*n + d - 1
int d = (x % 9) + 1;
x /= 9;
// x = n
n = x*10 + d;
} else {
n = x+1;
}
while (e) {
n *= 10;
e--;
}
return n;
}
class CMainCleanup
{
public:
CMainCleanup() {}
~CMainCleanup() {
// block headers
std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
for (; it1 != mapBlockIndex.end(); it1++)
delete (*it1).second;
mapBlockIndex.clear();
// orphan blocks
std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
for (; it2 != mapOrphanBlocks.end(); it2++)
delete (*it2).second;
mapOrphanBlocks.clear();
// orphan transactions
std::map<uint256, CDataStream*>::iterator it3 = mapOrphanTransactions.begin();
for (; it3 != mapOrphanTransactions.end(); it3++)
delete (*it3).second;
mapOrphanTransactions.clear();
}
} instance_of_cmaincleanup;
| [
"peter lee"
] | peter lee |
7c6dd26767e7beac730c1677d90966903393c4a6 | 57bf836353b6f80623b44eae3a94690dfffee4bd | /SYCameraCtrlServer/CameraCtrlDemo/SocketServer/SocketServer/SocketServer.cpp | f813b2d6d367731f956000d9f3b5b06958791019 | [] | no_license | alxp8600/workspace | e3329ad033bb9db509706dc598281cb0d145048e | 78e8b8bc6af0d99c1d3505f0751f56f9d9e30b60 | refs/heads/master | 2020-06-04T09:57:39.945251 | 2014-11-19T07:10:09 | 2014-11-19T07:10:09 | 26,844,032 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,979 | cpp | // SocketServer.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "../../include/SYCameraCtrlInterface.h"
#include "../../include/TestDemoMacro.h"
std::string g_strIp;
class DemoClass : public ICameraCtrlServerCallback
{
public:
virtual void OnRecvCameraChannelCallback(unsigned short nChannel);
virtual void OnCameraLinkStatusNotify(emCameraCtrlType type, emCameraLinkStatus status);
};
void DemoClass::OnRecvCameraChannelCallback( unsigned short nChannel )
{
printf("Recv channel No. is %d\n", nChannel);
}
void DemoClass::OnCameraLinkStatusNotify( emCameraCtrlType type, emCameraLinkStatus status )
{
std::string strType;
std::string strStatus;
switch (type)
{
case emCameraCtrl_AutoMode:
strType = "AutoMode";
break;
case emCameraCtrl_Channel:
strType = "Channel";
break;
}
switch (status)
{
case emCameraLinkStatus_Unlink:
strStatus = "Unlink";
break;
case emCameraLinkStatus_LinkWaiting:
strStatus = "LinkWaiting";
break;
case emCameraLinkStatus_Linked:
strStatus = "Linked";
break;
}
printf("Camera ctrl type[%s]'s status: %s\n", strType, strStatus);
}
void TestCameraDll()
{
DemoClass demo;
CameraCtrlServer server(g_strIp.c_str(), SERVER_PORT);
server.SetClassCallback(&demo);
server.Start();
while(1)
{
char c = getchar();
if(c == 'q')
break;
else if( c == '2')
{
if(server.SetAutoMode())
printf("SetAutoMode OK! --------------------------------------------------------\n");
}
else if(c == '1')
{
if(server.SetAutoMode(false))
{
printf("SetMaunalMode OK! --------------------------------------------------------\n");
}
}
}
server.Stop();
}
int _tmain(int argc, _TCHAR* argv[])
{
printf("When auto mode link is success, please input '1' char to set manual mode, or input '2' char to set auto mode!\n");
printf("Please input ip addr(if use local computer, please input 'localhost' string):\n");
std::cin>>g_strIp;
TestCameraDll();
return 0;
}
| [
"alxp8600@163.com"
] | alxp8600@163.com |
0223891b3e045119c3e37e9d2577a76f5c7fea07 | 3f161b079564c3155c078942f5a9ac85aac6c847 | /src/chainparams.cpp | 856eb26cce40f14ce0a5ed4c1d511d91bdc81b42 | [
"MIT"
] | permissive | EazyPayZa/EazyPayZa | 66d82631a4206ef8522bea879f07e08cd939abc2 | 553c86b1770b7065350f42a6447b2b496c3a2ccd | refs/heads/master | 2020-12-20T17:02:01.750585 | 2020-02-05T09:43:07 | 2020-02-05T09:43:07 | 221,440,245 | 0 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 18,348 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2019 The EazyPayZa Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "libzerocoin/Params.h"
#include "chainparams.h"
#include "random.h"
#include "util.h"
#include "utilstrencodings.h"
#include <assert.h>
#include <limits>
#include <boost/assign/list_of.hpp>
using namespace std;
using namespace boost::assign;
static bool regenerate = false;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
/**
* Main network
*/
//! Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress>& vSeedsOut, const SeedSpec6* data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7 * 24 * 60 * 60;
for (unsigned int i = 0; i < count; i++) {
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static Checkpoints::MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
(0, uint256("0x00000661208f4530c1a9e0824cd5ff6d1ce4c66e2d5a244ba73d0f784d95b93e"))
;
static const Checkpoints::CCheckpointData data = {
&mapCheckpoints,
1555685085, // * UNIX timestamp of last checkpoint block
0, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
0 // * estimated number of transactions per day after checkpoint
};
static Checkpoints::MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of(0, uint256("0"));
static const Checkpoints::CCheckpointData dataTestnet = {&mapCheckpointsTestnet, 0, 0, 0};
static Checkpoints::MapCheckpoints mapCheckpointsRegtest = boost::assign::map_list_of(0, uint256("0"));
static const Checkpoints::CCheckpointData dataRegtest = {&mapCheckpointsRegtest, 0, 0, 0};
libzerocoin::ZerocoinParams* CChainParams::Zerocoin_Params() const
{
assert(this);
static CBigNum bnTrustedModulus;
bnTrustedModulus.SetDec(zerocoinModulus);
static libzerocoin::ZerocoinParams ZCParams = libzerocoin::ZerocoinParams(bnTrustedModulus);
return &ZCParams;
}
libzerocoin::ZerocoinParams* CChainParams::OldZerocoin_Params() const
{
assert(this);
static CBigNum bnTrustedModulus;
bnTrustedModulus.SetHex(zerocoinModulus);
static libzerocoin::ZerocoinParams ZCParams = libzerocoin::ZerocoinParams(bnTrustedModulus);
return &ZCParams;
}
class CMainParams : public CChainParams
{
public:
CMainParams()
{
networkID = CBaseChainParams::MAIN;
strNetworkID = "main";
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 4-byte int at any alignment.
*/
pchMessageStart[0] = 0xa2;
pchMessageStart[1] = 0xba;
pchMessageStart[2] = 0x44;
pchMessageStart[3] = 0x4c;
vAlertPubKey = ParseHex("04659d53bd8f7ad9d34a17281febedac754e5a6eb136142d3a9c6c0ea21b6ed7498ceb3d872eed00ae755f7aeadaeb1d9ab5e1a8f1e7efcd0ddcb39d4623c12790");
nDefaultPort = 11771;
bnProofOfWorkLimit = ~uint256(0) >> 20;
nMaxReorganizationDepth = 100;
nEnforceBlockUpgradeMajority = 999999999;
nRejectBlockOutdatedMajority = 950;
nToCheckBlockUpgradeMajority = 1000;
nMinerThreads = 0;
nTargetTimespan = 1 * 60;
nTargetSpacing = 2 * 60; // EazyPayZa: 2 minutes
nMaturity = 100;
nMasternodeCountDrift = 20;
nMaxMoneyOut = 21000000 * COIN;
/** Height or Time Based Activations **/
nLastPOWBlock = 1000;
nModifierUpdateBlock = 9999999;
nZerocoinStartHeight = 9999999;
const char* pszTimestamp = "EazyPayZa new blockchain for swap 06 Jan 2020 - Remapper";
CMutableTransaction txNew;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vout[0].nValue = 0 * COIN;
txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1579201348;
genesis.nBits = 0x1e0ffff0; // 504365040
genesis.nNonce = 203219;
hashGenesisBlock = genesis.GetHash();
if (regenerate) {
hashGenesisBlock = uint256S("");
genesis.nNonce = 0;
if (true && (genesis.GetHash() != hashGenesisBlock)) {
while (genesis.GetHash() > bnProofOfWorkLimit)
{
++genesis.nNonce;
if (genesis.nNonce == 0)
{
++genesis.nTime;
}
}
std::cout << "// Mainnet ---";
std::cout << " nonce: " << genesis.nNonce;
std::cout << " time: " << genesis.nTime;
std::cout << " hash: 0x" << genesis.GetHash().ToString().c_str();
std::cout << " merklehash: 0x" << genesis.hashMerkleRoot.ToString().c_str() << "\n";
}
} else {
assert(hashGenesisBlock == uint256("0x00000661208f4530c1a9e0824cd5ff6d1ce4c66e2d5a244ba73d0f784d95b93e"));
assert(genesis.hashMerkleRoot == uint256("0xe04ae41c68cd6f25b497465ae55fe9e4848df78e8ac2292480c1cc1267b36902"));
}
// Seed nodes
vFixedSeeds.clear();
vSeeds.clear();
vSeeds.push_back(CDNSSeedData("1", "156.96.46.60")); //Team 1
vSeeds.push_back(CDNSSeedData("2", "156.96.46.61")); //Team 2
vSeeds.push_back(CDNSSeedData("3", "156.96.46.62")); //Team 3
vSeeds.push_back(CDNSSeedData("4", "156.96.46.63")); //Team 4
vSeeds.push_back(CDNSSeedData("5", "104.238.135.93")); //Remapper 1
vSeeds.push_back(CDNSSeedData("6", "8.9.3.101")); //Remapper 2
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 80);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 63);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 25);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x02)(0x2D)(0x25)(0x33).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x02)(0x21)(0x31)(0x2B).convert_to_container<std::vector<unsigned char> >();
// BIP44 coin type is from https://github.com/satoshilabs/slips/blob/master/slip-0044.md
base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x04)(0x61).convert_to_container<std::vector<unsigned char> >();
bech32_hrp = "ez";
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
fMiningRequiresPeers = true;
fAllowMinDifficultyBlocks = false;
fDefaultConsistencyChecks = false;
fRequireStandard = true;
fMineBlocksOnDemand = false;
fSkipProofOfWorkCheck = true;
fTestnetToBeDeprecatedFieldRPC = false;
fHeadersFirstSyncingActive = false;
nPoolMaxTransactions = 3;
strSporkKey = "04d45416e4a64b1b051e2a2ebd80ced5efe148cf5fbcb70e56860957675a2da1a21fd522c42c1ed18a1ec42641589a09cf3f58678d213825dc21798183a005a984";
strObfuscationPoolDummyAddress = "JYw365YSYahSDbhvWLN8NYwP9RPxZPDStB";
/** Zerocoin */
zerocoinModulus = "25195908475657893494027183240048398571429282126204032027777137836043662020707595556264018525880784"
"4069182906412495150821892985591491761845028084891200728449926873928072877767359714183472702618963750149718246911"
"6507761337985909570009733045974880842840179742910064245869181719511874612151517265463228221686998754918242243363"
"7259085141865462043576798423387184774447920739934236584823824281198163815010674810451660377306056201619676256133"
"8441436038339044149526344321901146575444541784240209246165157233507787077498171257724679629263863563732899121548"
"31438167899885040445364023527381951378636564391212010397122822120720357";
nZerocoinLastOldParams = 99999999; // Updated to defer zerocoin v2 for further testing.
nMaxZerocoinSpendsPerTransaction = 7; // Assume about 20kb each
nMinZerocoinMintFee = 1 * CENT; //high fee required for zerocoin mints
nMintRequiredConfirmations = 20; //the maximum amount of confirmations until accumulated in 19
nRequiredAccumulation = 1;
nDefaultSecurityLevel = 100; //full security level for accumulators
nZerocoinHeaderVersion = 4; //Block headers must be this version once zerocoin is active
nBudgetFeeConfirmations = 6; // Number of confirmations for the finalization fee
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return data;
}
};
static CMainParams mainParams;
/**
* Testnet (v3)
*/
class CTestNetParams : public CMainParams
{
public:
CTestNetParams()
{
networkID = CBaseChainParams::TESTNET;
strNetworkID = "test";
pchMessageStart[0] = 0x11;
pchMessageStart[1] = 0x22;
pchMessageStart[2] = 0x33;
pchMessageStart[3] = 0x44;
vAlertPubKey = ParseHex("04d7e13bc896eb07e2db2d7272f5ddfaedfb64b8ed4caa4d917d6e0781b59ca44f8b5d40995622008e40707b47687eebee11cbe3bbaf2348622cc271c7f0d0bd0a");
nDefaultPort = 11773;
nEnforceBlockUpgradeMajority = 51;
nRejectBlockOutdatedMajority = 75;
nToCheckBlockUpgradeMajority = 100;
nMinerThreads = 0;
nTargetTimespan = 1 * 60; // EazyPayZa: 1 day
nTargetSpacing = 1 * 10; // EazyPayZa: 1 minute
nMaturity = 15;
nMasternodeCountDrift = 4;
nModifierUpdateBlock = 1; //approx Mon, 17 Apr 2017 04:00:00 GMT
nMaxMoneyOut = 43199500 * COIN;
nLastPOWBlock = 2400;
nZerocoinStartHeight = 200;
nZerocoinLastOldParams = 50000;
//! Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nTime = 1505224800;
genesis.nNonce = 12346;
hashGenesisBlock = genesis.GetHash();
//assert(hashGenesisBlock == uint256("0xfab709a0c107fe7cf6b0d552c514ef3228f9e0f107cd3c9b2fcea96512342cd8"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 139); // Testnet eazypayza addresses start with 'x' or 'y'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 19); // Testnet eazypayza script addresses start with '8' or '9'
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239); // Testnet private keys start with '9' or 'c' (Bitcoin defaults)
// Testnet eazypayza BIP32 pubkeys start with 'DRKV'
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x3a)(0x80)(0x61)(0xa0).convert_to_container<std::vector<unsigned char> >();
// Testnet eazypayza BIP32 prvkeys start with 'DRKP'
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x3a)(0x80)(0x58)(0x37).convert_to_container<std::vector<unsigned char> >();
// Testnet eazypayza BIP44 coin type is '1' (All coin's testnet default)
base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x01)(0x00)(0x00)(0x80).convert_to_container<std::vector<unsigned char> >();
bech32_hrp = "tp";
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
fMiningRequiresPeers = true;
fAllowMinDifficultyBlocks = true;
fDefaultConsistencyChecks = false;
fRequireStandard = true;
fMineBlocksOnDemand = false;
fTestnetToBeDeprecatedFieldRPC = true;
nPoolMaxTransactions = 2;
strSporkKey = "040d2595becca91020213bf94735fa26bb92a206aa21be45b0e95f205ff8588ecb9398c5c7d8cfaf78149d230b8dc066c3660573ff2104dac98e43283d6dc882d6";
strObfuscationPoolDummyAddress = "PCYiHgGJJ6xGHqivmdZrYjRnhaYf6AJ2Mp";
nBudgetFeeConfirmations = 3; // Number of confirmations for the finalization fee. We have to make this very short
// here because we only have a 8 block finalization window on testnet
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return dataTestnet;
}
};
static CTestNetParams testNetParams;
/**
* Regression test
*/
class CRegTestParams : public CTestNetParams
{
public:
CRegTestParams()
{
networkID = CBaseChainParams::REGTEST;
strNetworkID = "regtest";
strNetworkID = "regtest";
pchMessageStart[0] = 0xa2;
pchMessageStart[1] = 0xcf;
pchMessageStart[2] = 0x7e;
pchMessageStart[3] = 0xac;
nEnforceBlockUpgradeMajority = 750;
nRejectBlockOutdatedMajority = 950;
nToCheckBlockUpgradeMajority = 1000;
nMinerThreads = 1;
nTargetTimespan = 24 * 60 * 60; // EazyPayZa: 1 day
nTargetSpacing = 1 * 60; // EazyPayZa: 1 minutes
bnProofOfWorkLimit = ~uint256(0) >> 1;
genesis.nTime = 1505224800;
genesis.nBits = 0x207fffff;
genesis.nNonce = 12345;
nMaturity = 0;
nLastPOWBlock = 999999999; // PoS complicates Regtest because of timing issues
nZerocoinLastOldParams = 499;
nZerocoinStartHeight = 100;
hashGenesisBlock = genesis.GetHash();
nDefaultPort = 11773;
//assert(hashGenesisBlock == uint256("0x2b1a0f66712aad59ad283662d5b919415a25921ce89511d73019107e380485bf"));
bech32_hrp = "phrt";
vFixedSeeds.clear(); //! Testnet mode doesn't have any fixed seeds.
vSeeds.clear(); //! Testnet mode doesn't have any DNS seeds.
fMiningRequiresPeers = false;
fAllowMinDifficultyBlocks = true;
fDefaultConsistencyChecks = true;
fRequireStandard = false;
fMineBlocksOnDemand = true;
fTestnetToBeDeprecatedFieldRPC = false;
nRequiredAccumulation = 1;
// {
// "PrivateKey": "923EhWh2bJHynX6d4Tqt2Q75bhTDCT1b4kff3qzDKDZHZ6pkQs7",
// "PublicKey": "04866dc02c998b7e1ab16fe14e0d86554595da90c36acb706a4d763b58ed0edb1f82c87e3ced065c5b299b26e12496956b9e5f9f19aa008b5c46229b15477c875a"
// }
strSporkKey = "04866dc02c998b7e1ab16fe14e0d86554595da90c36acb706a4d763b58ed0edb1f82c87e3ced065c5b299b26e12496956b9e5f9f19aa008b5c46229b15477c875a";
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
return dataRegtest;
}
};
static CRegTestParams regTestParams;
/**
* Unit test
*/
class CUnitTestParams : public CMainParams, public CModifiableParams
{
public:
CUnitTestParams()
{
networkID = CBaseChainParams::UNITTEST;
strNetworkID = "unittest";
nDefaultPort = 11774;
vFixedSeeds.clear(); //! Unit test mode doesn't have any fixed seeds.
vSeeds.clear(); //! Unit test mode doesn't have any DNS seeds.
fMiningRequiresPeers = false;
fDefaultConsistencyChecks = true;
fAllowMinDifficultyBlocks = false;
fMineBlocksOnDemand = true;
}
const Checkpoints::CCheckpointData& Checkpoints() const
{
// UnitTest share the same checkpoints as MAIN
return data;
}
//! Published setters to allow changing values in unit test cases
virtual void setEnforceBlockUpgradeMajority(int anEnforceBlockUpgradeMajority) { nEnforceBlockUpgradeMajority = anEnforceBlockUpgradeMajority; }
virtual void setRejectBlockOutdatedMajority(int anRejectBlockOutdatedMajority) { nRejectBlockOutdatedMajority = anRejectBlockOutdatedMajority; }
virtual void setToCheckBlockUpgradeMajority(int anToCheckBlockUpgradeMajority) { nToCheckBlockUpgradeMajority = anToCheckBlockUpgradeMajority; }
virtual void setDefaultConsistencyChecks(bool afDefaultConsistencyChecks) { fDefaultConsistencyChecks = afDefaultConsistencyChecks; }
virtual void setAllowMinDifficultyBlocks(bool afAllowMinDifficultyBlocks) { fAllowMinDifficultyBlocks = afAllowMinDifficultyBlocks; }
virtual void setSkipProofOfWorkCheck(bool afSkipProofOfWorkCheck) { fSkipProofOfWorkCheck = afSkipProofOfWorkCheck; }
};
static CUnitTestParams unitTestParams;
static CChainParams* pCurrentParams = 0;
CModifiableParams* ModifiableParams()
{
assert(pCurrentParams);
assert(pCurrentParams == &unitTestParams);
return (CModifiableParams*)&unitTestParams;
}
const CChainParams& Params()
{
assert(pCurrentParams);
return *pCurrentParams;
}
CChainParams& Params(CBaseChainParams::Network network)
{
switch (network) {
case CBaseChainParams::MAIN:
return mainParams;
case CBaseChainParams::TESTNET:
return testNetParams;
case CBaseChainParams::REGTEST:
return regTestParams;
case CBaseChainParams::UNITTEST:
return unitTestParams;
default:
assert(false && "Unimplemented network");
return mainParams;
}
}
void SelectParams(CBaseChainParams::Network network)
{
SelectBaseParams(network);
pCurrentParams = &Params(network);
}
bool SelectParamsFromCommandLine()
{
CBaseChainParams::Network network = NetworkIdFromCommandLine();
if (network == CBaseChainParams::MAX_NETWORK_TYPES)
return false;
SelectParams(network);
return true;
}
| [
"nikki.bisschoff@gmail.com"
] | nikki.bisschoff@gmail.com |
a15b77ce4c898700a90036a3336e05a3f9c03e62 | 40788854db468a5ce1542300de81928c7299dc98 | /Contact_Manager/PointerList.h | 0dfd711c51f012a1b01ca36ebe7079e79c280ad3 | [] | no_license | jgalsurkar/CPP_Practice_Projects | cbfd8ecd3120e4e46ff5dbf449943dcc8060422c | 36d0a8c8f85f89ebc323e18e892f584ec991ca53 | refs/heads/master | 2021-01-17T19:20:33.537157 | 2016-07-13T22:01:02 | 2016-07-13T22:01:02 | 63,274,234 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,024 | h | /**********************************************************
Title: PBList.hpp
Author: Jonathan Galsurkar
Description: Pointer Based implementation of the List
Purpose: Linked list with its functionality
**********************************************************/
#ifndef PointerList_h
#define PointerList_h
#include "AbstractList.h"
template <class T>
struct Node {
T data;
Node * next;
};
template <class T>
class PointerList : public AbstractList<T> {
private:
Node<T> * head;
int count;
Node<T> * find (int pos); //returns the node at the given position
public:
PointerList ();
~PointerList ();
bool isEmpty () {return count == 0;}
int getLength () {return count;}
void insert (T item);
void remove (int pos);
T retrieve (int pos);
};
template <class T>
PointerList<T>::PointerList () {
head = NULL; //sets head to NULL and the count to 0
count = 0;
}
template <class T>
PointerList<T>::~PointerList () {
while (!isEmpty()) //Removes everything from the list
remove(1);
}
template <class T>
Node<T> * PointerList<T>::find (int pos) {
if (pos < 1 || pos > count + 1)
throw -1;
Node<T> * temp = head; //make a temporary node to head and traverse until we hit the position
for (int i = 1; i < pos; ++i) {
temp = temp->next;
}
return temp;
}
template <class T>
void PointerList<T>::insert (T item){
Node<T> * node = new Node<T>();
//Inserting sorted. We first set nodes data equal to the item or contact in our case
node->data = item;
Node<T> * temp = head;
//If the list is empty or the first positons last name is greates then our contacts last name we place it in the first position
if(head == NULL || node->data < head->data){
node->next = head;
head = node;
}
//Otherwise we loop until temps nexts last name gets greater then nodes last name
//which means temp is right before node so we place node right after it
else{
while(temp->next != NULL && temp->next->data < node->data)
temp = temp->next;
node->next = temp->next;
temp->next = node;
}
++count;
}
template <class T>
void PointerList<T>::remove (int pos) {
if (pos < 1 || pos > count)
throw -1;
Node<T> * curr = find(pos);
if (pos == 1) //If removing form the head, we just point head to whatever currents next was pointing to
head = curr->next;
else {
Node<T> * prev = find(pos-1);// otherwise get the previous node and make its next point
prev->next = curr->next; //to whatever current was pointing too
}
delete curr; //delete curr and set it equal to null to avoid a memory leakr
curr = NULL;
--count;
}
template <class T>
T PointerList<T>::retrieve (int pos) {
if (pos < 1 || pos > count)
throw -1;
return find(pos)->data;
}
#endif /* PointerList_h */
| [
"jgalsurkar@gmail.com"
] | jgalsurkar@gmail.com |
0e58cf0df1faa92ba1b6aa851043056d56df72e4 | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_1/Z6.0+poreleaserelease+ctrlonceonce+poonceonce.c.cbmc_out.cpp | 4e38bde13587706be7bbc1ccef6f8de66bf12a99 | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 41,255 | cpp | // 0:vars:3
// 3:atom_1_X0_1:1
// 4:atom_2_X1_0:1
// 5:thr0:1
// 6:thr1:1
// 7:thr2:1
#define ADDRSIZE 8
#define NPROC 4
#define NCONTEXT 1
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NPROC*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NPROC*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NPROC*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NPROC*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NPROC*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NPROC*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NPROC*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NPROC*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NPROC*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NPROC];
int cdy[NPROC];
int cds[NPROC];
int cdl[NPROC];
int cisb[NPROC];
int caddr[NPROC];
int cctrl[NPROC];
int cstart[NPROC];
int creturn[NPROC];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
int r0= 0;
char creg_r0;
int r1= 0;
char creg_r1;
int r2= 0;
char creg_r2;
int r3= 0;
char creg_r3;
int r4= 0;
char creg_r4;
int r5= 0;
char creg_r5;
int r6= 0;
char creg_r6;
int r7= 0;
char creg_r7;
int r8= 0;
char creg_r8;
int r9= 0;
char creg_r9;
int r10= 0;
char creg_r10;
int r11= 0;
char creg_r11;
char old_cctrl= 0;
char old_cr= 0;
char old_cdy= 0;
char old_cw= 0;
char new_creg= 0;
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
buff(0,4) = 0;
pw(0,4) = 0;
cr(0,4) = 0;
iw(0,4) = 0;
cw(0,4) = 0;
cx(0,4) = 0;
is(0,4) = 0;
cs(0,4) = 0;
crmax(0,4) = 0;
buff(0,5) = 0;
pw(0,5) = 0;
cr(0,5) = 0;
iw(0,5) = 0;
cw(0,5) = 0;
cx(0,5) = 0;
is(0,5) = 0;
cs(0,5) = 0;
crmax(0,5) = 0;
buff(0,6) = 0;
pw(0,6) = 0;
cr(0,6) = 0;
iw(0,6) = 0;
cw(0,6) = 0;
cx(0,6) = 0;
is(0,6) = 0;
cs(0,6) = 0;
crmax(0,6) = 0;
buff(0,7) = 0;
pw(0,7) = 0;
cr(0,7) = 0;
iw(0,7) = 0;
cw(0,7) = 0;
cx(0,7) = 0;
is(0,7) = 0;
cs(0,7) = 0;
crmax(0,7) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
buff(1,4) = 0;
pw(1,4) = 0;
cr(1,4) = 0;
iw(1,4) = 0;
cw(1,4) = 0;
cx(1,4) = 0;
is(1,4) = 0;
cs(1,4) = 0;
crmax(1,4) = 0;
buff(1,5) = 0;
pw(1,5) = 0;
cr(1,5) = 0;
iw(1,5) = 0;
cw(1,5) = 0;
cx(1,5) = 0;
is(1,5) = 0;
cs(1,5) = 0;
crmax(1,5) = 0;
buff(1,6) = 0;
pw(1,6) = 0;
cr(1,6) = 0;
iw(1,6) = 0;
cw(1,6) = 0;
cx(1,6) = 0;
is(1,6) = 0;
cs(1,6) = 0;
crmax(1,6) = 0;
buff(1,7) = 0;
pw(1,7) = 0;
cr(1,7) = 0;
iw(1,7) = 0;
cw(1,7) = 0;
cx(1,7) = 0;
is(1,7) = 0;
cs(1,7) = 0;
crmax(1,7) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
buff(2,4) = 0;
pw(2,4) = 0;
cr(2,4) = 0;
iw(2,4) = 0;
cw(2,4) = 0;
cx(2,4) = 0;
is(2,4) = 0;
cs(2,4) = 0;
crmax(2,4) = 0;
buff(2,5) = 0;
pw(2,5) = 0;
cr(2,5) = 0;
iw(2,5) = 0;
cw(2,5) = 0;
cx(2,5) = 0;
is(2,5) = 0;
cs(2,5) = 0;
crmax(2,5) = 0;
buff(2,6) = 0;
pw(2,6) = 0;
cr(2,6) = 0;
iw(2,6) = 0;
cw(2,6) = 0;
cx(2,6) = 0;
is(2,6) = 0;
cs(2,6) = 0;
crmax(2,6) = 0;
buff(2,7) = 0;
pw(2,7) = 0;
cr(2,7) = 0;
iw(2,7) = 0;
cw(2,7) = 0;
cx(2,7) = 0;
is(2,7) = 0;
cs(2,7) = 0;
crmax(2,7) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
buff(3,0) = 0;
pw(3,0) = 0;
cr(3,0) = 0;
iw(3,0) = 0;
cw(3,0) = 0;
cx(3,0) = 0;
is(3,0) = 0;
cs(3,0) = 0;
crmax(3,0) = 0;
buff(3,1) = 0;
pw(3,1) = 0;
cr(3,1) = 0;
iw(3,1) = 0;
cw(3,1) = 0;
cx(3,1) = 0;
is(3,1) = 0;
cs(3,1) = 0;
crmax(3,1) = 0;
buff(3,2) = 0;
pw(3,2) = 0;
cr(3,2) = 0;
iw(3,2) = 0;
cw(3,2) = 0;
cx(3,2) = 0;
is(3,2) = 0;
cs(3,2) = 0;
crmax(3,2) = 0;
buff(3,3) = 0;
pw(3,3) = 0;
cr(3,3) = 0;
iw(3,3) = 0;
cw(3,3) = 0;
cx(3,3) = 0;
is(3,3) = 0;
cs(3,3) = 0;
crmax(3,3) = 0;
buff(3,4) = 0;
pw(3,4) = 0;
cr(3,4) = 0;
iw(3,4) = 0;
cw(3,4) = 0;
cx(3,4) = 0;
is(3,4) = 0;
cs(3,4) = 0;
crmax(3,4) = 0;
buff(3,5) = 0;
pw(3,5) = 0;
cr(3,5) = 0;
iw(3,5) = 0;
cw(3,5) = 0;
cx(3,5) = 0;
is(3,5) = 0;
cs(3,5) = 0;
crmax(3,5) = 0;
buff(3,6) = 0;
pw(3,6) = 0;
cr(3,6) = 0;
iw(3,6) = 0;
cw(3,6) = 0;
cx(3,6) = 0;
is(3,6) = 0;
cs(3,6) = 0;
crmax(3,6) = 0;
buff(3,7) = 0;
pw(3,7) = 0;
cr(3,7) = 0;
iw(3,7) = 0;
cw(3,7) = 0;
cx(3,7) = 0;
is(3,7) = 0;
cs(3,7) = 0;
crmax(3,7) = 0;
cl[3] = 0;
cdy[3] = 0;
cds[3] = 0;
cdl[3] = 0;
cisb[3] = 0;
caddr[3] = 0;
cctrl[3] = 0;
cstart[3] = get_rng(0,NCONTEXT-1);
creturn[3] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(0+2,0) = 0;
mem(3+0,0) = 0;
mem(4+0,0) = 0;
mem(5+0,0) = 0;
mem(6+0,0) = 0;
mem(7+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
co(1,0) = 0;
delta(1,0) = -1;
co(2,0) = 0;
delta(2,0) = -1;
co(3,0) = 0;
delta(3,0) = -1;
co(4,0) = 0;
delta(4,0) = -1;
co(5,0) = 0;
delta(5,0) = -1;
co(6,0) = 0;
delta(6,0) = -1;
co(7,0) = 0;
delta(7,0) = -1;
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !35, metadata !DIExpression()), !dbg !44
// br label %label_1, !dbg !45
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !43), !dbg !46
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !36, metadata !DIExpression()), !dbg !47
// call void @llvm.dbg.value(metadata i64 1, metadata !39, metadata !DIExpression()), !dbg !47
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !48
// ST: Guess
// : Release
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
ASSUME(cw(1,0+1*1) >= cr(1,0+0));
ASSUME(cw(1,0+1*1) >= cr(1,0+1));
ASSUME(cw(1,0+1*1) >= cr(1,0+2));
ASSUME(cw(1,0+1*1) >= cr(1,3+0));
ASSUME(cw(1,0+1*1) >= cr(1,4+0));
ASSUME(cw(1,0+1*1) >= cr(1,5+0));
ASSUME(cw(1,0+1*1) >= cr(1,6+0));
ASSUME(cw(1,0+1*1) >= cr(1,7+0));
ASSUME(cw(1,0+1*1) >= cw(1,0+0));
ASSUME(cw(1,0+1*1) >= cw(1,0+1));
ASSUME(cw(1,0+1*1) >= cw(1,0+2));
ASSUME(cw(1,0+1*1) >= cw(1,3+0));
ASSUME(cw(1,0+1*1) >= cw(1,4+0));
ASSUME(cw(1,0+1*1) >= cw(1,5+0));
ASSUME(cw(1,0+1*1) >= cw(1,6+0));
ASSUME(cw(1,0+1*1) >= cw(1,7+0));
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 1;
mem(0+1*1,cw(1,0+1*1)) = 1;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
is(1,0+1*1) = iw(1,0+1*1);
cs(1,0+1*1) = cw(1,0+1*1);
ASSUME(creturn[1] >= cw(1,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !40, metadata !DIExpression()), !dbg !49
// call void @llvm.dbg.value(metadata i64 1, metadata !42, metadata !DIExpression()), !dbg !49
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !50
// ST: Guess
// : Release
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
ASSUME(cw(1,0) >= cr(1,0+0));
ASSUME(cw(1,0) >= cr(1,0+1));
ASSUME(cw(1,0) >= cr(1,0+2));
ASSUME(cw(1,0) >= cr(1,3+0));
ASSUME(cw(1,0) >= cr(1,4+0));
ASSUME(cw(1,0) >= cr(1,5+0));
ASSUME(cw(1,0) >= cr(1,6+0));
ASSUME(cw(1,0) >= cr(1,7+0));
ASSUME(cw(1,0) >= cw(1,0+0));
ASSUME(cw(1,0) >= cw(1,0+1));
ASSUME(cw(1,0) >= cw(1,0+2));
ASSUME(cw(1,0) >= cw(1,3+0));
ASSUME(cw(1,0) >= cw(1,4+0));
ASSUME(cw(1,0) >= cw(1,5+0));
ASSUME(cw(1,0) >= cw(1,6+0));
ASSUME(cw(1,0) >= cw(1,7+0));
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 1;
mem(0,cw(1,0)) = 1;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
is(1,0) = iw(1,0);
cs(1,0) = cw(1,0);
ASSUME(creturn[1] >= cw(1,0));
// ret i8* null, !dbg !51
ret_thread_1 = (- 1);
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !54, metadata !DIExpression()), !dbg !70
// br label %label_2, !dbg !53
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !68), !dbg !72
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !57, metadata !DIExpression()), !dbg !73
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !56
// LD: Guess
old_cr = cr(2,0);
cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0)] == 2);
ASSUME(cr(2,0) >= iw(2,0));
ASSUME(cr(2,0) >= 0);
ASSUME(cr(2,0) >= cdy[2]);
ASSUME(cr(2,0) >= cisb[2]);
ASSUME(cr(2,0) >= cdl[2]);
ASSUME(cr(2,0) >= cl[2]);
// Update
creg_r0 = cr(2,0);
crmax(2,0) = max(crmax(2,0),cr(2,0));
caddr[2] = max(caddr[2],0);
if(cr(2,0) < cw(2,0)) {
r0 = buff(2,0);
} else {
if(pw(2,0) != co(0,cr(2,0))) {
ASSUME(cr(2,0) >= old_cr);
}
pw(2,0) = co(0,cr(2,0));
r0 = mem(0,cr(2,0));
}
ASSUME(creturn[2] >= cr(2,0));
// call void @llvm.dbg.value(metadata i64 %0, metadata !59, metadata !DIExpression()), !dbg !73
// %conv = trunc i64 %0 to i32, !dbg !57
// call void @llvm.dbg.value(metadata i32 %conv, metadata !55, metadata !DIExpression()), !dbg !70
// %cmp = icmp eq i32 %conv, 0, !dbg !58
// %conv1 = zext i1 %cmp to i32, !dbg !58
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !60, metadata !DIExpression()), !dbg !70
// %tobool = icmp ne i32 %conv1, 0, !dbg !59
// br i1 %tobool, label %if.then, label %if.else, !dbg !61
old_cctrl = cctrl[2];
cctrl[2] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[2] >= old_cctrl);
ASSUME(cctrl[2] >= max(creg_r0,0));
ASSUME(cctrl[2] >= 0);
if(((r0==0)!=0)) {
goto T2BLOCK2;
} else {
goto T2BLOCK3;
}
T2BLOCK2:
// br label %lbl_label125, !dbg !62
goto T2BLOCK4;
T2BLOCK3:
// br label %lbl_label125, !dbg !63
goto T2BLOCK4;
T2BLOCK4:
// call void @llvm.dbg.label(metadata !69), !dbg !82
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !61, metadata !DIExpression()), !dbg !83
// call void @llvm.dbg.value(metadata i64 1, metadata !63, metadata !DIExpression()), !dbg !83
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !66
// ST: Guess
iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,0+2*1);
cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,0+2*1)] == 2);
ASSUME(active[cw(2,0+2*1)] == 2);
ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(cw(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cw(2,0+2*1) >= old_cw);
ASSUME(cw(2,0+2*1) >= cr(2,0+2*1));
ASSUME(cw(2,0+2*1) >= cl[2]);
ASSUME(cw(2,0+2*1) >= cisb[2]);
ASSUME(cw(2,0+2*1) >= cdy[2]);
ASSUME(cw(2,0+2*1) >= cdl[2]);
ASSUME(cw(2,0+2*1) >= cds[2]);
ASSUME(cw(2,0+2*1) >= cctrl[2]);
ASSUME(cw(2,0+2*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+2*1) = 1;
mem(0+2*1,cw(2,0+2*1)) = 1;
co(0+2*1,cw(2,0+2*1))+=1;
delta(0+2*1,cw(2,0+2*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+2*1));
// %cmp2 = icmp eq i32 %conv, 1, !dbg !67
// %conv3 = zext i1 %cmp2 to i32, !dbg !67
// call void @llvm.dbg.value(metadata i32 %conv3, metadata !64, metadata !DIExpression()), !dbg !70
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !65, metadata !DIExpression()), !dbg !86
// %1 = zext i32 %conv3 to i64
// call void @llvm.dbg.value(metadata i64 %1, metadata !67, metadata !DIExpression()), !dbg !86
// store atomic i64 %1, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !69
// ST: Guess
iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,3);
cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,3)] == 2);
ASSUME(active[cw(2,3)] == 2);
ASSUME(sforbid(3,cw(2,3))== 0);
ASSUME(iw(2,3) >= max(creg_r0,0));
ASSUME(iw(2,3) >= 0);
ASSUME(cw(2,3) >= iw(2,3));
ASSUME(cw(2,3) >= old_cw);
ASSUME(cw(2,3) >= cr(2,3));
ASSUME(cw(2,3) >= cl[2]);
ASSUME(cw(2,3) >= cisb[2]);
ASSUME(cw(2,3) >= cdy[2]);
ASSUME(cw(2,3) >= cdl[2]);
ASSUME(cw(2,3) >= cds[2]);
ASSUME(cw(2,3) >= cctrl[2]);
ASSUME(cw(2,3) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,3) = (r0==1);
mem(3,cw(2,3)) = (r0==1);
co(3,cw(2,3))+=1;
delta(3,cw(2,3)) = -1;
ASSUME(creturn[2] >= cw(2,3));
// ret i8* null, !dbg !70
ret_thread_2 = (- 1);
// Dumping thread 3
int ret_thread_3 = 0;
cdy[3] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[3] >= cstart[3]);
T3BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !91, metadata !DIExpression()), !dbg !104
// br label %label_3, !dbg !51
goto T3BLOCK1;
T3BLOCK1:
// call void @llvm.dbg.label(metadata !103), !dbg !106
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !92, metadata !DIExpression()), !dbg !107
// call void @llvm.dbg.value(metadata i64 2, metadata !94, metadata !DIExpression()), !dbg !107
// store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !54
// ST: Guess
iw(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,0+2*1);
cw(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,0+2*1)] == 3);
ASSUME(active[cw(3,0+2*1)] == 3);
ASSUME(sforbid(0+2*1,cw(3,0+2*1))== 0);
ASSUME(iw(3,0+2*1) >= 0);
ASSUME(iw(3,0+2*1) >= 0);
ASSUME(cw(3,0+2*1) >= iw(3,0+2*1));
ASSUME(cw(3,0+2*1) >= old_cw);
ASSUME(cw(3,0+2*1) >= cr(3,0+2*1));
ASSUME(cw(3,0+2*1) >= cl[3]);
ASSUME(cw(3,0+2*1) >= cisb[3]);
ASSUME(cw(3,0+2*1) >= cdy[3]);
ASSUME(cw(3,0+2*1) >= cdl[3]);
ASSUME(cw(3,0+2*1) >= cds[3]);
ASSUME(cw(3,0+2*1) >= cctrl[3]);
ASSUME(cw(3,0+2*1) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,0+2*1) = 2;
mem(0+2*1,cw(3,0+2*1)) = 2;
co(0+2*1,cw(3,0+2*1))+=1;
delta(0+2*1,cw(3,0+2*1)) = -1;
ASSUME(creturn[3] >= cw(3,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !96, metadata !DIExpression()), !dbg !109
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !56
// LD: Guess
old_cr = cr(3,0+1*1);
cr(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM
// Check
ASSUME(active[cr(3,0+1*1)] == 3);
ASSUME(cr(3,0+1*1) >= iw(3,0+1*1));
ASSUME(cr(3,0+1*1) >= 0);
ASSUME(cr(3,0+1*1) >= cdy[3]);
ASSUME(cr(3,0+1*1) >= cisb[3]);
ASSUME(cr(3,0+1*1) >= cdl[3]);
ASSUME(cr(3,0+1*1) >= cl[3]);
// Update
creg_r1 = cr(3,0+1*1);
crmax(3,0+1*1) = max(crmax(3,0+1*1),cr(3,0+1*1));
caddr[3] = max(caddr[3],0);
if(cr(3,0+1*1) < cw(3,0+1*1)) {
r1 = buff(3,0+1*1);
} else {
if(pw(3,0+1*1) != co(0+1*1,cr(3,0+1*1))) {
ASSUME(cr(3,0+1*1) >= old_cr);
}
pw(3,0+1*1) = co(0+1*1,cr(3,0+1*1));
r1 = mem(0+1*1,cr(3,0+1*1));
}
ASSUME(creturn[3] >= cr(3,0+1*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !98, metadata !DIExpression()), !dbg !109
// %conv = trunc i64 %0 to i32, !dbg !57
// call void @llvm.dbg.value(metadata i32 %conv, metadata !95, metadata !DIExpression()), !dbg !104
// %cmp = icmp eq i32 %conv, 0, !dbg !58
// %conv1 = zext i1 %cmp to i32, !dbg !58
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !99, metadata !DIExpression()), !dbg !104
// call void @llvm.dbg.value(metadata i64* @atom_2_X1_0, metadata !100, metadata !DIExpression()), !dbg !113
// %1 = zext i32 %conv1 to i64
// call void @llvm.dbg.value(metadata i64 %1, metadata !102, metadata !DIExpression()), !dbg !113
// store atomic i64 %1, i64* @atom_2_X1_0 seq_cst, align 8, !dbg !60
// ST: Guess
iw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,4);
cw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,4)] == 3);
ASSUME(active[cw(3,4)] == 3);
ASSUME(sforbid(4,cw(3,4))== 0);
ASSUME(iw(3,4) >= max(creg_r1,0));
ASSUME(iw(3,4) >= 0);
ASSUME(cw(3,4) >= iw(3,4));
ASSUME(cw(3,4) >= old_cw);
ASSUME(cw(3,4) >= cr(3,4));
ASSUME(cw(3,4) >= cl[3]);
ASSUME(cw(3,4) >= cisb[3]);
ASSUME(cw(3,4) >= cdy[3]);
ASSUME(cw(3,4) >= cdl[3]);
ASSUME(cw(3,4) >= cds[3]);
ASSUME(cw(3,4) >= cctrl[3]);
ASSUME(cw(3,4) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,4) = (r1==0);
mem(4,cw(3,4)) = (r1==0);
co(4,cw(3,4))+=1;
delta(4,cw(3,4)) = -1;
ASSUME(creturn[3] >= cw(3,4));
// ret i8* null, !dbg !61
ret_thread_3 = (- 1);
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// %thr2 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !123, metadata !DIExpression()), !dbg !161
// call void @llvm.dbg.value(metadata i8** %argv, metadata !124, metadata !DIExpression()), !dbg !161
// %0 = bitcast i64* %thr0 to i8*, !dbg !79
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !79
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !125, metadata !DIExpression()), !dbg !163
// %1 = bitcast i64* %thr1 to i8*, !dbg !81
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !81
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !129, metadata !DIExpression()), !dbg !165
// %2 = bitcast i64* %thr2 to i8*, !dbg !83
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !83
// call void @llvm.dbg.declare(metadata i64* %thr2, metadata !130, metadata !DIExpression()), !dbg !167
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !131, metadata !DIExpression()), !dbg !168
// call void @llvm.dbg.value(metadata i64 0, metadata !133, metadata !DIExpression()), !dbg !168
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !86
// ST: Guess
iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+2*1);
cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+2*1)] == 0);
ASSUME(active[cw(0,0+2*1)] == 0);
ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(cw(0,0+2*1) >= iw(0,0+2*1));
ASSUME(cw(0,0+2*1) >= old_cw);
ASSUME(cw(0,0+2*1) >= cr(0,0+2*1));
ASSUME(cw(0,0+2*1) >= cl[0]);
ASSUME(cw(0,0+2*1) >= cisb[0]);
ASSUME(cw(0,0+2*1) >= cdy[0]);
ASSUME(cw(0,0+2*1) >= cdl[0]);
ASSUME(cw(0,0+2*1) >= cds[0]);
ASSUME(cw(0,0+2*1) >= cctrl[0]);
ASSUME(cw(0,0+2*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+2*1) = 0;
mem(0+2*1,cw(0,0+2*1)) = 0;
co(0+2*1,cw(0,0+2*1))+=1;
delta(0+2*1,cw(0,0+2*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !134, metadata !DIExpression()), !dbg !170
// call void @llvm.dbg.value(metadata i64 0, metadata !136, metadata !DIExpression()), !dbg !170
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !88
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !137, metadata !DIExpression()), !dbg !172
// call void @llvm.dbg.value(metadata i64 0, metadata !139, metadata !DIExpression()), !dbg !172
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !90
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !140, metadata !DIExpression()), !dbg !174
// call void @llvm.dbg.value(metadata i64 0, metadata !142, metadata !DIExpression()), !dbg !174
// store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !92
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// call void @llvm.dbg.value(metadata i64* @atom_2_X1_0, metadata !143, metadata !DIExpression()), !dbg !176
// call void @llvm.dbg.value(metadata i64 0, metadata !145, metadata !DIExpression()), !dbg !176
// store atomic i64 0, i64* @atom_2_X1_0 monotonic, align 8, !dbg !94
// ST: Guess
iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,4);
cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,4)] == 0);
ASSUME(active[cw(0,4)] == 0);
ASSUME(sforbid(4,cw(0,4))== 0);
ASSUME(iw(0,4) >= 0);
ASSUME(iw(0,4) >= 0);
ASSUME(cw(0,4) >= iw(0,4));
ASSUME(cw(0,4) >= old_cw);
ASSUME(cw(0,4) >= cr(0,4));
ASSUME(cw(0,4) >= cl[0]);
ASSUME(cw(0,4) >= cisb[0]);
ASSUME(cw(0,4) >= cdy[0]);
ASSUME(cw(0,4) >= cdl[0]);
ASSUME(cw(0,4) >= cds[0]);
ASSUME(cw(0,4) >= cctrl[0]);
ASSUME(cw(0,4) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,4) = 0;
mem(4,cw(0,4)) = 0;
co(4,cw(0,4))+=1;
delta(4,cw(0,4)) = -1;
ASSUME(creturn[0] >= cw(0,4));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !95
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call9 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !96
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %call10 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !97
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[3] >= cdy[0]);
// %3 = load i64, i64* %thr0, align 8, !dbg !98, !tbaa !99
// LD: Guess
old_cr = cr(0,5);
cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,5)] == 0);
ASSUME(cr(0,5) >= iw(0,5));
ASSUME(cr(0,5) >= 0);
ASSUME(cr(0,5) >= cdy[0]);
ASSUME(cr(0,5) >= cisb[0]);
ASSUME(cr(0,5) >= cdl[0]);
ASSUME(cr(0,5) >= cl[0]);
// Update
creg_r3 = cr(0,5);
crmax(0,5) = max(crmax(0,5),cr(0,5));
caddr[0] = max(caddr[0],0);
if(cr(0,5) < cw(0,5)) {
r3 = buff(0,5);
} else {
if(pw(0,5) != co(5,cr(0,5))) {
ASSUME(cr(0,5) >= old_cr);
}
pw(0,5) = co(5,cr(0,5));
r3 = mem(5,cr(0,5));
}
ASSUME(creturn[0] >= cr(0,5));
// %call11 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !103
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %4 = load i64, i64* %thr1, align 8, !dbg !104, !tbaa !99
// LD: Guess
old_cr = cr(0,6);
cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,6)] == 0);
ASSUME(cr(0,6) >= iw(0,6));
ASSUME(cr(0,6) >= 0);
ASSUME(cr(0,6) >= cdy[0]);
ASSUME(cr(0,6) >= cisb[0]);
ASSUME(cr(0,6) >= cdl[0]);
ASSUME(cr(0,6) >= cl[0]);
// Update
creg_r4 = cr(0,6);
crmax(0,6) = max(crmax(0,6),cr(0,6));
caddr[0] = max(caddr[0],0);
if(cr(0,6) < cw(0,6)) {
r4 = buff(0,6);
} else {
if(pw(0,6) != co(6,cr(0,6))) {
ASSUME(cr(0,6) >= old_cr);
}
pw(0,6) = co(6,cr(0,6));
r4 = mem(6,cr(0,6));
}
ASSUME(creturn[0] >= cr(0,6));
// %call12 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !105
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// %5 = load i64, i64* %thr2, align 8, !dbg !106, !tbaa !99
// LD: Guess
old_cr = cr(0,7);
cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,7)] == 0);
ASSUME(cr(0,7) >= iw(0,7));
ASSUME(cr(0,7) >= 0);
ASSUME(cr(0,7) >= cdy[0]);
ASSUME(cr(0,7) >= cisb[0]);
ASSUME(cr(0,7) >= cdl[0]);
ASSUME(cr(0,7) >= cl[0]);
// Update
creg_r5 = cr(0,7);
crmax(0,7) = max(crmax(0,7),cr(0,7));
caddr[0] = max(caddr[0],0);
if(cr(0,7) < cw(0,7)) {
r5 = buff(0,7);
} else {
if(pw(0,7) != co(7,cr(0,7))) {
ASSUME(cr(0,7) >= old_cr);
}
pw(0,7) = co(7,cr(0,7));
r5 = mem(7,cr(0,7));
}
ASSUME(creturn[0] >= cr(0,7));
// %call13 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !107
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[3]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !147, metadata !DIExpression()), !dbg !191
// %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) seq_cst, align 8, !dbg !109
// LD: Guess
old_cr = cr(0,0+2*1);
cr(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,0+2*1)] == 0);
ASSUME(cr(0,0+2*1) >= iw(0,0+2*1));
ASSUME(cr(0,0+2*1) >= 0);
ASSUME(cr(0,0+2*1) >= cdy[0]);
ASSUME(cr(0,0+2*1) >= cisb[0]);
ASSUME(cr(0,0+2*1) >= cdl[0]);
ASSUME(cr(0,0+2*1) >= cl[0]);
// Update
creg_r6 = cr(0,0+2*1);
crmax(0,0+2*1) = max(crmax(0,0+2*1),cr(0,0+2*1));
caddr[0] = max(caddr[0],0);
if(cr(0,0+2*1) < cw(0,0+2*1)) {
r6 = buff(0,0+2*1);
} else {
if(pw(0,0+2*1) != co(0+2*1,cr(0,0+2*1))) {
ASSUME(cr(0,0+2*1) >= old_cr);
}
pw(0,0+2*1) = co(0+2*1,cr(0,0+2*1));
r6 = mem(0+2*1,cr(0,0+2*1));
}
ASSUME(creturn[0] >= cr(0,0+2*1));
// call void @llvm.dbg.value(metadata i64 %6, metadata !149, metadata !DIExpression()), !dbg !191
// %conv = trunc i64 %6 to i32, !dbg !110
// call void @llvm.dbg.value(metadata i32 %conv, metadata !146, metadata !DIExpression()), !dbg !161
// %cmp = icmp eq i32 %conv, 2, !dbg !111
// %conv14 = zext i1 %cmp to i32, !dbg !111
// call void @llvm.dbg.value(metadata i32 %conv14, metadata !150, metadata !DIExpression()), !dbg !161
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !152, metadata !DIExpression()), !dbg !195
// %7 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !113
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r7 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r7 = buff(0,3);
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r7 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i64 %7, metadata !154, metadata !DIExpression()), !dbg !195
// %conv18 = trunc i64 %7 to i32, !dbg !114
// call void @llvm.dbg.value(metadata i32 %conv18, metadata !151, metadata !DIExpression()), !dbg !161
// call void @llvm.dbg.value(metadata i64* @atom_2_X1_0, metadata !156, metadata !DIExpression()), !dbg !198
// %8 = load atomic i64, i64* @atom_2_X1_0 seq_cst, align 8, !dbg !116
// LD: Guess
old_cr = cr(0,4);
cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,4)] == 0);
ASSUME(cr(0,4) >= iw(0,4));
ASSUME(cr(0,4) >= 0);
ASSUME(cr(0,4) >= cdy[0]);
ASSUME(cr(0,4) >= cisb[0]);
ASSUME(cr(0,4) >= cdl[0]);
ASSUME(cr(0,4) >= cl[0]);
// Update
creg_r8 = cr(0,4);
crmax(0,4) = max(crmax(0,4),cr(0,4));
caddr[0] = max(caddr[0],0);
if(cr(0,4) < cw(0,4)) {
r8 = buff(0,4);
} else {
if(pw(0,4) != co(4,cr(0,4))) {
ASSUME(cr(0,4) >= old_cr);
}
pw(0,4) = co(4,cr(0,4));
r8 = mem(4,cr(0,4));
}
ASSUME(creturn[0] >= cr(0,4));
// call void @llvm.dbg.value(metadata i64 %8, metadata !158, metadata !DIExpression()), !dbg !198
// %conv22 = trunc i64 %8 to i32, !dbg !117
// call void @llvm.dbg.value(metadata i32 %conv22, metadata !155, metadata !DIExpression()), !dbg !161
// %and = and i32 %conv18, %conv22, !dbg !118
creg_r9 = max(creg_r7,creg_r8);
ASSUME(active[creg_r9] == 0);
r9 = r7 & r8;
// call void @llvm.dbg.value(metadata i32 %and, metadata !159, metadata !DIExpression()), !dbg !161
// %and23 = and i32 %conv14, %and, !dbg !119
creg_r10 = max(max(creg_r6,0),creg_r9);
ASSUME(active[creg_r10] == 0);
r10 = (r6==2) & r9;
// call void @llvm.dbg.value(metadata i32 %and23, metadata !160, metadata !DIExpression()), !dbg !161
// %cmp24 = icmp eq i32 %and23, 1, !dbg !120
// br i1 %cmp24, label %if.then, label %if.end, !dbg !122
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg_r10);
ASSUME(cctrl[0] >= 0);
if((r10==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([130 x i8], [130 x i8]* @.str.1, i64 0, i64 0), i32 noundef 71, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !123
// unreachable, !dbg !123
r11 = 1;
T0BLOCK2:
// %9 = bitcast i64* %thr2 to i8*, !dbg !126
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !126
// %10 = bitcast i64* %thr1 to i8*, !dbg !126
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !126
// %11 = bitcast i64* %thr0 to i8*, !dbg !126
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !126
// ret i32 0, !dbg !127
ret_thread_0 = 0;
ASSERT(r11== 0);
}
| [
"tuan-phong.ngo@it.uu.se"
] | tuan-phong.ngo@it.uu.se |
5ff670af72404a07d8beaa4fa6c99cd3ea59524b | 58f2b221b0849b9df67958cce4120929795a65bd | /myRayTracer/Paint/Paint.h | 4396bdabe52cdc97fd877caf57e4ba7ce7d4bfc2 | [] | no_license | gykeve/RayTracer | d214c06bae59185c740b90be04c1b7756e3fa64a | f364db9629da1a3ef7c9efa5dcf4df0efa0f204b | refs/heads/master | 2020-04-28T21:39:08.098821 | 2013-07-14T13:47:01 | 2013-07-14T13:47:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | h | #ifndef PAINT_H_INCLUDED
#define PAINT_H_INCLUDED
#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glut.h>
#include "../Utilities/RGBColor.h"
class Paint{
Paint() ;
~Paint() ;
public :
void setPixel( int x , int y , float r, float g, float b) ;
};
#endif
| [
"shicao.li@gmail.com"
] | shicao.li@gmail.com |
4d3f2d23e938cf739a506d3680de8a0c23c3487c | 363ecd3ccf2b588018c4c96c596013d1ebc69562 | /Loadouts/customFactions/BLUFOR/2014 Finnish Army/bluefor_standard.hpp | bb708f6da4417f939e6e825130e4a3c0d20fd165 | [] | no_license | derbismarck/bsm_sandbox_vXX.VR | 92e1c1a132b19fc98520dbc1292b11698a55f49c | fb36d768357fe40d5f00c3c4b2056ec94ee46947 | refs/heads/master | 2021-01-10T12:00:01.627129 | 2016-02-12T08:11:51 | 2016-02-12T08:11:51 | 51,565,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,143 | hpp | //Author:
//Description: BLUFOR (NATO) Standard
// ====================================================================================
class blu_f {
// Here we're creating definitions for weapons and magazines that are called later.
//Rifle
#define WEST_RIFLE "hlc_rifle_ak12"
#define WEST_RIFLE_MAG "hlc_30Rnd_545x39_B_AK:10"
//GL Rifle
#define WEST_GLRIFLE "hlc_rifle_ak12GL"
#define WEST_GLRIFLE_MAG "hlc_30Rnd_545x39_B_AK:10"
#define WEST_GLRIFLE_MAG_SMOKE "hlc_GRD_White:4","hlc_GRD_green:2","hlc_GRD_Red:3"
#define WEST_GLRIFLE_MAG_HE "hlc_VOG25_AK:8"
#define WEST_GLRIFLE_MAG_FLARE "UGL_FlareRed_F:0","UGL_FlareGreen_F:0"
//Carbine
#define WEST_CARBINE "hlc_rifle_ak12"
#define WEST_CARBINE_MAG "hlc_30Rnd_545x39_B_AK:10"
//Diver
#define SDAR "arifle_SDAR_F"
#define SDAR_MAG "20Rnd_556x45_UW_mag:6"
// AR
#define WEST_AR "hlc_rifle_RPK12"
#define WEST_AR_MAG "hlc_45Rnd_545x39_t_rpk:6"
#define WEST_AR_MAG2 "hlc_45Rnd_545x39_t_rpk:6"
// AT
#define WEST_AT "launch_NLAW_F"
#define WEST_AT_MAG "NLAW_F"
// MMG
#define WEST_MMG "MMG_02_black_F"
#define WEST_MMG_MAG "130Rnd_338_Mag:5"
// MAT
#define WEST_MAT "launch_B_Titan_short_F"
#define WEST_MAT_MAG "Titan_AT:3"
// SAM
#define WEST_SAM "launch_B_Titan_F"
#define WEST_SAM_MAG "Titan_AA:2"
// Sniper Rifle
#define WEST_SNIPER "srifle_DMR_02_F"
#define WEST_SNIPER_MAG "10Rnd_338_Mag:8"
// Spotter Rifle
#define WEST_SPOTTER "arifle_MX_F"
#define WEST_SPOTTER_MAG "30Rnd_65x39_caseless_mag:8"
// SMG
#define WEST_SMG "arifle_MXC_F"
#define WEST_SMG_MAG "30Rnd_65x39_caseless_mag:6"
// Pistol
#define WEST_PISTOL "hgun_ACPC2_F"
#define WEST_PISTOL_MAG "9Rnd_45ACP_Mag:4"
// Grenades, Smoke and Frag
#define WEST_GRENADE "HandGrenade:2"
#define WEST_SMOKE_WHITE "SmokeShell:2"
#define WEST_SMOKE_GREEN "SmokeShellGreen"
#define WEST_SMOKE_RED "SmokeShellRed"
// ====================================================================================
class Car {
TransportMagazines[] = {WEST_RIFLE_MAG,WEST_RIFLE_MAG,WEST_CARBINE_MAG,WEST_AR_MAG,WEST_AR_MAG,WEST_GLRIFLE_MAG_HE,WEST_AT_MAG};
TransportItems[] = {"ACE_fieldDressing:12","ACE_morphine:4"};
};
class Tank {
TransportMagazines[] = {WEST_RIFLE_MAG,WEST_RIFLE_MAG,WEST_CARBINE_MAG,WEST_AR_MAG,WEST_AR_MAG,WEST_GLRIFLE_MAG_HE,WEST_AT_MAG};
TransportItems[] = {"ACE_fieldDressing:12","ACE_morphine:4"};
};
class Helicopter {
TransportMagazines[] = {WEST_RIFLE_MAG,WEST_RIFLE_MAG,WEST_CARBINE_MAG,WEST_AR_MAG,WEST_AR_MAG,WEST_GLRIFLE_MAG_HE};
TransportItems[] = {"ACE_fieldDressing:12","ACE_morphine:4"};
};
class Plane {
TransportMagazines[] = {};
};
class Ship_F {
TransportMagazines[] = {};
};
// ====================================================================================
// Leadership INF and Groupies
class B_Soldier_F {// rifleman
uniform[] = {"MNP_CombatUniform_Fin_A","MNP_CombatUniform_Fin_B"}; /// randomized
vest[] = {"MNP_Vest_FIN_1","MNP_Vest_FIN_2"}; /// randomized
headgear[] = {"MNP_Boonie_FIN","MNP_Helmet_FIN_T"}; /// randomized
backpack[] = {"B_TacticalPack_blk"}; /// randomized
backpackItems[] = {"ACE_fieldDressing:3","ACE_morphine","ACE_IR_Strobe_item"};
weapons[] = {WEST_RIFLE}; /// randomized
launchers[] = {}; /// randomized
handguns[] = {}; /// randomized
magazines[] = {WEST_RIFLE_MAG,WEST_GRENADE,WEST_SMOKE_WHITE};
items[] = {"ACRE_PRC343"};
linkedItems[] = {"ItemMap","ItemCompass","ItemWatch"};
attachments[] = {"optic_ACO_grn"};
};
class B_officer_F: B_Soldier_F {// CO and DC
weapons[] = {WEST_GLRIFLE};
vest[] = {"MNP_Vest_FIN_1","MNP_Vest_FIN_2"}; /// randomized
headgear[] = {"MNP_Boonie_FIN","MNP_Helmet_FIN_T"}; /// randomized
magazines[] = {WEST_GLRIFLE_MAG,WEST_GLRIFLE_MAG_HE,WEST_GLRIFLE_MAG_SMOKE,WEST_GLRIFLE_MAG_FLARE,WEST_PISTOL_MAG,WEST_GRENADE,WEST_SMOKE_WHITE,WEST_SMOKE_GREEN};
handguns[] = {WEST_PISTOL}; /// randomized
backpackItems[] += {"ACE_key_west", "ACRE_PRC117F"};
linkedItems[] = {"ItemMap","ItemCompass","ItemWatch","NVGoggles","ItemGPS","ACE_Vector"};
items[] = {"ACE_MapTools","ACRE_PRC148"};
};
class B_Soldier_SL_F: B_Officer_F {// SL
linkedItems[] = {"ItemMap","ItemCompass","ItemWatch","ItemGPS","Binocular"};
items[] = {"ACE_MapTools","ACRE_PRC148", "ACRE_PRC343"};
backpackItems[] = {"ACE_fieldDressing:4","ACE_morphine","ACE_IR_Strobe_item"};
};
class B_soldier_UAV_F: B_Soldier_F {
backpack[] = {"B_Kitbag_mcamo"}; /// randomized
linkedItems[] += {"B_uavterminal"};
};
class B_medic_F: B_Soldier_F {// Medic
vest[] = {"MNP_Vest_FIN_1","MNP_Vest_FIN_2"}; /// randomized
weapons[] = {WEST_CARBINE};
magazines[] = {WEST_CARBINE_MAG,WEST_SMOKE_WHITE};
backpackItems[] = {"ACE_fieldDressing:31","ACE_epinephrine:8","ACE_bloodIV:2","ACE_morphine:14"};
};
// ====================================================================================
// Grunt Infantry
class B_Soldier_TL_F: B_Soldier_F {// FTL
weapons[] = {WEST_GLRIFLE};
headgear[] = {"MNP_Boonie_FIN","MNP_Helmet_FIN_T"}; /// randomized
magazines[] = {WEST_GLRIFLE_MAG,WEST_GLRIFLE_MAG_HE,WEST_GLRIFLE_MAG_SMOKE,WEST_GLRIFLE_MAG_FLARE,WEST_SMOKE_WHITE,WEST_GRENADE,WEST_SMOKE_WHITE,WEST_GRENADE,WEST_SMOKE_WHITE};
backpackItems[] += {"ACE_key_west"};
linkedItems[] += {"ItemGPS","Binocular"};
};
class B_Soldier_AR_F: B_Soldier_F {// AR
vest[] = {"MNP_Vest_FIN_1","MNP_Vest_FIN_2"}; /// randomized
weapons[] = {WEST_AR};
magazines[] = {WEST_AR_MAG,WEST_PISTOL_MAG,WEST_GRENADE,WEST_SMOKE_WHITE};
handguns[] = {WEST_PISTOL}; /// randomized
};
class B_Soldier_AAR_F: B_Soldier_F {// AAR
backpackItems[] += {WEST_AR_MAG2};
attachments[] = {};
linkedItems[] += {"Binocular"};
};
class B_Soldier_A_F: B_Soldier_AAR_F {// AAR
};
class B_Soldier_LAT_F: B_Soldier_F {// RAT
weapons[] = {WEST_CARBINE};
magazines[] = {WEST_CARBINE_MAG,WEST_AT_MAG,WEST_GRENADE,WEST_SMOKE_WHITE};
launchers[] = {WEST_AT}; /// randomized
};
// ====================================================================================
// Support Infantry
class B_support_MG_F: B_Soldier_F {// MMG
weapons[] = {WEST_MMG};
magazines[] = {WEST_MMG_MAG,WEST_PISTOL_MAG,WEST_GRENADE,WEST_SMOKE_WHITE};
handguns[] = {WEST_PISTOL}; /// randomized
attachments[] = {};
};
class B_support_AMG_F: B_Soldier_F {// MMG Spotter/Ammo Bearer
backpackItems[] += {WEST_MMG_MAG};
linkedItems[] += {"ACE_Vector"};
items[] += {"ACRE_PRC148"};
};
class B_soldier_AT_F: B_Soldier_F {// MAT Gunner
weapons[] = {WEST_CARBINE};
magazines[] = {WEST_CARBINE_MAG,WEST_GRENADE,WEST_SMOKE_WHITE};
launchers[] = {WEST_MAT}; /// randomized
items[] = {"ACE_fieldDressing:3","ACE_morphine","ACRE_PRC148"};
backpackItems[] = {WEST_MAT_MAG};
};
class B_Soldier_AAT_F: B_Soldier_F {// MAT Spotter/Ammo Bearer
backpackItems[] = {WEST_MAT_MAG};
linkedItems[] += {"ACE_Vector"};
items[] += {"ACRE_PRC148"};
};
class B_soldier_AA_F: B_Soldier_F {// SAM Gunner
weapons[] = {WEST_CARBINE};
magazines[] = {WEST_CARBINE_MAG,WEST_GRENADE,WEST_GRENADE,WEST_SMOKE_WHITE};
launchers[] = {WEST_SAM}; /// randomized
backpackItems[] += {WEST_SAM_MAG};
};
class B_Soldier_AAA_F: B_Soldier_F {// SAM Spotter/Ammo Bearer
backpackItems[] = {WEST_SAM_MAG};
linkedItems[] += {"ACE_Vector"};
items[] += {"ACRE_PRC148"};
};
class B_support_Mort_F: B_Soldier_F {// Mortar Gunner
weapons[] = {WEST_CARBINE};
magazines[] = {WEST_CARBINE_MAG,WEST_GRENADE,WEST_SMOKE_WHITE};
items[] = {"ACE_fieldDressing:3","ACE_morphine"};
backpack[] = {"B_Mortar_01_weapon_F"}; /// randomized
};
class B_support_AMort_F: B_Soldier_F {// Assistant Mortar
backpack[] = {"B_Mortar_01_support_F"}; /// randomized
linkedItems[] += {"ACE_Vector"};
items[] = {"ACE_fieldDressing:3","ACE_morphine","ACRE_PRC148"};
};
class B_spotter_F {// Spotter
uniform[] = {"U_B_CombatUniform_mcam"}; /// randomized
vest[] = {"V_Chestrig_rgr"}; /// randomized
headgear[] = {"H_Watchcap_camo"}; /// randomized
weapons[] = {WEST_SPOTTER}; /// randomized
magazines[] = {WEST_SPOTTER_MAG,WEST_SMOKE_WHITE,WEST_GRENADE};
items[] = {"ACE_fieldDressing:3","ACE_morphine", "ACRE_PRC343", "ACRE_PRC148"};
linkedItems[] = {"ItemMap","ItemCompass","ItemWatch","ItemGPS","LaserDesignator"};
attachments[] = {"optic_Holosight","acc_pointer_IR"};
};
class B_sniper_F {// Sniper
uniform[] = {"U_B_CombatUniform_mcam"}; /// randomized
vest[] = {"V_Chestrig_rgr"}; /// randomized
headgear[] = {"H_Watchcap_camo"}; /// randomized
weapons[] = {WEST_SNIPER}; /// randomized
magazines[] = {WEST_SNIPER_MAG,WEST_SMOKE_WHITE,WEST_GRENADE};
items[] = {"ACE_fieldDressing:3","ACE_morphine", "ACRE_PRC343"};
linkedItems[] = {"ItemMap","ItemCompass","ItemWatch","ItemGPS"};
attachments[] = {"optic_SOS","acc_pointer_IR"};
};
// ====================================================================================
// Vehicle Infantry
class B_Helipilot_F {// Pilot
uniform[] = {"U_B_HeliPilotCoveralls"}; /// randomized
backpack[] = {"B_AssaultPack_blk"};
vest[] = {"V_TacVest_blk"}; /// randomized
headgear[] = {"H_PilotHelmetHeli_B"}; /// randomized
weapons[] = {WEST_SMG}; /// randomized
magazines[] = {WEST_SMG_MAG,WEST_SMOKE_WHITE};
backpackItems[] += {"ACE_key_west","ACRE_PRC117F"};
items[] = {"ACE_fieldDressing:3","ACE_morphine","ACRE_PRC148"};
linkedItems[] = {"ItemMap","ItemCompass","ItemWatch","itemGPS","NVgoggles"};
};
class B_helicrew_F: B_Helipilot_F { // Pilot
};
class B_Pilot_F: B_Helipilot_F { // Pilot
uniform[] = {"U_B_PilotCoveralls"}; /// randomized
headgear[] = {"H_PilotHelmetFighter_B"}; /// randomized
};
class B_crew_F {// Crew
uniform[] = {"U_B_CombatUniform_mcam"}; // randomized
vest[] = {"V_TacVest_blk"}; // randomized
headgear[] = {"H_Watchcap_camo"}; /// randomized
backpack[] = {"B_Carryall_mcamo"};
weapons[] = {WEST_CARBINE}; /// randomized
magazines[] = {WEST_CARBINE_MAG,WEST_SMOKE_WHITE};
items[] = {"ACE_fieldDressing:3","ACE_morphine"};
backpackItems[] += {"ACE_key_west","ACRE_PRC148","ACRE_PRC117F"};
linkedItems[] = {"ItemMap","ItemCompass","ItemWatch","ItemGPS"};
};
class B_soldier_repair_F: B_crew_F {// Repair Specialist
backpack[] = {"B_Carryall_mcamo"};
backpackItems[] = {"Toolkit"};
vest[] = {"V_PlateCarrier1_rgr"}; /// randomized
items[] += {"ACRE_PRC343"};
linkedItems[] = {"ItemMap", "ItemCompass", "ItemWatch"};
};
class B_soldier_exp_F: B_soldier_repair_F {// Explosive Specialist
backpack[] = {"B_Carryall_mcamo"};
backpackItems[] = {"Toolkit","ACE_DefusalKit","ACE_Clacker","MineDetector"};
magazines[] = {WEST_CARBINE_MAG,"DemoCharge_Remote_Mag:3","SatchelCharge_Remote_Mag:2"};
};
class B_engineer_F: B_soldier_repair_F {// Mine Specialist
backpack[] = {"B_Carryall_mcamo"};
backpackItems[] = {"Toolkit","ACE_DefusalKit","ACE_Clacker","MineDetector"};
magazines[] = {WEST_CARBINE_MAG,"ATMine_Range_Mag:2","APERSBoundingMine_Range_Mag:2","APERSMine_Range_Mag:2"};
};
// ====================================================================================
// Special Infantry
class B_diver_TL_F: B_Soldier_TL_F {// Diver TL
weapons[] = {SDAR};
magazines[] = {SDAR_MAG,WEST_CARBINE_MAG,WEST_GRENADE,WEST_SMOKE_WHITE};
uniform[] = {"U_B_Wetsuit"}; /// randomized
vest[] = {"V_RebreatherB"}; /// randomized
backpack[] = {"MNP_B_WD_CA"};
headgear[] = {};
backpackItems[] += {/*"U_B_CombatUniform_mcam","V_PlateCarrier1_rgr","H_HelmetB",*/WEST_CARBINE};
linkedItems[] += {"G_B_Diving"};
};
class B_diver_F: B_Soldier_F {// Diver
weapons[] = {SDAR};
magazines[] = {SDAR_MAG,WEST_CARBINE_MAG,WEST_GRENADE,WEST_SMOKE_WHITE};
uniform[] = {"U_B_Wetsuit"}; /// randomized
vest[] = {"V_RebreatherB"}; /// randomized
backpack[] = {"MNP_B_WD_CA"};
headgear[] = {};
backpackItems[] += {/*"U_B_CombatUniform_mcam","V_PlateCarrier1_rgr","H_HelmetB",*/WEST_CARBINE};
linkedItems[] += {"G_B_Diving"};
};
}; | [
"pankgaming@gmail.com"
] | pankgaming@gmail.com |
34af35637cbb64b3a24668fcec42c1220b327360 | 3728db88d8f8268ded2af24c4240eec9f9dc9068 | /mln/io/pfm/load.hh | a2fd67f4a4aee8cc65ffe77207861350e15f0e1b | [] | no_license | KDE/kolena | ca01613a49b7d37f0f74953916a49aceb162daf8 | 0e0eff22f44e3834e8ebaf2c226eaba602b1ebf6 | refs/heads/master | 2021-01-19T06:40:53.365100 | 2011-03-29T11:53:16 | 2011-03-29T11:53:16 | 42,732,429 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,966 | hh | // Copyright (C) 2007, 2008, 2009 EPITA Research and Development Laboratory (LRDE)
//
// This file is part of Olena.
//
// Olena is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation, version 2 of the License.
//
// Olena 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 Olena. If not, see <http://www.gnu.org/licenses/>.
//
// As a special exception, you may use this file as part of a free
// software project without restriction. Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to produce
// an executable, this file does not by itself cause the resulting
// executable to be covered by the GNU General Public License. This
// exception does not however invalidate any other reasons why the
// executable file might be covered by the GNU General Public License.
#ifndef MLN_IO_PFM_LOAD_HH
# define MLN_IO_PFM_LOAD_HH
/// \file
///
/// Define a function which loads an image of kind pfm with
/// given path.
# include <iostream>
# include <fstream>
# include <mln/core/image/image2d.hh>
# include <mln/value/int_u8.hh>
namespace mln
{
namespace io
{
namespace pfm
{
/// Load a pfm image in a Milena image.
///
/// \param[out] ima A reference to the image2d<float> which will receive
/// data.
/// \param[in] filename The source.
///
void load(image2d<float>& ima,
const std::string& filename);
/// Load a pfm image in a image2d<float>.
///
/// \param[in] filename The image source.
///
/// \return An image2d<float> which contains loaded data.
///
image2d<float> load(const std::string& filename);
# ifndef MLN_INCLUDE_ONLY
namespace internal
{
inline
void abort()
{
std::cerr << " aborting." << std::endl;
exit(0);
}
inline
bool read_pfm_header(std::istream& file,
int& nrows, int& ncols,
bool test = false)
{
std::string tag;
// get size
file >> nrows;
file >> ncols;
if (file.get() != '\n')
goto err;
// check tag == float
file >> tag;
if (tag != "float")
goto err;
if (file.get() != '\n')
goto err;
return true;
err:
if (! test)
{
std::cerr << "error: badly formed header!"
<< std::endl;
abort();
}
return false;
}
/// load_raw_2d.
template <typename I>
inline
void load_raw_2d(std::ifstream& file, I& ima)
{
point2d p = point2d(0, 0);
const mln_deduce(I, site, coord)
min_row = geom::min_row(ima),
max_row = geom::max_row(ima);
unsigned int
ncols = geom::ncols(ima);
for (p.row() = min_row; p.row() <= max_row; ++p.row())
file.read((char*)(&(ima(p))),
sizeof(float) * ncols);
}
} // end of namespace mln::io::internal
inline
image2d<float> load(const std::string& filename)
{
trace::entering("mln::io::pfm::load");
std::ifstream file(filename.c_str());
if (! file)
{
std::cerr << "error: file '" << filename
<< "' not found!";
abort();
}
int nrows, ncols;
internal::read_pfm_header(file, nrows, ncols);
image2d<float> ima(nrows, ncols);
internal::load_raw_2d(file, ima);
trace::exiting("mln::io::pfm::load");
return ima;
}
inline
void load(image2d<float>& ima,
const std::string& filename)
{
ima = load(filename);
}
# endif // ! MLN_INCLUDE_ONLY
} // end of namespace mln::io::pfm
} // end of namespace mln::io
} // end of namespace mln
#endif // ! MLN_IO_PFM_LOAD_HH
| [
"trueg@kde.org"
] | trueg@kde.org |
feab8a90a0300faff1cae005f618b3f40268822e | 3624e9f0a026b57ebdafa4e842b93f56e5a8504d | /CodeChef/WF/Easy Medium/RRPLAYER/A.cc | 2143d03bf4954ce2e1b4111a4149b8f9ef4e8a04 | [
"MIT"
] | permissive | ailyanlu1/Competitive-Programming-2 | 54109c8644d3ac02715dc4570916b212412c25c0 | 6c990656178fb0cd33354cbe5508164207012f24 | refs/heads/master | 2020-03-23T07:48:20.560283 | 2018-02-15T06:49:49 | 2018-02-15T06:49:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,502 | cc | #include <bits/stdc++.h>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define foreach(it, v) for(auto it=(v).begin(); it != (v).end(); ++it)
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
#define tr(...) cout<<__FUNCTION__<<' '<<__LINE__<<" = ";trace(#__VA_ARGS__, __VA_ARGS__)
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
template<typename S, typename T>
ostream& operator<<(ostream& out,pair<S,T> const& p){out<<'('<<p.fi<<", "<<p.se<<')';return out;}
template<typename T>
ostream& operator<<(ostream& out,vector<T> const& v){
int l=v.size();for(int i=0;i<l-1;i++)out<<v[i]<<' ';if(l>0)out<<v[l-1];return out;}
template<typename T>
void trace(const char* name, T&& arg1){cout<<name<<" : "<<arg1<<endl;}
template<typename T, typename... Args>
void trace(const char* names, T&& arg1, Args&&... args){
const char* comma = strchr(names + 1, ',');cout.write(names, comma-names)<<" : "<<arg1<<" | ";trace(comma+1,args...);}
const ld PI = 3.1415926535897932384626433832795;
void solve(){
double n;
cin >> n;
double ans = 0;
for(int i = 1; i <= n; i++){
ans += n / i;
}
cout << fixed << setprecision(10) << ans << endl;
}
int main(){
int t;
cin >> t;
while(t--) solve();
return 0;
}
| [
"adityapaliwal95@gmail.com"
] | adityapaliwal95@gmail.com |
643fb36d9b975656f67759bbcfc694a60cda5068 | 5b45c4c1fcdf9b2ba9ba312a283e8f3ea8e00f32 | /RotateArray.cpp | 3686b3edc7cf4845deccab368eea495a850726f5 | [] | no_license | Maicius/TargetOffer | d8bcf5a450e831779ab59928c38ee783ee70f42b | ac2cb9ef7e811165c3c7a798e47faa51fdfb804b | refs/heads/master | 2020-08-23T00:47:26.053031 | 2019-11-07T04:55:01 | 2019-11-07T04:55:01 | 216,509,455 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 980 | cpp | #include<iostream>
#include<vector>
using namespace std;
//题目描述
/**
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
**/
class Solution {
public:
int minNumberInRotateArray(vector<int> rotateArray) {
if (rotateArray.size() == 0){
return 0;
} else if(rotateArray.size() == 1){
return rotateArray[0];
}
for(int i=0; i < rotateArray.size() - 1; i++){
if (rotateArray[i] > rotateArray[i + 1]){
return rotateArray[i + 1];
}else {
if (i == rotateArray.size() - 2){
return rotateArray[0];
}
}
}
}
}; | [
"maicius@outlook.com"
] | maicius@outlook.com |
80219689c6a3a8def15f3c12fc7d62bf2f4fae83 | 2508a5346ae7b09ad31cfa470420940b8145e3a1 | /src/primitives/zerocoin.h | 1f96231e72386ac054f3684d4bff7bf3b74903a4 | [
"MIT"
] | permissive | saniisan/GHRCoin | a6a7a6f31288177af16e829f25242006c1728edf | 2a1d1926763f88f69b806fe2e96e212bd429cdaf | refs/heads/master | 2020-06-06T23:14:34.327772 | 2019-06-20T09:25:35 | 2019-06-20T09:25:35 | 192,873,114 | 0 | 0 | MIT | 2019-06-20T07:40:08 | 2019-06-20T07:40:08 | null | UTF-8 | C++ | false | false | 7,899 | h | // Copyright (c) 2017-2018 The PIVX developers
// Copyright (c) 2019 The GHRCoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef GHRCoin_ZEROCOIN_H
#define GHRCoin_ZEROCOIN_H
#include <amount.h>
#include <limits.h>
#include "libzerocoin/bignum.h"
#include "libzerocoin/Denominations.h"
#include "key.h"
#include "serialize.h"
//struct that is safe to store essential mint data, without holding any information that allows for actual spending (serial, randomness, private key)
struct CMintMeta
{
int nHeight;
uint256 hashSerial;
uint256 hashPubcoin;
uint256 hashStake; //requires different hashing method than hashSerial above
uint8_t nVersion;
libzerocoin::CoinDenomination denom;
uint256 txid;
bool isUsed;
bool isArchived;
bool isDeterministic;
bool operator <(const CMintMeta& a) const;
};
uint256 GetSerialHash(const CBigNum& bnSerial);
uint256 GetPubCoinHash(const CBigNum& bnValue);
class CZerocoinMint
{
private:
libzerocoin::CoinDenomination denomination;
int nHeight;
CBigNum value;
CBigNum randomness;
CBigNum serialNumber;
uint256 txid;
CPrivKey privkey;
uint8_t version;
bool isUsed;
public:
static const int STAKABLE_VERSION = 2;
static const int CURRENT_VERSION = 2;
CZerocoinMint()
{
SetNull();
}
CZerocoinMint(libzerocoin::CoinDenomination denom, const CBigNum& value, const CBigNum& randomness, const CBigNum& serialNumber, bool isUsed, const uint8_t& nVersion, CPrivKey* privkey = nullptr)
{
SetNull();
this->denomination = denom;
this->value = value;
this->randomness = randomness;
this->serialNumber = serialNumber;
this->isUsed = isUsed;
this->version = nVersion;
if (nVersion >= 2 && privkey)
this->privkey = *privkey;
}
void SetNull()
{
isUsed = false;
randomness = 0;
value = 0;
denomination = libzerocoin::ZQ_ERROR;
nHeight = 0;
txid = 0;
version = 1;
privkey.clear();
}
uint256 GetHash() const;
CBigNum GetValue() const { return value; }
void SetValue(CBigNum value){ this->value = value; }
libzerocoin::CoinDenomination GetDenomination() const { return denomination; }
int64_t GetDenominationAsAmount() const { return denomination * COIN; }
void SetDenomination(libzerocoin::CoinDenomination denom){ this->denomination = denom; }
int GetHeight() const { return nHeight; }
void SetHeight(int nHeight){ this->nHeight = nHeight; }
bool IsUsed() const { return this->isUsed; }
void SetUsed(bool isUsed){ this->isUsed = isUsed; }
CBigNum GetRandomness() const{ return randomness; }
void SetRandomness(CBigNum rand){ this->randomness = rand; }
CBigNum GetSerialNumber() const { return serialNumber; }
void SetSerialNumber(CBigNum serial){ this->serialNumber = serial; }
uint256 GetTxHash() const { return this->txid; }
void SetTxHash(uint256 txid) { this->txid = txid; }
uint8_t GetVersion() const { return this->version; }
void SetVersion(const uint8_t nVersion) { this->version = nVersion; }
CPrivKey GetPrivKey() const { return this->privkey; }
void SetPrivKey(const CPrivKey& privkey) { this->privkey = privkey; }
bool GetKeyPair(CKey& key) const;
inline bool operator <(const CZerocoinMint& a) const { return GetHeight() < a.GetHeight(); }
CZerocoinMint(const CZerocoinMint& other) {
denomination = other.GetDenomination();
nHeight = other.GetHeight();
value = other.GetValue();
randomness = other.GetRandomness();
serialNumber = other.GetSerialNumber();
txid = other.GetTxHash();
isUsed = other.IsUsed();
version = other.GetVersion();
privkey = other.privkey;
}
std::string ToString() const;
bool operator == (const CZerocoinMint& other) const
{
return this->GetValue() == other.GetValue();
}
// Copy another CZerocoinMint
inline CZerocoinMint& operator=(const CZerocoinMint& other) {
denomination = other.GetDenomination();
nHeight = other.GetHeight();
value = other.GetValue();
randomness = other.GetRandomness();
serialNumber = other.GetSerialNumber();
txid = other.GetTxHash();
isUsed = other.IsUsed();
version = other.GetVersion();
privkey = other.GetPrivKey();
return *this;
}
// why 6 below (SPOCK)
inline bool checkUnused(int denom, int Height) const {
if (IsUsed() == false && GetDenomination() == denomination && GetRandomness() != 0 && GetSerialNumber() != 0 && GetHeight() != -1 && GetHeight() != INT_MAX && GetHeight() >= 1 && (GetHeight() + 6 <= Height)) {
return true;
} else {
return false;
}
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(isUsed);
READWRITE(randomness);
READWRITE(serialNumber);
READWRITE(value);
READWRITE(denomination);
READWRITE(nHeight);
READWRITE(txid);
bool fVersionedMint = true;
try {
READWRITE(version);
} catch (...) {
fVersionedMint = false;
}
if (version > CURRENT_VERSION) {
version = 1;
fVersionedMint = false;
}
if (fVersionedMint)
READWRITE(privkey);
};
};
class CZerocoinSpend
{
private:
CBigNum coinSerial;
uint256 hashTx;
CBigNum pubCoin;
libzerocoin::CoinDenomination denomination;
unsigned int nAccumulatorChecksum;
int nMintCount; //memory only - the amount of mints that belong to the accumulator this is spent from
public:
CZerocoinSpend()
{
SetNull();
}
CZerocoinSpend(CBigNum coinSerial, uint256 hashTx, CBigNum pubCoin, libzerocoin::CoinDenomination denomination, unsigned int nAccumulatorChecksum)
{
this->coinSerial = coinSerial;
this->hashTx = hashTx;
this->pubCoin = pubCoin;
this->denomination = denomination;
this->nAccumulatorChecksum = nAccumulatorChecksum;
}
void SetNull()
{
coinSerial = 0;
hashTx = 0;
pubCoin = 0;
denomination = libzerocoin::ZQ_ERROR;
}
CBigNum GetSerial() const { return coinSerial; }
uint256 GetTxHash() const { return hashTx; }
void SetTxHash(uint256 hash) { this->hashTx = hash; }
CBigNum GetPubCoin() const { return pubCoin; }
libzerocoin::CoinDenomination GetDenomination() const { return denomination; }
unsigned int GetAccumulatorChecksum() const { return this->nAccumulatorChecksum; }
uint256 GetHash() const;
void SetMintCount(int nMintsAdded) { this->nMintCount = nMintsAdded; }
int GetMintCount() const { return nMintCount; }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(coinSerial);
READWRITE(hashTx);
READWRITE(pubCoin);
READWRITE(denomination);
READWRITE(nAccumulatorChecksum);
};
};
class CZerocoinSpendReceipt
{
private:
std::string strStatusMessage;
int nStatus;
int nNeededSpends;
std::vector<CZerocoinSpend> vSpends;
public:
void AddSpend(const CZerocoinSpend& spend);
std::vector<CZerocoinSpend> GetSpends();
void SetStatus(std::string strStatus, int nStatus, int nNeededSpends = 0);
std::string GetStatusMessage();
int GetStatus();
int GetNeededSpends();
};
#endif //GHRCoin_ZEROCOIN_H
| [
"51785548+GHRcoin@users.noreply.github.com"
] | 51785548+GHRcoin@users.noreply.github.com |
10ff1418a1fdfa0f0777943d504f201fd6183ac0 | db557a30a28f77774cf4662c119a9197fb3ae0a0 | /HelperFunctions/getVkMappedMemoryRange.cpp | 0ea3714572e2b82a2cad0b1de7440b8083bdb09e | [
"Apache-2.0"
] | permissive | dkaip/jvulkan-natives-Linux-x86_64 | b076587525a5ee297849e08368f32d72098ae87e | ea7932f74e828953c712feea11e0b01751f9dc9b | refs/heads/master | 2021-07-14T16:57:14.386271 | 2020-09-13T23:04:39 | 2020-09-13T23:04:39 | 183,515,517 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,963 | cpp | /*
* Copyright 2019-2020 Douglas Kaip
*
* 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.
*/
/*
* getVkMappedMemoryRange.cpp
*
* Created on: Oct 28, 2019
* Author: Douglas Kaip
*/
#include "JVulkanHelperFunctions.hh"
#include "slf4j.hh"
namespace jvulkan
{
void getVkMappedMemoryRange(
JNIEnv *env,
const jobject jVkMappedMemoryRangeObject,
VkMappedMemoryRange *vkMappedMemoryRange,
std::vector<void *> *memoryToFree)
{
jclass theClass = env->GetObjectClass(jVkMappedMemoryRangeObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find class for jVkMappedMemoryRangeObject");
return;
}
////////////////////////////////////////////////////////////////////////
VkStructureType sTypeValue = getSType(env, jVkMappedMemoryRangeObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getSType failed.");
return;
}
////////////////////////////////////////////////////////////////////////
jobject jpNextObject = getpNextObject(env, jVkMappedMemoryRangeObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getpNext failed.");
return;
}
if (jpNextObject != nullptr)
{
LOGERROR(env, "%s", "pNext must be null.");
return;
}
void *pNext = nullptr;
////////////////////////////////////////////////////////////////////////
jmethodID methodId = env->GetMethodID(theClass, "getMemory", "()Lcom/CIMthetics/jvulkan/VulkanCore/Handles/VkDeviceMemory;");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find method id for getMemory");
return;
}
jobject jVulkanHandleObject = env->CallObjectMethod(jVkMappedMemoryRangeObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallObjectMethod");
return;
}
VkDeviceMemory vkDeviceMemoryHandle = (VkDeviceMemory)jvulkan::getHandleValue(env, jVulkanHandleObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not retrieve VkDeviceMemory handle");
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(theClass, "getOffset", "()J");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find method id for getOffset");
return;
}
jlong offset = env->CallLongMethod(jVkMappedMemoryRangeObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallObjectMethod");
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(theClass, "getSize", "()J");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find method id for getSize");
return;
}
jlong size = env->CallLongMethod(jVkMappedMemoryRangeObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallObjectMethod");
return;
}
vkMappedMemoryRange->sType = sTypeValue;
vkMappedMemoryRange->pNext = pNext;
vkMappedMemoryRange->memory = vkDeviceMemoryHandle;
vkMappedMemoryRange->offset = offset;
vkMappedMemoryRange->size = size;
}
}
| [
"dkaip@earthlink.net"
] | dkaip@earthlink.net |
26a9701e97547666d23ba1af3b5fe62da7d6acbf | 96ac933f4ba9b2b11479ffcaa7a20902d6f251df | /src/main.cpp | c367a9a9d7eca67fb79e130ec292f39d63dc59ae | [] | no_license | victorcmoura/oo2019-2-aula1-ecommerce | 7870275d2adb953b83624b449b8f156210a1e00e | 6795a8f6488f58128d76dcdc4f44bedc4cb0b9a7 | refs/heads/master | 2020-07-07T18:02:09.020296 | 2019-08-22T04:04:47 | 2019-08-22T04:04:47 | 203,431,583 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,487 | cpp | #include <bits/stdc++.h>
#include "comentario.hpp"
#include "produto.hpp"
#include "carrinho.hpp"
int main(){
// Usando a classe comentário
Comentario c;
c.set_titulo("Meu titulo");
c.set_autor("Victor Moura");
c.set_texto("Muito bom");
std::cout << c.get_titulo() << std::endl;
// Usando a classe produto
Produto p;
p.set_nome("Produto 1");
p.set_preco(10.0);
p.set_peso(10.5);
p.set_quantidade(2);
std::cout << p.get_nome() << std::endl;
// Usando as classes comentário e produto ao mesmo tempo
p.add_comentario(c);
std::cout << "Comentarios: " << std::endl;
for(auto &comentario : p.get_comentarios()){
std::cout << "\t" << comentario.get_titulo() << "(" + comentario.get_autor() + "):" << std::endl;
std::cout << "\t\t" << comentario.get_texto() << std::endl;
}
// Usando a classe Carrinho
Carrinho carr = Carrinho();
std::cout << carr.get_total() + carr.get_frete() << std::endl;
// Usando todas as classes ao mesmo tempo
carr.add_produto(p);
std::cout << "Carrinho: " << std::endl;
for(auto &produto : carr.get_produtos()){
std::cout << "\t" + produto.get_nome() + " - " << produto.get_preco() << " x " << produto.get_quantidade() << std::endl;
}
std::cout << "Total: " << carr.get_total() << "/Frete: " << carr.get_frete() << std::endl;
std::cout << "Valor final: " << carr.get_total() + carr.get_frete() << std::endl;
return 0;
} | [
"victor_cmoura@hotmail.com"
] | victor_cmoura@hotmail.com |
d395d2e0def61ad70c76377355f4d106fead95f4 | 234d3f475095bc9e2b6d4784fd2c0ac9f97cb994 | /DeviceFission11Ext/DeviceFission11Ext.cpp | 2c544012869fa813fabb64c101d9b7b2f3b3a7ae | [] | no_license | easonwang27/amd_2.8 | 2cf3a95dc063987b28134fedb0c6b7c058428b15 | 9a1416a28e4bfe3139aa69e29893136d8e521d2c | refs/heads/master | 2022-11-30T05:49:12.467729 | 2020-08-06T08:21:49 | 2020-08-06T08:21:49 | 285,514,703 | 0 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 26,659 | cpp | /**********************************************************************
Copyright ©2012 Advanced Micro Devices, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
• Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
• Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************/
#include "DeviceFission11Ext.hpp"
static clCreateSubDevicesEXT_fn pfn_clCreateSubDevicesEXT = NULL;
static clReleaseDeviceEXT_fn pfn_clReleaseDeviceEXT = NULL;
int
DeviceFission::setupDeviceFission()
{
// make sure length is multiple of group size * numSubDevices
unsigned int mulFactor = GROUP_SIZE * numSubDevices;
length = (length < mulFactor) ? mulFactor : length;
length = (length / mulFactor) * mulFactor;
input = (float*)malloc(length * sizeof(float));
CHECK_ALLOCATION(input, "Failed to allocate host memory. (input)");
// Random initialisation of input
sampleCommon->fillRandom<cl_float>(input, length, 1, 0, 5);
// Unless quiet mode has been enabled, print the INPUT array
if(!quiet)
sampleCommon->printArray<cl_float>("Input", input, VALUES_PRINTED, 1);
rOutput = (float*)malloc(length * sizeof(float));
CHECK_ALLOCATION(rOutput, "Failed to allocate host memory. (output)");
memset(rOutput, 0, length * sizeof(cl_float));
subOutput = (float*)malloc(length * sizeof(float));
CHECK_ALLOCATION(subOutput, "Failed to allocate host memory. (subOutput)");
memset(subOutput, 0, length * sizeof(cl_float));
return SDK_SUCCESS;
}
int
DeviceFission::setupCLPlatform()
{
cl_int status = CL_SUCCESS;
cl_device_type dType;
if(deviceType.compare("cpu") == 0)
dType = CL_DEVICE_TYPE_CPU;
else //deviceType = "gpu"
{
std::cout << "Not supported on GPU. Falling back to CPU device" << std::endl;
dType = CL_DEVICE_TYPE_CPU;
deviceId = 0;
}
/*
* Have a look at the available platforms and pick either
* the AMD one if available or a reasonable default.
*/
cl_platform_id platform = NULL;
int retValue = sampleCommon->getPlatform(platform, platformId, isPlatformEnabled());
CHECK_ERROR(retValue, SDK_SUCCESS, "sampleCommon::getPlatform() failed");
// Display available devices.
retValue = sampleCommon->displayDevices(platform, dType);
CHECK_ERROR(retValue, SDK_SUCCESS, "sampleCommon::displayDevices() failed");
/*
* If we could find our platform, use it. Otherwise use just available platform.
*/
cl_context_properties cps[3] =
{
CL_CONTEXT_PLATFORM,
(cl_context_properties)platform,
0
};
rContext = clCreateContextFromType(
cps,
dType,
NULL,
NULL,
&status);
CHECK_OPENCL_ERROR( status, "clCreateContextFromType failed.");
// getting device on which to run the sample
status = sampleCommon->getDevices(rContext, &rootDevices, deviceId, isDeviceIdEnabled());
CHECK_ERROR(status, SDK_SUCCESS, "sampleCommon::getDevices() failed");
//Set device info of given cl_device_id
retValue = deviceInfo.setDeviceInfo(rootDevices[deviceId]);
CHECK_ERROR(retValue, 0, "SDKDeviceInfo::setDeviceInfo() failed");
// Check if byte-addressable store is supported
if(!strstr(deviceInfo.extensions, "cl_ext_device_fission"))
{
reqdExtSupport = CL_FALSE;
OPENCL_EXPECTED_ERROR("Device does not support cl_ext_device_fission extension!");
}
// Initialize required partition property
cl_device_partition_property_ext partitionPrty[3] =
{
CL_DEVICE_PARTITION_EQUALLY_EXT,
1,
CL_PROPERTIES_LIST_END_EXT
};
// Initialize clCreateSubDevicesEXT and clReleaseDeviceEXT function pointers
INIT_CL_EXT_FCN_PTR(clCreateSubDevicesEXT);
INIT_CL_EXT_FCN_PTR(clReleaseDeviceEXT);
// Get number of sub-devices
status = pfn_clCreateSubDevicesEXT(rootDevices[deviceId],
partitionPrty,
0,
NULL,
&numSubDevices);
CHECK_OPENCL_ERROR(status, "clCreateSubDevicesEXT failed.");
subDevices = (cl_device_id*)malloc(numSubDevices * sizeof(cl_device_id));
CHECK_ALLOCATION(subDevices, "Failed to allocate memory(subDevices)");
status = pfn_clCreateSubDevicesEXT(rootDevices[deviceId],
partitionPrty,
numSubDevices,
subDevices,
NULL);
CHECK_OPENCL_ERROR(status, "clCreateSubDevicesEXT failed.");
// Create context for sub-devices
subContext = clCreateContext(cps,
numSubDevices,
subDevices,
NULL,
NULL,
&status);
CHECK_OPENCL_ERROR(status, "clCreateContext failed.");
return SDK_SUCCESS;
}
int
DeviceFission::genBinaryImage()
{
streamsdk::bifData binaryData;
binaryData.kernelName = std::string("DeviceFission11Ext_Kernels.cl");
binaryData.flagsStr = std::string("");
if(isComplierFlagsSpecified())
binaryData.flagsFileName = std::string(flags.c_str());
binaryData.binaryName = std::string(dumpBinary.c_str());
int status = sampleCommon->generateBinaryImage(binaryData);
return status;
}
int
DeviceFission::setupCLRuntime()
{
cl_int status = CL_SUCCESS;
// Create command queue
rCmdQueue = clCreateCommandQueue(rContext,
rootDevices[deviceId],
0,
&status);
CHECK_OPENCL_ERROR(status, "clCreateCommandQueue failed.");
// Create and initialize memory objects
rInBuf = clCreateBuffer(rContext,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
length * sizeof(cl_float),
input,
&status);
CHECK_OPENCL_ERROR(status, "clCreateBuffer failed. (rInBuf)");
// Create memory objects for root device output
rOutBuf = clCreateBuffer(rContext,
CL_MEM_WRITE_ONLY |
CL_MEM_USE_HOST_PTR,
length * sizeof(cl_float),
rOutput,
&status);
CHECK_OPENCL_ERROR(status, "clCreateBuffer failed. (rOutBuf)");
// create a CL program using the kernel source
streamsdk::buildProgramData buildData;
buildData.kernelName = std::string("DeviceFission11Ext_Kernels.cl");
buildData.devices = rootDevices;
buildData.deviceId = deviceId;
buildData.flagsStr = std::string("");
if(isLoadBinaryEnabled())
buildData.binaryName = std::string(loadBinary.c_str());
if(isComplierFlagsSpecified())
buildData.flagsFileName = std::string(flags.c_str());
status = sampleCommon->buildOpenCLProgram(program, rContext, buildData);
CHECK_ERROR(status, SDK_SUCCESS, "sampleCommon::buildOpenCLProgram() failed");
// Get a kernel object handle for a kernel with the given name
rKernel = clCreateKernel(program,
"copy",
&status);
CHECK_OPENCL_ERROR(status, "clCreateKernel failed.");
// Check whether specified groupSize is plausible on current kernel
status = clGetKernelWorkGroupInfo(rKernel,
rootDevices[deviceId],
CL_KERNEL_WORK_GROUP_SIZE,
sizeof(size_t),
&kernelWorkGroupSize,
0);
CHECK_OPENCL_ERROR(status, "clGetKernelWorkGroupInfo failed.");
// If groupSize exceeds the maximum supported on kernel, fall back
if(groupSize > kernelWorkGroupSize)
{
if(!quiet)
{
std::cout << "Out of Resources!" << std::endl;
std::cout << "Group Size specified : " << groupSize << std::endl;
std::cout << "Max Group Size supported on the kernel : "
<< kernelWorkGroupSize << std::endl;
std::cout << "Falling back to " << kernelWorkGroupSize << std::endl;
}
groupSize = kernelWorkGroupSize;
}
//Setup sub-devices runtime resoureces
subCmdQueue = (cl_command_queue*)malloc(numSubDevices * sizeof(cl_command_queue));
CHECK_ALLOCATION(subCmdQueue,"Failed to allocate memory(subCmdQueue)");
for(cl_uint i = 0; i < numSubDevices; i++)
{
// Create command queue
subCmdQueue[i] = clCreateCommandQueue(subContext,
subDevices[i],
0,
&status);
CHECK_OPENCL_ERROR(status, "clCreateCommandQueue failed.");
}
// Create and initialize memory objects
subInBuf = (cl_mem*)malloc(numSubDevices * sizeof(cl_mem));
CHECK_OPENCL_ERROR(status, "Failed to allocate memory(subInBuf)");
for(cl_uint i = 0; i < numSubDevices; i++)
{
subInBuf[i] = clCreateBuffer(subContext,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
(length / numSubDevices) * sizeof(cl_float),
&input[(length / numSubDevices) * i],
&status);
CHECK_OPENCL_ERROR(status, "clCreateBuffer failed. (rInBuf)");
}
// Create memory objects for root device output
subOutBuf = clCreateBuffer(subContext,
CL_MEM_WRITE_ONLY,
(length / numSubDevices) * sizeof(cl_float) ,
NULL,
&status);
CHECK_OPENCL_ERROR(status, "clCreateBuffer failed. (rOutBuf)");
streamsdk::SDKFile kernelFile;
std::string kernelPath = sampleCommon->getPath();
char * source = NULL;
size_t sourceSize[] = {0};
char * binary = NULL;
size_t binarySize = 0;
if(isLoadBinaryEnabled())
{
kernelPath += loadBinary;
if(kernelFile.readBinaryFromFile(kernelPath.c_str()))
{
std::cout << "Failed to load kernel file : " << kernelPath << std::endl;
return SDK_FAILURE;
}
// Get binaries and binary sizes for all devices
char** subBinaries = (char**)malloc(numSubDevices * sizeof(char*));
if(subBinaries == NULL)
{
sampleCommon->error("Failed to allocate memory(subBinaries)");
return SDK_FAILURE;
}
size_t* subBinariesSize = (size_t*)malloc(numSubDevices * sizeof(size_t*));
if(subBinariesSize == NULL)
{
sampleCommon->error("Failed to allocate memory(subBinariesSize)");
return SDK_FAILURE;
}
for(cl_uint i = 0; i < numSubDevices; ++i)
{
subBinaries[i] = (char*)kernelFile.source().c_str();
subBinariesSize[i] = kernelFile.source().size();
}
subProgram = clCreateProgramWithBinary(subContext,
numSubDevices,
subDevices,
(const size_t *)subBinariesSize,
(const unsigned char**)subBinaries,
NULL,
&status);
if(sampleCommon->checkVal(status,
CL_SUCCESS,
"clCreateProgramWithBinary failed."))
{
return SDK_FAILURE;
}
free(subBinaries);
free(subBinariesSize);
subBinariesSize = NULL;
subBinaries = NULL;
}
else
{
kernelPath.append("DeviceFission11Ext_Kernels.cl");
if(!kernelFile.open(kernelPath.c_str()))//bool
{
std::cout << "Failed to load kernel file: " << kernelPath << std::endl;
return SDK_FAILURE;
}
const char * source = kernelFile.source().c_str();
size_t sourceSize[] = {strlen(source)};
// create a CL program using the kernel source
subProgram = clCreateProgramWithSource(subContext,
1,
(const char**)&source,
sourceSize,
&status);
CHECK_OPENCL_ERROR(status, "clCreateProgramWithSource failed.");
}
// create a cl program executable for all the devices specified
status = clBuildProgram(subProgram,
numSubDevices,
subDevices,
NULL,
NULL,
NULL);
if(status != CL_SUCCESS)
{
if(status == CL_BUILD_PROGRAM_FAILURE)
{
cl_int logStatus;
char * buildLog = NULL;
size_t buildLogSize = 0;
logStatus = clGetProgramBuildInfo(subProgram,
subDevices[0],
CL_PROGRAM_BUILD_LOG,
buildLogSize,
buildLog,
&buildLogSize);
if(!sampleCommon->checkVal(logStatus,
CL_SUCCESS,
"clGetProgramBuildInfo failed."))
return SDK_FAILURE;
buildLog = (char*)malloc(buildLogSize);
if(NULL == buildLog)
{
sampleCommon->error("Failed to allocate host memory.(buildLog)");
return SDK_FAILURE;
}
memset(buildLog, 0, buildLogSize);
logStatus = clGetProgramBuildInfo(subProgram,
subDevices[0],
CL_PROGRAM_BUILD_LOG,
buildLogSize,
buildLog,
NULL);
if(!sampleCommon->checkVal(logStatus,
CL_SUCCESS,
"clGetProgramBuildInfo failed."))
{
free(buildLog);
return SDK_FAILURE;
}
std::cout << " \n\t\t\tBUILD LOG(SUB-DEVICES)\n";
std::cout << " ************************************************\n";
std::cout << buildLog << std::endl;
std::cout << " ************************************************\n";
free(buildLog);
}
if(!sampleCommon->checkVal(status,
CL_SUCCESS,
"clBuildProgram failed."))
return SDK_FAILURE;
}
// Get a kernel object handle for a kernel with the given name
subKernel = clCreateKernel(subProgram,
"copy",
&status);
CHECK_OPENCL_ERROR(status, "clCreateKernel failed.");
return SDK_SUCCESS;
}
int
DeviceFission::runCLRootDeviceKerenls()
{
cl_int status;
cl_event events[1];
// Set appropriate arguments to the kernel
// Set input
status = clSetKernelArg(rKernel, 0, sizeof(cl_mem),(void*)&rInBuf);
CHECK_OPENCL_ERROR(status, "clSetKernelArg failed. (rInBuf)");
// Set rOutBuf as second argument
status = clSetKernelArg(rKernel, 1, sizeof(cl_mem), (void*)&rOutBuf);
CHECK_OPENCL_ERROR(status, "clSetKernelArg failed. (rOutBuf)");
// Set global and local work items
size_t globalThreads[] = {length};
size_t localThreads[] = {groupSize};
// Enqueue kernel
status = clEnqueueNDRangeKernel(rCmdQueue,
rKernel,
1,
NULL,
globalThreads,
localThreads,
0,
NULL,
NULL);
CHECK_OPENCL_ERROR(status, "clEnqueueNDRangeKernel failed.");
status = clFinish(rCmdQueue);
CHECK_OPENCL_ERROR(status, "clFinish failed.");
/* Enqueue readBuffer*/
status = clEnqueueReadBuffer(rCmdQueue,
rOutBuf,
CL_TRUE,
0,
length * sizeof(cl_float),
rOutput,
0,
NULL,
&events[0]);
CHECK_OPENCL_ERROR(status, "clEnqueueReadBuffer failed.");
status = sampleCommon->waitForEventAndRelease(&events[0]);
CHECK_ERROR(status, SDK_SUCCESS, "WaitForEventAndRelease(events[0]) Failed");
return SDK_SUCCESS;
}
int
DeviceFission::runCLSubDeviceKerenls()
{
cl_int status;
cl_event events[1];
// Set appropriate arguments to the kernel
// Set subOutBuf as second argument
status = clSetKernelArg(subKernel, 1, sizeof(cl_mem), (void*)&subOutBuf);
CHECK_OPENCL_ERROR(status, "clSetKernelArg failed. (subOutBuf)");
// Set global and local work items
size_t globalThreads[] = {length / numSubDevices};
size_t localThreads[] = {groupSize};
for(cl_uint i = 0; i < numSubDevices; ++i)
{
// Set input
status = clSetKernelArg(subKernel, 0, sizeof(cl_mem),(void*)&subInBuf[i]);
CHECK_OPENCL_ERROR(status, "clSetKernelArg failed. (subInBuf)");
// Enqueue kernel
status = clEnqueueNDRangeKernel(subCmdQueue[i],
subKernel,
1,
NULL,
globalThreads,
localThreads,
0,
NULL,
NULL);
CHECK_OPENCL_ERROR(status, "clEnqueueNDRangeKernel failed.");
status = clFinish(subCmdQueue[i]);
CHECK_OPENCL_ERROR(status, "clFinish failed.");
/* Enqueue readBuffer*/
status = clEnqueueReadBuffer(subCmdQueue[i],
subOutBuf,
CL_TRUE,
0,
(length / numSubDevices) * sizeof(cl_float),
&subOutput[(length / numSubDevices) * i],
0,
NULL,
&events[0]);
CHECK_OPENCL_ERROR(status, "clEnqueueReadBuffer failed.");
status = sampleCommon->waitForEventAndRelease(&events[0]);
CHECK_ERROR(status, SDK_SUCCESS, "WaitForEventAndRelease(events[0]) Failed");
}
return SDK_SUCCESS;
}
int
DeviceFission::runCLKernels()
{
// Run kernel on root device
if(runCLRootDeviceKerenls() != CL_SUCCESS)
return SDK_FAILURE;
// Run kernsl on all sub-devices
if(runCLSubDeviceKerenls() != CL_SUCCESS)
return SDK_FAILURE;
return SDK_SUCCESS;
}
int DeviceFission::initialize()
{
// Call base class Initialize to get default configuration
if(this->SDKSample::initialize())
return SDK_FAILURE;
// Now add customized options
streamsdk::Option* array_length = new streamsdk::Option;
CHECK_ALLOCATION(array_length, "Memory allocation error.\n");
array_length->_sVersion = "x";
array_length->_lVersion = "length";
array_length->_description = "Length of the Input array";
array_length->_type = streamsdk::CA_ARG_INT;
array_length->_value = &length;
sampleArgs->AddOption(array_length);
delete array_length;
return SDK_SUCCESS;
}
int
DeviceFission::setup()
{
cl_int retValue = setupCLPlatform();
if(retValue != SDK_SUCCESS)
return (retValue == SDK_EXPECTED_FAILURE)? SDK_EXPECTED_FAILURE:SDK_FAILURE;
if(setupDeviceFission() != SDK_SUCCESS)
return SDK_FAILURE;
if(setupCLRuntime() != SDK_SUCCESS)
return SDK_FAILURE;
return SDK_SUCCESS;
}
int DeviceFission::run()
{
if(!reqdExtSupport)
return SDK_SUCCESS;
int timer = sampleCommon->createTimer();
sampleCommon->resetTimer(timer);
sampleCommon->startTimer(timer);
// Execute kernel on device
if(runCLKernels() != SDK_SUCCESS)
return SDK_FAILURE;
sampleCommon->stopTimer(timer);
// Compute average kernel time
kernelTimeGlobal = (double)(sampleCommon->readTimer(timer));
if(!quiet)
sampleCommon->printArray<cl_float>("Output", rOutput, VALUES_PRINTED, 1);
sampleCommon->resetTimer(timer);
sampleCommon->startTimer(timer);
return SDK_SUCCESS;
}
int DeviceFission::verifyResults()
{
if(verify)
{
bool rootDeviceRlt = sampleCommon->compare(input, rOutput, length);
bool subDevicesRlt =sampleCommon->compare(input, subOutput, length);
if(rootDeviceRlt && subDevicesRlt)
{
std::cout << "Passed!\n" << std::endl;
return SDK_SUCCESS;
}
else
{
std::cout << "Failed\n" << std::endl;
return SDK_FAILURE;
}
}
return SDK_SUCCESS;
}
void DeviceFission::printStats()
{
if(!reqdExtSupport)
return;
std::string strArray[2] =
{
"Input length",
"RunTime(sec)"
};
std::string stats[2];
stats[0] = sampleCommon->toString(length, std::dec);
stats[1] = sampleCommon->toString(kernelTimeGlobal, std::dec);
this->SDKSample::printStats(strArray, stats, 2);
}
int
DeviceFission::cleanup()
{
// Releases all OpenCL resources of root device
cl_int status;
status = clReleaseKernel(rKernel);
CHECK_OPENCL_ERROR(status, "clReleaseKernel failed.(rKernel)");
status = clReleaseProgram(program);
CHECK_OPENCL_ERROR(status, "clReleaseProgram failed.(program)");
status = clReleaseMemObject(rInBuf);
CHECK_OPENCL_ERROR(status, "clReleaseMemObject failed. (rInBuf)");
status = clReleaseMemObject(rOutBuf);
CHECK_OPENCL_ERROR(status, "clReleaseMemObject failed.(rOutBuf)");
status = clReleaseCommandQueue(rCmdQueue);
CHECK_OPENCL_ERROR(status, "clReleaseCommandQueue failed.(rCmdQueue)");
status = clReleaseContext(rContext);
CHECK_OPENCL_ERROR(status, "clReleaseContext failed.");
// Release all OpenCL resources for sub-devices
status = clReleaseKernel(subKernel);
CHECK_OPENCL_ERROR(status, "clReleaseKernel failed.(subKernel)");
status = clReleaseProgram(subProgram);
CHECK_OPENCL_ERROR(status, "clReleaseProgram failed. (subProgram)");
status = clReleaseMemObject(subOutBuf);
CHECK_OPENCL_ERROR(status, "clReleaseMemObject failed. (subOutBuf)");
for(cl_uint i = 0; i < numSubDevices; ++i)
{
status = clReleaseMemObject(subInBuf[i]);
CHECK_OPENCL_ERROR(status, "clReleaseMemObject failed.");
status = clReleaseCommandQueue(subCmdQueue[i]);
CHECK_OPENCL_ERROR(status, "clReleaseCommandQueue failed.");
}
status = clReleaseContext(subContext);
CHECK_OPENCL_ERROR(status, "clReleaseContext failed. (subContext)");
status = pfn_clReleaseDeviceEXT(rootDevices[deviceId]);
CHECK_OPENCL_ERROR(status, "clReleaseContext failed.");
return SDK_SUCCESS;
}
DeviceFission::~DeviceFission()
{
/* release program resources (input memory etc.) */
FREE(input);
FREE(rOutput);
FREE(subOutput);
FREE(rootDevices);
FREE(subDevices);
FREE(subCmdQueue);
FREE(subInBuf);
}
int
main(int argc, char * argv[])
{
DeviceFission clDeviceFission("OpenCL DeviceFission");
// Initialize
if(clDeviceFission.initialize() != SDK_SUCCESS)
return SDK_FAILURE;
// ParseCommandLine
if(clDeviceFission.parseCommandLine(argc, argv))
return SDK_FAILURE;
if(clDeviceFission.isDumpBinaryEnabled())
{
if(clDeviceFission.genBinaryImage() != SDK_SUCCESS)
return SDK_FAILURE;
return SDK_SUCCESS;
}
else
{
// Setup
cl_int retValue = clDeviceFission.setup();
if(retValue != SDK_SUCCESS)
return (retValue == SDK_EXPECTED_FAILURE)? SDK_SUCCESS: SDK_FAILURE;
// Run
if(clDeviceFission.run() != SDK_SUCCESS)
return SDK_FAILURE;
// VerifyResults
if(clDeviceFission.verifyResults() != SDK_SUCCESS)
return SDK_FAILURE;
// Cleanup
if(clDeviceFission.cleanup() != SDK_SUCCESS)
return SDK_FAILURE;
clDeviceFission.printStats();
}
return SDK_SUCCESS;
}
| [
"easonwang27@163.com"
] | easonwang27@163.com |
8131602f9a33f3d631f2c54de0d6e05127d23b93 | 1dd3c78eaed4b2646a0efafc49676cba4bf5a0f1 | /04_old/ex04_todo/MiningBarge.cpp | ea0e306d8c96e7210ac9a0b21538e1d83bd0b7b1 | [] | no_license | luckylu91/Cpp-days | 389a831c00dfa1a47a70cace240a56a151445f09 | 53809c495ea140827111f4f447d99a01815eeeb7 | refs/heads/master | 2023-07-24T03:24:43.710742 | 2021-09-09T16:23:25 | 2021-09-09T16:23:25 | 375,081,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | cpp | #include "MiningBarge.hpp"
void MiningBarge::equip(IMiningLaser * laser)
{
if (length < 4)
this->lasers[this->length++] = laser;
}
void MiningBarge::mine(IAsteroid * asteroid) const
{
for (int i = 0; i < this->length; i++)
{
this->lasers[i]->mine(asteroid);
}
}
| [
"zins.lucas@gmail.com"
] | zins.lucas@gmail.com |
8473d524b708c90b0fa132aa0cd47ce630d1f9bb | d3c74128e505bb4c7b1b6ebbcc755818fad98f02 | /project2/.history/main_20200406225331.cpp | 1548f582770d1d6582e4482aa525d0b3d0df559c | [] | no_license | Ricardokevins/NJU_2020Spring_Advanced-Programming | 32870f90694cc9dfae8f09ea9dd45bee9f75dc7a | 8033b6c8f5abfb6f4a922b1deed0f7bf6039e736 | refs/heads/master | 2021-02-10T22:30:13.620954 | 2020-04-24T16:44:30 | 2020-04-24T16:44:30 | 244,425,072 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | cpp | #include <Windows.h>
#include<iostream>
#include<io.h>//使用_setmode(_fileno(stdout), _O_U16TEXT)必须加的头文件
#include<fcntl.h>//使用_setmode(_fileno(stdout), _O_U16TEXT)必须加的头文件
using namespace std;
void modeset(int w,int h) {
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD size = {w, h};
SetConsoleScreenBufferSize(hOut,size);
SMALL_RECT rc = {1,1, w, h};
SetConsoleWindowInfo(hOut ,true ,&rc);
system("cls");
return;
}
int main(){
modeset(100,50);
_setmode(_fileno(stdout), _O_U16TEXT);//让控制台启用Unicode 16
//L告诉编译器使用两个字节的Unicode字符集
for(int i(0);i<40;i++)
{
wcout<< L"\u2550";
}
wcout<<endl;
for(int i(0);i<5;i++)
{
wcout<< L"\u2550";
}
for(int i(0);i<40;i++)
{
wcout<< L"\u2550";
}
wcout<<endl;
for(int i(0);i<5;i++)
{
wcout<< L"\u2550";
}
\u2551
return 0;
}
/*
for(int i(0);i<5;i++)
{
wcout<< L"\u2588";
}
wcout<<endl;
for(int i(0);i<5;i++)
{
wcout<< L"\u2588";
}
wcout<<endl;
*/
| [
"3121416933@qq.com"
] | 3121416933@qq.com |
e8c11419106e91889b858f9adf6ba4e170df5ee5 | 2c148e207664a55a5809a3436cbbd23b447bf7fb | /src/net/third_party/http2/tools/random_util.cc | 322f5c3d34d412de4096202bb3e6aa6f1f5f16be | [
"BSD-3-Clause"
] | permissive | nuzumglobal/Elastos.Trinity.Alpha.Android | 2bae061d281ba764d544990f2e1b2419b8e1e6b2 | 4c6dad6b1f24d43cadb162fb1dbec4798a8c05f3 | refs/heads/master | 2020-05-21T17:30:46.563321 | 2018-09-03T05:16:16 | 2018-09-03T05:16:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,883 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/third_party/http2/tools/random_util.h"
#include <cmath>
#include "base/rand_util.h"
#include "net/third_party/http2/tools/http2_random.h"
namespace net {
namespace test {
namespace {
const char kWebsafe64[] =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_";
// Generate two independent standard normal random variables using the polar
// method.
void GenerateRandomSizeSkewedLowHelper(size_t max, size_t* x, size_t* y) {
double a, b, s;
do {
// Draw uniformly on [-1, 1).
a = 2 * base::RandDouble() - 1.0;
b = 2 * base::RandDouble() - 1.0;
s = a * a + b * b;
} while (s >= 1.0);
double t = std::sqrt(-2.0 * std::log(s) / s);
*x = static_cast<size_t>(a * t * max);
*y = static_cast<size_t>(b * t * max);
}
} // anonymous namespace
Http2String RandomString(RandomBase* rng, int len, Http2StringPiece alphabet) {
Http2String random_string;
random_string.reserve(len);
for (int i = 0; i < len; ++i)
random_string.push_back(alphabet[rng->Uniform(alphabet.size())]);
return random_string;
}
size_t GenerateUniformInRange(size_t lo, size_t hi, RandomBase* rng) {
if (lo + 1 >= hi) {
return lo;
}
return lo + rng->Rand64() % (hi - lo);
}
// Here "word" means something that starts with a lower-case letter, and has
// zero or more additional characters that are numbers or lower-case letters.
Http2String GenerateHttp2HeaderName(size_t len, RandomBase* rng) {
Http2StringPiece alpha_lc = "abcdefghijklmnopqrstuvwxyz";
// If the name is short, just make it one word.
if (len < 8) {
return RandomString(rng, len, alpha_lc);
}
// If the name is longer, ensure it starts with a word, and after that may
// have any character in alphanumdash_lc. 4 is arbitrary, could be as low
// as 1.
Http2StringPiece alphanumdash_lc = "abcdefghijklmnopqrstuvwxyz0123456789-";
return RandomString(rng, 4, alpha_lc) +
RandomString(rng, len - 4, alphanumdash_lc);
}
Http2String GenerateWebSafeString(size_t len, RandomBase* rng) {
return RandomString(rng, len, kWebsafe64);
}
Http2String GenerateWebSafeString(size_t lo, size_t hi, RandomBase* rng) {
return GenerateWebSafeString(GenerateUniformInRange(lo, hi, rng), rng);
}
size_t GenerateRandomSizeSkewedLow(size_t max, RandomBase* rng) {
if (max == 0) {
return 0;
}
// Generate a random number with a Gaussian distribution, centered on zero;
// take the absolute, and then keep in range 0 to max.
for (int i = 0; i < 5; i++) {
size_t x, y;
GenerateRandomSizeSkewedLowHelper(max, &x, &y);
if (x <= max)
return x;
if (y <= max)
return y;
}
return rng->Uniform(max + 1);
}
} // namespace test
} // namespace net
| [
"jiawang.yu@spreadtrum.com"
] | jiawang.yu@spreadtrum.com |
861c27d34c5c839acfb67bde8d24ecb1defc7c29 | 2561a8f5c02fbf9da386dfe3075453f39e2b2dce | /components/segmentation_platform/internal/execution/model_execution_manager_impl.h | c5c5da18c60c2872b2e46dd5183ee54828ec7b61 | [
"BSD-3-Clause"
] | permissive | nyaxs/chromium | 5f64fe9297461c73dd210bd840f51ff1caa10ec1 | a161b3eae46540b6828b8d367d848f30b95aaf2d | refs/heads/master | 2023-05-07T13:53:51.342025 | 2021-06-24T01:10:08 | 2021-06-24T01:10:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,875 | h | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SEGMENTATION_PLATFORM_INTERNAL_EXECUTION_MODEL_EXECUTION_MANAGER_IMPL_H_
#define COMPONENTS_SEGMENTATION_PLATFORM_INTERNAL_EXECUTION_MODEL_EXECUTION_MANAGER_IMPL_H_
#include <map>
#include <memory>
#include <vector>
#include "base/memory/weak_ptr.h"
#include "base/sequenced_task_runner.h"
#include "components/optimization_guide/core/model_executor.h"
#include "components/optimization_guide/proto/models.pb.h"
#include "components/segmentation_platform/internal/database/segment_info_database.h"
#include "components/segmentation_platform/internal/execution/model_execution_manager.h"
#include "components/segmentation_platform/internal/execution/segmentation_model_handler.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace base {
class Clock;
} // namespace base
namespace segmentation_platform {
class FeatureAggregator;
class SignalDatabase;
namespace proto {
class SegmentInfo;
} // namespace proto
// The ModelExecutionManagerImpl is the core implementation of the
// ModelExecutionManager that hooks up the SegmentInfoDatabase (metadata) and
// SignalDatabase (raw signals) databases, and uses a FeatureCalculator for each
// feature to go from metadata and raw signals to create an input tensor to use
// when executing the ML model. It then uses this input tensor to execute the
// model and returns the result through a callback.
// This class is implemented by having a long chain of callbacks and storing all
// necessary state as part of an ExecutionState struct. This simplifies state
// management, particularly in the case of executing multiple models
// simultaneously, or the same model multiple times without waiting for the
// requests to finish.
// The vector of OptimizationTargets need to be passed in at construction time
// so the SegmentationModelHandler instances can be created early.
class ModelExecutionManagerImpl : public ModelExecutionManager {
public:
using ModelHandlerCreator =
base::RepeatingCallback<std::unique_ptr<SegmentationModelHandler>(
optimization_guide::proto::OptimizationTarget)>;
explicit ModelExecutionManagerImpl(
std::vector<OptimizationTarget> segment_ids,
ModelHandlerCreator model_handler_creator,
base::Clock* clock,
SegmentInfoDatabase* segment_database,
SignalDatabase* signal_database,
std::unique_ptr<FeatureAggregator> feature_aggregator);
~ModelExecutionManagerImpl() override;
// Disallow copy/assign.
ModelExecutionManagerImpl(const ModelExecutionManagerImpl&) = delete;
ModelExecutionManagerImpl& operator=(const ModelExecutionManagerImpl&) =
delete;
// ModelExecutionManager overrides.
void ExecuteModel(optimization_guide::proto::OptimizationTarget segment_id,
ModelExecutionCallback callback) override;
private:
struct ExecutionState;
void OnSegmentInfoFetched(std::unique_ptr<ExecutionState> state,
absl::optional<proto::SegmentInfo> segment_info);
void ProcessFeatures(std::unique_ptr<ExecutionState> state);
void RunModelExecutionCallback(ModelExecutionCallback callback,
float result,
ModelExecutionStatus status);
std::map<OptimizationTarget, std::unique_ptr<SegmentationModelHandler>>
model_handlers_;
base::Clock* clock_;
SegmentInfoDatabase* segment_database_;
SignalDatabase* signal_database_;
std::unique_ptr<FeatureAggregator> feature_aggregator_;
base::WeakPtrFactory<ModelExecutionManagerImpl> weak_ptr_factory_{this};
};
} // namespace segmentation_platform
#endif // COMPONENTS_SEGMENTATION_PLATFORM_INTERNAL_EXECUTION_MODEL_EXECUTION_MANAGER_IMPL_H_
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
2e2028340ac332e6ccf554b0b033c8b80c14dab4 | e798f3cd0d6cc6ad191702bbb387afdb0ae9eab0 | /Classes/Shopping/HomeDialog/ShoppingSecretDialog.cpp | 7a507009b10e8a3e55ca528d2789bb87f84ef5ef | [] | no_license | Morgan87/FlameDragonX | 9dbd359c939df08a1f7c7a8a769d9408bf50ca10 | 15ed056572c52df76cfea8990cc1e5f81331c8fc | refs/heads/master | 2021-05-07T04:08:19.692309 | 2016-11-29T22:41:46 | 2016-11-29T22:41:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 556 | cpp | //
// ShoppingSecretDialog.cpp
// FlameDragonX
//
// Created by SuiYi on 11/3/16.
//
//
#include "ShoppingSecretDialog.hpp"
#include "LocalizedStrings.hpp"
void ShoppingSecretDialog::initMessage()
{
std::string message = LocalizedStrings::getInstance()->getMessageString(51);
this->setMessage(message);
}
void ShoppingSecretDialog::updateMessage()
{
std::string message = LocalizedStrings::getInstance()->getMessageString(52);
this->setMessage(message);
}
ShopType ShoppingSecretDialog::getShopType()
{
return ShopType_Secret;
}
| [
"charlie_5899@hotmail.com"
] | charlie_5899@hotmail.com |
20bd910b558f8120d36b1ee4be9715f62f0c62b0 | 43aace892d3641bd9d0863b9b12c498a33edce7e | /Arrays_linkedList_recursion/InsertionSort.cpp | 658dafc1ce530c109e93231ff055d7554075ffe8 | [] | no_license | Paulmburu/cpp- | 164c2a5b993a7cc09f7aa7af40fab9762ae76e08 | c02543bfe90348faa613d8b45b564ba5a6ba5370 | refs/heads/master | 2020-08-30T12:38:36.906638 | 2019-10-29T21:07:41 | 2019-10-29T21:07:41 | 218,382,878 | 0 | 0 | null | 2019-10-29T21:01:28 | 2019-10-29T21:01:28 | null | UTF-8 | C++ | false | false | 505 | cpp | #include <iostream>
void insertionSort(int* A, int n){ // sort an array of n characters
for (int i = 1; i < n; i++)
{
char cur=A[i]; // current character to insert
int j=i-1; // start a previous character
while((j>=0) && (A[j]>cur)){ // while A[j] is out of order
A[j+1]=A[j]; // move A[j] right
j--; // decrement j
}
A[j+1]=cur; // this is the proper place for cur
}
}
int main(){
int A[]={5,3,6,2,4};
int x=5;
insertionSort(A,x);
for(int i:A)
std::cout<<i<<" ";
}
| [
"paulmburu53@gmail.com"
] | paulmburu53@gmail.com |
c3349379467989360b52318a1f10a4c704c8ee47 | e90c4fd02cc8667142f792fda003a59d4a7ca61c | /C++ Operating Systems/old/my code/pcb.h | b48f864c834b91b8fa2bca2cc44cc31dc608119a | [] | no_license | wpegg-dev/College-Work | a8bf1f31fcd8d028ff6d33520d6b555619ec8d71 | 3f6287627486c6c58c5f935cb779a48544c7e29c | refs/heads/master | 2016-09-15T22:39:51.112788 | 2015-06-25T03:26:21 | 2015-06-25T03:26:21 | 35,346,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,512 | h |
#pragma once
#include "pcb_types.h"
const int NUM_PROCESSES = 30;
class pcb
{
public:
pcb(void);
~pcb(void);
bool setInBufSize(const int&, const int&);
bool setOutBufSize(const int&, const int&);
bool setTempBufSize(const int&, const int&);
bool setCodeSize(const int&, const unsigned long&);
bool setCpuId(const int&, const unsigned int&);
bool setPc(const int& pid, const unsigned long&);
bool setPriority(const int&, const int&);
bool setStatus(const int&, const STATUS&);
bool setCodeStartAddress(const int&, const unsigned int&);
bool setInputBufferAddress(const int&, const unsigned int&);
bool setOutputBufferAddress(const int&, const unsigned int&);
bool setTempBufferAddress(const int&, const unsigned int&);
bool setCodeDiskAddress(const int&, const unsigned int&);
bool setDataDiskAddress(const int&, const unsigned int&);
int getCodeSize(const int&);
int getCpuId(const int&);
int getPc(const int&);
int getPriority(const int&);
int getStatus(const int&);
int getInputBufferSize(const int&);
int getOutputBufferSize(const int&);
int getTempBufferSize(const int&);
unsigned int getCodeDiskAddress(const int&);
unsigned int getDataDiskAddress(const int&);
unsigned int getCodeStartRamAddress(const int&);
unsigned int getInputBufferRamAddress(const int&);
unsigned int getOutputBufferRamAddress(const int&);
unsigned int getTempBufferRamAddress(const int&);
PCB getPcbInfo(const int&);
void outputPcbInfo(const int&);
private:
PCB pcb_array[NUM_PROCESSES];
};
| [
"william.pegg.dev@gmail.com"
] | william.pegg.dev@gmail.com |
0d215fff4d20a3c8cc6f61364483ca397b16ebe0 | ddbb15437426ba4fe4ca9a9ce2d210a1ce4b3964 | /data_pi/bcode/lib/descriptor/edgeDetector.h | 0fdd244f7414c858168980252352cd5f3f639df5 | [] | no_license | wingggg/FYP_final | 4fb466b17bed641942854d72d9b70d46262210c1 | ded118ec37b5f8fbe20ba206fee204ff3136f2f0 | refs/heads/master | 2020-04-03T09:53:30.603382 | 2016-06-21T22:23:33 | 2016-06-21T22:23:33 | 61,905,432 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | h | #ifndef _edgeDetector_h_
#define _edgeDetector_h_
#include "../ImageContent/imageContent.h"
#include "../gauss_iir/gauss_iir.h"
using namespace std;
#include<vector>
void cannyEdges(DARY *dx,DARY *dy, DARY *edge, float lower_threshold, float higher_threshold);
void cannyEdges(DARY *img, DARY *edge, float scale, float lower_threshold, float higher_threshold);
void cannyEdges(DARY *dy, DARY *dx, DARY *grad, DARY *edge, float lower_threshold,
float higher_threshold);
void cannyEdges(DARY *img, DARY *edge, float lower_threshold, float higher_threshold);
#endif
| [
"wsn12@ic.ac.uk"
] | wsn12@ic.ac.uk |
80ab853bec84410d479c6e6ce44b4c70ca414b5b | 98895869f814fc5afa968d36167c9df578e4c3e2 | /assignments/assgin3/main.cpp | 7b2e94ad72efb5c72bb9894e63a2f8f32c9658db | [] | no_license | galgol/computer_graphics_course | 061fc1ae33d4a37bcefccb7b2a57eed33d65e235 | 2ecdf1f4eac945779a8b33f53c14dc34cc65c115 | refs/heads/master | 2020-07-08T03:34:03.490717 | 2019-08-21T09:55:59 | 2019-08-21T09:55:59 | 203,552,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,848 | cpp | #include <Windows.h>
#include <iostream>
#include "display.h"
#include "mesh.h"
#include "shader.h"
#include "inputManager.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include "GLFW\glfw3.h"
using namespace glm;
static const int NUM_OF_CUBES = 5;
int picked = -1;
float prevX;
float prevY;
float tmpPrevX;
float tmpPrevY;
static const int DISPLAY_WIDTH = 800;
static const int DISPLAY_HEIGHT = 800;
float transX;
float transY;
mat4 transUpdate = mat4(1);
int transUpdateIDX = -2;
mat4 M = mat4(1);
Display display1(DISPLAY_WIDTH, DISPLAY_HEIGHT, "OpenGL");
Shader shader("./res/shaders/basicShader");
Shader shader1("./res/shaders/test");
vec3 pos = vec3(0, 0, -30);
vec3 forward = glm::vec3(0.0f, 0.0f, 1.0f);
vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
mat4 P = glm::perspective(60.0f, (float)DISPLAY_WIDTH / (float)DISPLAY_HEIGHT, 0.1f, 100.0f)* glm::lookAt(pos, pos + forward, up);
mat4 TR[NUM_OF_CUBES + 1][5];
mat4 MVP = P*M;
bool IK;
int countIK = 0;
Vertex vertices[] =
{
Vertex(glm::vec3(-1, -1, -1), glm::vec2(1, 0), glm::vec3(0, 0, -1),glm::vec3(0, 0, 1)),
Vertex(glm::vec3(-1, 1, -1), glm::vec2(0, 0), glm::vec3(0, 0, -1),glm::vec3(0, 0, 1)),
Vertex(glm::vec3(1, 1, -1), glm::vec2(0, 1), glm::vec3(0, 0, -1),glm::vec3(0, 0, 1)),
Vertex(glm::vec3(1, -1, -1), glm::vec2(1, 1), glm::vec3(0, 0, -1),glm::vec3(0, 0, 1)),
Vertex(glm::vec3(-1, -1, 1), glm::vec2(1, 0), glm::vec3(0, 0, 1),glm::vec3(0, 0, 1)),
Vertex(glm::vec3(-1, 1, 1), glm::vec2(0, 0), glm::vec3(0, 0, 1),glm::vec3(0, 0, 1)),
Vertex(glm::vec3(1, 1, 1), glm::vec2(0, 1), glm::vec3(0, 0, 1),glm::vec3(0, 0, 1)),
Vertex(glm::vec3(1, -1, 1), glm::vec2(1, 1), glm::vec3(0, 0, 1),glm::vec3(0, 0, 1)),
Vertex(glm::vec3(-1, -1, -1), glm::vec2(0, 1), glm::vec3(0, -1, 0),glm::vec3(0, 1, 0)),
Vertex(glm::vec3(-1, -1, 1), glm::vec2(1, 1), glm::vec3(0, -1, 0),glm::vec3(0, 1, 0)),
Vertex(glm::vec3(1, -1, 1), glm::vec2(1, 0), glm::vec3(0, -1, 0),glm::vec3(0, 1, 0)),
Vertex(glm::vec3(1, -1, -1), glm::vec2(0, 0), glm::vec3(0, -1, 0),glm::vec3(0, 1, 0)),
Vertex(glm::vec3(-1, 1, -1), glm::vec2(0, 1), glm::vec3(0, 1, 0),glm::vec3(0, 1, 0)),
Vertex(glm::vec3(-1, 1, 1), glm::vec2(1, 1), glm::vec3(0, 1, 0),glm::vec3(0, 1, 0)),
Vertex(glm::vec3(1, 1, 1), glm::vec2(1, 0), glm::vec3(0, 1, 0),glm::vec3(0, 1, 0)),
Vertex(glm::vec3(1, 1, -1), glm::vec2(0, 0), glm::vec3(0, 1, 0),glm::vec3(0, 1, 0)),
Vertex(glm::vec3(-1, -1, -1), glm::vec2(1, 1), glm::vec3(-1, 0, 0),glm::vec3(1, 0, 0)),
Vertex(glm::vec3(-1, -1, 1), glm::vec2(1, 0), glm::vec3(-1, 0, 0),glm::vec3(1, 0, 0)),
Vertex(glm::vec3(-1, 1, 1), glm::vec2(0, 0), glm::vec3(-1, 0, 0),glm::vec3(1, 0, 0)),
Vertex(glm::vec3(-1, 1, -1), glm::vec2(0, 1), glm::vec3(-1, 0, 0),glm::vec3(1, 0, 0)),
Vertex(glm::vec3(1, -1, -1), glm::vec2(1, 1), glm::vec3(1, 0, 0),glm::vec3(1, 0, 0)),
Vertex(glm::vec3(1, -1, 1), glm::vec2(1, 0), glm::vec3(1, 0, 0),glm::vec3(1, 0, 0)),
Vertex(glm::vec3(1, 1, 1), glm::vec2(0, 0), glm::vec3(1, 0, 0),glm::vec3(1, 0, 0)),
Vertex(glm::vec3(1, 1, -1), glm::vec2(0, 1), glm::vec3(1, 0, 0),glm::vec3(1, 0, 0))
};
unsigned int indices[] = { 0, 1, 2,
0, 2, 3,
6, 5, 4,
7, 6, 4,
10, 9, 8,
11, 10, 8,
12, 13, 14,
12, 14, 15,
16, 17, 18,
16, 18, 19,
22, 21, 20,
23, 22, 20
};
Mesh mesh(vertices, sizeof(vertices) / sizeof(vertices[0]), indices, sizeof(indices) / sizeof(indices[0]));
void updateTRz(int k) {
TR[0][3] = TR[0][0] * TR[0][1] * TR[0][4] * TR[0][2];
for (int i = 1; i < k; i++) {
TR[i][3] = TR[i - 1][3] * TR[i][0] * TR[i][1] * TR[i][4] * TR[i][2];
}
TR[k][0] = glm::translate(mat4(1), vec3(0.0f, 0.0f, -2.05f));
TR[k][2] = glm::translate(mat4(1), vec3(0.0f, 0.0f, 6.15f));
//TR[k][3] = TR[k - 1][3] * TR[k][0] * TR[k][1] * TR[k][2];
for (int i = k ; i < NUM_OF_CUBES; i++) {
TR[i][3] = TR[i - 1][3] * TR[i][0] * TR[i][1] * TR[i][4] * TR[i][2];
}
TR[k][0] = glm::translate(mat4(1), vec3(0.0f, 0.0f, 2.05f));
TR[k][2] = glm::translate(mat4(1), vec3(0.0f, 0.0f, 2.05f));
TR[NUM_OF_CUBES][3] = TR[0][3] * TR[NUM_OF_CUBES][0] * TR[NUM_OF_CUBES][1] * TR[NUM_OF_CUBES][4] * TR[NUM_OF_CUBES][2];
}
void updateTR() {
TR[0][3] = TR[0][0] * TR[0][1] *TR[0][4]* TR[0][2];
for (int i = 1; i < NUM_OF_CUBES; i++) {
TR[i][3] = TR[i - 1][3] * TR[i][0] * TR[i][1] * TR[i][4] * TR[i][2];
}
TR[NUM_OF_CUBES][3] = TR[0][3] * TR[NUM_OF_CUBES][0] * TR[NUM_OF_CUBES][1] * TR[NUM_OF_CUBES][4] * TR[NUM_OF_CUBES][2];
if (transUpdateIDX > 0) {
TR[transUpdateIDX][3] = transUpdate* TR[transUpdateIDX][3];
transUpdate = mat4(1);
transUpdateIDX = -2;
}
}
void updatePicked(float xpos, float ypos) {
unsigned char res[4];
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
glReadPixels(xpos, viewport[3] - ypos, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &res);
GLint id;
glGetIntegerv(GL_CURRENT_PROGRAM, &id);
float depth;
glReadPixels(xpos, viewport[3] - ypos, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
float z = 100.0f + depth*(0.1f - 100.0f);
if (prevX == NULL) {
prevX = xpos;
}
if (prevY == NULL) {
prevY = ypos;
}
float xrel = xpos- prevX;
float yrel = ypos- prevY;
float M_PI = 3.141592654;
transX = 1 * (xrel) / (float)(viewport[2])*0.1f*2.0*tan(60.0f*M_PI / 360.0)*(100.0f / z);
transY = (yrel) / (float)(viewport[3])*0.1f*2.0*tan(60.0f*M_PI / 360.0)*(100.0f / z);
prevX = xpos;
prevY = ypos;
switch (res[0]) {
case(255):picked = 5;
break;
case(128):picked = 1;
break;
case(85):picked = 2;
break;
case(64):picked = 3;
break;
case(51):picked = 4;
break;
case(0):picked = -1;
break;
default:
printf("\n");
}
}
void rotateZ(int i, float angle, float clock) {
if (i == -1) {
TR[0][4] = glm::rotate(mat4(1), angle, vec3(0.0f, 0.0f, clock))*TR[0][4];
updateTR();
}
else if (i == NUM_OF_CUBES||i==1) {
TR[i][4] = glm::rotate(mat4(1), angle, vec3(0.0f, 0.0f, clock))*TR[i][4];
updateTR();
}
else {
TR[i][4] = glm::rotate(mat4(1), angle, vec3(0.0f, 0.0f, clock))*TR[i][4];
updateTRz(i);
}
}
void rotateX(int i, float angle,float clock) {
if (i == -1) {
TR[0][1] = glm::rotate(mat4(1), angle, vec3(clock, 0.0f, 0.0f))*TR[0][1];
}
else {
TR[i][1] = glm::rotate(mat4(1), angle, vec3(clock, 0.0f, 0.0f))*TR[i][1];
}
updateTR();
}
void SolveIK() {
mat4 tmp_0 = TR[NUM_OF_CUBES][3];
mat4 tmpE = TR[NUM_OF_CUBES - 1][3];
vec3 D = vec3(tmp_0[3][0], tmp_0[3][1], tmp_0[3][2]);
vec3 E = vec3(tmpE[3][0], tmpE[3][1], tmpE[3][2] + 2.05f);
vec3 distance = D - E;
float currDistance = glm::length(distance);
if (currDistance > 16) {
printf("cannot reach\n");
IK = false;
}
if (currDistance <= 0.1f) {
printf("end of IK solver\n");
IK = false;
}
for (int i = NUM_OF_CUBES - 1; i > 0 && IK; i--) {
mat4 tmp = TR[i][3];
vec3 R = vec3(tmp[3][0], tmp[3][1], tmp[3][2] - 2.05f);
tmpE = TR[NUM_OF_CUBES - 1][3];
E = vec3(tmpE[3][0], tmpE[3][1], tmpE[3][2] + 2.05f);
vec3 RE = glm::normalize(E - R);
vec3 RD = glm::normalize(D - R);
vec3 crossed = vec3(glm::cross(RE, RD));
float cosA = glm::clamp(dot(RE, RD), -1.0f, 1.0f);
float angle = glm::acos(cosA);
TR[i][1] = glm::rotate(mat4(1), angle, crossed)*TR[i][1];
updateTR();
distance = D - E;
}
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
switch (key)
{
case GLFW_KEY_SPACE:
if (action == GLFW_PRESS) {
if (countIK % 2 == 0)
IK = true;
else
IK = false;
countIK++;
}
break;
case GLFW_KEY_ESCAPE:
if (action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
break;
case GLFW_KEY_UP:
if (action == GLFW_PRESS) {
rotateX(picked,5.0f, 1.0f);
}
break;
case GLFW_KEY_DOWN:
if (action == GLFW_PRESS) {
rotateX(picked, 5.0f, -1.0f);
}
break;
case GLFW_KEY_LEFT:
if (action == GLFW_PRESS) {
rotateZ(picked, 5.0f, -1.0f);
}
break;
case GLFW_KEY_RIGHT:
if (action == GLFW_PRESS) {
rotateZ(picked, 5.0f, 1.0f);
}
break;
default:
break;
}
}
void scroll_callback(GLFWwindow* window,double xpos,
double ypos) {
}
void cursor_position_callback(GLFWwindow* window, double xpos,
double ypos)
{
display1.Clear(1.0f, 1.0f, 1.0f, 1.0f);
vec3 color = vec3(1.0f, 1.0f, 1.0f);
MVP = P*M*TR[NUM_OF_CUBES][3];
shader1.Bind();
shader1.Update(MVP, M, color);
mesh.Draw();
for (int i = 1; i < NUM_OF_CUBES; i++) {
MVP = P*M*TR[i][3]* glm::scale(mat4(1), vec3(1.0f, 1.0f, 2.0f));
color = vec3(1.0f / (i + 1), 1.0f / (i + 2), 1.0f / (i + 3));
shader1.Bind();
shader1.Update(MVP, M, color);
mesh.Draw();
}
float deltaX =abs(xpos - prevX);
float deltaY = abs(ypos - prevY);
tmpPrevX = prevX;
tmpPrevY = prevY;
updatePicked(xpos, ypos);
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_3) ==
GLFW_REPEAT)
{
}
else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) ==
GLFW_PRESS)
{
//updatePicked(xpos, ypos);
if (picked == NUM_OF_CUBES) {
TR[NUM_OF_CUBES][3] = glm::translate(mat4(1), vec3(-transX, -transY/2, 0.0f ))*TR[NUM_OF_CUBES][3];
//updateTR();
}
else {
for (int j = 1; j < NUM_OF_CUBES; j++) {
TR[j][3] = glm::translate(mat4(1), vec3(-transX, -transY/2,0.0f))*TR[j][3];
//transUpdateIDX = j;
//updateTR();
}
}
}
else
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) ==
GLFW_PRESS)
{
if (deltaX > deltaY) {
if (xpos > tmpPrevX) {
rotateZ(picked, 0.5f, 1.0f);
}
else {
rotateZ(picked, 0.5f, -1.0f);
}
}
else {
if (ypos > tmpPrevY) {
rotateX(picked, 0.5f, -1.0f);
}
else {
rotateX(picked, 0.5f, 1.0f);
}
}
}
}
void initialize() {
TR[0][0] = mat4(1);
TR[0][1] = rotate(mat4(1), -90.0f, vec3(1.0f, 0, 0));
TR[0][2] = mat4(1);
TR[0][4] = mat4(1);
TR[1][0] = glm::translate(mat4(1), vec3(0.0f, 0.0f, -2.05f));
TR[1][1] = mat4(1);
TR[1][2] = glm::translate(mat4(1), vec3(0.0f, 0.0f, 2.05f));
TR[1][4] = mat4(1);
TR[NUM_OF_CUBES][0] = glm::translate(mat4(1), vec3(5.0f, 0.0f, 0.0f));
TR[NUM_OF_CUBES][1] = mat4(1);
TR[NUM_OF_CUBES][2] = mat4(1);
TR[NUM_OF_CUBES][4] = mat4(1);
for (int i = 2; i < NUM_OF_CUBES; i++) {
TR[i][0] = glm::translate(mat4(1), vec3(0.0f, 0.0f, 2.05f));
TR[i][1] = mat4(1);
TR[i][2] = glm::translate(mat4(1), vec3(0.0f, 0.0f, 2.05f));
TR[i][4] = mat4(1);
}
}
int main(int argc, char** argv)
{
glfwSetKeyCallback(display1.m_window, key_callback);
glfwSetCursorPosCallback(display1.m_window, cursor_position_callback);
glfwSetScrollCallback(display1.m_window, scroll_callback);
initialize();
updateTR();
while (!glfwWindowShouldClose(display1.m_window))
{
Sleep(3);
display1.Clear(1.0f, 1.0f, 1.0f, 1.0f);
if (IK) {
SolveIK();
}
shader.Bind();
MVP = P*M*TR[NUM_OF_CUBES][3];
shader.Update(MVP, M, vec3(1.0f, 1.0f, 1.0f));
mesh.Draw();
for (int i = 1; i < NUM_OF_CUBES; i++) {
MVP = P*M*TR[i][3]*glm::scale(mat4(1),vec3(1.0f,1.0f,2.0f));
shader.Bind();
shader.Update(MVP, M, vec3(1.0f, 1.0f, 1.0f));
glEnable(GL_COLOR_MATERIAL);
glBegin(GL_LINES);
//X Axis
glVertex3f(-5.0, 0.0, -1.025);
glVertex3f(5.0, 0.0, -1.025);
//Y Axix
glVertex3f(0.0, -5.0, -1.025);
glVertex3f(0.0, 5.0, -1.025);
//Z Axis
glVertex3f(0.0, 0.0, -5.0);
glVertex3f(0.0, 0.0, 5.0);
glEnd();
glDisable(GL_COLOR_MATERIAL);
mesh.Draw();
}
display1.SwapBuffers();
glfwPollEvents();
}
return 0;
}
| [
"galgold@post.bgu.ac.il"
] | galgold@post.bgu.ac.il |
243019f3cc9626e1de6c0d4806da633f0d9077d2 | e17c43db9488f57cb835129fa954aa2edfdea8d5 | /Libraries/IFC/IFC4/include/IfcApplication.h | 0f3cd13ab538e8a87c5875c56a7fbb8b5349e8af | [] | no_license | claudioperez/Rts | 6e5868ab8d05ea194a276b8059730dbe322653a7 | 3609161c34f19f1649b713b09ccef0c8795f8fe7 | refs/heads/master | 2022-11-06T15:57:39.794397 | 2020-06-27T23:00:11 | 2020-06-27T23:00:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,668 | h | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "IfcPPBasicTypes.h"
#include "IfcPPObject.h"
#include "IfcPPGlobal.h"
class IFCPP_EXPORT IfcOrganization;
class IFCPP_EXPORT IfcLabel;
class IFCPP_EXPORT IfcIdentifier;
//ENTITY
class IFCPP_EXPORT IfcApplication : public IfcPPEntity
{
public:
IfcApplication();
IfcApplication( int id );
~IfcApplication();
virtual shared_ptr<IfcPPObject> getDeepCopy( IfcPPCopyOptions& options );
virtual void getStepLine( std::stringstream& stream ) const;
virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
virtual void readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<IfcPPEntity> >& map );
virtual void setInverseCounterparts( shared_ptr<IfcPPEntity> ptr_self );
virtual size_t getNumAttributes() { return 4; }
virtual void getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes );
virtual void getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes );
virtual void unlinkFromInverseCounterparts();
virtual const char* className() const { return "IfcApplication"; }
virtual const std::wstring toString() const;
// IfcApplication -----------------------------------------------------------
// attributes:
shared_ptr<IfcOrganization> m_ApplicationDeveloper;
shared_ptr<IfcLabel> m_Version;
shared_ptr<IfcLabel> m_ApplicationFullName;
shared_ptr<IfcIdentifier> m_ApplicationIdentifier;
};
| [
"steva44@hotmail.com"
] | steva44@hotmail.com |
9fd6c5871b2e5b7071c61ee43a51f70ca8098bd7 | b8e75751ad78a676ab3f59ab5b1b913ddc4dd101 | /src_refactoring/upload_factory/http_src/upload_report.cpp | de6c24c178c18e755ee3542b22311d96f1c852a5 | [] | no_license | dwerdwer/anti | faaf7b3407555e5f8d30092b0616920cb43cf3d1 | 54b4af98b74b35c1dad7116e76d2160f6e15667c | refs/heads/master | 2021-10-20T03:06:25.279123 | 2019-02-25T09:19:05 | 2019-02-25T09:19:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,829 | cpp |
#include <iostream>
#include <map>
#include <stdio.h>
#include <cstring>
#include <sys/select.h>
#include <unistd.h>
#include "zip.h" // needs to be placed after iostream
#include "curl/curl.h"
#include "debug_print.h"
#include "http_uploader.h"
#include "utils/utils_library.h"
/* 5 seconds
* 若多处理过程中有一个挂起的 timeout 比 MULTI_WAIT_MSECS 短 则将使用较短 timeout
*/
#define MULTI_WAIT_MAX 5*1000
typedef struct
{
CURL *curl;
curl_slist *p_head;
struct curl_httppost *p_post;
upload_info_t *p_info;
void *p_param;
char *zip_buf; // zip only
}curlitem_t;
struct upload_handler
{
upload_handler();
~upload_handler();
void enter_lock(void);
void leave_lock(void);
CURLM *curl_m;
bool run_flag;
state_cb_t state_cb;
active_cb_t active_cb;
void *p_active_param;
std::map<int64_t, curlitem_t> curl_cache_map;
private:
pthread_spinlock_t spinlock;
};
/* note: member only */
static void release_item_content(curlitem_t *p_item)
{
if (p_item->curl) {
curl_easy_cleanup(p_item->curl);
p_item->curl = NULL;
}
if (p_item->p_post) {
curl_formfree(p_item->p_post);
p_item->p_post = NULL;
}
if (p_item->p_head) {
curl_slist_free_all(p_item->p_head);
p_item->p_head = NULL;
}
if (p_item->zip_buf) {
delete [] p_item->zip_buf;
p_item->zip_buf = NULL;
}
}
upload_handler::upload_handler()
{
curl_global_init(CURL_GLOBAL_ALL);
this->curl_m = curl_multi_init();
this->run_flag = true;
pthread_spin_init(&this->spinlock, 0);
}
upload_handler::~upload_handler()
{
this->run_flag = false;
pthread_spin_destroy(&this->spinlock);
if (!this->curl_cache_map.empty()) // It makes sense to stop by force
{
std::map<int64_t, curlitem_t>::iterator mit = this->curl_cache_map.begin();
for (; mit != this->curl_cache_map.end(); ++mit)
release_item_content(&(mit->second));
this->curl_cache_map.clear();
}
curl_multi_cleanup(this->curl_m);
curl_global_cleanup();
}
void upload_handler::enter_lock(void)
{
pthread_spin_lock(&this->spinlock);
}
void upload_handler::leave_lock(void)
{
pthread_spin_unlock(&this->spinlock);
}
static curlitem_t prepare_buf_upload(const char *url, const char *buf_name,
const char *buf, uint64_t buf_size, uint32_t timeout)
{
curlitem_t result;
memset(&result, 0, sizeof(curlitem_t));
if (NULL == url || NULL == buf_name || NULL == buf) {
return result;
}
result.curl = curl_easy_init();
if(NULL == result.curl)
return result;
struct curl_httppost *lastptr = NULL;
result.p_head = curl_slist_append(result.p_head, "Expect:");
curl_easy_setopt(result.curl, CURLOPT_HTTPHEADER, result.p_head);
curl_formadd(&result.p_post, &lastptr, CURLFORM_COPYNAME, "file",
CURLFORM_BUFFER, buf_name, CURLFORM_BUFFERPTR, buf,
// !!! for compatible must convert to long
CURLFORM_BUFFERLENGTH, (long)buf_size, CURLFORM_END);
curl_formadd(&result.p_post, &lastptr, CURLFORM_COPYNAME, "submit",
CURLFORM_COPYCONTENTS, "Submit", CURLFORM_END);
curl_easy_setopt(result.curl, CURLOPT_URL, url);
curl_easy_setopt(result.curl, CURLOPT_TIMEOUT, timeout);
curl_easy_setopt(result.curl, CURLOPT_HTTPPOST, result.p_post);
return result;
}
static int zip_to_buf(const char *p_buf, const int buf_size,
const char *file_name, char *zip_buf, int *p_zip_size)
{
int result = -1;
if ( NULL == zip_buf || NULL == p_buf) {
return result;
}
// TODO:replace this buf
char *target_buf = new char[*p_zip_size]();
HZIP current_zip = CreateZip(target_buf, (unsigned int)*p_zip_size, NULL);
if (NULL == current_zip) {
delete [] target_buf;
return result;
}
if (ZipAdd(current_zip, file_name, (void*)p_buf, buf_size) == ZR_OK)
{
char *p_index = NULL;
unsigned long mem_len = 0;
if (ZipGetMemory(current_zip, (void**)&p_index, &mem_len) == ZR_OK)
{
if ((unsigned long)*p_zip_size >= mem_len)
memcpy(zip_buf, p_index, mem_len);
*p_zip_size = mem_len;
result = 0;
}
}
delete [] target_buf;
target_buf = NULL;
CloseZip(current_zip);
return result;
}
static curlitem_t prepare_zip_upload(const char *url, const char *file_name,
const char *zip_name, const char *p_buf, uint64_t buf_size, uint32_t timeout)
{
curlitem_t result;
memset(&result, 0, sizeof(curlitem_t));
if (NULL == url || NULL == file_name || NULL == zip_name || NULL == p_buf) {
return result;
}
int zip_size = buf_size + 1024;
char *zip_buf = new char[zip_size];
if (NULL != zip_buf)
{
if (0 == zip_to_buf(p_buf, buf_size, file_name, zip_buf, &zip_size)) {
result = prepare_buf_upload(url, zip_name, zip_buf, zip_size, timeout);
}
if (NULL == result.curl) {
delete [] zip_buf;
zip_buf = NULL;
} else {
result.zip_buf = zip_buf;
}
}
return result;
}
static curlitem_t prepare_file_upload(const char *url, const char *file_path, uint32_t timeout)
{
curlitem_t result;
memset(&result, 0, sizeof(curlitem_t));
if (NULL == url || NULL == file_path){
return result;
}
result.curl = curl_easy_init();
if (NULL == result.curl) {
return result;
}
struct curl_httppost *lastptr = NULL;
result.p_head = curl_slist_append(result.p_head, "Expect:");
curl_formadd(&result.p_post, &lastptr, CURLFORM_COPYNAME,
"file", CURLFORM_FILE, file_path, CURLFORM_END);
curl_formadd(&result.p_post, &lastptr, CURLFORM_COPYNAME,
"submit", CURLFORM_COPYCONTENTS, "Submit", CURLFORM_END);
curl_easy_setopt(result.curl, CURLOPT_URL, url);
curl_easy_setopt(result.curl, CURLOPT_HTTPHEADER, result.p_head);
curl_easy_setopt(result.curl, CURLOPT_HTTPPOST, result.p_post);
curl_easy_setopt(result.curl, CURLOPT_TIMEOUT, timeout);
return result;
}
static curlitem_t prepare_log_upload(const char *url, const char *p_buf, uint64_t buf_size, uint32_t timeout)
{
curlitem_t result;
memset(&result, 0, sizeof(curlitem_t));
if (NULL == url || NULL == p_buf) {
return result;
}
result.curl = curl_easy_init();
if (NULL == result.curl)
return result;
result.p_head = curl_slist_append(result.p_head, "content-type: text/plain");
curl_easy_setopt(result.curl, CURLOPT_URL, url);
curl_easy_setopt(result.curl, CURLOPT_HTTPHEADER, result.p_head);
curl_easy_setopt(result.curl, CURLOPT_POSTFIELDS, p_buf);
curl_easy_setopt(result.curl, CURLOPT_POSTFIELDSIZE, buf_size);
curl_easy_setopt(result.curl, CURLOPT_TIMEOUT, timeout);
return result;
}
LIB_PUBLIC upload_handler_t *init_upload_handler()
{
upload_handler_t *p_upload = new upload_handler_t;
return p_upload;
}
LIB_PUBLIC void priv_upload_cb(upload_handler_t *p_upload, state_cb_t state_cb,
active_cb_t active_cb, void *p_active_param)
{
if (NULL == p_upload)
return;
p_upload->state_cb = state_cb;
p_upload->active_cb = active_cb;
p_upload->p_active_param = p_active_param;
}
static void multi_read_return(upload_handler_t *p_upload)
{
/* return part */
std::map<int64_t, curlitem_t>::iterator mit;
curlitem_t current_item; // current curl item
int msgs_left = 0;
int http_code = 0;
CURLMsg *multi_msg = NULL;
//bool flag = false;
while((multi_msg = curl_multi_info_read(p_upload->curl_m, &msgs_left)))
{
if (CURLMSG_DONE == multi_msg->msg)
{
http_code = 0;
memset(¤t_item, 0, sizeof(curlitem_t));
p_upload->enter_lock();
mit = p_upload->curl_cache_map.find((int64_t)multi_msg->easy_handle);
if (mit != p_upload->curl_cache_map.end()) {
memcpy(¤t_item, &(mit->second), sizeof(curlitem_t));
p_upload->curl_cache_map.erase(mit);
}
curl_multi_remove_handle(p_upload->curl_m, multi_msg->easy_handle);
p_upload->leave_lock();
curl_easy_getinfo(multi_msg->easy_handle, CURLINFO_RESPONSE_CODE, &http_code);
debug_print("CURL RETURN CODE: %d HTTP CODE: %d\n", multi_msg->data.result, http_code);
if (CURLE_OK == multi_msg->data.result && http_code < 400)
{
p_upload->state_cb(true, current_item.p_info, current_item.p_param);
} else {
#ifdef DEBUG
debug_print("FOR DEBUG\n");
p_upload->state_cb(true, current_item.p_info, current_item.p_param);
#else
p_upload->state_cb(false, current_item.p_info, current_item.p_param);
#endif
}
if (current_item.curl)
release_item_content(&(current_item));
}
}
}
LIB_PUBLIC void priv_run_upload(upload_handler_t *p_upload)
{
if (NULL == p_upload)
return;
int running_number = 0; // current runing number
int wait_fd = 0;
upload_info_t *p_active_info = NULL;
void *p_cb_param = NULL;
while(p_upload->run_flag)
{
do {
wait_fd = 0;
if (CURLM_OK != curl_multi_wait(p_upload->curl_m, NULL, 0,
MULTI_WAIT_MAX, &wait_fd)) {
break;
}
curl_multi_perform(p_upload->curl_m, &running_number);
multi_read_return(p_upload);
} while(running_number);
running_number = 0;
/* active access to external cached data */
if (NULL != p_upload->active_cb) {
p_cb_param = NULL;
p_active_info = NULL;
p_upload->active_cb(p_upload->p_active_param, &p_active_info, &p_cb_param);
priv_common_upload(p_upload, p_active_info, p_cb_param);
}
usleep(500000); // 0.5s
//debug_print("- - - BIG UPLOAD LOOP RUN - - -\n");
}
}
LIB_PUBLIC void priv_stop_upload(upload_handler_t *p_upload)
{
if (NULL == p_upload)
return;
p_upload->run_flag = false;
}
LIB_PUBLIC int priv_common_upload(upload_handler_t *p_upload,
upload_info_t *p_info, void *p_param)
{
int result = -1;
if (NULL == p_upload || NULL == p_info || NULL == p_upload->state_cb) {
return result;
}
curlitem_t item;
memset(&item, 0, sizeof(curlitem_t));
//debug_print("TARGET URL: %s\n", p_info->url);
switch (p_info->type)
{
case UPLOAD_TYPE_BUF:
if (p_info->iszip) {
item = prepare_zip_upload(p_info->url.c_str(), p_info->name.c_str(), p_info->zip.c_str(),
p_info->buf, p_info->buf_size, p_info->timeout);
} else if (!p_info->name.empty()) {
item = prepare_buf_upload(p_info->url.c_str(), p_info->name.c_str(),
p_info->buf, p_info->buf_size, p_info->timeout);
} else {
item = prepare_log_upload(p_info->url.c_str(), p_info->buf, p_info->buf_size, p_info->timeout);
}
break;
case UPLOAD_TYPE_FILE:
item = prepare_file_upload(p_info->url.c_str(), p_info->name.c_str(), p_info->timeout);
break;
default:
break;
}
if (item.curl != NULL)
{
item.p_info = p_info;
item.p_param = p_param;
p_upload->enter_lock();
// remove after the send
if ( 0 == curl_multi_add_handle(p_upload->curl_m, item.curl))
{
p_upload->curl_cache_map.insert(std::pair<int64_t, curlitem_t>((int64_t)item.curl, item));
result = 0;
}
p_upload->leave_lock();
}
return result;
}
LIB_PUBLIC void release_upload_handler(upload_handler_t *p_upload)
{
if (p_upload) {
delete p_upload;
}
}
| [
"707676926@qq.com"
] | 707676926@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.