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 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
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 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
745565c3d29638134dbcfd7de519c316583338ae | d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3 | /Modules/ThirdParty/VNL/src/vxl/core/vnl/vnl_least_squares_cost_function.cxx | a2fbb4bed7daf6b91ad3306bdfcd4ba05f8095c6 | [
"SMLNJ",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-mit-old-style",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"NTP",
"IJG",
"GPL-1.0-or-later",
"libtiff",
"BSD-4.3TAHOE",
"... | permissive | nalinimsingh/ITK_4D | 18e8929672df64df58a6446f047e6ec04d3c2616 | 95a2eacaeaffe572889832ef0894239f89e3f303 | refs/heads/master | 2020-03-17T18:58:50.953317 | 2018-10-01T20:46:43 | 2018-10-01T21:21:01 | 133,841,430 | 0 | 0 | Apache-2.0 | 2018-05-17T16:34:54 | 2018-05-17T16:34:53 | null | UTF-8 | C++ | false | false | 1,366 | cxx | // This is core/vnl/vnl_least_squares_cost_function.cxx
#ifdef VCL_NEEDS_PRAGMA_INTERFACE
#pragma implementation
#endif
//
// vnl_least_squares_cost_function
// Author: Andrew W. Fitzgibbon, Oxford RRG
// Created: 20 Aug 99
//
//-----------------------------------------------------------------------------
#include "vnl_least_squares_cost_function.h"
vnl_least_squares_cost_function::vnl_least_squares_cost_function(vnl_least_squares_function* func):
vnl_cost_function(func->get_number_of_unknowns()),
storage_(func->get_number_of_residuals()),
jacobian_(func->get_number_of_residuals(), func->get_number_of_unknowns()),
f_(func)
{
}
double vnl_least_squares_cost_function::f(const vnl_vector<double>& x)
{
f_->f(x, storage_);
return storage_.squared_magnitude();
}
void vnl_least_squares_cost_function::gradf(const vnl_vector<double>& x, vnl_vector<double>& gradient)
{
// residuals = a, b, c, ...
// params = x, y, z, ...
// f = a^2 + b^2 + c^2 + ...
// df/dx = 2a*da/dx + 2b*db/dx + ...
if (f_->has_gradient()) {
f_->f(x,storage_);
f_->gradf(x, jacobian_);
for (unsigned int c=0; c<jacobian_.columns(); ++c) {
gradient[c] = 0.0;
for (unsigned int r=0; r<jacobian_.rows(); ++r)
gradient[c] += storage_[r] * jacobian_(r,c);
gradient[c] *= 2;
}
}
}
| [
"ruizhi@csail.mit.edu"
] | ruizhi@csail.mit.edu |
1663905909db48ae99f29263257576795ab278a1 | f2c3250674d484b91dd9385d7fac50017b034e4b | /others/2017icpc-shenyang/K.cpp | 5508d78620265cb61474801e1954724ee7296ed2 | [] | no_license | DQSSSSS/Algorithm-Competition-Code | a01d4e8b3a9b9da02a400eb5bb4e063eaade33c9 | 574a0806fadf1433fcb4fac4489a237c58daab3c | refs/heads/master | 2023-01-06T06:17:12.295671 | 2020-11-11T22:44:41 | 2020-11-11T22:44:41 | 309,434,336 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 821 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef long double LD;
typedef pair<LL,LL> pii;
const int SZ = 1048600;
const int INF = 1e9 + 10;
const int mod = 1e9 + 7;
const LD eps = 1e-8;
LL read() {
LL n = 0;
char a = getchar();
bool flag = 0;
while(a > '9' || a < '0') { if(a == '-') flag = 1; a = getchar(); }
while(a <= '9' && a >= '0') { n = n * 10 + a - '0',a = getchar(); }
if(flag) n = -n;
return n;
}
int a[23333];
int main() {
int T = read();
while(T --) {
int n = read();
int ans = 0;
for(int i = 1;i <= n;i ++) {
a[i] = read();
if(i > 1) ans += a[i] - a[i - 1] - 1;
}
int x = a[2] - a[1] - 1;
int y = a[n] - a[n - 1] - 1;
ans -= min(x,y);
printf("%d\n",ans);
}
return 0;
}
| [
"1053181679@qq.com"
] | 1053181679@qq.com |
47476199d1c368868d71baa795f8e99951140d96 | 73cfd700522885a3fec41127e1f87e1b78acd4d3 | /_Include/boost/flyweight/intermodule_holder.hpp | ca15f26135fabbbdc4bd078b7973ef7399ac4834 | [] | no_license | pu2oqa/muServerDeps | 88e8e92fa2053960671f9f57f4c85e062c188319 | 92fcbe082556e11587887ab9d2abc93ec40c41e4 | refs/heads/master | 2023-03-15T12:37:13.995934 | 2019-02-04T10:07:14 | 2019-02-04T10:07:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,679 | hpp | ////////////////////////////////////////////////////////////////////////////////
// intermodule_holder.hpp
/* Copyright 2006-2011 Joaquin M Lopez Munoz.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org/libs/flyweight for library home page.
*/
#ifndef BOOST_FLYWEIGHT_INTERMODULE_HOLDER_HPP
#define BOOST_FLYWEIGHT_INTERMODULE_HOLDER_HPP
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */
#include <boost/flyweight/holder_tag.hpp>
#include <boost/flyweight/intermodule_holder_fwd.hpp>
#include <boost/interprocess/detail/intermodule_singleton.hpp>
#include <boost/mpl/aux_/lambda_support.hpp>
/* intermodule_holder_class guarantees a unique instance across all dynamic
* modules of a program.
*/
namespace boost{
namespace flyweights{
template<typename C>
struct intermodule_holder_class:
interprocess::ipcdetail::intermodule_singleton<C,true>,
holder_marker
{
typedef intermodule_holder_class type;
BOOST_MPL_AUX_LAMBDA_SUPPORT(1,intermodule_holder_class,(C))
};
/* intermodule_holder_class specifier */
struct intermodule_holder:holder_marker
{
template<typename C>
struct apply
{
typedef intermodule_holder_class<C> type;
};
};
} /* namespace flyweights */
} /* namespace boost */
#endif
/////////////////////////////////////////////////
// vnDev.Games - Trong.LIVE - DAO VAN TRONG //
////////////////////////////////////////////////////////////////////////////////
| [
"langley.joshua@gmail.com"
] | langley.joshua@gmail.com |
e4cf219043e1fbdc906f38abef0e00f6ec0dcca1 | 6ea6691636a1a5072f12efe0aad9d778d32f126c | /OGLplus_build/include/oglplus/ext/NV_path_rendering/stroke_cover_mode.hpp | 16ce263376095bcd29546105b3869d81272229b2 | [
"BSL-1.0"
] | permissive | pm990320/OpenGLLearning | 6c63234da5f00193bf3799ee4b97b16bd14cdc6b | d4f83a047dbfe816631d59ea1115176514d9fad6 | refs/heads/master | 2021-01-10T06:21:34.592102 | 2014-07-04T10:42:52 | 2014-07-04T10:42:52 | 54,271,323 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,123 | hpp | /**
* @file oglplus/ext/NV_path_rendering/stroke_cover_mode.hpp
* @brief Wrapper for the NV_path_rendering stroke cover mode enumeration
*
* @author Matus Chochlik
*
* Copyright 2010-2014 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#pragma once
#ifndef OGLPLUS_EXT_NV_PATH_RENDERING_STROKE_COVER_MODE_1203031902_HPP
#define OGLPLUS_EXT_NV_PATH_RENDERING_STROKE_COVER_MODE_1203031902_HPP
#include <oglplus/enumerations.hpp>
namespace oglplus {
/// Path stroke covering move
/**
* @ingroup enumerations
*
* @glsymbols
* @glextref{NV,path_rendering}
*/
OGLPLUS_ENUM_CLASS_BEGIN(PathNVStrokeCoverMode, GLenum)
#include <oglplus/enums/ext/nv_path_stroke_cover_mode.ipp>
OGLPLUS_ENUM_CLASS_END(PathNVStrokeCoverMode)
#if !OGLPLUS_NO_ENUM_VALUE_NAMES
#include <oglplus/enums/ext/nv_path_stroke_cover_mode_names.ipp>
#endif
#if !OGLPLUS_ENUM_VALUE_RANGES
#include <oglplus/enums/ext/nv_path_stroke_cover_mode_range.ipp>
#endif
} // namespace oglplus
#endif // include guard
| [
"patmenlove@gmail.com"
] | patmenlove@gmail.com |
6730aaade77bcdee250d492a7fac5c5ed9ffbcdb | b1aa9ad6733efcb53d465809d5109e9174dabf04 | /CCode/GameCode/MGCharacter.h | 4e70c06431e1f0cfd9704d531607d7feef160b33 | [] | no_license | dumpinfo/GameMatrixTest | d21545dbef9ade76fe092343a8362da4c8b142ca | 9e4a73ad17555ddb90020c47e2486698b90e4d0d | refs/heads/master | 2023-02-04T01:52:05.342214 | 2020-12-23T17:22:36 | 2020-12-23T17:22:36 | 323,961,033 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,268 | h | //=============================================================
//
// C4 Engine version 4.5
// Copyright 1999-2015, by Terathon Software LLC
//
// This file is part of the C4 Engine and is provided under the
// terms of the license agreement entered by the registed user.
//
// Unauthorized redistribution of source code is strictly
// prohibited. Violators will be prosecuted.
//
//=============================================================
#ifndef MGCharacter_h
#define MGCharacter_h
#include "C4Models.h"
#include "C4Character.h"
#include "MGBase.h"
namespace C4
{
typedef Type CharacterType;
enum : RigidBodyType
{
kRigidBodyCharacter = 'char'
};
enum : CharacterType
{
kCharacterPlayer = 'play',
kCharacterMonster = 'mnst',
kCharacterAnimal = 'anml'
};
enum
{
kCharacterDead = 1 << 0,
kCharacterGround = 1 << 1,
kCharacterOffGround = 1 << 2,
kCharacterJumping = 1 << 3,
kCharacterFlying = 1 << 4,
kCharacterSwimming = 1 << 5,
kCharacterAttackable = 1 << 6
};
enum
{
kDamageBloodInhibit = 1 << 0
};
enum CharacterStatus
{
kCharacterUnaffected,
kCharacterDamaged,
kCharacterKilled
};
struct SubstanceData;
struct DamageLocation
{
Point3D position;
Vector3D momentum;
};
class GameCharacterController : public CharacterController, public LinkTarget<GameCharacterController>
{
private:
CharacterType characterType;
unsigned_int32 characterState;
float standingTime;
float offGroundTime;
protected:
GameCharacterController(CharacterType charType, ControllerType contType);
GameCharacterController(const GameCharacterController& gameCharacterController);
void SetAttackable(bool attackable);
public:
virtual ~GameCharacterController();
CharacterType GetCharacterType(void) const
{
return (characterType);
}
unsigned_int32 GetCharacterState(void) const
{
return (characterState);
}
void SetCharacterState(unsigned_int32 state)
{
characterState = state;
}
void ResetStandingTime(void)
{
standingTime = 0.0F;
SetVelocityMultiplier(1.0F);
}
float GetOffGroundTime(void) const
{
return (offGroundTime);
}
Model *GetTargetNode(void) const
{
return (static_cast<Model *>(Controller::GetTargetNode()));
}
void Pack(Packer& data, unsigned_int32 packFlags) const override;
void Unpack(Unpacker& data, unsigned_int32 unpackFlags) override;
bool UnpackChunk(const ChunkHeader *chunkHeader, Unpacker& data, unsigned_int32 unpackFlags);
void Move(void) override;
void HandlePhysicsSpaceExit(void) override;
const SubstanceData *GetGroundSubstanceData(void) const;
virtual void EnterWorld(World *world, const Point3D& worldPosition);
virtual CharacterStatus Damage(Fixed damage, unsigned_int32 flags, GameCharacterController *attacker, const Point3D *position = nullptr, const Vector3D *impulse = nullptr);
virtual void Kill(GameCharacterController *attacker, const Point3D *position = nullptr, const Vector3D *impulse = nullptr);
};
class CharacterStateMessage : public ControllerMessage
{
friend class CharacterController;
private:
Point3D initialPosition;
Vector3D initialVelocity;
public:
CharacterStateMessage(ControllerMessageType type, int32 controllerIndex);
CharacterStateMessage(ControllerMessageType type, int32 controllerIndex, const Point3D& position, const Vector3D& velocity);
~CharacterStateMessage();
const Point3D& GetInitialPosition(void) const
{
return (initialPosition);
}
const Vector3D& GetInitialVelocity(void) const
{
return (initialVelocity);
}
void Compress(Compressor& data) const override;
bool Decompress(Decompressor& data) override;
};
class AnimationBlender : public Packable
{
private:
int32 blendParity;
BlendAnimator blendAnimator;
FrameAnimator frameAnimator[2];
public:
AnimationBlender();
~AnimationBlender();
BlendAnimator *GetBlendAnimator(void)
{
return (&blendAnimator);
}
FrameAnimator *GetFrameAnimator(int32 index)
{
return (&frameAnimator[index]);
}
FrameAnimator *GetRecentAnimator(void)
{
return (&frameAnimator[blendParity]);
}
void SetFrameAnimatorObserver(FrameAnimator::ObserverType *observer)
{
frameAnimator[0].SetObserver(observer);
frameAnimator[1].SetObserver(observer);
}
void Pack(Packer& data, unsigned_int32 packFlags) const override;
void Unpack(Unpacker& data, unsigned_int32 unpackFlags) override;
bool UnpackChunk(const ChunkHeader *chunkHeader, Unpacker& data, unsigned_int32 unpackFlags);
void Preprocess(Model *model);
FrameAnimator *StartAnimation(const char *name, unsigned_int32 mode, Interpolator::CompletionProc *proc = nullptr, void *cookie = nullptr);
FrameAnimator *BlendAnimation(const char *name, unsigned_int32 mode, float blendRate, Interpolator::CompletionProc *proc = nullptr, void *cookie = nullptr);
};
}
#endif
// ZYUQURM
| [
"twtravel@126.com"
] | twtravel@126.com |
78f1964610b29d1ddeaa2592a9b557dc3e747b31 | 6e4a268b2495060532aebcc3b37b2863b9e7151c | /prototypes/EW_Performance_v1/src/ClipScreen.cpp | d3e9646fffdcbb0c0599ab03150b2b12ed79e93b | [] | no_license | wearecollins/MMI-Prototypes | 3f6e97e8a4e814b520e768d73ebea9b73dfc6048 | 90318eb874770ac5fd339df85140b6c4ffc87489 | refs/heads/master | 2021-05-31T02:00:07.338058 | 2016-04-06T23:34:24 | 2016-04-06T23:34:24 | 34,803,634 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,447 | cpp | #include "ClipScreen.h"
namespace mmi {
#pragma mark clip
//--------------------------------------------------------------
bool Clip::setup( string path, string name, string perf ){
movie.load(path);
movie.setVolume(0);
width = movie.getWidth();
height = movie.getHeight();
bOver = false;
this->title= name;
this->performers = perf;
return true;
}
//--------------------------------------------------------------
void Clip::draw(){
movie.update();
ofPushMatrix();
ofTranslate(this->x, this->y);
movie.draw(0,0, this->width, this->height);
auto & fontA = ofxAssets::font(FONT_HEAD, FONT_BUTTON_SIZE);
auto & fontB = ofxAssets::font(FONT_LIGHT, FONT_BUTTON_SIZE);
fontA.drawString(this->title, this->x, this->y + this->height + FONT_BUTTON_SIZE );
fontB.drawString(this->performers, this->x, this->y + this->height + FONT_BUTTON_SIZE );
ofPopMatrix();
}
//--------------------------------------------------------------
void Clip::draw( float x, float y, float w, float h ){
movie.update();
if ( w == 0 ) w = this->width;
if ( h == 0 ) h = this->height;
movie.draw(x,y,w,h);
if ( bOver ){
ofSetColor(255,100);
ofDrawRectangle(x,y,w,h);
ofSetColor(255);
}
// set my values to match latest/greatest
this->x = x;
this->y = y;
this->width = w;
this->height = h;
}
//--------------------------------------------------------------
ofVideoPlayer & Clip::v(){
return movie;
}
#pragma mark ClipScreen
//--------------------------------------------------------------
void ClipScreen::setup( Mode myMode ){
Screen::setup(myMode);
currentClip = nullptr;
ofXml settings;
bool bSettingsLoaded = settings.load("videos.xml");
if ( bSettingsLoaded ){
settings.setTo("settings");
int n = settings.getNumChildren();
for ( int i=0; i<n; i++ ){
settings.setToChild(i);
clips.push_back( Clip());
clips.back().setup( settings.getValue("file"),
settings.getValue("name"),
settings.getValue("performers")
);
clips.back().v().play();
clips.back().v().setVolume(0);
// clips.back().v().setFrame(0);
clips.back().v().setPaused(true);
settings.setToParent();
}
settings.setToParent();
}
ofAddListener(ofEvents().mousePressed, this, &ClipScreen::onMousePressed);
}
// to-do: destructor
//--------------------------------------------------------------
void ClipScreen::update(){
Screen::update();
}
//--------------------------------------------------------------
void ClipScreen::draw(){
Screen::draw();
float x = 0;
float y = 0;
float sp = 10;
static float total_w = -1;
static float total_h = -1;
if ( total_w == -1){
for ( auto & c : clips ){
total_w += c.v().getWidth();
if ( c.v().getHeight() > total_h)
total_h = c.v().getHeight();
}
total_w += sp * (clips.size() - 1);
}
float scale = ofGetWidth()/total_w;
y = ofGetHeight()/2.0 - (total_h * scale)/2.;
for ( auto & c : clips ){
float c_w = c.v().getWidth() * scale;
float c_h = c.v().getHeight() * scale;
if ( &c == currentClip){
ofSetColor(150);
ofDrawRectangle(x, y, c_w, c_h);
ofSetColor(255);
} else
c.draw(x,y,c_w, c_h);
x += c_w;
x += sp;
}
// draw 'preview' if selected clip
if ( currentClip != nullptr ){
drawPreview();
}
}
//--------------------------------------------------------------
void ClipScreen::drawPreview(){
// overlay
ofPushStyle();
ofSetColor(0,150);
ofDrawRectangle(0, 0, ofGetWidth(), ofGetHeight());
ofSetColor(255);
if ( currentClip != nullptr ){
auto & v = currentClip->v();
float w = (ofGetWidth() * 2/3);
float s = w/currentClip->v().getWidth();
float x = ofGetWidth()/2.0 - ( v.getWidth() * s/2.0 );
float y = ofGetHeight()/2.0 - ( v.getHeight() * s/2.0 );
currentClip->draw(x, y, v.getWidth() * s, v.getHeight() * s);
}
ofPopStyle();
}
//--------------------------------------------------------------
void ClipScreen::setPos( float x, float y, float s){
mPos.x = x;
mPos.y = y;
mPos.z = s;
}
void ClipScreen::onStart(){
Screen::onStart();
for (auto & c : clips ){
c.v().play();
}
}
void ClipScreen::onEnd(){
Screen::onEnd();
}
//--------------------------------------------------------------
void ClipScreen::onMousePressed( ofMouseEventArgs & e ){
ofVec2f m(e.x,e.y);
for ( auto & c : clips ){
if ( c.inside(m)){
if ( currentClip != nullptr ){
currentClip->v().setVolume(0.);
currentClip->v().setPosition(0);
currentClip = nullptr;
} else {
currentClip = &c;
currentClip->v().setPosition(0);
currentClip->v().play();
currentClip->v().setVolume(1.);
}
break;
}
}
}
//--------------------------------------------------------------
void ClipScreen::onMouseMoved( ofMouseEventArgs & e ){
}
} | [
"brett@robotconscience.com"
] | brett@robotconscience.com |
72fc306ada1f2b8ce4079803bd639c4a91359eea | 844969bd953d7300f02172c867725e27b518c08e | /SDK/BP_WaterVolume_Optimized_functions.cpp | 8977f6a90ab032a186193a0708bbbfc4ed393f53 | [] | no_license | zanzo420/SoT-Python-Offset-Finder | 70037c37991a2df53fa671e3c8ce12c45fbf75a5 | d881877da08b5c5beaaca140f0ab768223b75d4d | refs/heads/main | 2023-07-18T17:25:01.596284 | 2021-09-09T12:31:51 | 2021-09-09T12:31:51 | 380,604,174 | 0 | 0 | null | 2021-06-26T22:07:04 | 2021-06-26T22:07:03 | null | UTF-8 | C++ | false | false | 4,533 | cpp | // Name: SoT, Version: 2.2.1.1
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BP_WaterVolume_Optimized.BP_WaterVolume_Optimized_C.CollectRippleGenerators
// (Public, BlueprintCallable, BlueprintEvent)
void ABP_WaterVolume_Optimized_C::CollectRippleGenerators()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function BP_WaterVolume_Optimized.BP_WaterVolume_Optimized_C.CollectRippleGenerators");
ABP_WaterVolume_Optimized_C_CollectRippleGenerators_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WaterVolume_Optimized.BP_WaterVolume_Optimized_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void ABP_WaterVolume_Optimized_C::UserConstructionScript()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function BP_WaterVolume_Optimized.BP_WaterVolume_Optimized_C.UserConstructionScript");
ABP_WaterVolume_Optimized_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WaterVolume_Optimized.BP_WaterVolume_Optimized_C.ReceiveBeginPlay
// (Event, Public, BlueprintEvent)
void ABP_WaterVolume_Optimized_C::ReceiveBeginPlay()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function BP_WaterVolume_Optimized.BP_WaterVolume_Optimized_C.ReceiveBeginPlay");
ABP_WaterVolume_Optimized_C_ReceiveBeginPlay_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WaterVolume_Optimized.BP_WaterVolume_Optimized_C.ReceiveActorBeginOverlap
// (Event, Public, BlueprintEvent)
// Parameters:
// class AActor* OtherActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_WaterVolume_Optimized_C::ReceiveActorBeginOverlap(class AActor* OtherActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function BP_WaterVolume_Optimized.BP_WaterVolume_Optimized_C.ReceiveActorBeginOverlap");
ABP_WaterVolume_Optimized_C_ReceiveActorBeginOverlap_Params params;
params.OtherActor = OtherActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WaterVolume_Optimized.BP_WaterVolume_Optimized_C.ReceiveActorEndOverlap
// (Event, Public, BlueprintEvent)
// Parameters:
// class AActor* OtherActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_WaterVolume_Optimized_C::ReceiveActorEndOverlap(class AActor* OtherActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function BP_WaterVolume_Optimized.BP_WaterVolume_Optimized_C.ReceiveActorEndOverlap");
ABP_WaterVolume_Optimized_C_ReceiveActorEndOverlap_Params params;
params.OtherActor = OtherActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_WaterVolume_Optimized.BP_WaterVolume_Optimized_C.ExecuteUbergraph_BP_WaterVolume_Optimized
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_WaterVolume_Optimized_C::ExecuteUbergraph_BP_WaterVolume_Optimized(int EntryPoint)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function BP_WaterVolume_Optimized.BP_WaterVolume_Optimized_C.ExecuteUbergraph_BP_WaterVolume_Optimized");
ABP_WaterVolume_Optimized_C_ExecuteUbergraph_BP_WaterVolume_Optimized_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void ABP_WaterVolume_Optimized_C::AfterRead()
{
AWaterVolume::AfterRead();
READ_PTR_FULL(WaterPlaneActivatationVolume, UStaticMeshComponent);
READ_PTR_FULL(FlatWaterPlane, UFlatWaterPlaneComponent);
READ_PTR_FULL(FlatWaterMesh, UFlatWaterMeshComponent);
READ_PTR_FULL(Root, USceneComponent);
}
void ABP_WaterVolume_Optimized_C::BeforeDelete()
{
AWaterVolume::BeforeDelete();
DELE_PTR_FULL(WaterPlaneActivatationVolume);
DELE_PTR_FULL(FlatWaterPlane);
DELE_PTR_FULL(FlatWaterMesh);
DELE_PTR_FULL(Root);
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"51171051+DougTheDruid@users.noreply.github.com"
] | 51171051+DougTheDruid@users.noreply.github.com |
9c8ec569ed0a4d420f69453cd3a4ff5ae216c032 | 2d7e3b4a580d4476a6415866754354de287602a3 | /pemc/formula/bounded_unary_formula.cc | 799cd471ac632cca9a1e6204c1d16937a233e162 | [
"MIT"
] | permissive | joleuger/pemc | ff3439808ebeea654dbcea34dd4d0d6980f88e6b | ba1608a8b575bbd324d59e376a60f54f1f55526b | refs/heads/master | 2023-07-07T15:35:07.134183 | 2023-06-27T19:19:43 | 2023-06-27T19:19:43 | 147,083,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,034 | cc | // SPDX-License-Identifier: MIT
// The MIT License (MIT)
//
// Copyright (c) 2014-2018, Institute for Software & Systems Engineering
// Copyright (c) 2018-2019, Johannes Leupolz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "pemc/formula/bounded_unary_formula.h"
#include "pemc/formula/formula_visitor.h"
namespace pemc {
BoundedUnaryFormula::BoundedUnaryFormula(std::shared_ptr<Formula> _operand,
UnaryOperator _unaryOperator,
int _bound,
const std::string& _identifier)
: Formula(_identifier),
operand(_operand),
unaryOperator(_unaryOperator),
bound(_bound){
}
UnaryOperator BoundedUnaryFormula::getOperator() {
return unaryOperator;
}
Formula* BoundedUnaryFormula::getOperand() {
return operand.get();
}
int BoundedUnaryFormula::getBound() {
return this->bound;
}
void BoundedUnaryFormula::visit(FormulaVisitor* visitor) {
visitor->visitBoundedUnaryFormula(this);
}
}
| [
"johannes.leupolz@googlemail.com"
] | johannes.leupolz@googlemail.com |
b27fb678fc6b45cc2e836564275ed734e3d12473 | 9f2230964f2b8959ee1d2104915f04a25026241a | /8 день 20 задача.cpp | 31f8cb0455b28d55cf7715d22a267362ebd1fbad | [] | no_license | VLadkravch/OPtaAMpracticePS3 | 331f127a4b18875f1f8c70ad4a262ad6614d6b6a | e019c622f460b7b3b1a9db27fecc0ee39e87396c | refs/heads/master | 2020-06-23T03:03:48.508750 | 2016-12-02T11:02:55 | 2016-12-02T11:02:55 | 74,670,176 | 0 | 0 | null | 2016-11-24T12:13:16 | 2016-11-24T12:13:16 | null | UTF-8 | C++ | false | false | 748 | cpp | #include <iostream.h>
#include <conio.h>
struct biblioteka
{
char Avtor[200];
int Kilkist;
char Kniga[200];
};
int main()
{
int n;
cout<<"Dobavte knigu v BD:\n";
cout<<"Kilkist knig :";
cin>>n;
biblioteka s[n];
for (int i=0;i<n;i++)
{
cout<<"\n Avtor "<<i+1<<" knigi : ";
cin>>s[i].Avtor;
cout<<"\n Nazva "<<i+1<<" knigi : ";
cin>>s[i].Kniga;
cout<<"\n Kilkist "<<i+1<<" primirnikov : ";
cin>>s[i].Kilkist;
cout<<endl;
}
cout<<"\n Avtor \tNazva\t Kilkist"<<endl;
for (int i=0;i<n;i++)
{
cout<<s[i].Avtor<<"\t"<<s[i].Kniga<<"\t"<<s[i].Kilkist<<endl;
}
system("pause");
return 0;
}
| [
"vladkravch1999@gmail.com"
] | vladkravch1999@gmail.com |
38ff651570d44dcaaca9287ff30b745809f39235 | d1eda4ae4d82009e22b081db357d5ebafabac4f3 | /starts/meaning-vm/level-2-wip-stmtexprs/baseref.hpp | 84c9c13bb6109f0efaf1f1db002404b3fd0510ac | [] | no_license | xloem/intellect | 88ba8475a8a6d93a434fe6ec2a91cacc2cd8bab2 | 6f876e68699f4310f0fb77951f3db7e3f5700569 | refs/heads/master | 2023-05-28T12:26:28.846227 | 2021-02-18T15:30:13 | 2021-02-18T15:30:13 | 204,706,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 559 | hpp | #pragma once
#include "common.hpp"
#include "../level-1/ref.hpp"
#include "statementref.hpp"
namespace intellect {
namespace level2 {
template <typename ref>
struct baseref : public level1::baseref<ref>
{
using level1::baseref<ref>::baseref;
baseref(level1::ref other) : level1::baseref<ref>(other.ptr()) { }
operator level1::ref() { return ptr(); }
statementref operator=(ref other) { return assignop(self, other); }
statementref operator,(ref other) { return commaop(self, other); }
ref operator[](ref other) { return subop(self, other); }
}
}
}
| [
"olpc@xo-5d-f7-86.localdomain"
] | olpc@xo-5d-f7-86.localdomain |
68cfdbc9996b0d220e8967eaf6fb457f21d579ac | f8170782a9cb73e5b7ca66cf28c20e521ec80f84 | /OpenGL_5/Common/CSolidCube.cpp | 6e26bb1cc771a646cd9c0e0eba8ea63b84d5fec9 | [] | no_license | youweit/CG-Final-Project | 65f359e2a71f2f8d65f5ddda5bd6fd3b1befabb1 | 6b3bf8cc449039839f6aca40d9784d88f570d259 | refs/heads/master | 2020-05-04T08:33:25.943941 | 2015-09-24T15:03:59 | 2015-09-24T15:03:59 | 42,936,521 | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 10,502 | cpp | #include "CSolidCube.h"
//for testing
#define CUBE_LENGTH 3
#define CUBE_WIDTH 3
#define CUBE_HEIGHT 3
CSolidCube::CSolidCube()
{
m_iNumVtx = SOLIDCUBE_NUM;
m_pPoints = NULL; m_pNormals = NULL; m_pTex1 = NULL;
m_pPoints = new vec4[m_iNumVtx];
m_pNormals = new vec3[m_iNumVtx];
m_pColors = new vec4[m_iNumVtx];
m_pTex1 = new vec2[m_iNumVtx];
m_vertices[0] = point4(-m_fWidth, -m_fHeight, m_fLength, 1.0);
m_vertices[1] = point4(-m_fWidth, m_fHeight, m_fLength, 1.0);
m_vertices[2] = point4(m_fWidth, m_fHeight, m_fLength, 1.0);
m_vertices[3] = point4(m_fWidth, -m_fHeight, m_fLength, 1.0);
m_vertices[4] = point4(-m_fWidth, -m_fHeight, -m_fLength, 1.0);
m_vertices[5] = point4(-m_fWidth, m_fHeight, -m_fLength, 1.0);
m_vertices[6] = point4(m_fWidth, m_fHeight, -m_fLength, 1.0);
m_vertices[7] = point4(m_fWidth, -m_fHeight, -m_fLength, 1.0);
m_iIndex = 0;
// generate 12 triangles: 36 vertices and 36 colors
Quad( 1, 0, 3, 2 ); //0
Quad( 2, 3, 7, 6 ); //6
Quad( 3, 0, 4, 7 ); //12
Quad( 6, 5, 1, 2 ); //18
Quad( 4, 5, 6, 7 ); //24
Quad( 5, 4, 0, 1 ); //32
// 預設將所有的面都設定成灰色
for( int i = 0 ; i < m_iNumVtx ; i++ ) m_pColors[i] = vec4(-1.0f,-1.0f,-1.0f,1.0f);
#ifdef LIGHTING_WITHCPU
// Default Set shader's name
SetShaderName("vsLighting_CPU.glsl", "fsLighting_CPU.glsl");
#else // lighting with GPU
#ifdef PERVERTEX_LIGHTING
SetShaderName("vsLighting_GPU.glsl", "fsLighting_GPU.glsl");
#else
SetShaderName("vsPerPixelLighting.glsl", "fsPerPixelLighting.glsl");
#endif
#endif
// Create and initialize a buffer object ,將此部分的設定移入 SetShader 中
// CreateBufferObject();
// 設定材質
SetMaterials(vec4(0), vec4(0.4f, 0.4f, 0.4f, 1), vec4(1.0f, 1.0f, 1.0f, 1.0f));
SetKaKdKsShini(0, 0.8f, 0.2f, 1);
}
//長寬高
void CSolidCube::SetWallSize(vec3 size)
{
m_fLength = size.x / 2;
m_fWidth = size.y / 2;
m_fHeight = size.z / 2;
m_vertices[0] = point4(-m_fWidth, -m_fHeight, m_fLength, 1.0);
m_vertices[1] = point4(-m_fWidth, m_fHeight, m_fLength, 1.0);
m_vertices[2] = point4(m_fWidth, m_fHeight, m_fLength, 1.0);
m_vertices[3] = point4(m_fWidth, -m_fHeight, m_fLength, 1.0);
m_vertices[4] = point4(-m_fWidth, -m_fHeight, -m_fLength, 1.0);
m_vertices[5] = point4(-m_fWidth, m_fHeight, -m_fLength, 1.0);
m_vertices[6] = point4(m_fWidth, m_fHeight, -m_fLength, 1.0);
m_vertices[7] = point4(m_fWidth, -m_fHeight, -m_fLength, 1.0);
m_max = GetPosition() + vec3(m_fWidth, m_fLength, m_fHeight);
m_min = GetPosition() - vec3(m_fWidth, m_fLength, m_fHeight);
}
CSolidCube::CSolidCube(vec3 size)
{
m_fLength = size.x / 2;
m_fWidth = size.y / 2;
m_fHeight = size.z / 2;
m_iNumVtx = SOLIDCUBE_NUM;
m_pPoints = NULL; m_pNormals = NULL; m_pTex1 = NULL;
m_pPoints = new vec4[m_iNumVtx];
m_pNormals = new vec3[m_iNumVtx];
m_pColors = new vec4[m_iNumVtx];
m_pTex1 = new vec2[m_iNumVtx];
m_vertices[0] = point4(-m_fWidth, -m_fHeight, m_fLength, 1.0);
m_vertices[1] = point4(-m_fWidth, m_fHeight, m_fLength, 1.0);
m_vertices[2] = point4(m_fWidth, m_fHeight, m_fLength, 1.0);
m_vertices[3] = point4(m_fWidth, -m_fHeight, m_fLength, 1.0);
m_vertices[4] = point4(-m_fWidth, -m_fHeight, -m_fLength, 1.0);
m_vertices[5] = point4(-m_fWidth, m_fHeight, -m_fLength, 1.0);
m_vertices[6] = point4(m_fWidth, m_fHeight, -m_fLength, 1.0);
m_vertices[7] = point4(m_fWidth, -m_fHeight, -m_fLength, 1.0);
m_iIndex = 0;
// generate 12 triangles: 36 vertices and 36 colors
Quad(1, 0, 3, 2); //0
Quad(2, 3, 7, 6); //6
Quad(3, 0, 4, 7); //12
Quad(6, 5, 1, 2); //18
Quad(4, 5, 6, 7); //24
Quad(5, 4, 0, 1); //32
// 預設將所有的面都設定成灰色
for (int i = 0; i < m_iNumVtx; i++) m_pColors[i] = vec4(-1.0f, -1.0f, -1.0f, 1.0f);
#ifdef LIGHTING_WITHCPU
// Default Set shader's name
SetShaderName("vsLighting_CPU.glsl", "fsLighting_CPU.glsl");
#else // lighting with GPU
#ifdef PERVERTEX_LIGHTING
SetShaderName("vsLighting_GPU.glsl", "fsLighting_GPU.glsl");
#else
SetShaderName("vsPerPixelLighting.glsl", "fsPerPixelLighting.glsl");
#endif
#endif
// Create and initialize a buffer object ,將此部分的設定移入 SetShader 中
// CreateBufferObject();
// 設定材質
SetMaterials(vec4(0), vec4(0.4f, 0.4f, 0.4f, 1), vec4(1.0f, 1.0f, 1.0f, 1.0f));
SetKaKdKsShini(0, 0.8f, 0.2f, 1);
}
void CSolidCube::Quad( int a, int b, int c, int d )
{
// Initialize temporary vectors along the quad's edge to
// compute its face normal
vec4 u = m_vertices[b] - m_vertices[a];
vec4 v = m_vertices[c] - m_vertices[b];
vec3 normal = normalize( cross(u, v) );
m_pNormals[m_iIndex] = normal; m_pPoints[m_iIndex] = m_vertices[a]; m_pTex1[m_iIndex] = vec2(0,0);m_iIndex++;
m_pNormals[m_iIndex] = normal; m_pPoints[m_iIndex] = m_vertices[b]; m_pTex1[m_iIndex] = vec2(1,0);m_iIndex++;
m_pNormals[m_iIndex] = normal; m_pPoints[m_iIndex] = m_vertices[c]; m_pTex1[m_iIndex] = vec2(1,1);m_iIndex++;
m_pNormals[m_iIndex] = normal; m_pPoints[m_iIndex] = m_vertices[a]; m_pTex1[m_iIndex] = vec2(0,0);m_iIndex++;
m_pNormals[m_iIndex] = normal; m_pPoints[m_iIndex] = m_vertices[c]; m_pTex1[m_iIndex] = vec2(1,1);m_iIndex++;
m_pNormals[m_iIndex] = normal; m_pPoints[m_iIndex] = m_vertices[d]; m_pTex1[m_iIndex] = vec2(0,1);m_iIndex++;
}
void CSolidCube::Draw()
{
// glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // Change to wireframe mode
DrawingSetShader();
glBindTexture(GL_TEXTURE_2D, m_uiTexObject[0]);
glDrawArrays( GL_TRIANGLES, 0, SOLIDCUBE_NUM );
glBindTexture(GL_TEXTURE_2D, 0);
// glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // Return to solid mode
}
void CSolidCube::DrawW()
{
DrawingWithoutSetShader();
glBindTexture(GL_TEXTURE_2D, m_uiTexObject[0]);
glDrawArrays( GL_TRIANGLES, 0, SOLIDCUBE_NUM );
glBindTexture(GL_TEXTURE_2D, 0);
}
void CSolidCube::RenderWithFlatShading(vec4 vLightPos, color4 vLightI)
{
// 以每一個面的三個頂點計算其重心,以該重心作為顏色計算的點頂
// 根據 Phong lighting model 計算相對應的顏色,並將顏色儲存到此三個點頂
// 因為每一個平面的頂點的 Normal 都相同,所以此處並沒有計算此三個頂點的平均 Normal
vec4 vCentroidP;
for( int i = 0 ; i < m_iNumVtx ; i += 3 ) {
// 計算三角形的重心
vCentroidP = (m_pPoints[i] + m_pPoints[i+1] + m_pPoints[i+2])/3.0f;
m_pColors[i] = m_pColors[i+1] = m_pColors[i+2] = PhongReflectionModel(vCentroidP, m_pNormals[i], vLightPos, vLightI);
}
glBindBuffer( GL_ARRAY_BUFFER, m_uiBuffer );
glBufferSubData( GL_ARRAY_BUFFER, sizeof(vec4)*m_iNumVtx+sizeof(vec3)*m_iNumVtx, sizeof(vec4)*m_iNumVtx, m_pColors ); // vertcies' Color
}
void CSolidCube::RenderWithGouraudShading(vec4 vLightPos, color4 vLightI)
{
vec4 vCentroidP;
for( int i = 0 ; i < m_iNumVtx ; i += 6 ) {
m_pColors[i] = m_pColors[i+3] = PhongReflectionModel(m_pPoints[i], m_pNormals[i], vLightPos, vLightI);
m_pColors[i+2] = m_pColors[i+4] = PhongReflectionModel(m_pPoints[i+2], m_pNormals[i+2], vLightPos, vLightI);
m_pColors[i+1] = PhongReflectionModel(m_pPoints[i+1], m_pNormals[i+1], vLightPos, vLightI);
m_pColors[i+5] = PhongReflectionModel(m_pPoints[i+5], m_pNormals[i+5], vLightPos, vLightI);
}
glBindBuffer( GL_ARRAY_BUFFER, m_uiBuffer );
glBufferSubData( GL_ARRAY_BUFFER, sizeof(vec4)*m_iNumVtx+sizeof(vec3)*m_iNumVtx, sizeof(vec4)*m_iNumVtx, m_pColors ); // vertcies' Color
}
// 此處所給的 vLightPos 必須是世界座標的確定絕對位置
void CSolidCube::Update(float dt, point4 vLightPos, color4 vLightI)
{
#ifdef LIGHTING_WITHCPU
if( m_bMVUpdated ) { // Model View 的相關矩陣內容有更動
m_mxMVFinal = m_mxModelView * m_mxTRS;
m_mxMV3X3Final = mat3(
m_mxMVFinal._m[0].x, m_mxMVFinal._m[1].x, m_mxMVFinal._m[2].x,
m_mxMVFinal._m[0].y, m_mxMVFinal._m[1].y, m_mxMVFinal._m[2].y,
m_mxMVFinal._m[0].z, m_mxMVFinal._m[1].z, m_mxMVFinal._m[2].z);
#ifdef GENERAL_CASE
m_mxITMV = InverseTransposeMatrix(m_mxMVFinal);
#endif
m_bMVUpdated = false;
}
if( m_iMode == FLAT_SHADING ) RenderWithFlatShading(vLightPos, vLightI);
else RenderWithGouraudShading(vLightPos, vLightI);
#else // Lighting With GPU
if( m_bMVUpdated ) {
m_mxMVFinal = m_mxModelView * m_mxTRS;
m_bMVUpdated = false;
}
m_vLightInView = m_mxModelView * vLightPos; // 將 Light 轉換到鏡頭座標再傳入
// 算出 AmbientProduct DiffuseProduct 與 SpecularProduct 的內容
m_AmbientProduct = m_Material.ka * m_Material.ambient * vLightI;
m_DiffuseProduct = m_Material.kd * m_Material.diffuse * vLightI;
m_SpecularProduct = m_Material.ks * m_Material.specular * vLightI;
#endif
}
void CSolidCube::Update(float dt, const structLightSource &LightSource)
{
#ifdef LIGHTING_WITHCPU
if( m_bMVUpdated ) { // Model View 的相關矩陣內容有更動
m_mxMVFinal = m_mxModelView * m_mxTRS;
m_mxMV3X3Final = mat3(
m_mxMVFinal._m[0].x, m_mxMVFinal._m[1].x, m_mxMVFinal._m[2].x,
m_mxMVFinal._m[0].y, m_mxMVFinal._m[1].y, m_mxMVFinal._m[2].y,
m_mxMVFinal._m[0].z, m_mxMVFinal._m[1].z, m_mxMVFinal._m[2].z);
#ifdef GENERAL_CASE
m_mxITMV = InverseTransposeMatrix(m_mxMVFinal);
#endif
m_bMVUpdated = false;
}
if( m_iMode == FLAT_SHADING ) RenderWithFlatShading(LightSource.position, LightSource.diffuse);
else RenderWithGouraudShading(LightSource.position, LightSource.diffuse);
#else // Lighting With GPU
if( m_bMVUpdated ) {
m_mxMVFinal = m_mxModelView * m_mxTRS;
m_bMVUpdated = false;
}
m_vLightInView = m_mxModelView * LightSource.position; // 將 Light 轉換到鏡頭座標再傳入
// 算出 AmbientProduct DiffuseProduct 與 SpecularProduct 的內容
m_AmbientProduct = m_Material.ka * m_Material.ambient * LightSource.ambient;
m_DiffuseProduct = m_Material.kd * m_Material.diffuse * LightSource.diffuse;
m_SpecularProduct = m_Material.ks * m_Material.specular * LightSource.specular;
#endif
m_max = GetPosition() + vec3(m_fWidth, m_fHeight, m_fLength);
m_min = GetPosition() - vec3(m_fWidth, m_fHeight, m_fLength);
}
void CSolidCube::Update(float dt)
{
if( m_bMVUpdated ) { // Model View 的相關矩陣內容有更動
m_mxMVFinal = m_mxModelView * m_mxTRS;
m_mxITMV = InverseTransposeMatrix(m_mxMVFinal);
}
} | [
"ranyouwei3@gmail.com"
] | ranyouwei3@gmail.com |
cd4bdc665bd20874200a68489eba381d346b0498 | c2dd65a9021aafe0ba242db05fbedf390394729d | /203.cpp | 2356f0aece856009886a7719e3bf4b83b126084b | [] | no_license | ry0u/yukicoder | 4f8e6c2db7f728883e8c2faec056d178368ae745 | 0b080dace7f894638bf2eaa2678eb44dd702daf7 | refs/heads/master | 2021-01-19T03:23:35.495825 | 2015-10-21T16:32:17 | 2015-10-21T16:32:17 | 33,320,448 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 753 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <sstream>
#include <map>
#include <set>
#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
#define INF 1<<30
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
int main() {
string s,t;
cin >> s >> t;
s += t;
int ans = 0;
rep(i,s.size()) {
if(s[i] == 'x') continue;
int cnt = 1;
REP(j,i+1,s.size()) {
if(s[j] == 'o') {
i++;
cnt++;
continue;
} else break;
}
ans = max(ans,cnt);
}
cout << ans << endl;
return 0;
}
| [
"ry0u_yd@yahoo.co.jp"
] | ry0u_yd@yahoo.co.jp |
70a604b8b454c5b9de23529d84b6c68d21b823e3 | 8ded25366e840e9a4471f270159b29165826dc74 | /flamingoserver/fileserversrc/FileSession.h | e654a2699523922a27f304d65dacd902e53c0ed8 | [] | no_license | 736229999/flamingo | 46660342079976157135dbdf15c179cbc1fc7063 | 29ed03d4fbebf1e7b2880e1b86e818257aef3526 | refs/heads/master | 2021-01-15T11:11:53.393161 | 2017-08-02T01:37:26 | 2017-08-02T01:37:26 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,313 | h | /**
* FileSession.h
* zhangyl, 2017.03.17
**/
#pragma once
#include "../net/buffer.h"
#include "TcpSession.h"
class FileSession : public TcpSession
{
public:
FileSession(const std::shared_ptr<TcpConnection>& conn, const char* filebasedir = "filecache/");
virtual ~FileSession();
FileSession(const FileSession& rhs) = delete;
FileSession& operator =(const FileSession& rhs) = delete;
//有数据可读, 会被多个工作loop调用
void OnRead(const std::shared_ptr<TcpConnection>& conn, Buffer* pBuffer, Timestamp receivTime);
private:
bool Process(const std::shared_ptr<TcpConnection>& conn, const char* inbuf, size_t length);
void OnUploadFileResponse(const std::string& filemd5, int64_t offset, int64_t filesize, const std::string& filedata, const std::shared_ptr<TcpConnection>& conn);
void OnDownloadFileResponse(const std::string& filemd5, int64_t offset, int64_t filesize, const std::shared_ptr<TcpConnection>& conn);
void ResetFile();
private:
int32_t m_id; //session id
int32_t m_seq; //当前Session数据包序列号
//当前文件信息
FILE* m_fp{};
int64_t m_offset{};
int64_t m_filesize{};
std::string m_strFileBaseDir; //文件目录
}; | [
"yuanlong.zhang@baidao.com"
] | yuanlong.zhang@baidao.com |
bb44c622b862ab1c051ac04e84c8ebea87ca8a54 | 80f13dc24307667d8b6f86334d5ef77077f5f3f0 | /MIFlib/src/ElementArea.cpp | 9e4ad26fd76c20553ba49615f910294f395c1180 | [
"BSD-3-Clause",
"MIT"
] | permissive | zadinvit/BIGpluginMitsuba | 200307d949bed1d2c48dd19dd0cfb40e4e503519 | 0bf7bf7527fc769ac5ea9b51f46490b0cfe148db | refs/heads/main | 2023-04-12T01:22:38.604139 | 2021-05-09T08:16:15 | 2021-05-09T08:16:15 | 343,452,776 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,931 | cpp | /**
* MIFlib - Multi-Image Format Library - version 0.4
* --------------------------------------------------------
* Copyright (C) 2021, Radomir Vavra (vavra.radomir@gmail.com) and Jiri Filip
* Report bugs and download new versions at https://github.com/RadomirVavra/MIFlib/
*
* This library is distributed under the 3-clause BSD license. See notice at the end
* of this file.
*
* This library uses parts of Image Library, which are:
* Copyright (C) 2019-2021, by Radomir Vavra (vavra.radomir@gmail.com)
*
*
* Version History of class ElementArea:
* 1.0 First stable version.
*
* TODO List of class ElementArea:
* - implement unit tests
* - add noexcept specifiers
*/
#include "../include/ElementArea.hpp"
namespace mif
{
ElementArea::ElementArea(const std::string & id, double top, double left, double height, double width, double whole_height, double whole_width, const std::string & units, const Attributes & attributes, const elements_t & elements)
: Element("area", elements, attributes), top(top), left(left), height(height), width(width), whole_height(whole_height), whole_width(whole_width), units(units)
{
setId(id);
}
ElementArea::ElementArea(const Element & element) : Element(element)
{
if (element.getElementName() != "area") {
clear();
return;
}
top = stringToDouble(element.getChildElement("top").getElementText());
left = stringToDouble(element.getChildElement("left").getElementText());
height = stringToDouble(element.getChildElement("height").getElementText());
width = stringToDouble(element.getChildElement("width").getElementText());
whole_height = stringToDouble(element.getChildElement("whole").getAttribute("height"));
whole_width = stringToDouble(element.getChildElement("whole").getAttribute("width"));
units = element.getAttribute("units");
const Element & resolution = element.getChildElement("resolution");
DPI = stringToDouble(resolution.getChildElement("dpi").getElementText());
ppmm = stringToDouble(resolution.getChildElement("ppmm").getElementText());
pixel_size = stringToDouble(resolution.getChildElement("pixel_size").getElementText());
pixel_size_unit = resolution.getChildElement("pixel_size").getAttribute("unit");
}
Element ElementArea::toElement() const
{
Element e = *this;
// store top, left, height and width
e.getChildElement("top").setElementText(doubleToString(top));
e.getChildElement("left").setElementText(doubleToString(left));
e.getChildElement("height").setElementText(doubleToString(height));
e.getChildElement("width").setElementText(doubleToString(width));
// store whole height and width
if (whole_height > 0 && whole_width > 0) {
Element & whole = e.getChildElement("whole");
whole.setAttribute("height", doubleToString(whole_height));
whole.setAttribute("width", doubleToString(whole_width));
}
else {
e.removeChildElement("whole");
}
// set units
e.setAttribute("units", units);
// store resolution
Element & resolution = e.getChildElement("resolution");
if (DPI > 0) resolution.getChildElement("dpi").setElementText(doubleToString(DPI));
else resolution.removeChildElement("dpi");
if (ppmm > 0) resolution.getChildElement("ppmm").setElementText(doubleToString(ppmm));
else resolution.removeChildElement("ppmm");
if (pixel_size > 0) {
resolution.getChildElement("pixel_size").setElementText(doubleToString(pixel_size));
resolution.getChildElement("pixel_size").setAttribute("unit", pixel_size_unit);
}
else resolution.removeChildElement("pixel_size");
// return final element
return e;
}
void ElementArea::setArea(double top, double left, double height, double width, double whole_height, double whole_width, const std::string & units)
{
this->top = top;
this->left = left;
this->height = height;
this->width = width;
this->whole_height = whole_height;
this->whole_width = whole_width;
this->units = units;
}
}
/**
* 3-Clause BSD License
*
* Copyright (c) 2021, Radomir Vavra (vavra.radomir@gmail.com) and Jiri Filip.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder 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 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.
*/
| [
"vitek.zadina@gmail.com"
] | vitek.zadina@gmail.com |
a078e5e0a07e98a099f856d89c76b1837402ed0f | 5e4955439f5f3a0cd2ad451da4bee7f9eecb7b3e | /src/walletdb.cpp | b388b7e115bc396a79087c689774908a6f88ac5d | [
"MIT"
] | permissive | mjk22/SlashDash | 2ca9de4b69d8782e313bd6666ea0df9575adc4a2 | 17447f9f412ff0480ea6e211cbe224d30bca1b86 | refs/heads/master | 2020-03-17T05:02:36.624209 | 2018-05-19T07:47:22 | 2018-05-19T07:47:22 | 131,763,549 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,606 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "walletdb.h"
#include "base58.h"
#include "protocol.h"
#include "serialize.h"
#include "sync.h"
#include "util.h"
#include "utiltime.h"
#include "wallet.h"
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/thread.hpp>
#include <fstream>
using namespace boost;
using namespace std;
static uint64_t nAccountingEntryNumber = 0;
//
// CWalletDB
//
bool CWalletDB::WriteName(const string& strAddress, const string& strName)
{
nWalletDBUpdated++;
return Write(make_pair(string("name"), strAddress), strName);
}
bool CWalletDB::EraseName(const string& strAddress)
{
// This should only be used for sending addresses, never for receiving addresses,
// receiving addresses must always have an address book entry if they're not change return.
nWalletDBUpdated++;
return Erase(make_pair(string("name"), strAddress));
}
bool CWalletDB::WritePurpose(const string& strAddress, const string& strPurpose)
{
nWalletDBUpdated++;
return Write(make_pair(string("purpose"), strAddress), strPurpose);
}
bool CWalletDB::ErasePurpose(const string& strPurpose)
{
nWalletDBUpdated++;
return Erase(make_pair(string("purpose"), strPurpose));
}
bool CWalletDB::WriteTx(uint256 hash, const CWalletTx& wtx)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("tx"), hash), wtx);
}
bool CWalletDB::EraseTx(uint256 hash)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("tx"), hash));
}
bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
{
nWalletDBUpdated++;
if (!Write(std::make_pair(std::string("keymeta"), vchPubKey),
keyMeta, false))
return false;
// hash pubkey/privkey to accelerate wallet load
std::vector<unsigned char> vchKey;
vchKey.reserve(vchPubKey.size() + vchPrivKey.size());
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());
return Write(std::make_pair(std::string("key"), vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false);
}
bool CWalletDB::WriteCryptedKey(const CPubKey& vchPubKey,
const std::vector<unsigned char>& vchCryptedSecret,
const CKeyMetadata& keyMeta)
{
const bool fEraseUnencryptedKey = true;
nWalletDBUpdated++;
if (!Write(std::make_pair(std::string("keymeta"), vchPubKey),
keyMeta))
return false;
if (!Write(std::make_pair(std::string("ckey"), vchPubKey), vchCryptedSecret, false))
return false;
if (fEraseUnencryptedKey) {
Erase(std::make_pair(std::string("key"), vchPubKey));
Erase(std::make_pair(std::string("wkey"), vchPubKey));
}
return true;
}
bool CWalletDB::WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("mkey"), nID), kMasterKey, true);
}
bool CWalletDB::WriteCScript(const uint160& hash, const CScript& redeemScript)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("cscript"), hash), redeemScript, false);
}
bool CWalletDB::WriteWatchOnly(const CScript& dest)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("watchs"), dest), '1');
}
bool CWalletDB::EraseWatchOnly(const CScript& dest)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("watchs"), dest));
}
bool CWalletDB::WriteMultiSig(const CScript& dest)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("multisig"), dest), '1');
}
bool CWalletDB::EraseMultiSig(const CScript& dest)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("multisig"), dest));
}
bool CWalletDB::WriteBestBlock(const CBlockLocator& locator)
{
nWalletDBUpdated++;
return Write(std::string("bestblock"), locator);
}
bool CWalletDB::ReadBestBlock(CBlockLocator& locator)
{
return Read(std::string("bestblock"), locator);
}
bool CWalletDB::WriteOrderPosNext(int64_t nOrderPosNext)
{
nWalletDBUpdated++;
return Write(std::string("orderposnext"), nOrderPosNext);
}
// presstab HyperStake
bool CWalletDB::WriteStakeSplitThreshold(uint64_t nStakeSplitThreshold)
{
nWalletDBUpdated++;
return Write(std::string("stakeSplitThreshold"), nStakeSplitThreshold);
}
//presstab HyperStake
bool CWalletDB::WriteMultiSend(std::vector<std::pair<std::string, int> > vMultiSend)
{
nWalletDBUpdated++;
bool ret = true;
for (unsigned int i = 0; i < vMultiSend.size(); i++) {
std::pair<std::string, int> pMultiSend;
pMultiSend = vMultiSend[i];
if (!Write(std::make_pair(std::string("multisend"), i), pMultiSend, true))
ret = false;
}
return ret;
}
//presstab HyperStake
bool CWalletDB::EraseMultiSend(std::vector<std::pair<std::string, int> > vMultiSend)
{
nWalletDBUpdated++;
bool ret = true;
for (unsigned int i = 0; i < vMultiSend.size(); i++) {
std::pair<std::string, int> pMultiSend;
pMultiSend = vMultiSend[i];
if (!Erase(std::make_pair(std::string("multisend"), i)))
ret = false;
}
return ret;
}
//presstab HyperStake
bool CWalletDB::WriteMSettings(bool fMultiSendStake, bool fMultiSendMasternode, int nLastMultiSendHeight)
{
nWalletDBUpdated++;
std::pair<bool, bool> enabledMS(fMultiSendStake, fMultiSendMasternode);
std::pair<std::pair<bool, bool>, int> pSettings(enabledMS, nLastMultiSendHeight);
return Write(std::string("msettingsv2"), pSettings, true);
}
//presstab HyperStake
bool CWalletDB::WriteMSDisabledAddresses(std::vector<std::string> vDisabledAddresses)
{
nWalletDBUpdated++;
bool ret = true;
for (unsigned int i = 0; i < vDisabledAddresses.size(); i++) {
if (!Write(std::make_pair(std::string("mdisabled"), i), vDisabledAddresses[i]))
ret = false;
}
return ret;
}
//presstab HyperStake
bool CWalletDB::EraseMSDisabledAddresses(std::vector<std::string> vDisabledAddresses)
{
nWalletDBUpdated++;
bool ret = true;
for (unsigned int i = 0; i < vDisabledAddresses.size(); i++) {
if (!Erase(std::make_pair(std::string("mdisabled"), i)))
ret = false;
}
return ret;
}
bool CWalletDB::WriteAutoCombineSettings(bool fEnable, CAmount nCombineThreshold)
{
nWalletDBUpdated++;
std::pair<bool, CAmount> pSettings;
pSettings.first = fEnable;
pSettings.second = nCombineThreshold;
return Write(std::string("autocombinesettings"), pSettings, true);
}
bool CWalletDB::WriteDefaultKey(const CPubKey& vchPubKey)
{
nWalletDBUpdated++;
return Write(std::string("defaultkey"), vchPubKey);
}
bool CWalletDB::ReadPool(int64_t nPool, CKeyPool& keypool)
{
return Read(std::make_pair(std::string("pool"), nPool), keypool);
}
bool CWalletDB::WritePool(int64_t nPool, const CKeyPool& keypool)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("pool"), nPool), keypool);
}
bool CWalletDB::ErasePool(int64_t nPool)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("pool"), nPool));
}
bool CWalletDB::WriteMinVersion(int nVersion)
{
return Write(std::string("minversion"), nVersion);
}
bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
{
account.SetNull();
return Read(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
{
return Write(make_pair(string("acc"), strAccount), account);
}
bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry)
{
return Write(std::make_pair(std::string("acentry"), std::make_pair(acentry.strAccount, nAccEntryNum)), acentry);
}
bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
{
return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
}
CAmount CWalletDB::GetAccountCreditDebit(const string& strAccount)
{
list<CAccountingEntry> entries;
ListAccountCreditDebit(strAccount, entries);
CAmount nCreditDebit = 0;
BOOST_FOREACH (const CAccountingEntry& entry, entries)
nCreditDebit += entry.nCreditDebit;
return nCreditDebit;
}
void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
{
bool fAllAccounts = (strAccount == "*");
Dbc* pcursor = GetCursor();
if (!pcursor)
throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
unsigned int fFlags = DB_SET_RANGE;
while (true) {
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << std::make_pair(std::string("acentry"), std::make_pair((fAllAccounts ? string("") : strAccount), uint64_t(0)));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
if (ret == DB_NOTFOUND)
break;
else if (ret != 0) {
pcursor->close();
throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
}
// Unserialize
string strType;
ssKey >> strType;
if (strType != "acentry")
break;
CAccountingEntry acentry;
ssKey >> acentry.strAccount;
if (!fAllAccounts && acentry.strAccount != strAccount)
break;
ssValue >> acentry;
ssKey >> acentry.nEntryNo;
entries.push_back(acentry);
}
pcursor->close();
}
DBErrors CWalletDB::ReorderTransactions(CWallet* pwallet)
{
LOCK(pwallet->cs_wallet);
// Old wallets didn't have any defined order for transactions
// Probably a bad idea to change the output of this
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef multimap<int64_t, TxPair> TxItems;
TxItems txByTime;
for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it) {
CWalletTx* wtx = &((*it).second);
txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
}
list<CAccountingEntry> acentries;
ListAccountCreditDebit("", acentries);
BOOST_FOREACH (CAccountingEntry& entry, acentries) {
txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
}
int64_t& nOrderPosNext = pwallet->nOrderPosNext;
nOrderPosNext = 0;
std::vector<int64_t> nOrderPosOffsets;
for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it) {
CWalletTx* const pwtx = (*it).second.first;
CAccountingEntry* const pacentry = (*it).second.second;
int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
if (nOrderPos == -1) {
nOrderPos = nOrderPosNext++;
nOrderPosOffsets.push_back(nOrderPos);
if (pwtx) {
if (!WriteTx(pwtx->GetHash(), *pwtx))
return DB_LOAD_FAIL;
} else if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
} else {
int64_t nOrderPosOff = 0;
BOOST_FOREACH (const int64_t& nOffsetStart, nOrderPosOffsets) {
if (nOrderPos >= nOffsetStart)
++nOrderPosOff;
}
nOrderPos += nOrderPosOff;
nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
if (!nOrderPosOff)
continue;
// Since we're changing the order, write it back
if (pwtx) {
if (!WriteTx(pwtx->GetHash(), *pwtx))
return DB_LOAD_FAIL;
} else if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
}
WriteOrderPosNext(nOrderPosNext);
return DB_LOAD_OK;
}
class CWalletScanState
{
public:
unsigned int nKeys;
unsigned int nCKeys;
unsigned int nKeyMeta;
bool fIsEncrypted;
bool fAnyUnordered;
int nFileVersion;
vector<uint256> vWalletUpgrade;
CWalletScanState()
{
nKeys = nCKeys = nKeyMeta = 0;
fIsEncrypted = false;
fAnyUnordered = false;
nFileVersion = 0;
}
};
bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, CWalletScanState& wss, string& strType, string& strErr)
{
try {
// Unserialize
// Taking advantage of the fact that pair serialization
// is just the two items serialized one after the other
ssKey >> strType;
if (strType == "name") {
string strAddress;
ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()].name;
} else if (strType == "purpose") {
string strAddress;
ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()].purpose;
} else if (strType == "tx") {
uint256 hash;
ssKey >> hash;
CWalletTx wtx;
ssValue >> wtx;
CValidationState state;
// false because there is no reason to go through the zerocoin checks for our own wallet
if (!(CheckTransaction(wtx, false, false, state) && (wtx.GetHash() == hash) && state.IsValid()))
return false;
// Undo serialize changes in 31600
if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703) {
if (!ssValue.empty()) {
char fTmp;
char fUnused;
ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s",
wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount, hash.ToString());
wtx.fTimeReceivedIsTxTime = fTmp;
} else {
strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString());
wtx.fTimeReceivedIsTxTime = 0;
}
wss.vWalletUpgrade.push_back(hash);
}
if (wtx.nOrderPos == -1)
wss.fAnyUnordered = true;
pwallet->AddToWallet(wtx, true);
} else if (strType == "acentry") {
string strAccount;
ssKey >> strAccount;
uint64_t nNumber;
ssKey >> nNumber;
if (nNumber > nAccountingEntryNumber)
nAccountingEntryNumber = nNumber;
if (!wss.fAnyUnordered) {
CAccountingEntry acentry;
ssValue >> acentry;
if (acentry.nOrderPos == -1)
wss.fAnyUnordered = true;
}
} else if (strType == "watchs") {
CScript script;
ssKey >> script;
char fYes;
ssValue >> fYes;
if (fYes == '1')
pwallet->LoadWatchOnly(script);
// Watch-only addresses have no birthday information for now,
// so set the wallet birthday to the beginning of time.
pwallet->nTimeFirstKey = 1;
} else if (strType == "multisig") {
CScript script;
ssKey >> script;
char fYes;
ssValue >> fYes;
if (fYes == '1')
pwallet->LoadMultiSig(script);
// MultiSig addresses have no birthday information for now,
// so set the wallet birthday to the beginning of time.
pwallet->nTimeFirstKey = 1;
} else if (strType == "key" || strType == "wkey") {
CPubKey vchPubKey;
ssKey >> vchPubKey;
if (!vchPubKey.IsValid()) {
strErr = "Error reading wallet database: CPubKey corrupt";
return false;
}
CKey key;
CPrivKey pkey;
uint256 hash = 0;
if (strType == "key") {
wss.nKeys++;
ssValue >> pkey;
} else {
CWalletKey wkey;
ssValue >> wkey;
pkey = wkey.vchPrivKey;
}
// Old wallets store keys as "key" [pubkey] => [privkey]
// ... which was slow for wallets with lots of keys, because the public key is re-derived from the private key
// using EC operations as a checksum.
// Newer wallets store keys as "key"[pubkey] => [privkey][hash(pubkey,privkey)], which is much faster while
// remaining backwards-compatible.
try {
ssValue >> hash;
} catch (...) {
}
bool fSkipCheck = false;
if (hash != 0) {
// hash pubkey/privkey to accelerate wallet load
std::vector<unsigned char> vchKey;
vchKey.reserve(vchPubKey.size() + pkey.size());
vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
vchKey.insert(vchKey.end(), pkey.begin(), pkey.end());
if (Hash(vchKey.begin(), vchKey.end()) != hash) {
strErr = "Error reading wallet database: CPubKey/CPrivKey corrupt";
return false;
}
fSkipCheck = true;
}
if (!key.Load(pkey, vchPubKey, fSkipCheck)) {
strErr = "Error reading wallet database: CPrivKey corrupt";
return false;
}
if (!pwallet->LoadKey(key, vchPubKey)) {
strErr = "Error reading wallet database: LoadKey failed";
return false;
}
} else if (strType == "mkey") {
unsigned int nID;
ssKey >> nID;
CMasterKey kMasterKey;
ssValue >> kMasterKey;
if (pwallet->mapMasterKeys.count(nID) != 0) {
strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
return false;
}
pwallet->mapMasterKeys[nID] = kMasterKey;
if (pwallet->nMasterKeyMaxID < nID)
pwallet->nMasterKeyMaxID = nID;
} else if (strType == "ckey") {
vector<unsigned char> vchPubKey;
ssKey >> vchPubKey;
vector<unsigned char> vchPrivKey;
ssValue >> vchPrivKey;
wss.nCKeys++;
if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey)) {
strErr = "Error reading wallet database: LoadCryptedKey failed";
return false;
}
wss.fIsEncrypted = true;
} else if (strType == "keymeta") {
CPubKey vchPubKey;
ssKey >> vchPubKey;
CKeyMetadata keyMeta;
ssValue >> keyMeta;
wss.nKeyMeta++;
pwallet->LoadKeyMetadata(vchPubKey, keyMeta);
// find earliest key creation time, as wallet birthday
if (!pwallet->nTimeFirstKey ||
(keyMeta.nCreateTime < pwallet->nTimeFirstKey))
pwallet->nTimeFirstKey = keyMeta.nCreateTime;
} else if (strType == "defaultkey") {
ssValue >> pwallet->vchDefaultKey;
} else if (strType == "pool") {
int64_t nIndex;
ssKey >> nIndex;
CKeyPool keypool;
ssValue >> keypool;
pwallet->setKeyPool.insert(nIndex);
// If no metadata exists yet, create a default with the pool key's
// creation time. Note that this may be overwritten by actually
// stored metadata for that key later, which is fine.
CKeyID keyid = keypool.vchPubKey.GetID();
if (pwallet->mapKeyMetadata.count(keyid) == 0)
pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
} else if (strType == "version") {
ssValue >> wss.nFileVersion;
if (wss.nFileVersion == 10300)
wss.nFileVersion = 300;
} else if (strType == "cscript") {
uint160 hash;
ssKey >> hash;
CScript script;
ssValue >> script;
if (!pwallet->LoadCScript(script)) {
strErr = "Error reading wallet database: LoadCScript failed";
return false;
}
} else if (strType == "orderposnext") {
ssValue >> pwallet->nOrderPosNext;
} else if (strType == "stakeSplitThreshold") //presstab HyperStake
{
ssValue >> pwallet->nStakeSplitThreshold;
} else if (strType == "multisend") //presstab HyperStake
{
unsigned int i;
ssKey >> i;
std::pair<std::string, int> pMultiSend;
ssValue >> pMultiSend;
if (CBitcoinAddress(pMultiSend.first).IsValid()) {
pwallet->vMultiSend.push_back(pMultiSend);
}
} else if (strType == "msettingsv2") //presstab HyperStake
{
std::pair<std::pair<bool, bool>, int> pSettings;
ssValue >> pSettings;
pwallet->fMultiSendStake = pSettings.first.first;
pwallet->fMultiSendMasternodeReward = pSettings.first.second;
pwallet->nLastMultiSendHeight = pSettings.second;
} else if (strType == "mdisabled") //presstab HyperStake
{
std::string strDisabledAddress;
ssValue >> strDisabledAddress;
pwallet->vDisabledAddresses.push_back(strDisabledAddress);
} else if (strType == "autocombinesettings") {
std::pair<bool, CAmount> pSettings;
ssValue >> pSettings;
pwallet->fCombineDust = pSettings.first;
pwallet->nAutoCombineThreshold = pSettings.second;
} else if (strType == "destdata") {
std::string strAddress, strKey, strValue;
ssKey >> strAddress;
ssKey >> strKey;
ssValue >> strValue;
if (!pwallet->LoadDestData(CBitcoinAddress(strAddress).Get(), strKey, strValue)) {
strErr = "Error reading wallet database: LoadDestData failed";
return false;
}
}
} catch (...) {
return false;
}
return true;
}
static bool IsKeyType(string strType)
{
return (strType == "key" || strType == "wkey" ||
strType == "mkey" || strType == "ckey");
}
DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
{
pwallet->vchDefaultKey = CPubKey();
CWalletScanState wss;
bool fNoncriticalErrors = false;
DBErrors result = DB_LOAD_OK;
try {
LOCK(pwallet->cs_wallet);
int nMinVersion = 0;
if (Read((string) "minversion", nMinVersion)) {
if (nMinVersion > CLIENT_VERSION)
return DB_TOO_NEW;
pwallet->LoadMinVersion(nMinVersion);
}
// Get cursor
Dbc* pcursor = GetCursor();
if (!pcursor) {
LogPrintf("Error getting wallet database cursor\n");
return DB_CORRUPT;
}
while (true) {
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue);
if (ret == DB_NOTFOUND)
break;
else if (ret != 0) {
LogPrintf("Error reading next record from wallet database\n");
return DB_CORRUPT;
}
// Try to be tolerant of single corrupt records:
string strType, strErr;
if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr)) {
// losing keys is considered a catastrophic error, anything else
// we assume the user can live with:
if (IsKeyType(strType))
result = DB_CORRUPT;
else {
// Leave other errors alone, if we try to fix them we might make things worse.
fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
if (strType == "tx")
// Rescan if there is a bad transaction record:
SoftSetBoolArg("-rescan", true);
}
}
if (!strErr.empty())
LogPrintf("%s\n", strErr);
}
pcursor->close();
} catch (boost::thread_interrupted) {
throw;
} catch (...) {
result = DB_CORRUPT;
}
if (fNoncriticalErrors && result == DB_LOAD_OK)
result = DB_NONCRITICAL_ERROR;
// Any wallet corruption at all: skip any rewriting or
// upgrading, we don't want to make it worse.
if (result != DB_LOAD_OK)
return result;
LogPrintf("nFileVersion = %d\n", wss.nFileVersion);
LogPrintf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n",
wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys);
// nTimeFirstKey is only reliable if all keys have metadata
if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta)
pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value'
BOOST_FOREACH (uint256 hash, wss.vWalletUpgrade)
WriteTx(hash, pwallet->mapWallet[hash]);
// Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000))
return DB_NEED_REWRITE;
if (wss.nFileVersion < CLIENT_VERSION) // Update
WriteVersion(CLIENT_VERSION);
if (wss.fAnyUnordered)
result = ReorderTransactions(pwallet);
return result;
}
DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector<uint256>& vTxHash, vector<CWalletTx>& vWtx)
{
pwallet->vchDefaultKey = CPubKey();
bool fNoncriticalErrors = false;
DBErrors result = DB_LOAD_OK;
try {
LOCK(pwallet->cs_wallet);
int nMinVersion = 0;
if (Read((string) "minversion", nMinVersion)) {
if (nMinVersion > CLIENT_VERSION)
return DB_TOO_NEW;
pwallet->LoadMinVersion(nMinVersion);
}
// Get cursor
Dbc* pcursor = GetCursor();
if (!pcursor) {
LogPrintf("Error getting wallet database cursor\n");
return DB_CORRUPT;
}
while (true) {
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue);
if (ret == DB_NOTFOUND)
break;
else if (ret != 0) {
LogPrintf("Error reading next record from wallet database\n");
return DB_CORRUPT;
}
string strType;
ssKey >> strType;
if (strType == "tx") {
uint256 hash;
ssKey >> hash;
CWalletTx wtx;
ssValue >> wtx;
vTxHash.push_back(hash);
vWtx.push_back(wtx);
}
}
pcursor->close();
} catch (boost::thread_interrupted) {
throw;
} catch (...) {
result = DB_CORRUPT;
}
if (fNoncriticalErrors && result == DB_LOAD_OK)
result = DB_NONCRITICAL_ERROR;
return result;
}
DBErrors CWalletDB::ZapWalletTx(CWallet* pwallet, vector<CWalletTx>& vWtx)
{
// build list of wallet TXs
vector<uint256> vTxHash;
DBErrors err = FindWalletTx(pwallet, vTxHash, vWtx);
if (err != DB_LOAD_OK)
return err;
// erase each wallet TX
BOOST_FOREACH (uint256& hash, vTxHash) {
if (!EraseTx(hash))
return DB_CORRUPT;
}
return DB_LOAD_OK;
}
void ThreadFlushWalletDB(const string& strFile)
{
// Make this thread recognisable as the wallet flushing thread
RenameThread("slashdash-wallet");
static bool fOneThread;
if (fOneThread)
return;
fOneThread = true;
if (!GetBoolArg("-flushwallet", true))
return;
unsigned int nLastSeen = nWalletDBUpdated;
unsigned int nLastFlushed = nWalletDBUpdated;
int64_t nLastWalletUpdate = GetTime();
while (true) {
MilliSleep(500);
if (nLastSeen != nWalletDBUpdated) {
nLastSeen = nWalletDBUpdated;
nLastWalletUpdate = GetTime();
}
if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2) {
TRY_LOCK(bitdb.cs_db, lockDb);
if (lockDb) {
// Don't do this if any databases are in use
int nRefCount = 0;
map<string, int>::iterator mi = bitdb.mapFileUseCount.begin();
while (mi != bitdb.mapFileUseCount.end()) {
nRefCount += (*mi).second;
mi++;
}
if (nRefCount == 0) {
boost::this_thread::interruption_point();
map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
if (mi != bitdb.mapFileUseCount.end()) {
LogPrint("db", "Flushing wallet.dat\n");
nLastFlushed = nWalletDBUpdated;
int64_t nStart = GetTimeMillis();
// Flush wallet.dat so it's self contained
bitdb.CloseDb(strFile);
bitdb.CheckpointLSN(strFile);
bitdb.mapFileUseCount.erase(mi++);
LogPrint("db", "Flushed wallet.dat %dms\n", GetTimeMillis() - nStart);
}
}
}
}
}
}
bool BackupWallet(const CWallet& wallet, const string& strDest)
{
if (!wallet.fFileBacked)
return false;
while (true) {
{
LOCK(bitdb.cs_db);
if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0) {
// Flush log data to the dat file
bitdb.CloseDb(wallet.strWalletFile);
bitdb.CheckpointLSN(wallet.strWalletFile);
bitdb.mapFileUseCount.erase(wallet.strWalletFile);
// Copy wallet.dat
filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
filesystem::path pathDest(strDest);
if (filesystem::is_directory(pathDest))
pathDest /= wallet.strWalletFile;
try {
#if BOOST_VERSION >= 158000
filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
#else
std::ifstream src(pathSrc.string(), std::ios::binary);
std::ofstream dst(pathDest.string(), std::ios::binary);
dst << src.rdbuf();
#endif
LogPrintf("copied wallet.dat to %s\n", pathDest.string());
return true;
} catch (const filesystem::filesystem_error& e) {
LogPrintf("error copying wallet.dat to %s - %s\n", pathDest.string(), e.what());
return false;
}
}
}
MilliSleep(100);
}
return false;
}
//
// Try to (very carefully!) recover wallet.dat if there is a problem.
//
bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
{
// Recovery procedure:
// move wallet.dat to wallet.timestamp.bak
// Call Salvage with fAggressive=true to
// get as much data as possible.
// Rewrite salvaged data to wallet.dat
// Set -rescan so any missing transactions will be
// found.
int64_t now = GetTime();
std::string newFilename = strprintf("wallet.%d.bak", now);
int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
newFilename.c_str(), DB_AUTO_COMMIT);
if (result == 0)
LogPrintf("Renamed %s to %s\n", filename, newFilename);
else {
LogPrintf("Failed to rename %s to %s\n", filename, newFilename);
return false;
}
std::vector<CDBEnv::KeyValPair> salvagedData;
bool allOK = dbenv.Salvage(newFilename, true, salvagedData);
if (salvagedData.empty()) {
LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename);
return false;
}
LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size());
bool fSuccess = allOK;
boost::scoped_ptr<Db> pdbCopy(new Db(&dbenv.dbenv, 0));
int ret = pdbCopy->open(NULL, // Txn pointer
filename.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0) {
LogPrintf("Cannot create database file %s\n", filename);
return false;
}
CWallet dummyWallet;
CWalletScanState wss;
DbTxn* ptxn = dbenv.TxnBegin();
BOOST_FOREACH (CDBEnv::KeyValPair& row, salvagedData) {
if (fOnlyKeys) {
CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
string strType, strErr;
bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue,
wss, strType, strErr);
if (!IsKeyType(strType))
continue;
if (!fReadOK) {
LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType, strErr);
continue;
}
}
Dbt datKey(&row.first[0], row.first.size());
Dbt datValue(&row.second[0], row.second.size());
int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
ptxn->commit(0);
pdbCopy->close(0);
return fSuccess;
}
bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename)
{
return CWalletDB::Recover(dbenv, filename, false);
}
bool CWalletDB::WriteDestData(const std::string& address, const std::string& key, const std::string& value)
{
nWalletDBUpdated++;
return Write(std::make_pair(std::string("destdata"), std::make_pair(address, key)), value);
}
bool CWalletDB::EraseDestData(const std::string& address, const std::string& key)
{
nWalletDBUpdated++;
return Erase(std::make_pair(std::string("destdata"), std::make_pair(address, key)));
}
bool CWalletDB::WriteZerocoinSpendSerialEntry(const CZerocoinSpend& zerocoinSpend)
{
return Write(make_pair(string("zcserial"), zerocoinSpend.GetSerial()), zerocoinSpend, true);
}
bool CWalletDB::EraseZerocoinSpendSerialEntry(const CBigNum& serialEntry)
{
return Erase(make_pair(string("zcserial"), serialEntry));
}
bool CWalletDB::ReadZerocoinSpendSerialEntry(const CBigNum& bnSerial)
{
CZerocoinSpend spend;
return Read(make_pair(string("zcserial"), bnSerial), spend);
}
bool CWalletDB::WriteZerocoinMint(const CZerocoinMint& zerocoinMint)
{
CDataStream ss(SER_GETHASH, 0);
ss << zerocoinMint.GetValue();
uint256 hash = Hash(ss.begin(), ss.end());
Erase(make_pair(string("zerocoin"), hash));
return Write(make_pair(string("zerocoin"), hash), zerocoinMint, true);
}
bool CWalletDB::ReadZerocoinMint(const CBigNum &bnPubCoinValue, CZerocoinMint& zerocoinMint)
{
CDataStream ss(SER_GETHASH, 0);
ss << bnPubCoinValue;
uint256 hash = Hash(ss.begin(), ss.end());
return Read(make_pair(string("zerocoin"), hash), zerocoinMint);
}
bool CWalletDB::EraseZerocoinMint(const CZerocoinMint& zerocoinMint)
{
CDataStream ss(SER_GETHASH, 0);
ss << zerocoinMint.GetValue();
uint256 hash = Hash(ss.begin(), ss.end());
return Erase(make_pair(string("zerocoin"), hash));
}
bool CWalletDB::ArchiveMintOrphan(const CZerocoinMint& zerocoinMint)
{
CDataStream ss(SER_GETHASH, 0);
ss << zerocoinMint.GetValue();
uint256 hash = Hash(ss.begin(), ss.end());;
if (!Write(make_pair(string("zco"), hash), zerocoinMint)) {
LogPrintf("%s : failed to database orphaned zerocoin mint\n", __func__);
return false;
}
if (!Erase(make_pair(string("zerocoin"), hash))) {
LogPrintf("%s : failed to erase orphaned zerocoin mint\n", __func__);
return false;
}
return true;
}
bool CWalletDB::UnarchiveZerocoin(const CZerocoinMint& mint)
{
CDataStream ss(SER_GETHASH, 0);
ss << mint.GetValue();
uint256 hash = Hash(ss.begin(), ss.end());;
if (!Erase(make_pair(string("zco"), hash))) {
LogPrintf("%s : failed to erase archived zerocoin mint\n", __func__);
return false;
}
return WriteZerocoinMint(mint);
}
std::list<CZerocoinMint> CWalletDB::ListMintedCoins(bool fUnusedOnly, bool fMaturedOnly, bool fUpdateStatus)
{
std::list<CZerocoinMint> listPubCoin;
Dbc* pcursor = GetCursor();
if (!pcursor)
throw runtime_error(std::string(__func__)+" : cannot create DB cursor");
unsigned int fFlags = DB_SET_RANGE;
vector<CZerocoinMint> vOverWrite;
vector<CZerocoinMint> vArchive;
for (;;)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << make_pair(string("zerocoin"), uint256(0));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
pcursor->close();
throw runtime_error(std::string(__func__)+" : error scanning DB");
}
// Unserialize
string strType;
ssKey >> strType;
if (strType != "zerocoin")
break;
uint256 value;
ssKey >> value;
CZerocoinMint mint;
ssValue >> mint;
if (fUnusedOnly) {
if (mint.IsUsed())
continue;
//double check that we have no record of this serial being used
if (ReadZerocoinSpendSerialEntry(mint.GetSerialNumber())) {
mint.SetUsed(true);
vOverWrite.emplace_back(mint);
continue;
}
}
if (fMaturedOnly || fUpdateStatus) {
//if there is not a record of the block height, then look it up and assign it
if (!mint.GetHeight()) {
CTransaction tx;
uint256 hashBlock;
if(!GetTransaction(mint.GetTxHash(), tx, hashBlock, true)) {
LogPrintf("%s failed to find tx for mint txid=%s\n", __func__, mint.GetTxHash().GetHex());
vArchive.emplace_back(mint);
continue;
}
//if not in the block index, most likely is unconfirmed tx
if (mapBlockIndex.count(hashBlock)) {
mint.SetHeight(mapBlockIndex[hashBlock]->nHeight);
vOverWrite.emplace_back(mint);
} else if (fMaturedOnly){
continue;
}
}
//not mature
if (mint.GetHeight() > chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations()) {
if (!fMaturedOnly)
listPubCoin.emplace_back(mint);
continue;
}
//if only requesting an update (fUpdateStatus) then skip the rest and add to list
if (fMaturedOnly) {
// check to make sure there are at least 3 other mints added to the accumulators after this
if (chainActive.Height() < mint.GetHeight() + 1)
continue;
CBlockIndex *pindex = chainActive[mint.GetHeight() + 1];
int nMintsAdded = 0;
while(pindex->nHeight < chainActive.Height() - 30) { // 30 just to make sure that its at least 2 checkpoints from the top block
nMintsAdded += count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), mint.GetDenomination());
if(nMintsAdded >= Params().Zerocoin_RequiredAccumulation())
break;
pindex = chainActive[pindex->nHeight + 1];
}
if(nMintsAdded < Params().Zerocoin_RequiredAccumulation())
continue;
}
}
listPubCoin.emplace_back(mint);
}
pcursor->close();
//overwrite any updates
for (CZerocoinMint mint : vOverWrite) {
if(!this->WriteZerocoinMint(mint))
LogPrintf("%s failed to update mint from tx %s\n", __func__, mint.GetTxHash().GetHex());
}
// archive mints
for (CZerocoinMint mint : vArchive) {
if (!this->ArchiveMintOrphan(mint))
LogPrintf("%s failed to archive mint from %s\n", __func__, mint.GetTxHash().GetHex());
}
return listPubCoin;
}
// Just get the Serial Numbers
std::list<CBigNum> CWalletDB::ListMintedCoinsSerial()
{
std::list<CBigNum> listPubCoin;
std::list<CZerocoinMint> listCoins = ListMintedCoins(true, false, false);
for ( auto& coin : listCoins) {
listPubCoin.push_back(coin.GetSerialNumber());
}
return listPubCoin;
}
std::list<CZerocoinSpend> CWalletDB::ListSpentCoins()
{
std::list<CZerocoinSpend> listCoinSpend;
Dbc* pcursor = GetCursor();
if (!pcursor)
throw runtime_error(std::string(__func__)+" : cannot create DB cursor");
unsigned int fFlags = DB_SET_RANGE;
for (;;)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << make_pair(string("zcserial"), CBigNum(0));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
pcursor->close();
throw runtime_error(std::string(__func__)+" : error scanning DB");
}
// Unserialize
string strType;
ssKey >> strType;
if (strType != "zcserial")
break;
CBigNum value;
ssKey >> value;
CZerocoinSpend zerocoinSpendItem;
ssValue >> zerocoinSpendItem;
listCoinSpend.push_back(zerocoinSpendItem);
}
pcursor->close();
return listCoinSpend;
}
// Just get the Serial Numbers
std::list<CBigNum> CWalletDB::ListSpentCoinsSerial()
{
std::list<CBigNum> listPubCoin;
std::list<CZerocoinSpend> listCoins = ListSpentCoins();
for ( auto& coin : listCoins) {
listPubCoin.push_back(coin.GetSerial());
}
return listPubCoin;
}
std::list<CZerocoinMint> CWalletDB::ListArchivedZerocoins()
{
std::list<CZerocoinMint> listMints;
Dbc* pcursor = GetCursor();
if (!pcursor)
throw runtime_error(std::string(__func__)+" : cannot create DB cursor");
unsigned int fFlags = DB_SET_RANGE;
for (;;)
{
// Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (fFlags == DB_SET_RANGE)
ssKey << make_pair(string("zco"), CBigNum(0));
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
fFlags = DB_NEXT;
if (ret == DB_NOTFOUND)
break;
else if (ret != 0)
{
pcursor->close();
throw runtime_error(std::string(__func__)+" : error scanning DB");
}
// Unserialize
string strType;
ssKey >> strType;
if (strType != "zco")
break;
uint256 value;
ssKey >> value;
CZerocoinMint mint;
ssValue >> mint;
listMints.push_back(mint);
}
pcursor->close();
return listMints;
}
| [
"feltersnatch@protonmail.com"
] | feltersnatch@protonmail.com |
a065291a0ff673b7e4e5ccc962a6a6a6d157b319 | 1bc0394f21b0085e23fc9f1975792db4e96d6761 | /src/milkshapemodel.cpp | db0391282c5bbd6861856f8ae9b290adbc72f445 | [] | no_license | davidsansome/baarbarity | e503ee1c1e8b605c59c1da6c3add4f481637813d | 97c80c6cdb9ad231384b624570c82f4d39f77134 | refs/heads/master | 2016-08-07T07:30:06.250430 | 2015-08-01T07:39:19 | 2015-08-01T07:39:19 | 32,302,681 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,898 | cpp | /***************************************************************************
* 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. *
***************************************************************************/
#include "milkshapemodel.h"
#include <QFile>
#include <QDataStream>
#include <QDebug>
#include <math.h>
#ifdef Q_OS_DARWIN
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
MilkshapeModel::MilkshapeModel(const QString& fileName)
: Model(),
m_dirty(true),
m_boundingBoxDirty(true)
{
QFile file(fileName);
file.open(QIODevice::ReadOnly);
QDataStream stream(&file);
stream.setByteOrder(QDataStream::LittleEndian);
stream.setVersion(QDataStream::Qt_4_2);
// Skip header
stream.skipRawData(14);
// Read vertices
quint16 vertexCount;
stream >> vertexCount;
for (int i=0 ; i<vertexCount ; ++i)
{
MS3DVertex vertex;
stream >> vertex.flags;
stream >> vertex.vertex[0] >> vertex.vertex[1] >> vertex.vertex[2];
stream >> vertex.boneId;
stream >> vertex.referenceCount;
m_vertices << vertex;
}
// Read triangles
unsigned short triangleCount;
stream >> triangleCount;
for (int i=0 ; i<triangleCount ; ++i)
{
MS3DTriangle triangle;
stream >> triangle.flags;
stream >> triangle.vertexIndices[0] >> triangle.vertexIndices[1] >> triangle.vertexIndices[2];
stream >> triangle.vertexNormals[0][0] >> triangle.vertexNormals[0][1] >> triangle.vertexNormals[0][2];
stream >> triangle.vertexNormals[1][0] >> triangle.vertexNormals[1][1] >> triangle.vertexNormals[1][2];
stream >> triangle.vertexNormals[2][0] >> triangle.vertexNormals[2][1] >> triangle.vertexNormals[2][2];
stream >> triangle.s[0] >> triangle.s[1] >> triangle.s[2];
stream >> triangle.t[0] >> triangle.t[1] >> triangle.t[2];
stream >> triangle.smoothingGroup;
stream >> triangle.groupIndex;
m_triangles << triangle;
}
// Calculate bounds
m_limits[0][0] = HUGE_VAL;
m_limits[0][1] = -HUGE_VAL;
m_limits[1][0] = HUGE_VAL;
m_limits[1][1] = -HUGE_VAL;
m_limits[2][0] = HUGE_VAL;
m_limits[2][1] = -HUGE_VAL;
m_boundingSphereRadius = 0.0f;
for (int i=0 ; i<m_vertices.count() ; ++i)
{
float radialDistance = 0.0f;
for (int v=0 ; v<3 ; ++v)
{
if (m_vertices[i].vertex[v] < m_limits[v][0])
m_limits[v][0] = m_vertices[i].vertex[v];
if (m_vertices[i].vertex[v] > m_limits[v][1])
m_limits[v][1] = m_vertices[i].vertex[v];
radialDistance += m_vertices[i].vertex[v] * m_vertices[i].vertex[v];
}
radialDistance = sqrt(radialDistance);
if (radialDistance > m_boundingSphereRadius)
m_boundingSphereRadius = radialDistance;
}
}
void MilkshapeModel::renderTriangle(int i)
{
MS3DTriangle triangle = m_triangles[i];
for (int v=0 ; v<3 ; ++v)
{
MS3DVertex vertex = m_vertices[triangle.vertexIndices[v]];
glNormal3f(triangle.vertexNormals[v][0], triangle.vertexNormals[v][1], triangle.vertexNormals[v][2]);
//glColor3f(1.0f, 1.0f, 1.0f);
glVertex3f(vertex.vertex[0], vertex.vertex[1], vertex.vertex[2]);
}
}
void MilkshapeModel::draw()
{
if (!m_dirty)
glCallList(m_displayList);
else
{
m_displayList = glGenLists(1);
m_dirty = false;
glNewList(m_displayList, GL_COMPILE_AND_EXECUTE);
glBegin(GL_TRIANGLES);
for (int i=0 ; i<m_triangles.count() ; ++i)
renderTriangle(i);
glEnd();
glEndList();
}
}
void MilkshapeModel::drawBoundingBox()
{
glPushMatrix();
if (!m_boundingBoxDirty)
glCallList(m_boundingBoxDisplayList);
else
{
m_boundingBoxDisplayList = glGenLists(1);
m_boundingBoxDirty = false;
glNewList(m_boundingBoxDisplayList, GL_COMPILE_AND_EXECUTE);
glBegin(GL_QUAD_STRIP);
glVertex3f(m_limits[0][1], m_limits[1][1], m_limits[2][1]);
glVertex3f(m_limits[0][0], m_limits[1][1], m_limits[2][1]);
glVertex3f(m_limits[0][1], m_limits[1][1], m_limits[2][0]);
glVertex3f(m_limits[0][0], m_limits[1][1], m_limits[2][0]);
glVertex3f(m_limits[0][1], m_limits[1][0], m_limits[2][0]);
glVertex3f(m_limits[0][0], m_limits[1][0], m_limits[2][0]);
glVertex3f(m_limits[0][1], m_limits[1][0], m_limits[2][1]);
glVertex3f(m_limits[0][0], m_limits[1][0], m_limits[2][1]);
glVertex3f(m_limits[0][1], m_limits[1][1], m_limits[2][1]);
glVertex3f(m_limits[0][0], m_limits[1][1], m_limits[2][1]);
glEnd();
glBegin(GL_QUADS);
glVertex3f(m_limits[0][0], m_limits[1][1], m_limits[2][1]);
glVertex3f(m_limits[0][0], m_limits[1][1], m_limits[2][0]);
glVertex3f(m_limits[0][0], m_limits[1][0], m_limits[2][0]);
glVertex3f(m_limits[0][0], m_limits[1][0], m_limits[2][1]);
glVertex3f(m_limits[0][1], m_limits[1][1], m_limits[2][1]);
glVertex3f(m_limits[0][1], m_limits[1][1], m_limits[2][0]);
glVertex3f(m_limits[0][1], m_limits[1][0], m_limits[2][0]);
glVertex3f(m_limits[0][1], m_limits[1][0], m_limits[2][1]);
glEnd();
glEndList();
}
glPopMatrix();
}
| [
"me@davidsansome.com"
] | me@davidsansome.com |
b74aa16163e65fb43e022942dc765288913cb723 | ffa427f7667d7fc05c4e872966cbb272242d3c19 | /abc/200/220/abc226/f/main.cpp | 8e129c0383d5c658ba455c228a9b9e2a27f6c911 | [] | no_license | kubonits/atcoder | 10fb6c9477c9b5ff7f963224a2c851aaf10b4b65 | 5aa001aab4aaabdac2de8c1abd624e3d1c08d3e3 | refs/heads/master | 2022-10-02T06:42:32.535800 | 2022-08-29T15:44:55 | 2022-08-29T15:44:55 | 160,827,483 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,040 | cpp | #include <algorithm>
#include <cmath>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <utility>
#include <vector>
#define MOD 1000000007
using namespace std;
typedef long long ll;
#include <cstring>
ll kai[200001], inv[200001];
int n, k;
ll mod_pow(ll x, ll n, ll mod) {
ll res = 1;
while (n > 0) {
if (n & 1) {
res = res * x % mod;
}
x = x * x % mod;
n /= 2;
}
return res;
}
void init() {
kai[0] = 1LL;
for (ll i = 1LL; i <= 200000; i++) {
kai[i] = kai[i - 1] * i;
kai[i] %= MOD;
}
inv[200000] = mod_pow(kai[200000], MOD - 2LL, MOD);
for (ll i = 199999; i >= 0; i--) {
inv[i] = inv[i + 1] * (i + 1);
inv[i] %= MOD;
}
}
ll comb(ll r, ll c) {
ll res;
res = kai[r];
res *= inv[c];
res %= MOD;
res *= inv[r - c];
res %= MOD;
return res;
}
ll dp[51][51];
int main() {
cin >> n >> k;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
dp[i][j] = -1LL;
}
}
}
| [
"kouhei.08.10.09.s@gmail.com"
] | kouhei.08.10.09.s@gmail.com |
887e0bcf1fa60d7e6047adda0ac493c4ea05dfee | 8d2e1a022480f2f6ad62074366708690c14a36ff | /src/RtcmNode/ntripclient.hpp | 2320b0ff9760b892247e3357373d3f1595d08f67 | [
"MIT"
] | permissive | hyperspec-ai/orion-ros2-reference | 96863d601442debdbe9dc53748efb9ed088cdc84 | 78e6ae38aae02bc7e5ddf126dbf6dfe05f892db9 | refs/heads/master | 2023-03-06T10:12:10.177821 | 2020-12-22T12:09:17 | 2020-12-22T12:09:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,499 | hpp | /***
* NTRIP Client
* */
#pragma once
#include <algorithm>
#include <atomic>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <map>
#include <mutex>
#include <stdexcept>
#include <string>
#include <system_error>
#include <thread>
#include <vector>
#include "base64/base64.h"
#include "ntripcallback.hpp"
#include "rclcpp/rclcpp.hpp"
#include "socket.hpp"
namespace ntrip
{
/*! Response structure for reading data from the http connection*/
struct Response final
{
/*Status Codes from http*/
enum Status
{
STATUS_CONTINUE = 100,
STATUS_SWITCHINGPROTOCOLS = 101,
STATUS_PROCESSING = 102,
STATUS_EARLYHINTS = 103,
STATUS_OK = 200,
STATUS_CREATED = 201,
STATUS_ACCEPTED = 202,
STATUS_NONAUTHORITATIVEINFORMATION = 203,
STATUS_NOCONTENT = 204,
STATUS_RESETCONTENT = 205,
STATUS_PARTIALCONTENT = 206,
STATUS_MULTISTATUS = 207,
STATUS_ALREADYREPORTED = 208,
STATUS_IMUSED = 226,
STATUS_MULTIPLECHOICES = 300,
STATUS_MOVEDPERMANENTLY = 301,
STATUS_FOUND = 302,
STATUS_SEEOTHER = 303,
STATUS_NOTMODIFIED = 304,
STATUS_USEPROXY = 305,
STATUS_TEMPORARYREDIRECT = 307,
STATUS_PERMANENTREDIRECT = 308,
STATUS_BADREQUEST = 400,
STATUS_UNAUTHORIZED = 401,
STATUS_PAYMENTREQUIRED = 402,
STATUS_FORBIDDEN = 403,
STATUS_NOTFOUND = 404,
STATUS_METHODNOTALLOWED = 405,
STATUS_NOTACCEPTABLE = 406,
STATUS_PROXYAUTHENTICATIONREQUIRED = 407,
STATUS_REQUESTTIMEOUT = 408,
STATUS_CONFLICT = 409,
STATUS_GONE = 410,
STATUS_LENGTHREQUIRED = 411,
STATUS_PRECONDITIONFAILED = 412,
STATUS_PAYLOADTOOLARGE = 413,
STATUS_URITOOLONG = 414,
STATUS_UNSUPPORTEDMEDIATYPE = 415,
STATUS_RANGENOTSATISFIABLE = 416,
STATUS_EXPECTATIONFAILED = 417,
STATUS_IMATEAPOT = 418,
STATUS_MISDIRECTEDREQUEST = 421,
STATUS_UNPROCESSABLEENTITY = 422,
STATUS_LOCKED = 423,
STATUS_FAILEDDEPENDENCY = 424,
STATUS_TOOEARLY = 425,
STATUS_UPGRADEREQUIRED = 426,
STATUS_PRECONDITIONREQUIRED = 428,
STATUS_TOOMANYREQUESTS = 429,
STATUS_REQUESTHEADERFIELDSTOOLARGE = 431,
STATUS_UNAVAILABLEFORLEGALREASONS = 451,
STATUS_INTERNALSERVERERROR = 500,
STATUS_NOTIMPLEMENTED = 501,
STATUS_BADGATEWAY = 502,
STATUS_SERVICEUNAVAILABLE = 503,
STATUS_GATEWAYTIMEOUT = 504,
STATUS_HTTPVERSIONNOTSUPPORTED = 505,
STATUS_VARIANTALSONEGOTIATES = 506,
STATUS_INSUFFICIENTSTORAGE = 507,
STATUS_LOOPDETECTED = 508,
STATUS_NOTEXTENDED = 510,
STATUS_NETWORKAUTHENTICATIONREQUIRED = 511
};
/*!Returned state (only valid in case of starting communication)*/
int32_t status = 0;
/*!Returned headers (only valid in case of starting communication)*/
std::vector<std::string> headers;
/*!Returned data*/
std::vector<uint8_t> body;
};
/*! Ntrip Client implementation*/
class NtripClient
{
public:
/**
* Constructor
*
* @param onst std::string& host host name or ip address
* @param uint16_t port Port
* @param const std::string& mount_point NTRIP Mountpoint
* @param NtripCallback* callback Callbacj for received RTCM sentences
* @param const std::string& user User Name for ntrip server, only base Auth is supported
* @param onst std::string& password Password for ntrip server, only base Auth is supported
*/
NtripClient(const std::string& host, uint16_t port, const std::string& mount_point,
NtripCallback* callback, const std::string& user, const std::string& password);
/**
* Shutting down ntrip server
**/
void shutdown();
/**
* Update gga NMEA sentence / position information to update VRS position
* @param std::string gga GPGGA NMEA Sentence of the current position
**/
void set_gga(std::string gga);
private:
enum recv_state_t
{
RECV_START = 0,
RECV_CONT = 1
};
enum recv_success_t
{
RECV_OK = 0,
RECV_FAILED = 1,
RECV_DISCONNECTED = 2
};
/**
* Receive Thread started by constructor and shut down with call of shutdown()
**/
void worker_thread();
/**
* Write data to socket
* @param Socket& socket Socket data to be send
* @param std::string requestData data to be send
**/
uint8_t write_to_socket(Socket& socket, std::string requestData);
/**
* Reads data from socket
* @param Socket& socket socket to read from
* @param uint8_t* state returns the staus of the reas operation
* @param recv_state_t rstate in case of RECV_START http header is read and analysed
**/
Response read_from_socket(Socket& socket, recv_success_t* state, recv_state_t rstate);
/*!GGA NMEA Sentence of current situation, initial Position is Berlin Tiergarten*/
std::string m_gga = "$GPGGA,144434.860,5230.791,N,01321.387,E,1,12,1.0,0.0,M,0.0,M,,*64\r\n";
/*Pointer to thread object for worker_thread()*/
std::thread* m_thread;
std::string m_host;
uint16_t m_port;
std::string m_auth;
std::string m_mount_point;
NtripCallback* m_callback;
std::atomic<bool> m_running;
std::mutex m_gga_mutex;
};
} // namespace ntrip | [
"marcus.von_wilamowitz-moellendorff@daimler.com"
] | marcus.von_wilamowitz-moellendorff@daimler.com |
b46329287cc696572418a7247d97f61467d7a3b9 | 00da051c69eeb22e97bf7eef3c488701a989006f | /main.cpp | e734bb76b938486f96d9898c2d809fb56382e536 | [] | no_license | RegularRabbit05/Amogus-File-Encoder | 89c46db0bdedad24018603f4ceae2966fba4b550 | aa0a966384e4cb38a439afbf050df9e780e365e2 | refs/heads/master | 2023-08-18T21:24:31.985264 | 2021-10-06T20:23:04 | 2021-10-06T20:23:04 | 408,963,819 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,915 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <bitset>
#include <sys/stat.h>
#include <fstream>
#include <ctime>
#include <algorithm>
#include <iterator>
using namespace std;
const string colors[] = {"red??", "green", "orang", "black", "pinkk", "yello", "brown", "coral"};
int RandomNumber ()
{
return rand() % (colors->size());
}
unsigned char ToByte (bool b[8])
{
unsigned char c = 0;
for (int i=0; i < 8; ++i)
if (b[i])
c |= 1 << i;
return c;
}
bool FileExists (const string& name)
{
struct stat buffer{};
return (stat (name.c_str(), &buffer) == 0);
}
void Decode (const string& file, const string& result)
{
string content;
getline(ifstream(file.c_str()), content, '\0');
content.erase(std::remove(content.begin(), content.end(), ':'), content.end());
content.erase(std::remove(content.begin(), content.end(), ';'), content.end());
cout << "Finished reading file!" << endl;
bool n = true, tmp[8];
vector<char> fileBytes(content.size()/(4+5));
char pos = 0;
size_t c = 0;
for (size_t i = 0; i < content.size(); )
{
if (n) {
i += 5;
n = false;
} else
{
string b = "";
for (int j = 0; j < 4; ++j) b += content[i+j];
if(b == "SUS!") tmp[pos] = true; else tmp[pos] = false;
pos++;
if(pos > 7)
{
fileBytes[c] = ToByte(tmp);
c++;
for (int k = 0; k < 8; k++) {
tmp[k] = false;
}
pos = 0;
}
i+=4;
n = true;
}
}
cout << "Finished decoding!" << endl;
string fileBuilder;
for (size_t i = 0; i<c; i++) fileBuilder+=(fileBytes[i]);
//ofstream(result, ios::binary).write(fileBytes, c);
std::ofstream writeFile;
writeFile.open(result, std::ios::out | std::ios::binary);
if (!fileBytes.empty())
writeFile.write(reinterpret_cast<char*>(&fileBytes[0]),
fileBytes.size() * sizeof(fileBytes[0]));
cout << "Saved file!" << endl;
return;
}
void Encode (const string& file, const string& result)
{
ifstream input(file, ios::binary);
vector<char> bytes(
(istreambuf_iterator<char>(input)),
(istreambuf_iterator<char>()));
input.close();
cout << "Finished reading file!" << endl;
string outputString = "";
for (uint32_t i = 0; i < bytes.size(); ++i)
{
bitset<8> bitset(bytes[i]);
for (int j = 0; j < 8; j++)
{
string sus = "SAFE";
if (bitset[j]) sus = "SUS!";
outputString += colors[RandomNumber()] + ":" + sus + ";";
}
}
cout << "Finished encoding! (" << bytes.size() << ")" << endl;
ofstream out(result);
out << outputString;
cout << "Saved file!" << endl;
return;
}
int main (int argc, char *argv[])
{
string prog = argv[0];
vector<string> args;
if (argc > 3)
{
if (argc > 4)
{
cout << "Too many arguments!" << endl;
return 1;
}
args.assign(argv + 1, argv + argc);
} else
{
cout << "Not enough arguments, usage: \"encode/decode [sourcefile] [destination]\"" << endl;
return 1;
}
if (!FileExists(args[1]))
{
cout << "The source file doesn't exist!" << endl;
return 1;
}
if (FileExists(args[2]))
{
cout << "The destination file exists already!" << endl;
return 1;
}
if(args[0] == "encode")
{
srand(time(NULL) * getpid());
Encode(args[1], args[2]);
} else if(args[0] == "decode")
{
Decode(args[1], args[2]);
} else
{
cout << "Unknown operation: " << args[1] << endl;
return 1;
}
return 0;
} | [
"69511985+RegularRabbit05@users.noreply.github.com"
] | 69511985+RegularRabbit05@users.noreply.github.com |
52fc23e0dfdcb327426d6e7add9eedd4d643d6ff | 377981114bfb71f26b31b00788a996d112157721 | /include/lava/core/vr-event-type.hpp | 5f7062b21c18a078a9f5587c76837a6eccd3be10 | [
"MIT"
] | permissive | Breush/lava | 59ee88ab44681169356fcec0561805a45f2a2abc | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | refs/heads/master | 2021-07-18T03:17:52.063294 | 2020-12-17T08:00:39 | 2020-12-17T08:00:39 | 89,995,852 | 17 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 219 | hpp | #pragma once
#include <lava/core/macros.hpp>
$enum_class(lava, VrEventType,
ButtonPressed, // A controller's button has been pressed.
ButtonReleased, // A controller's button has released.
);
| [
"alexis.breust@gmail.com"
] | alexis.breust@gmail.com |
b14fb3e8f9d87b9f8695c4eec584e954bb96952b | 4cca0a3832d0ae01e6c5311e226735d637dc879e | /Simple_Windows_Debugger/Debugger.cpp | deda7633abfd416b793b09318bb6cd113852b80e | [
"MIT"
] | permissive | Liftu/Simple-x64-Windows-Debugger | 061f21c34d31b26e1001e97611da76abf474c5c0 | 966fa38a3f747f29501cafe75462861bc7dc8f10 | refs/heads/master | 2021-02-07T07:08:07.338155 | 2021-02-04T21:47:09 | 2021-02-04T21:47:09 | 243,995,662 | 1 | 1 | MIT | 2021-02-04T21:47:10 | 2020-02-29T15:45:28 | C++ | UTF-8 | C++ | false | false | 20,532 | cpp | #include "Debugger.h"
#include <iostream>//
Debugger::Debugger()
{
this->isDebuggerActive = FALSE;
this->hProcess = NULL;
this->processID = NULL;
this->hThread = NULL;
this->threadID = NULL;
this->processStatus = ProcessStatus::NONE;
this->continueStatus = DBG_CONTINUE;
this->firstBreakpointOccured = FALSE;
// Get the default memory page size.
SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
this->pageSize = systemInfo.dwPageSize;
}
Debugger::~Debugger()
{
if (this->isDebuggerActive)
{
this->detachProcess();
}
}
BOOL Debugger::loadProcess(LPCTSTR executablePath, LPTSTR arguments)
{
// Checks if a process isn't already being debugged
if (this->processStatus == ProcessStatus::NONE)
{
STARTUPINFO startupInfo;
// Clean all the members of startupInfo.
ZeroMemory(&startupInfo, sizeof(startupInfo));
// Provide the size of startupInfo to cb.
startupInfo.cb = sizeof(startupInfo);
startupInfo.dwFlags = STARTF_USESHOWWINDOW;
startupInfo.wShowWindow = SW_HIDE;
PROCESS_INFORMATION processInformation;
if (CreateProcess(executablePath, arguments, NULL, NULL, NULL,
DEBUG_ONLY_THIS_PROCESS | CREATE_NEW_CONSOLE | CREATE_SUSPENDED,
NULL, NULL, &startupInfo, &processInformation))
{
this->hProcess = processInformation.hProcess;
this->processID = processInformation.dwProcessId;
this->hThread = processInformation.hThread;
this->threadID = processInformation.dwThreadId;
this->processStatus = ProcessStatus::SUSPENDED;
this->isDebuggerActive = true;
return TRUE;
}
}
return FALSE;
}
BOOL Debugger::attachProcess(DWORD pid)
{
this->hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (DebugActiveProcess(pid))
{
this->isDebuggerActive = TRUE;
this->processID = pid;
this->processStatus = ProcessStatus::RUNNING;
return TRUE;
}
else
{
return FALSE;
}
}
BOOL Debugger::detachProcess()
{
if (DebugActiveProcessStop(this->processID))
{
this->isDebuggerActive = FALSE;
this->processStatus = ProcessStatus::NONE;
return TRUE;
}
else
{
return FALSE;
}
}
BOOL Debugger::continueProcess()
{
if (this->processStatus != ProcessStatus::NONE)
{
if (this->processStatus == ProcessStatus::SUSPENDED)
{
ResumeThread(this->hThread);
}
else
{
ContinueDebugEvent(this->processID, this->threadID, this->continueStatus);
}
DEBUG_EVENT debugEvent;
while (WaitForDebugEvent(&debugEvent, INFINITE))
{
if (this->debugEventHandler(&debugEvent))
{
ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, this->continueStatus);
}
else
{
break;
}
}
return TRUE;
}
return FALSE;
}
Debugger::ProcessStatus Debugger::getProcessStatus()
{
return this->processStatus;
}
BOOL Debugger::debugEventHandler(const DEBUG_EVENT* debugEvent)
{
switch (debugEvent->dwDebugEventCode)
{
case CREATE_PROCESS_DEBUG_EVENT:
return this->createProcessDebugEventHandler(debugEvent);
case CREATE_THREAD_DEBUG_EVENT:
return this->createThreadDebugEventHandler(debugEvent);
case EXCEPTION_DEBUG_EVENT:
return this->exceptionDebugEventHandler(debugEvent);
case EXIT_PROCESS_DEBUG_EVENT:
return this->exitProcessDebugEventHandler(debugEvent);
case EXIT_THREAD_DEBUG_EVENT:
return this->exitThreadDebugEventHandler(debugEvent);
case LOAD_DLL_DEBUG_EVENT:
return this->loadDllDebugEventHandler(debugEvent);
case UNLOAD_DLL_DEBUG_EVENT:
return this->unloadDllDebugEventHandler(debugEvent);
case OUTPUT_DEBUG_STRING_EVENT:
return this->outputDebugStringEventHandler(debugEvent);
case RIP_EVENT:
return this->RIPEventHandler(debugEvent);
default:
this->logEvent("Unknown debug event.\n");
return FALSE;
}
return true;
}
BOOL Debugger::exceptionDebugEventHandler(const DEBUG_EVENT* debugEvent)
{
switch (debugEvent->u.Exception.ExceptionRecord.ExceptionCode)
{
case EXCEPTION_ACCESS_VIOLATION:
//std::cout << "Exception access violation at address : 0x" << std::hex << exceptionAddress << std::dec << std::endl;
this->logEvent("Accedd violation debug event.\n");
this->processStatus = ProcessStatus::INTERRUPTED;
return FALSE;
case EXCEPTION_BREAKPOINT:
//This exception is for software breakpoints
return this->softwareBreakpointExceptionHandler(debugEvent);
case EXCEPTION_SINGLE_STEP:
// This exception is for hardware breakpoints
return this->hardwareBreakpointExceptionHandler(debugEvent);
case EXCEPTION_GUARD_PAGE:
// This exception is for memory breakpoints
return this->memoryBreakpointExceptionHandler(debugEvent);
default:
// Unhandled exceptions
//std::cout << "Exception not handled at address : 0x" << std::hex << exceptionAddress << std::dec << std::endl;
this->logEvent("Unhandled debug event.\n");
this->processStatus = ProcessStatus::INTERRUPTED;
return FALSE;;
}
}
BOOL Debugger::createProcessDebugEventHandler(const DEBUG_EVENT * debugEvent)
{
this->logEvent("Process created.\n");
return TRUE;
}
BOOL Debugger::createThreadDebugEventHandler(const DEBUG_EVENT * debugEvent)
{
this->logEvent("A new thread has been created.\n");
return TRUE;
}
BOOL Debugger::exitProcessDebugEventHandler(const DEBUG_EVENT * debugEvent)
{
this->logEvent("Process exited.\n");
this->processStatus = ProcessStatus::NONE;
return this->isDebuggerActive = FALSE;
}
BOOL Debugger::exitThreadDebugEventHandler(const DEBUG_EVENT * debugEvent)
{
this->logEvent("A thread has been exited.\n");
return TRUE;
}
BOOL Debugger::loadDllDebugEventHandler(const DEBUG_EVENT * debugEvent)
{
this->logEvent("Load dll [");
if (debugEvent->u.LoadDll.lpImageName != NULL)
{
// May be necessary to inscrease the maximum size of the string.
LPTSTR dllName = (LPTSTR)malloc(sizeof(LPTSTR) * MAX_PATH);
GetFinalPathNameByHandle(debugEvent->u.LoadDll.hFile, dllName, MAX_PATH, FILE_NAME_NORMALIZED);
this->logEvent(dllName);
}
else
{
this->logEvent("Unknown");
}
this->logEvent("]\n");
return TRUE;
}
BOOL Debugger::unloadDllDebugEventHandler(const DEBUG_EVENT * debugEvent)
{
this->logEvent("Unload dll");
return TRUE;
}
BOOL Debugger::outputDebugStringEventHandler(const DEBUG_EVENT * debugEvent)
{
this->logEvent("A debug string has been outputed.\n");
return FALSE;
}
BOOL Debugger::RIPEventHandler(const DEBUG_EVENT * debugEvent)
{
this->logEvent("A RIP event occured.\n");
return FALSE;
}
BOOL Debugger::softwareBreakpointExceptionHandler(const DEBUG_EVENT* debugEvent)
{
PVOID exceptionAddress = debugEvent->u.Exception.ExceptionRecord.ExceptionAddress;
std::cout << std::hex << "Exception software breakpoint at address : 0x" << exceptionAddress << std::dec << std::endl;//
this->threadID = debugEvent->dwThreadId;
this->hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, this->threadID);
if (this->softwareBreakpoints.count(exceptionAddress))
{
// We restore the changed byte and delete the breakpoint.
this->delSoftwareBreakpoint(exceptionAddress);
// We have to go back of 1 byte backward because the INT3 instruction got executed.
this->setRegister(debugEvent->dwThreadId, "RIP", (DWORD64)exceptionAddress);
}
else
{
if (!this->firstBreakpointOccured)
{
// I would like to give control to user so he can puts breakpoints after the process has started.
this->firstBreakpointOccured = TRUE;
}
}
return TRUE;
}
BOOL Debugger::hardwareBreakpointExceptionHandler(const DEBUG_EVENT* debugEvent)
{
PVOID exceptionAddress = debugEvent->u.Exception.ExceptionRecord.ExceptionAddress;
std::cout << std::hex << "Exception hardware breakpoint at address : 0x" << exceptionAddress << std::dec << std::endl;//
this->threadID = debugEvent->dwThreadId;
this->hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, this->threadID);
LPCONTEXT threadContext = this->getThreadContext(debugEvent->dwThreadId);
BYTE slot;
// DR6 set one of its 4 first bits corresponding to the breakpoint has been hit (DR0-DR3)
if ((threadContext->Dr6 & 0x1) && this->hardwareBreakpoints.count(0)) slot = 0;
else if ((threadContext->Dr6 & 0x2) && this->hardwareBreakpoints.count(1)) slot = 1;
else if ((threadContext->Dr6 & 0x4) && this->hardwareBreakpoints.count(2)) slot = 2;
else if ((threadContext->Dr6 & 0x8) && this->hardwareBreakpoints.count(3)) slot = 3;
else // not a hardware breakpoint
{
return TRUE;
}
// Removes the hardware breakpoint
this->delHardwareBreakpoint(slot);
return TRUE;
}
BOOL Debugger::memoryBreakpointExceptionHandler(const DEBUG_EVENT* debugEvent)
{
LPVOID exceptionAddress = (LPVOID)debugEvent->u.Exception.ExceptionRecord.ExceptionInformation[1];
std::cout << std::hex << "Exception memory breakpoint at address : 0x" << exceptionAddress << std::dec << std::endl;//
this->threadID = debugEvent->dwThreadId;
this->hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, this->threadID);
MemoryBreakpoints::iterator breakpoint = this->memoryBreakpoints.find(exceptionAddress);
if (breakpoint != this->memoryBreakpoints.end())
{
// If the exception is triggered by our memory breakpoint
//std::cout << std::hex << "Exception memory breakpoint at address : 0x" << exceptionAddress << std::dec << std::endl;//
if (breakpoint->second.isPersistent)
{
//MEMORY_BASIC_INFORMATION memoryBasicInfo;
//if (VirtualQueryEx(this->hProcess, exceptionAddress, &memoryBasicInfo, sizeof(memoryBasicInfo)) >= sizeof(memoryBasicInfo))
//{
// LPVOID exceptionAddressPage = memoryBasicInfo.BaseAddress;
// DWORD oldProtect;
// VirtualProtectEx(this->hProcess, exceptionAddressPage, 1, memoryBasicInfo.Protect | PAGE_GUARD, &oldProtect);
//}
//return TRUE;
}
else
{
this->delMemoryBreakpoint(exceptionAddress);
}
return TRUE;
}
else
{
// If the exception occurs in the page guard of our breakpoint but is not our breakpoint then restore the page guard.
// Running this code before process has really started seems to cause an infinite loop
// I'm trying to figure out how to break to the first windows driven breakpoint and then give control to the user.
//MEMORY_BASIC_INFORMATION memoryBasicInfo;
//if (VirtualQueryEx(this->hProcess, exceptionAddress, &memoryBasicInfo, sizeof(memoryBasicInfo)) >= sizeof(memoryBasicInfo))
//{
// LPVOID exceptionAddressPage = memoryBasicInfo.BaseAddress;
// DWORD oldProtect;
// VirtualProtectEx(this->hProcess, exceptionAddressPage, 1, memoryBasicInfo.Protect | PAGE_GUARD, &oldProtect);
//}
//return TRUE;
}
return TRUE;
}
UINT Debugger::enumerateThreads(THREADENTRY32* threadEntryArray[])
{
UINT threadsNumber = 0;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, this->processID);
if (snapshot)
{
THREADENTRY32 threadEntry;
threadEntry.dwSize = sizeof(threadEntry);
BOOL success = Thread32First(snapshot, &threadEntry);
while (success)
{
if (threadEntry.th32OwnerProcessID == this->processID)
{
threadsNumber++;
// Dynamically add an element to the array of thread entry.
THREADENTRY32* tempThreadEntryArray = new THREADENTRY32[threadsNumber];
memcpy_s(tempThreadEntryArray, (threadsNumber - 1) * sizeof(THREADENTRY32), *threadEntryArray, (threadsNumber - 1) * sizeof(THREADENTRY32));
tempThreadEntryArray[threadsNumber - 1] = threadEntry;
delete[] *threadEntryArray;
*threadEntryArray = tempThreadEntryArray;
}
success = Thread32Next(snapshot, &threadEntry);
}
CloseHandle(snapshot);
}
return threadsNumber;
}
LPCONTEXT Debugger::getThreadContext(DWORD threadID)
{
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, threadID);
CONTEXT threadContext;
threadContext.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
if (GetThreadContext(hThread, &threadContext))
{
CloseHandle(hThread);
return &threadContext;
}
else
{
return NULL;
}
}
BOOL Debugger::setThreadContext(DWORD threadID, LPCONTEXT threadContext)
{
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, threadID);
if (SetThreadContext(hThread, threadContext))
{
return TRUE;
}
else
{
return FALSE;
}
}
BOOL Debugger::setRegister(DWORD threadID, LPCTSTR reg, DWORD64 value)
{
LPCONTEXT threadContext = this->getThreadContext(threadID);
if (_stricmp(reg, "RAX") == 0) threadContext->Rax = value;
else if (_stricmp(reg, "RBX") == 0) threadContext->Rbx = value;
else if (_stricmp(reg, "RCX") == 0) threadContext->Rcx = value;
else if (_stricmp(reg, "RDX") == 0) threadContext->Rdx = value;
else if (_stricmp(reg, "RSI") == 0) threadContext->Rsi = value;
else if (_stricmp(reg, "RDI") == 0) threadContext->Rdi = value;
else if (_stricmp(reg, "RSP") == 0) threadContext->Rsp = value;
else if (_stricmp(reg, "RBP") == 0) threadContext->Rbp = value;
else if (_stricmp(reg, "RIP") == 0) threadContext->Rip = value;
else if (_stricmp(reg, "R8") == 0) threadContext->R8 = value;
else if (_stricmp(reg, "R9") == 0) threadContext->R9 = value;
else if (_stricmp(reg, "R10") == 0) threadContext->R10 = value;
else if (_stricmp(reg, "R11") == 0) threadContext->R11 = value;
else if (_stricmp(reg, "R12") == 0) threadContext->R12 = value;
else if (_stricmp(reg, "R13") == 0) threadContext->R13 = value;
else if (_stricmp(reg, "R14") == 0) threadContext->R14 = value;
else if (_stricmp(reg, "R15") == 0) threadContext->R15 = value;
else return FALSE;
if (this->setThreadContext(threadID, threadContext))
{
return TRUE;
}
else
{
return FALSE;
}
}
BOOL Debugger::addSoftwareBreakpoint(LPVOID address, BOOL isPersistent)
{
// Checks if address is already in soft breakpoint list
if (!this->softwareBreakpoints.count(address))
{
BYTE originalByte;
SIZE_T count;
if (ReadProcessMemory(this->hProcess, address, &originalByte, 1, &count))
{
BYTE INT3Byte = 0xCC;
if (WriteProcessMemory(this->hProcess, address, &INT3Byte, 1, &count))
{
SoftwareBreakpoint softwareBreakpoint = { address, originalByte, isPersistent };
this->softwareBreakpoints[address] = softwareBreakpoint;
return TRUE;
}
}
}
return FALSE;
}
BOOL Debugger::delSoftwareBreakpoint(LPVOID address)
{
SoftwareBreakpoints::iterator breakpoint = this->softwareBreakpoints.find(address);
if (breakpoint != this->softwareBreakpoints.end())
{
BYTE originalByte = breakpoint->second.originalByte;
SIZE_T count;
if (WriteProcessMemory(this->hProcess, address, &originalByte, 1, &count))
{
this->softwareBreakpoints.erase(breakpoint);
return TRUE;
}
}
return FALSE;
}
BOOL Debugger::addHardwareBreakpoint(LPVOID address, BYTE length, BYTE condition, BOOL isPersistent)
{
if (length == 1 || length == 2 || length == 4)
{
// length-- because the following codes are used for determining length :
// 00 - 1 byte length
// 01 - 2 byte length
// 10 - undefined
// 11 - 4 byte length
length--;
if (condition == HW_EXECUTE || condition == HW_WRITE || condition == HW_ACCESS)
{
// We may need to check if we already have a hardware breakpoint at an address.
// I don't kmow what happens when 2 hardware breakpoints target the same address.
// Checks for an available sport on DR registers
BYTE availableSlot;
if (!hardwareBreakpoints.count(0)) availableSlot = 0;
else if (!hardwareBreakpoints.count(1)) availableSlot = 1;
else if (!hardwareBreakpoints.count(2)) availableSlot = 2;
else if (!hardwareBreakpoints.count(3)) availableSlot = 3;
else
return FALSE;
THREADENTRY32* threadEntries = new THREADENTRY32[0];
INT threadsNumber = this->enumerateThreads(&threadEntries);
for (INT i = 0; i < threadsNumber; i++)
{
LPCONTEXT threadContext = this->getThreadContext(threadEntries[i].th32ThreadID);
// Stores the address in the available register.
switch (availableSlot)
{
case 0: threadContext->Dr0 = (DWORD64)address; break;
case 1: threadContext->Dr1 = (DWORD64)address; break;
case 2: threadContext->Dr2 = (DWORD64)address; break;
case 3: threadContext->Dr3 = (DWORD64)address; break;
default:
return FALSE;
}
// Enables the breakpoint by setting its type (Local/Global)
// in the first 8 bits (0-7) of DR7.
// The breakpoints are "Local" in our case.
threadContext->Dr7 |= 1 << (availableSlot * 2);
// Sets the condition of the breakpoint in the last 16 bits of DR7 (groups of 2 bits every 4 bits).
threadContext->Dr7 |= condition << ((availableSlot * 4) + 16);
// Sets the length of the breakpoint in the last 18 bits of DR7 (groups of 2 bits every 4 bits).
threadContext->Dr7 |= length << ((availableSlot * 4) + 18);
this->setThreadContext(threadEntries[i].th32ThreadID, threadContext);
}
// Adds the hardware breakpoint to the list.
HardwareBreakpoint hardwareBreakpoint = { address, length, condition, isPersistent };
hardwareBreakpoints[availableSlot] = hardwareBreakpoint;
return TRUE;
}
}
return FALSE;
}
BOOL Debugger::delHardwareBreakpoint(BYTE slot)
{
THREADENTRY32* threadEntries = new THREADENTRY32[0];
INT threadsNumber = this->enumerateThreads(&threadEntries);
for (INT i = 0; i < threadsNumber; i++)
{
LPCONTEXT threadContext = this->getThreadContext(threadEntries[i].th32ThreadID);
// Reset the breakpoint address in the register
switch (slot)
{
case 0: threadContext->Dr0 = 0x0; break;
case 1: threadContext->Dr1 = 0x0; break;
case 2: threadContext->Dr2 = 0x0; break;
case 3: threadContext->Dr3 = 0x0; break;
default: continue; break;
}
// Disable the breakpoint in DR7
threadContext->Dr7 &= ~(1 << (slot * 2));
// Reset the condition of the breakpoint in DR7
threadContext->Dr7 &= ~(3 << ((slot * 4) + 16));
// Reset the length of the breakpoint in DR7
threadContext->Dr7 &= ~(3 << ((slot * 4) + 18));
this->setThreadContext(threadEntries[i].th32ThreadID, threadContext);
}
this->hardwareBreakpoints.erase(slot);
return TRUE;
}
BOOL Debugger::addMemoryBreakpoint(LPVOID address, /*DWORD size, */BYTE condition, BOOL isPersistent)
{
// The size functionnality is disabled for the moment.
MEMORY_BASIC_INFORMATION memoryBasicInfo;
// Gets the memory page infos and checks if it got all the infos
if (VirtualQueryEx(this->hProcess, address, &memoryBasicInfo, sizeof(memoryBasicInfo)) >= sizeof(memoryBasicInfo))
{
// Get the base address of the current memory page;
LPVOID currentPage = memoryBasicInfo.BaseAddress;
// Loop on every pages within the range of the memory breakpoint
while ((DWORD64)currentPage <= ((DWORD64)address))// + size))
{
DWORD oldProtect;
// Sets the guard page protection on the memory page;
if (!VirtualProtectEx(this->hProcess, currentPage, 1, memoryBasicInfo.Protect | PAGE_GUARD, &oldProtect))
return FALSE;
// Next page (sorry, I didn't find a nicer way to do it)
currentPage = (LPVOID) ((DWORD64)currentPage + this->pageSize);
}
MemoryBreakpoint memorybreakpoint = { address, /*size, */condition, memoryBasicInfo, isPersistent };
memoryBreakpoints[address] = memorybreakpoint;
return TRUE;
}
return FALSE;
}
BOOL Debugger::delMemoryBreakpoint(LPVOID address)
{
MemoryBreakpoints::iterator breakpoint = memoryBreakpoints.find(address);
if (breakpoint != memoryBreakpoints.end())
{
LPVOID currentPage = breakpoint->second.memoryBasicInfo.BaseAddress;
while ((DWORD64)currentPage <= ((DWORD64)breakpoint->second.address))// + breakpoint->second.size))
{
// Checks if the memory page isn't in the range of another memory breakpoint before removing the guard page on it.
BOOL pageAlreadyUsed = FALSE;
for (MemoryBreakpoints::iterator breakpoints = this->memoryBreakpoints.begin();
breakpoints != this->memoryBreakpoints.end() && !pageAlreadyUsed; breakpoints++)
{
if (breakpoints != breakpoint)
{
LPVOID memoryPage = breakpoints->second.memoryBasicInfo.BaseAddress;
while ((DWORD64)memoryPage <= ((DWORD64)breakpoints->second.address))// + breakpoints->second.size))
{
if (memoryPage == currentPage)
{
pageAlreadyUsed = TRUE;
break;
}
memoryPage = (LPVOID) ((DWORD64)currentPage + this->pageSize);
}
}
}
// If this memory page has no other breakpoints using it : remove the guard page.
if (!pageAlreadyUsed)
{
DWORD oldProtect;
if (!VirtualProtectEx(this->hProcess, currentPage, 1, breakpoint->second.memoryBasicInfo.Protect, &oldProtect))
return FALSE;
}
currentPage = (LPVOID) ((DWORD64)currentPage + this->pageSize);
}
memoryBreakpoints.erase(breakpoint);
return TRUE;
}
return FALSE;
}
VOID Debugger::logEvent(LPCTSTR message)
{
// Just print it on stdout for now.
std::cout << message;
} | [
"louilou008@gmail.com"
] | louilou008@gmail.com |
caf1709bda2771ab55e7950b13a81e52e98e06a8 | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-3006.cpp | aba83f7542cb53af15f2a56c496e529ca7df7726 | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,612 | cpp | struct c0;
void __attribute__ ((noinline)) tester0(c0* p);
struct c0
{
bool active0;
c0() : active0(true) {}
virtual ~c0()
{
tester0(this);
active0 = false;
}
virtual void f0(){}
};
void __attribute__ ((noinline)) tester0(c0* p)
{
p->f0();
}
struct c1;
void __attribute__ ((noinline)) tester1(c1* p);
struct c1
{
bool active1;
c1() : active1(true) {}
virtual ~c1()
{
tester1(this);
active1 = false;
}
virtual void f1(){}
};
void __attribute__ ((noinline)) tester1(c1* p)
{
p->f1();
}
struct c2;
void __attribute__ ((noinline)) tester2(c2* p);
struct c2
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
}
struct c3;
void __attribute__ ((noinline)) tester3(c3* p);
struct c3 : virtual c1, virtual c2
{
bool active3;
c3() : active3(true) {}
virtual ~c3()
{
tester3(this);
c1 *p1_0 = (c1*)(c3*)(this);
tester1(p1_0);
c2 *p2_0 = (c2*)(c3*)(this);
tester2(p2_0);
active3 = false;
}
virtual void f3(){}
};
void __attribute__ ((noinline)) tester3(c3* p)
{
p->f3();
if (p->active1)
p->f1();
if (p->active2)
p->f2();
}
struct c4;
void __attribute__ ((noinline)) tester4(c4* p);
struct c4 : virtual c3, virtual c0, virtual c1
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c4*)(this);
tester0(p0_0);
c1 *p1_0 = (c1*)(c3*)(c4*)(this);
tester1(p1_0);
c1 *p1_1 = (c1*)(c4*)(this);
tester1(p1_1);
c2 *p2_0 = (c2*)(c3*)(c4*)(this);
tester2(p2_0);
c3 *p3_0 = (c3*)(c4*)(this);
tester3(p3_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
if (p->active2)
p->f2();
if (p->active3)
p->f3();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c4*)(new c4());
for (int i=0;i<2;i=inc(i))
{
tester0(ptrs0[i]);
delete ptrs0[i];
}
c1* ptrs1[25];
ptrs1[0] = (c1*)(new c1());
ptrs1[1] = (c1*)(c3*)(new c3());
ptrs1[2] = (c1*)(c3*)(c4*)(new c4());
ptrs1[3] = (c1*)(c4*)(new c4());
for (int i=0;i<4;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
ptrs2[1] = (c2*)(c3*)(new c3());
ptrs2[2] = (c2*)(c3*)(c4*)(new c4());
for (int i=0;i<3;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
ptrs3[1] = (c3*)(c4*)(new c4());
for (int i=0;i<2;i=inc(i))
{
tester3(ptrs3[i]);
delete ptrs3[i];
}
c4* ptrs4[25];
ptrs4[0] = (c4*)(new c4());
for (int i=0;i<1;i=inc(i))
{
tester4(ptrs4[i]);
delete ptrs4[i];
}
return 0;
}
| [
"ga72foq@mytum.de"
] | ga72foq@mytum.de |
60c690b05c0381f0d1c432e6599433c01b2d3df3 | 120df560b914e7694076555cf2c8facd8715dbff | /ISIS/application/sam-ba/examples/samba_multiple_programming/ole_with_mfc/OLE_MFC.cpp | cc8d68b1833388530544cee0f02ada0ab2da8887 | [] | no_license | israelaitan/Base-Aug-2019 | 318c880329dd52484eaec9e467a8eba4c4654ef0 | 6b33618d6c86e57a507e417d424801b6366fbf00 | refs/heads/master | 2022-12-18T12:27:31.696075 | 2020-09-09T10:40:19 | 2020-09-09T10:40:19 | 200,597,361 | 0 | 1 | null | 2020-07-22T06:23:20 | 2019-08-05T06:43:05 | C | UTF-8 | C++ | false | false | 2,582 | cpp | // OLE_MFC.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "OLE_MFC.h"
#include "OLE_MFCDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// COLE_MFCApp
BEGIN_MESSAGE_MAP(COLE_MFCApp, CWinApp)
//{{AFX_MSG_MAP(COLE_MFCApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// COLE_MFCApp construction
COLE_MFCApp::COLE_MFCApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only COLE_MFCApp object
COLE_MFCApp theApp;
/////////////////////////////////////////////////////////////////////////////
// COLE_MFCApp initialization
BOOL COLE_MFCApp::InitInstance()
{
// Initialize OLE libraries
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
// Parse the command line to see if launched as OLE server
if (RunEmbedded() || RunAutomated())
{
// Register all OLE server (factories) as running. This enables the
// OLE libraries to create objects from other applications.
COleTemplateServer::RegisterAll();
}
else
{
// When a server application is launched stand-alone, it is a good idea
// to update the system registry in case it has been damaged.
COleObjectFactory::UpdateRegistryAll();
}
COLE_MFCDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"israel.aitan@gmail.com"
] | israel.aitan@gmail.com |
c833a5f28a20c726e4402442e826c9f45d446b2a | 39f5ed1178375c65876323589a03ef5daf6e4739 | /components/sync/trusted_vault/trusted_vault_crypto_unittest.cc | a5bdbf4db7e986cd174d92c58385efaa2f105b85 | [
"BSD-3-Clause"
] | permissive | berber1016/chromium | 2718166c02fcb3aad24cc3bd326a4f8d2d7c0cae | 9dc373d511536c916dec337b4ccc53106967d28d | refs/heads/main | 2023-03-21T21:53:55.686443 | 2021-05-14T10:13:20 | 2021-05-14T10:13:20 | 367,332,075 | 1 | 0 | BSD-3-Clause | 2021-05-14T10:46:30 | 2021-05-14T10:46:29 | null | UTF-8 | C++ | false | false | 3,487 | cc | // Copyright 2020 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 "components/sync/trusted_vault/trusted_vault_crypto.h"
#include <memory>
#include "base/strings/string_number_conversions.h"
#include "components/sync/trusted_vault/securebox.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace syncer {
namespace {
using testing::Eq;
using testing::Ne;
const char kEncodedPrivateKey[] =
"49e052293c29b5a50b0013eec9d030ac2ad70a42fe093be084264647cb04e16f";
std::unique_ptr<SecureBoxKeyPair> MakeTestKeyPair() {
std::vector<uint8_t> private_key_bytes;
bool success = base::HexStringToBytes(kEncodedPrivateKey, &private_key_bytes);
DCHECK(success);
return SecureBoxKeyPair::CreateByPrivateKeyImport(private_key_bytes);
}
TEST(TrustedVaultCrypto, ShouldHandleDecryptionFailure) {
EXPECT_THAT(DecryptTrustedVaultWrappedKey(
MakeTestKeyPair()->private_key(),
/*wrapped_key=*/std::vector<uint8_t>{1, 2, 3, 4}),
Eq(base::nullopt));
}
TEST(TrustedVaultCrypto, ShouldEncryptAndDecryptWrappedKey) {
const std::vector<uint8_t> trusted_vault_key = {1, 2, 3, 4};
const std::unique_ptr<SecureBoxKeyPair> key_pair = MakeTestKeyPair();
base::Optional<std::vector<uint8_t>> decrypted_trusted_vault_key =
DecryptTrustedVaultWrappedKey(
key_pair->private_key(),
/*wrapped_key=*/ComputeTrustedVaultWrappedKey(key_pair->public_key(),
trusted_vault_key));
ASSERT_THAT(decrypted_trusted_vault_key, Ne(base::nullopt));
EXPECT_THAT(*decrypted_trusted_vault_key, Eq(trusted_vault_key));
}
TEST(TrustedVaultCrypto, ShouldComputeAndVerifyMemberProof) {
std::unique_ptr<SecureBoxKeyPair> key_pair = MakeTestKeyPair();
const std::vector<uint8_t> trusted_vault_key = {1, 2, 3, 4};
EXPECT_TRUE(VerifyMemberProof(
key_pair->public_key(), trusted_vault_key, /*member_proof=*/
ComputeMemberProof(key_pair->public_key(), trusted_vault_key)));
}
TEST(TrustedVaultCrypto, ShouldDetectIncorrectMemberProof) {
std::unique_ptr<SecureBoxKeyPair> key_pair = MakeTestKeyPair();
const std::vector<uint8_t> correct_trusted_vault_key = {1, 2, 3, 4};
const std::vector<uint8_t> incorrect_trusted_vault_key = {1, 2, 3, 5};
EXPECT_FALSE(VerifyMemberProof(
key_pair->public_key(), correct_trusted_vault_key, /*member_proof=*/
ComputeMemberProof(key_pair->public_key(), incorrect_trusted_vault_key)));
}
TEST(TrustedVaultCrypto, ShouldComputeAndVerifyRotationProof) {
const std::vector<uint8_t> trusted_vault_key = {1, 2, 3, 4};
const std::vector<uint8_t> prev_trusted_vault_key = {1, 2, 3, 5};
EXPECT_TRUE(VerifyRotationProof(
trusted_vault_key, prev_trusted_vault_key, /*rotation_proof=*/
ComputeRotationProof(trusted_vault_key, prev_trusted_vault_key)));
}
TEST(TrustedVaultCrypto, ShouldDetectIncorrectRotationProof) {
const std::vector<uint8_t> trusted_vault_key = {1, 2, 3, 4};
const std::vector<uint8_t> prev_trusted_vault_key = {1, 2, 3, 5};
const std::vector<uint8_t> incorrect_trusted_vault_key = {1, 2, 3, 6};
EXPECT_FALSE(VerifyRotationProof(
trusted_vault_key, prev_trusted_vault_key, /*rotation_proof=*/
ComputeRotationProof(trusted_vault_key, incorrect_trusted_vault_key)));
}
} // namespace
} // namespace syncer
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
2688729c9f88cc0ef978168e381d720304f345de | 0a4be1f3d0a85aebdc2385433d00ecb902bf7155 | /2266/source.cpp | c8e16a5ff44b1c8cbc082014a341efa83c5ba4db | [] | no_license | Moon-ChangHyun/BOJ | f5632bec92f72775ac786a951dd48796b77294b9 | 3126fe427d3dceb367370ee7d910d61cbd789d0a | refs/heads/master | 2020-04-04T20:13:49.852196 | 2018-11-11T10:16:29 | 2018-11-11T10:16:29 | 156,238,820 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | cpp | #include<cstdio>
short dp[501][2];
int main() {
int n, k;
scanf("%d%d", &n, &k);
dp[0][0] = dp[0][1] = 0;
for (int i = 1; i <= n; ++i)
dp[i][1] = i;
for (int j = 2; j <= k; ++j) {
for (int i = 1; i <= n; ++i) {
int a = (i - 1) >> 1;
int b = i - 1 - a;
for (; dp[a][(j + 1) % 2] > dp[b][j % 2]; --a, ++b);
dp[i][j % 2] = dp[b][j % 2] + 1;
}
}
printf("%d", dp[n][k % 2]);
} | [
"44778823+Moon-ChangHyun@users.noreply.github.com"
] | 44778823+Moon-ChangHyun@users.noreply.github.com |
ea58c183459f8fe51fc7721ff614ee18e16e274e | 74b7d2e04a23f61a68485c43acfcb0678ca0b93b | /Source/Atrc/Editor/Light/SHEnv.h | 6c4fe3a38fcf3d08017d4155d0888c1a9ed5c722 | [
"MIT"
] | permissive | Ilinite/Atrc | bded8e19d60dbe32b7265e797bb0afab25551ca6 | 94db1512755eb4df1b01679bafbc60e471f03b42 | refs/heads/master | 2020-06-28T13:16:45.337518 | 2019-06-04T07:12:06 | 2019-06-04T07:12:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 814 | h | #pragma once
#include <Atrc/Editor/Light/Light.h>
#include <Atrc/Editor/GL.h>
#include <Lib/ImFileBrowser/imfilebrowser.h>
namespace Atrc::Editor
{
class SHEnv : public ResourceCommonImpl<ILight, SHEnv>
{
int SHOrder_ = 1;
std::vector<Vec3f> coefs_ = { Vec3f() };
ImGui::FileBrowser fileBrowser_;
public:
using ResourceCommonImpl<ILight, SHEnv>::ResourceCommonImpl;
std::string Save(const std::filesystem::path &relPath) const override;
void Load(const AGZ::ConfigGroup ¶ms, const std::filesystem::path &relPath) override;
std::string Export(const std::filesystem::path &path) const override;
void Display() override;
bool IsMultiline() const noexcept override;
};
DEFINE_DEFAULT_RESOURCE_CREATOR(ILightCreator, SHEnv, "SHEnv");
} // namespace Atrc::Editor
| [
"airguanz@gmail.com"
] | airguanz@gmail.com |
8772998071e80204938d137f2362b0392db82d32 | 6059ef7bc48ab49c938f075dc5210a19ec08538e | /src/plugins/cstp/cstp.cpp | de8064b6015ebb855685f8d4ad268fe9543be3fe | [
"BSL-1.0"
] | permissive | Laura-lc/leechcraft | 92b40aff06af9667aca9edd0489407ffc22db116 | 8cd066ad6a6ae5ee947919a97b2a4dc96ff00742 | refs/heads/master | 2021-01-13T19:34:09.767365 | 2020-01-11T15:25:31 | 2020-01-11T15:25:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,797 | cpp | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "cstp.h"
#include <algorithm>
#include <QMenu>
#include <QTranslator>
#include <QLocale>
#include <QFileInfo>
#include <QTabWidget>
#include <QToolBar>
#include <QMessageBox>
#include <QModelIndex>
#include <QDir>
#include <QUrl>
#include <QTextCodec>
#include <QTranslator>
#include <QMainWindow>
#include <interfaces/entitytesthandleresult.h>
#include <interfaces/ijobholderrepresentationhandler.h>
#include <interfaces/core/icoreproxy.h>
#include <interfaces/core/ientitymanager.h>
#include <interfaces/core/irootwindowsmanager.h>
#include <util/sll/either.h>
#include <util/xpc/util.h>
#include <util/util.h>
#include "core.h"
#include "xmlsettingsmanager.h"
namespace LC
{
namespace CSTP
{
void CSTP::Init (ICoreProxy_ptr coreProxy)
{
Proxy_ = coreProxy;
Core::Instance ().SetCoreProxy (coreProxy);
Util::InstallTranslator ("cstp");
XmlSettingsDialog_.reset (new Util::XmlSettingsDialog ());
XmlSettingsDialog_->RegisterObject (&XmlSettingsManager::Instance (),
"cstpsettings.xml");
SetupToolbar ();
Core::Instance ().SetToolbar (Toolbar_);
connect (&Core::Instance (),
SIGNAL (error (QString)),
this,
SLOT (handleError (QString)));
}
void CSTP::SecondInit ()
{
}
void CSTP::Release ()
{
Core::Instance ().Release ();
XmlSettingsManager::Instance ().Release ();
XmlSettingsDialog_.reset ();
}
QByteArray CSTP::GetUniqueID () const
{
return "org.LeechCraft.CSTP";
}
QString CSTP::GetName () const
{
return "CSTP";
}
QString CSTP::GetInfo () const
{
return "Common Stream Transfer Protocols";
}
QStringList CSTP::Provides () const
{
return { "http", "https", "remoteable", "resume" };
}
QIcon CSTP::GetIcon () const
{
static QIcon icon ("lcicons:/plugins/cstp/resources/images/cstp.svg");
return icon;
}
qint64 CSTP::GetDownloadSpeed () const
{
return Core::Instance ().GetTotalDownloadSpeed ();
}
qint64 CSTP::GetUploadSpeed () const
{
return 0;
}
void CSTP::StartAll ()
{
Core::Instance ().startAllTriggered ();
}
void CSTP::StopAll ()
{
Core::Instance ().stopAllTriggered ();
}
EntityTestHandleResult CSTP::CouldDownload (const LC::Entity& e) const
{
return Core::Instance ().CouldDownload (e);
}
QFuture<IDownload::Result> CSTP::AddJob (LC::Entity e)
{
return Core::Instance ().AddTask (e);
}
QAbstractItemModel* CSTP::GetRepresentation () const
{
return Core::Instance ().GetRepresentationModel ();
}
IJobHolderRepresentationHandler_ptr CSTP::CreateRepresentationHandler ()
{
class Handler : public IJobHolderRepresentationHandler
{
public:
void HandleCurrentRowChanged (const QModelIndex& index) override
{
Core::Instance ().ItemSelected (index);
}
};
return std::make_shared<Handler> ();
}
Util::XmlSettingsDialog_ptr CSTP::GetSettingsDialog () const
{
return XmlSettingsDialog_;
}
void CSTP::SetupToolbar ()
{
Toolbar_ = new QToolBar;
Toolbar_->setWindowTitle ("CSTP");
QAction *remove = Toolbar_->addAction (tr ("Remove"));
connect (remove,
SIGNAL (triggered ()),
&Core::Instance (),
SLOT (removeTriggered ()));
remove->setProperty ("ActionIcon", "list-remove");
QAction *removeAll = Toolbar_->addAction (tr ("Remove all"));
connect (removeAll,
SIGNAL (triggered ()),
&Core::Instance (),
SLOT (removeAllTriggered ()));
removeAll->setProperty ("ActionIcon", "edit-clear-list");
Toolbar_->addSeparator ();
QAction *start = Toolbar_->addAction (tr ("Start"));
connect (start,
SIGNAL (triggered ()),
&Core::Instance (),
SLOT (startTriggered ()));
start->setProperty ("ActionIcon", "media-playback-start");
QAction *stop = Toolbar_->addAction (tr ("Stop"));
connect (stop,
SIGNAL (triggered ()),
&Core::Instance (),
SLOT (stopTriggered ()));
stop->setProperty ("ActionIcon", "media-playback-stop");
QAction *startAll = Toolbar_->addAction (tr ("Start all"));
connect (startAll,
SIGNAL (triggered ()),
&Core::Instance (),
SLOT (startAllTriggered ()));
startAll->setProperty ("ActionIcon", "media-seek-forward");
QAction *stopAll = Toolbar_->addAction (tr ("Stop all"));
connect (stopAll,
SIGNAL (triggered ()),
&Core::Instance (),
SLOT (stopAllTriggered ()));
stopAll->setProperty ("ActionIcon", "media-record");
}
void CSTP::handleFileExists (Core::FileExistsBehaviour *remove)
{
auto rootWM = Core::Instance ().GetCoreProxy ()->GetRootWindowsManager ();
auto userReply = QMessageBox::warning (rootWM->GetPreferredWindow (),
tr ("File exists"),
tr ("File %1 already exists, continue download?"),
QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
if (userReply == QMessageBox::Yes)
*remove = Core::FileExistsBehaviour::Continue;
else if (userReply == QMessageBox::No)
*remove = Core::FileExistsBehaviour::Remove;
else
*remove = Core::FileExistsBehaviour::Abort;
}
void CSTP::handleError (const QString& error)
{
Proxy_->GetEntityManager ()->HandleEntity (Util::MakeNotification ("HTTP error", error, Priority::Critical));
}
}
}
LC_EXPORT_PLUGIN (leechcraft_cstp, LC::CSTP::CSTP);
| [
"0xd34df00d@gmail.com"
] | 0xd34df00d@gmail.com |
cd73602b3a1489ebcdb2d9f7b8eba9924896f2de | 7f3a8bf1398a476358ea94ed97ee02a847dd1fb8 | /contracts/frax.reserve/frax.reserve.hpp | 0efe8b4a845402970c2d771a355c83b92517096e | [] | no_license | samkazemian/frax | 38555501429bc3322ea21a09f9e6294ed2a2cf70 | 955b2a0b7f67b3ec1243ee78483f6619aa7c2547 | refs/heads/master | 2020-09-02T00:07:53.004366 | 2019-10-24T00:43:00 | 2019-10-24T00:43:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,493 | hpp | #include <eosio/eosio.hpp>
#include <eosio/print.hpp>
#include <eosio/crypto.hpp>
#include <eosio/asset.hpp>
using namespace eosio;
using namespace std;
const symbol FRAX_SYMBOL = symbol(symbol_code("FRAX"), 4);
const symbol FXS_SYMBOL = symbol(symbol_code("FXS"), 4);
const symbol USDT_SYMBOL = symbol(symbol_code("USDT"), 4);
const name FRAX_TOKENS = name("fraxfitokens");
class [[eosio::contract("frax.reserve")]] fraxreserve : public contract {
public:
using contract::contract;
[[eosio::action]]
void addtoken(name contract, symbol ticker);
[[eosio::action]]
void buyfrax(name buyer, asset frax);
[[eosio::action]]
void settarget(asset reserve_usdt, asset reserve_fxs, uint64_t fxs_price);
// Public but not a directly callable action
// Called indirectly by sending EOS to this contract
void deposit( name from, name to, asset quantity, string memo );
// Deposits table
// Scoped by user
struct [[eosio::table]] account {
asset balance;
uint64_t primary_key() const { return balance.symbol.raw(); }
};
typedef eosio::multi_index<"accounts"_n, account> accounts;
// Token stats
// Contract scope
struct [[eosio::table]] stats_t {
asset supply;
name contract;
uint64_t primary_key() const { return supply.symbol.raw(); }
uint64_t by_contract() const { return contract.value; }
uint128_t by_contract_symbol() const { return merge_contract_symbol(contract, supply.symbol); }
};
typedef eosio::multi_index<"stats"_n, stats_t,
indexed_by<"bycontract"_n, const_mem_fun<stats_t, uint64_t, &stats_t::by_contract>>,
indexed_by<"byctrsym"_n, const_mem_fun<stats_t, uint128_t, &stats_t::by_contract_symbol>>
> stats;
// System parameters
// Singleton - Contract scope
struct [[eosio::table]] params_t {
asset target_usdt;
asset target_fxs;
uint64_t fxs_price; // (FXS / USDT) * 1e4. Ex: $20 FXS. Set to 20e4
uint64_t primary_key() const { return 1; } // constant primary key forces singleton
};
typedef eosio::multi_index<"sysparams"_n, params_t > sysparams;
private:
static uint128_t merge_contract_symbol( name contract, symbol sym ) {
uint128_t merged;
uint64_t raw_sym = sym.raw();
memcpy((uint8_t *)&merged, (uint8_t *)&contract.value, 8);
memcpy((uint8_t *)&merged + 8, (uint8_t *)&raw_sym, 8);
return merged;
}
};
| [
"kedarmail@gmail.com"
] | kedarmail@gmail.com |
cc38f17f57e55ed15932b14687fcd62ff3f2e9d9 | c65ce86fc9a3b20f805c414ff97c095602f96e3a | /OfferCode/46.cpp | 731ace9aa5dc6677ec3ec58a2f7253efc233d276 | [] | no_license | RosenX/Code | 63db2e718ac2ec25885841fae39faa837a142aa7 | 2233eec46952556d8dc34cda1b0c5353ed2b5f07 | refs/heads/master | 2021-01-25T14:56:46.247079 | 2017-09-05T03:18:23 | 2017-09-05T03:18:23 | 39,948,186 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,528 | cpp | /*
题目:每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
思路:循环链表模拟
*/
struct Node{
int val;
Node *next;
Node(){}
Node(int v): val(v), next(NULL){}
};
class Solution {
public:
int LastRemaining_Solution(int n, int m)
{
if(n < 1) return -1;
Node *head = new Node(0);
Node *p = head;
for(int i = 1; i < n; i++) {
p->next = new Node(i);
p = p->next;
}
p->next = head;
p = head;
while(p->next != p) {
int i = 0;
while(i++ < m - 2) p = p->next;
Node* toDelete = p->next;
p->next = toDelete->next;
delete toDelete;
p = p->next;
}
int ans = p->val;
delete p;
return ans;
}
}; | [
"Rosen9212@gmail.com"
] | Rosen9212@gmail.com |
d991a016f9b3dd0f25f4d0a98084f52cfab57954 | 62abb1563f1e48e9cdb048c2ce5893e29c29d3b0 | /IAM_512_SPN/src/DifferentialCryptanalysis.h | 4fa969b07bc99dc4417121e0eccadd42c7d50a5e | [] | no_license | dagenes/IAM_512_SPN | 7f490ec07288a99ab390ca2fcb56f1654311e7b9 | 143654641055c27d0e4d95700924ebd4063fd829 | refs/heads/master | 2022-07-14T09:01:36.961657 | 2020-05-16T19:55:35 | 2020-05-16T19:55:35 | 256,787,334 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 818 | h | /*
* Created by HardCore on 18/04/2020.
*/
#pragma once
#include <string>
#include <unordered_map>
#include <vector>
#include <iostream>
#include <cmath>
//JAVA TO C++ CONVERTER NOTE: Forward class declarations:
//namespace crypto {
class SPN;
//}
/**
* COPYRIGHT : yesterday is yesterday, today is today.
*/
//namespace crypto
//{
/**
* @author HC
* @date 19 Nis 2020
* @project_name IAM_512_SPN
*/
class DifferentialCryptanalysis {
unsigned long diff_input = 1;
unsigned long _diff_target = 1;
private:
SPN *spn;
int iterNumber;
bool verbose = false;
public:
virtual ~DifferentialCryptanalysis() {
delete spn;
}
DifferentialCryptanalysis(SPN *spn, int iterNumber, bool verbose);
virtual int attack(const std::vector<uint64_t> key);
};
//}
| [
"dagenes1@gmail.com"
] | dagenes1@gmail.com |
27e427a846bcd67ba9245e0f6dd2a8852b99c3a5 | 2f43afb7c9d4021eb11743cc42b90e5d452c02b8 | /satSolvers/BooleanSolver.h | 3d04a3a2eaccb1cb5ec4035fa02505f007e0dbd4 | [
"MIT"
] | permissive | manleviet/rime | e33e84402103e2da742a85412f0a0b869e0087ae | 5d5c6d47060db984a738b14cae6ea0c61784fa35 | refs/heads/master | 2022-09-05T03:54:24.894014 | 2020-05-27T21:43:07 | 2020-05-27T21:43:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,647 | h | #ifndef BOOLEANSOLVER_H
#define BOOLEANSOLVER_H
#include "satSolvers/SatSolver.h"
#include <string>
#include <map>
#include <vector>
#include <unordered_map>
class BooleanSolver: public SatSolver{
public:
BooleanSolver(std::string filename);
~BooleanSolver();
std::vector<std::vector<int>> clauses;
int vars;
std::vector<std::string> clauses_str;
std::unordered_map<std::string, int> clauses_unique_map;
std::map<std::vector<int>,int> clauses_map;
bool parse(std::string filename);
void add_clause(std::vector<int> cl);
std::string toString(std::vector<bool> &f);
//model rotation
int rotated_crits;
std::vector<std::vector<int>> hitmap_pos;
std::vector<std::vector<int>> hitmap_neg;
std::vector<bool> flip_edges_computed;
std::vector<std::vector<std::vector<int>>> flip_edges; // flip_edges[i][j][k] - i-th clause, j-th literal in the clause, k-th edge from i-th clause under j-th literal in the flip grap
std::vector<std::vector<int>> flip_edges_flatten;
void compute_flip_edges(int c);
void criticals_rotation(std::vector<bool>& criticals, std::vector<bool> subset);
std::vector<int> get_implied(std::vector<bool> mus, int c);
int critical_extension(std::vector<bool> &f, std::vector<bool> &crits);
std::vector<int> critical_extension_clause(std::vector<bool> &f, std::vector<bool> &crits, int c);
int critical_propagation(std::vector<bool> &f, std::vector<bool> &crits, int cl);
std::vector<bool> propagateToUnsat(std::vector<bool> base, std::vector<bool> cover, std::vector<int> implied);
std::vector<bool> shrink(std::vector<bool> &f, std::vector<bool> crits);
std::vector<bool> shrink_mcsmus(std::vector<bool> &f, std::vector<bool> crits = std::vector<bool>());
bool lit_occurences(std::vector<bool> subset, int c2);
std::vector<bool> shrink(std::vector<bool> &f, Explorer *e, std::vector<bool> crits);
std::vector<int> export_formula_wcnf(std::vector<bool> f, std::vector<bool> &conflicts, std::string filename);
std::vector<bool> grow_uwrmaxsat(std::vector<bool> &f, std::vector<bool> &conflicts);
std::vector<bool> grow_cmp(std::vector<bool> &f, std::vector<bool> &conflicts);
std::vector<bool> grow(std::vector<bool> &f, std::vector<bool> conflicts);
std::vector<bool> shrink_muser(std::string input, int hash2);
int muser_output(std::string filename);
std::vector<bool> import_formula_crits(std::string filename);
void export_formula_crits(std::vector<bool> f, std::string filename, std::vector<bool> crits);
std::vector<bool> satisfied(std::vector<int> &valuation);
std::vector<int> convert_clause(std::string clause);
};
#endif
| [
"xbendik@gmail.com"
] | xbendik@gmail.com |
c8e98e08a2016e3a7c7846695a822f27c1f32d73 | f1ded8bb18a493ec872d79128e7b54417f27c425 | /gui/otherprofilewidget.cpp | a0919690ecfe6bcdc1122a764a2034b1b4406099 | [] | no_license | nikname/LinQedIn | 7f893b02e4f1fe94b857290bda81b0be9e739747 | c541ed3a908107cf40a34c0dad5a039c327204bb | refs/heads/master | 2021-01-10T06:25:49.807807 | 2015-11-16T19:54:42 | 2015-11-16T19:54:42 | 45,493,764 | 0 | 0 | null | 2015-11-16T19:54:42 | 2015-11-03T20:33:05 | C++ | UTF-8 | C++ | false | false | 10,179 | cpp | #include <QLabel>
#include <QPushButton>
#include <QBoxLayout>
#include "editprofiledialog.h"
#include "lavoro.h"
#include "otherprofilewidget.h"
#include "otherinfowidget.h"
#include "titolo.h"
#include "utente.h"
#include "connectionswidget.h"
#include "educationswidget.h"
#include "experienceswidget.h"
#include "smartlavoro.h"
#include "smarttitolo.h"
#include "smartutente.h"
// COSTRUTTORE OtherProfileWidget
OtherProfileWidget::OtherProfileWidget( const SmartUtente& su, QList<QString> i,
bool c, QWidget *parent) :
ProfileWidget( su, parent )
{
initUI( i );
setupUI( c );
}
// METODO OtherProfileWidget::initUI( QList<QString> )
void OtherProfileWidget::initUI( QList<QString> i ) {
if( i.contains( "experiences" ) ) {
QVector<SmartLavoro> experiencesList = user->getExperiencesList();
if( experiencesList.size() == 0 )
lastExperienceLabel = new QLabel( "--", this );
else {
SmartLavoro aux = experiencesList.last();
lastExperienceLabel = new QLabel( aux->getTitle() + " at " + aux->getCompanyName(), this );
}
} else {
lastExperienceLabel = 0;
}
if( i.contains( "educations" ) ) {
QVector<SmartTitolo> educationsList = user->getEducationsList();
if( educationsList.size() == 0 )
lastEducationLabel = new QLabel( "--", this );
else {
SmartTitolo aux = educationsList.last();
lastEducationLabel = new QLabel( aux->getFieldOfStudy() + " at " + aux->getSchool(), this );
}
} else {
lastEducationLabel = 0;
}
if( i.contains( "contacts" ) ) {
QVector<SmartUtente> contactsList = user->getContactsList();
connectionsNumber = new QLabel(
QString::number( contactsList.size() ) + tr( " connections" ), this );
connectionsTabButton = new QPushButton( tr( "Connections" ), this );
connect( connectionsTabButton, SIGNAL( clicked() ), this, SLOT( showConnectionsTab() ) );
connectionsTab = new ConnectionsWidget( user, this );
connect( connectionsTab, SIGNAL( showContactSignal( SmartUtente ) ),
this, SIGNAL( showContactSignal( SmartUtente ) ) );
ProfileWidget::tabButtons.append( connectionsTabButton );
} else {
connectionsNumber = 0;
connectionsTabButton = 0;
connectionsTab = 0;
}
if( i.contains( "educations" ) || i.contains( "experiences" ) ) {
backgroundTabButton = new QPushButton( tr( "Background" ), this );
connect( backgroundTabButton, SIGNAL( clicked() ), this, SLOT( showBackgroundTab() ) );
ProfileWidget::tabButtons.append( backgroundTabButton );
backgroundTab = new QWidget( this );
if( i.contains( "experiences" ) ) {
experiencesLabel = new QLabel( tr( "Experiences" ), backgroundTab );
experiencesWidget = new ExperiencesWidget( user, backgroundTab );
} else {
experiencesLabel = 0;
experiencesWidget = 0;
}
if( i.contains( "educations" ) ) {
educationsLabel = new QLabel( tr( "Educations" ), backgroundTab );
educationsWidget = new EducationsWidget( user, backgroundTab );
} else {
educationsLabel = 0;
educationsWidget = 0;
}
} else {
backgroundTabButton = 0;
backgroundTab = 0;
experiencesLabel = 0;
experiencesWidget = 0;
educationsLabel = 0;
educationsWidget = 0;
}
connect( ProfileWidget::otherInfoTabButton, SIGNAL( clicked() ),
this, SLOT( showOtherInfoTab() ) );
addContactButton = new QPushButton( this );
connect( addContactButton, SIGNAL( clicked() ), this, SLOT( addContact() ) );
removeContactButton = new QPushButton( this );
connect( removeContactButton, SIGNAL( clicked() ), this, SLOT( removeContact() ) );
}
// METODO OtherProfileWidget::setupUI( bool )
void OtherProfileWidget::setupUI( bool c ) {
QWidget *header = new QWidget( this );
header->setStyleSheet( "background: white" );
nameSurnameLabel->setStyleSheet( "color: rgba(0,0,0,0.87)" );
if( lastExperienceLabel ) lastExperienceLabel->setStyleSheet( "color: rgba(0,0,0,0.54);" );
if( lastEducationLabel ) lastEducationLabel->setStyleSheet( "color: rgba(0,0,0,0.54);" );
QWidget *profileSummaryFiller = new QWidget( ProfileWidget::profileSummary );
profileSummaryFiller->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
QVBoxLayout *profileSummaryLayout = new QVBoxLayout( ProfileWidget::profileSummary );
profileSummaryLayout->addWidget( ProfileWidget::nameSurnameLabel );
if( lastExperienceLabel ) profileSummaryLayout->addWidget( lastExperienceLabel );
if( lastEducationLabel ) profileSummaryLayout->addWidget( lastEducationLabel );
if( connectionsNumber ) profileSummaryLayout->addWidget( connectionsNumber, 0, Qt::AlignRight );
profileSummaryLayout->addWidget( profileSummaryFiller );
QHBoxLayout *headerLayout = new QHBoxLayout( header );
headerLayout->addWidget( ProfileWidget::profilePicLabel );
headerLayout->addWidget( ProfileWidget::profileSummary );
QWidget *infoTabsWidget= new QWidget( this );
QWidget *infoTabsButtonsWidget = new QWidget( infoTabsWidget );
infoTabsButtonsWidget->setStyleSheet( "background: white" );
if( backgroundTabButton ) {
setProfileButtonProperties( backgroundTabButton );
setProfileButtonSelected( backgroundTabButton );
}
if( connectionsTabButton ) setProfileButtonProperties( connectionsTabButton );
addContactButton->setFixedSize( 50, 50 );
addContactButton->setIcon( QIcon( QPixmap( ":/icons/icon/account-plus.png" ) ) );
addContactButton->setStyleSheet(
"QPushButton { background: #003D5C; border-radius: 25px; outline: none; }"
"QPushButton:pressed { background: #3385AD; outline: none; }"
);
removeContactButton->setFixedSize( 50, 50 );
removeContactButton->setIcon( QIcon( QPixmap( ":/icons/icon/account-remove-white.png" ) ) );
removeContactButton->setStyleSheet(
"QPushButton { background: #FF1744; border-radius: 25px; outline: none; }"
"QPushButton:pressed { background: #FF5252; outline: none; }"
);
QWidget *buttonsFiller = new QWidget( infoTabsButtonsWidget );
buttonsFiller->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
if( c ) addContactButton->setVisible( false );
else removeContactButton->setVisible( false );
QHBoxLayout *infoTabsButtonLayout = new QHBoxLayout( infoTabsButtonsWidget );
if( backgroundTabButton ) infoTabsButtonLayout->addWidget( backgroundTabButton );
if( connectionsTabButton ) infoTabsButtonLayout->addWidget( connectionsTabButton );
infoTabsButtonLayout->addWidget( otherInfoTabButton );
infoTabsButtonLayout->addWidget( buttonsFiller );
infoTabsButtonLayout->addWidget( addContactButton );
infoTabsButtonLayout->addWidget( removeContactButton );
if( experiencesLabel )
experiencesLabel->setStyleSheet( "QLabel { color: rgba(0,0,0,0.54); padding-left: 10px; }" );
if( educationsLabel )
educationsLabel->setStyleSheet( "QLabel { color: rgba(0,0,0,0.54); padding-left: 10px; }" );
if( connectionsTab ) connectionsTab->hideToolsButtons();
if( experiencesWidget ) experiencesWidget->hideToolsButtons();
if( educationsWidget ) educationsWidget->hideToolsButtons();
ProfileWidget::otherInfoTab->hideToolsButtons();
if( backgroundTab ) {
QVBoxLayout *backgroundTabLayout = new QVBoxLayout( backgroundTab );
if( experiencesLabel ) backgroundTabLayout->addWidget( experiencesLabel );
if( experiencesWidget ) backgroundTabLayout->addWidget( experiencesWidget );
if( educationsLabel ) backgroundTabLayout->addWidget( educationsLabel );
if( educationsWidget ) backgroundTabLayout->addWidget( educationsWidget );
backgroundTabLayout->setMargin( 0 );
}
if( connectionsTab ) connectionsTab->setVisible( false );
if( backgroundTab ) otherInfoTab->setVisible( false );
QVBoxLayout *infoTabLayout = new QVBoxLayout( infoTabsWidget );
infoTabLayout->addWidget( infoTabsButtonsWidget );
if( backgroundTab ) infoTabLayout->addWidget( backgroundTab );
if( connectionsTab ) infoTabLayout->addWidget( connectionsTab );
infoTabLayout->addWidget( ProfileWidget::otherInfoTab );
infoTabLayout->setMargin( 0 );
QVBoxLayout *layout = new QVBoxLayout( this );
layout->addWidget( header );
layout->addWidget( infoTabsWidget);
}
// SLOT OtherProfileWidget::addContact
void OtherProfileWidget::addContact() {
emit addContactSignal( user );
addContactButton->setVisible( false );
removeContactButton->setVisible( true );
}
// SLOT OtherProfileWidget::removeContact
void OtherProfileWidget::removeContact() {
emit removeContactSignal( user );
addContactButton->setVisible( true );
removeContactButton->setVisible( false );
}
// SLOT OtherProfileWidget::showBackgroundTab
void OtherProfileWidget::showBackgroundTab() {
if( backgroundTab ) backgroundTab->setVisible( true );
if( backgroundTabButton ) setProfileButtonSelected( backgroundTabButton );
if( connectionsTab ) connectionsTab->setVisible( false );
ProfileWidget::otherInfoTab->setVisible( false );
}
// SLOT OtherProfileWidget::showConnectionsTab
void OtherProfileWidget::showConnectionsTab() {
if( backgroundTab ) backgroundTab->setVisible( false );
if( connectionsTab ) connectionsTab->setVisible( true );
if( connectionsTabButton ) setProfileButtonSelected( connectionsTabButton );
ProfileWidget::otherInfoTab->setVisible( false );
}
// SLOT OtherProfileWidget::showOtherInfoTab
void OtherProfileWidget::showOtherInfoTab() {
if( backgroundTab ) backgroundTab->setVisible( false );
if( connectionsTab ) connectionsTab->setVisible( false );
ProfileWidget::otherInfoTab->setVisible( true );
setProfileButtonSelected( ProfileWidget::otherInfoTabButton );
}
| [
"dalla.costa.nicola@gmail.com"
] | dalla.costa.nicola@gmail.com |
0eb8d448e2835804ba6e571b8b9ef4fc8d3fa80e | 0dbc70644b1aeaeed20c1e3249cdb50e9aff0801 | /String Intermediate/Convert a sentences into its equivalent mobile numeric keypad sequence/main.cpp | e696a20e64804a110b1ada80d32c75930592ea8f | [] | no_license | HimanshuDS14/String-Questions | 85157ff65ba2436d776faa489eb779074ec9ad9a | a778aff88a474f6a21ad6fd80af56b3f8719ab25 | refs/heads/master | 2022-11-15T13:02:59.467584 | 2020-07-08T05:09:03 | 2020-07-08T05:09:03 | 277,995,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cpp | #include <iostream>
using namespace std;
string printSeq(string arr[] , string s)
{
string output = "";
for(int i=0 ;i<s.length(); i++)
{
if(s[i] == ' ')
output+="0";
else
{
int position = s[i] - 'A';
output += arr[position];
}
}
return output;
}
int main()
{
string arr[] = { "2" , "22" , "222" ,
"3" , "33" ,"333" ,
"4" , "44" , "444" ,
"5" , "55" , "555" ,
"6" , "66" , "666" ,
"7" , "77" , "777" ,"7777",
"8" , "88" , "888" ,
"9" , "99" , "999" , "9999" };
string s = "GEEKSFORGEEKS";
cout << printSeq(arr,s);
return 0;
}
| [
"himanshu.poo.02@gmail.com"
] | himanshu.poo.02@gmail.com |
60a49a0fc72facdf5b62c36054ace25e695a9e43 | 35b17ff57a3c401d3a23c56f143b56a1d7d82344 | /cpp/cameras/ptgrey/publisher/publisher.cpp | f49404e0de3763394de52c3b2299e7fa607329d4 | [] | no_license | visiotufes/visiot | 7dc580a431fed44fdfb262bf0b828ef3b06b1212 | d560e8b732ba8c719c204468fb474f81b825428b | refs/heads/master | 2020-04-06T05:52:30.575026 | 2016-11-13T16:09:58 | 2016-11-13T16:09:58 | 73,625,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,589 | cpp | #include <thread>
#include <functional>
#include "ptgrey.hpp"
#include "utils/entity.hpp"
#include "data-publisher.hpp"
#include "service-provider.hpp"
using namespace is;
using namespace is::cameras;
void run_camera(unique_ptr<PointGrey> camera,
std::string broker,
is::entity entity,
std::string fps,
PropertyQueue& queue) {
auto name = entity.type + "." + entity.id;
auto channel = is::connect(broker, 5672, { "ispace", "ispace", "/" });
is::ServiceProvider server(channel, name);
// Expose FPS services
server.expose("fps", [&queue] (auto& service) {
float fps;
service.request(fps);
//std::cout << "Setting FPS [" << i << "]: " << fps << std::endl;
queue.push(CameraProperty(Property::fps, fps));
std::string reply { "ok" };
service.reply(reply);
});
// Expose DELAY services
server.expose("delay", [&queue] (auto& service) {
float delay;
service.request(delay);
//std::cout << "Setting DELAY [" << i << "]: " << delay << std::endl;
queue.push(CameraProperty(Property::delay, delay));
std::string reply { "ok" };
service.reply(reply);
});
// Expose IMAGE_TYPE services
server.expose("type", [&queue] (auto& service) {
int typeInt;
service.request(typeInt);
//std::cout << "Setting TYPE [" << i << "]: " << typeInt << std::endl;
queue.push(CameraProperty(Property::image_type, static_cast<ImageType>(typeInt)));
std::string reply { "ok" };
service.reply(reply);
});
// Expose RESOLUTION services
server.expose("resolution", [&queue] (auto& service) {
std::pair<int, int> res;
service.request(res);
//std::cout << "Setting RESOLUTION [" << i << "]: " << res.first << 'x' << res.second << std::endl;
queue.push(CameraProperty(Property::resolution, Resolution(res.first, res.second)));
std::string reply { "ok" };
service.reply(reply);
});
// Expose individual INFO services
server.expose("info", [&entity] (auto& service) {
service.reply(entity);
std::cout << "Info request[" << entity.id << "]" << std::endl;
});
server.listen();
is::DataPublisher publisher(broker, name);
camera->run();
while (1) {
Image frame;
camera->wait_frame();
while(camera->get_frame(frame)) {
// Publish frame and timestamp
publisher.publish(frame);
publisher.publish(frame.timestamp, camera->get_fps());
}
queue.consume_all([&] (auto& prop) {
camera->set_property(prop);
});
}
camera->stop();
}
int main (int argc, char** argv) {
if (argc < 2 || argc > 3) {
std::cout << ">> Usage: ./publisher <broker-address> <optional-fps>" << std::endl;
return 0;
}
std::string broker = argv[1];
std::string fps = (argc==3) ? argv[2] : "";
// Discovery cameras
auto cameras = PointGrey::discovery();
if(cameras.empty()) {
std::cout << ">> No camera found." << std::endl;
exit(-1);
}
// Sort cameras in specific order
PointGrey::sort_by_serial(cameras, {15358823, 15358824, 15385990, 15328550});
unsigned int ncam = (unsigned int) cameras.size();
// Create propreaty queues
std::vector<PropertyQueue> propsqueue(ncam);
// Create threads for each camera
std::vector<std::thread> threads;
for (int i = 0; i < ncam; ++i) {
is::entity entity {
"camera",
std::to_string(i),
{ "fps", "delay", "type", "resolution", "info" },
{ "frame", "timestamp" }
};
std::thread thread {
run_camera,
std::move(cameras.at(i)),
broker,
entity,
fps,
std::ref(propsqueue.at(i))
};
threads.push_back(std::move(thread));
}
std::cout << ">> Publishing...\n" << std::flush;
threads.back().join();
return 0;
} | [
"mendonca.felippe@gmail.com"
] | mendonca.felippe@gmail.com |
68b245ea8a748aa255ec6ce7c5dae99e96dacd1d | 299bac1a19fe1848e11f776fcfd6ea612a8f560f | /lab3/lab3.cpp | e423eda364449ba4d4ce6bf51cee73ff9ef3c42e | [] | no_license | jeremyroy/cmpe365 | c63415d52a5e082d5a64cd43a5e54ea5ebad5748 | 76107d68721bd69b3191021d7e020cbcc7fe1c2e | refs/heads/master | 2021-07-07T20:59:17.192398 | 2017-10-04T21:25:28 | 2017-10-04T21:25:28 | 105,600,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,751 | cpp | // Author: Jeremy Roy <jeremy.roy@queensu.ca>
// Student number: 10092487
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <map>
#include <utility> // std::pair
std::vector<std::vector<bool>> cvs_to_2d_vector(std::string filename)
{
std::string line;
std::ifstream in_file(filename);
std::vector<std::vector<bool>> rows;
std::vector<bool> col;
if (in_file.is_open())
{
// loop through all lines in file
while (getline (in_file, line))
{
// seperate commas, push csv entries to vector
std::stringstream lineStream(line);
std::string cell;
while (std::getline(lineStream,cell, ','))
{
col.push_back(std::stod(cell));
}
rows.push_back(col);
col.clear();
}
}
in_file.close();
return rows;
}
bool is_unique(std::map<int,std::pair<int,uint16_t>> image_map, int num_features, uint16_t bitmap)
{
if (image_map.count(num_features))
{
// At least one image in map has same number of features
auto same_numf = image_map.equal_range(num_features);
// Iterate through all images with same number of features
for (auto it = same_numf.first; it != same_numf.second; ++it)
{
// Check if this image has identical features.
auto elem = *it;
if (elem.second.second == bitmap)
{
return false;
}
// If last element, image is unique
if ( it++ == same_numf.second )
{
return true;
}
--it;
}
}
}
int main(int argc, char** argv)
{
std::string image_filename = "images.csv";
std::vector<std::vector<bool>> images;
int im_keep = std::stoi(argv[1]); // Number of images to keep (k)
std::map<int,std::pair<int,uint16_t>> best_images; // Order: num_features, index in file, bit-encoded features
std::map<int,std::pair<int,uint16_t>> other_images;
// load image parameters
images = cvs_to_2d_vector(image_filename);
int num_features = 0;
uint16_t bitmap = 0;
// Calculate number of features
for (int row = 0; row < 1000; ++row)
{
num_features = 0;
bitmap = 0;
for (int col = 0; col < 10; ++col)
{
num_features += images.at(row).at(col);
bitmap = (bitmap << 1) | images.at(row).at(col);
}
// If best images map isn't full, add image if unique
if (best_images.size() <= im_keep)
{
// Best image map full, determine whether or not to keep this image
// Check if any image with identical feature set exists
if ( is_unique(best_images, num_features, bitmap) )
{
std::pair<int,uint16_t> image_data(row, bitmap);
best_images.insert(std::pair<int,std::pair<int,uint16_t>>(num_features, image_data));
}
else
{
// Put image in "not best image" map
std::pair<int,uint16_t> image_data(row, bitmap);
other_images.insert(std::pair<int,std::pair<int,uint16_t>>(num_features, image_data));
}
}
else // Map is full. Check if new image is unique and better than a previous unique image. If it is, pop worst unique image.
{
// If image has less or same number of features as worst element in list, discard image
auto elem = *best_images.begin();
if ( num_features > elem.first )
{
// Check if image is unique.
if ( is_unique(best_images, num_features, bitmap) )
{
// Remove worst image from "best image" map.
best_images.erase(best_images.begin());
// Add image to "best image" map.
std::pair<int,uint16_t> image_data(row, bitmap);
best_images.insert(std::pair<int,std::pair<int,uint16_t>>(num_features, image_data));
}
}
}
}
// If best_images map isn't full, add best elements from other_images map.
if (best_images.size() < im_keep)
{
int missing_images = im_keep - best_images.size();
for (int i = 0; i < missing_images; ++i)
{
best_images.insert(*other_images.rbegin());
}
}
// Print images
for (auto it = best_images.begin(); it != best_images.end(); ++it)
{
auto elem = *it;
std::cout << elem.second.second << std::endl;
}
return 0;
} | [
"jeremy.roy@queensu.ca"
] | jeremy.roy@queensu.ca |
de94e5a7227cf22b5d789f5bc5d3fd7facbd7fff | c700154ce860a5d4981ea00890eae706047008ba | /detours/spawn_mob.cpp | f79ca266611e58e64a2a873e2e32423362090aed | [] | no_license | KyleSanderson/left4downtown2 | 392529c8c843fa15a42117159a2e9cc84eac0c26 | 920592613c68c9b9fc4ed6313c2d9b7de2bd4121 | refs/heads/master | 2021-01-01T10:36:02.848425 | 2014-03-02T18:39:11 | 2014-03-02T18:39:11 | 33,843,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,122 | cpp | /**
* vim: set ts=4 :
* =============================================================================
* Left 4 Downtown SourceMod Extension
* Copyright (C) 2009 Igor "Downtown1" Smirnov.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include "spawn_mob.h"
#include "extension.h"
namespace Detours
{
void SpawnMob::OnSpawnMob(int amount)
{
L4D_DEBUG_LOG("ZombieManager::SpawnMob(%d) has been called", amount);
cell_t result = Pl_Continue;
if(g_pFwdOnSpawnMob)
{
L4D_DEBUG_LOG("L4D_OnSpawnMob() forward has been sent out");
g_pFwdOnSpawnMob->PushCellByRef(&amount);
g_pFwdOnSpawnMob->Execute(&result);
}
if(result == Pl_Handled)
{
L4D_DEBUG_LOG("ZombieManager::SpawnMob will be skipped");
return;
}
else
{
(this->*(GetTrampoline()))(amount);
return;
}
}
};
| [
"dcx2gecko@gmail.com"
] | dcx2gecko@gmail.com |
d3ffbdb774d40f6af3815b3f0b9a95479ff0ebd4 | 4e59523f75a0c0386c941e8a9f9db57d587ef55a | /src/main.cpp | ad16570d45f31aebeadd8462040c0ae156e38d82 | [] | no_license | samwade240/BBST | fdce2e6a066211bb4510dca5fd17b82d0b381d51 | fa9715e3c43f4e34975c42091846a2069e307eb0 | refs/heads/master | 2023-01-30T08:15:33.533725 | 2020-12-15T16:11:25 | 2020-12-15T16:11:25 | 321,718,320 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,820 | cpp | #include<bits/stdc++.h>
#include "binarytree.hpp"
using namespace std;
int main()
{
AVLTree<int> tree;
std::string temp;
//Constructing tree given in
//the above figure
tree.put(9);
tree.put(5);
tree.put(10);
tree.put(0);
tree.put(6);
tree.put(11);
tree.put(-1);
tree.put(1);
tree.put(2);
AVLTree<int> secondTree(tree);
// The constructed AVL Tree would be
// 9
// / \
// 1 10
// / \ \
// 0 5 11
// / / \
// -1 2 6
cout << "Preorder traversal of the "
"constructed AVL tree is \n";
temp = tree.preorderString();
cout << temp <<"\n";
cout << tree.getHeight() <<"\n";
cout << "Preorder traversal of the "
"copied AVL tree is \n";
temp = secondTree.preorderString();
cout << temp <<"\n";
cout << secondTree.getHeight() <<"\n";
cout << "INorder traversal of the "
"constructed AVL tree is \n";
temp = tree.inorderString();
cout << temp <<"\n";
cout << tree.getHeight() <<"\n";
cout << "Postorder traversal of the "
"constructed AVL tree is \n";
temp = tree.postorderString();
cout << temp <<"\n";
cout << tree.getHeight() <<"\n";
tree.remove(10);
// The AVL Tree after deletion of 10
// 1
// / \
// 0 9
// / / \
// -1 5 11
// / \
// 2 6
cout << "\nPreorder traversal after"
<< " deletion of 10 \n";
temp = tree.preorderString();
cout << temp <<"\n";
cout << tree.getHeight() <<"\n";
cout <<"Contains 2 should be true: " <<tree.contains(2)<<"\n";
cout << "\nPreorder traversal after"
<< " deletion of 2 and 6 \n";
tree.remove(2);
tree.remove(6);
temp = tree.preorderString();
cout << temp <<"\n";
cout << tree.getHeight() <<"\n";
cout <<"Contains 2 should be false: " <<tree.contains(2)<<"\n";
cout << "\nStarting Treap Tree: \n";
TreapTree<int> treap;
std::string tmp;
srand(time(NULL));
treap.put(50);
treap.put(30);
treap.put(20);
treap.put(40);
treap.put(70);
treap.put(60);
treap.put(80);
// TreapTree<int> secondTreap(treap);
cout << "preorderString traversal of the given tree \n";
tmp = treap.preorderString();
cout << tmp << "\n";
// cout << "preorderString traversal of the copied tree \n";
// tmp = secondTreap.preorderString();
// cout << tmp << "\n";
cout << "inorderString traversal of the given tree \n";
tmp = treap.inorderString();
cout << tmp << "\n";
cout << "postorderString traversal of the given tree \n";
tmp = treap.postorderString();
cout << tmp << "\n";
cout << "\nDelete 20\n";
treap.remove(20);
cout << "postorderString traversal of the modified tree \n";
tmp = treap.postorderString();
cout << tmp << "\n";
cout << "\nDelete 30\n";
treap.remove(30);
cout << "postorderString traversal of the modified tree \n";
tmp = treap.postorderString();
cout << tmp << "\n";
cout << "\nDelete 50\n";
treap.remove(50);
cout << "postorderString traversal of the modified tree \n";
tmp = treap.postorderString();
cout << tmp << "\n";
TreapNode<int> *res = treap.search(50);
(res == NULL)? cout << "\n50 Not Found ":
cout << "\n50 found";
/*
TreapTree<int> treap;
AVLTree<int> tree2;
//Inserting elements of I to delete in the timed for loop
// for(int i = 1000; i < 10000; i += 1000){
for(int i = 1000; i < 10000; i += 100){
tree2.put(i);
treap.put(i);
}
// clock_t is the data type for storing timing information.
// * We must make two variables, one for the start and the other to capture
// * the difference.
clock_t start, diff;
// timeAmount is used to print out the time in seconds.
double timeAmount;
// We want to run our algorithm over varying sizes.
for (int i = 1000; i < 10000; i += 1000) {
// Capture the start clock
start = clock();
// This is were your algorithm should be called.
// Keep in mind that i is the SIZE of the input -- you may have to change it!
// tree2.put(i);
// treap.put(i);
tree2.remove(i);
// treap.remove(i);
// Capture the clock and subtract the start to get the total time elapsed.
diff = clock() - start;
// Convert clock_t into seconds as a floating point number.
timeAmount = diff * 1.0 / CLOCKS_PER_SEC;
// Print out first the size (i) and then the elapsed time.
std::cout << i << " " << timeAmount << "\n";
// We flush to ensure the timings is printed out.
std::cout << std::flush;
}
*/
return 0;
}
| [
"stwade@csustudent.net"
] | stwade@csustudent.net |
3f814a3a58f139c8283a96da86b965c1843f73ec | add70b6fd60742e5cb7bfda75ed6f00df542921d | /Eternity Engine (Outerspace)/Code/code/ETY-Engine/Dev-Libs/boost_old/mpl/list_c.hpp | 9277c062bd05baf1ac01aa2ce7a04a81c49bf83f | [] | no_license | jsaevecke/Harbinger-of-Eternity-2D-Space-Game | 0e6f3484c91154978eb374c8936dc1d3c0f94570 | 17185227648972c7ae206bbb8498cccff83b232e | refs/heads/master | 2021-09-29T08:18:35.420165 | 2018-02-26T16:34:22 | 2018-02-26T16:34:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,909 | hpp |
#ifndef BOOST_MPL_LIST_C_HPP_INCLUDED
#define BOOST_MPL_LIST_C_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: list_c.hpp 3 2013-07-17 10:04:05Z Trout-31 $
// $Date: 2013-07-17 12:04:05 +0200 (Mi, 17 Jul 2013) $
// $Revision: 3 $
#if !defined(BOOST_MPL_PREPROCESSING_MODE)
# include <boost/mpl/limits/list.hpp>
# include <boost/mpl/aux_/nttp_decl.hpp>
# include <boost/mpl/aux_/config/preprocessor.hpp>
# include <boost/preprocessor/inc.hpp>
# include <boost/preprocessor/cat.hpp>
# include <boost/preprocessor/stringize.hpp>
#if !defined(BOOST_NEEDS_TOKEN_PASTING_OP_FOR_TOKENS_JUXTAPOSING)
# define AUX778076_LIST_C_HEADER \
BOOST_PP_CAT(BOOST_PP_CAT(list,BOOST_MPL_LIMIT_LIST_SIZE),_c).hpp \
/**/
#else
# define AUX778076_LIST_C_HEADER \
BOOST_PP_CAT(BOOST_PP_CAT(list,BOOST_MPL_LIMIT_LIST_SIZE),_c)##.hpp \
/**/
#endif
# include BOOST_PP_STRINGIZE(boost/mpl/list/AUX778076_LIST_C_HEADER)
# undef AUX778076_LIST_C_HEADER
# include <climits>
#endif
#include <boost/mpl/aux_/config/use_preprocessed.hpp>
#if !defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \
&& !defined(BOOST_MPL_PREPROCESSING_MODE)
# define BOOST_MPL_PREPROCESSED_HEADER list_c.hpp
# include <boost/mpl/aux_/include_preprocessed.hpp>
#else
# include <boost/mpl/limits/list.hpp>
# define AUX778076_SEQUENCE_NAME list_c
# define AUX778076_SEQUENCE_LIMIT BOOST_MPL_LIMIT_LIST_SIZE
# define AUX778076_SEQUENCE_NAME_N(n) BOOST_PP_CAT(BOOST_PP_CAT(list,n),_c)
# define AUX778076_SEQUENCE_INTEGRAL_WRAPPER
# include <boost/mpl/aux_/sequence_wrapper.hpp>
#endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS
#endif // BOOST_MPL_LIST_C_HPP_INCLUDED
| [
"Julien.Saevecke@udo.edu"
] | Julien.Saevecke@udo.edu |
a596aa954c90fd873d81610c6ce54a0b3067db63 | a2e04e4eac1cf93bb4c1d429e266197152536a87 | /Cpp/SDK/Title_SD_TreacherousSeaDog_classes.h | b803d15a5ac231ccedb05db04c910964a105bbb6 | [] | no_license | zH4x-SDK/zSoT-SDK | 83a4b9fcdf628637613197cf644b7f4d101bb0cb | 61af221bee23701a5df5f60091f96f2cf929846e | refs/heads/main | 2023-07-16T18:23:41.914014 | 2021-08-27T15:44:23 | 2021-08-27T15:44:23 | 400,555,804 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 771 | h | #pragma once
// Name: SoT, Version: 2.2.1.1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Title_SD_TreacherousSeaDog.Title_SD_TreacherousSeaDog_C
// 0x0000 (FullSize[0x00E0] - InheritedSize[0x00E0])
class UTitle_SD_TreacherousSeaDog_C : public UTitleDesc
{
public:
static UClass* StaticClass()
{
static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass Title_SD_TreacherousSeaDog.Title_SD_TreacherousSeaDog_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
e6afd5972581149fa8c7744b7ab9a53196e7d7cf | d5c2a1e3873b76216eba7a767f064f6dbb260abb | /3. Longest Substring Without Repeating Characters/lengthOfLongestSubstring1.cpp | 590f16e5ec11ecb45459474dc67d432e041e3caa | [] | no_license | Ray-SunR/leetcode | 93cdc3d3f114428e6f58995c6ea393eb608aa371 | 693dc65005c65cf32313a7442d07b89890197249 | refs/heads/master | 2022-05-01T16:54:10.490623 | 2022-04-21T21:22:32 | 2022-04-21T21:22:32 | 34,715,133 | 0 | 1 | null | 2019-07-10T03:47:46 | 2015-04-28T07:19:25 | C++ | UTF-8 | C++ | false | false | 894 | cpp | #include <iostream>
#include <map>
using namespace std;
// abcabcbb
// abc
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
map<int, int> hash;
int left = 0; int right = 0; int max = 0;
while (right < s.size())
{
if (hash.find(s[right]) != hash.end())
{
int pos = hash[s[right]];
max = right - left > max ? right - left : max;
left = left < pos + 1 ? pos + 1 : left;
}
hash[s[right]] = right;
right++;
}
return right - left > max ? right - left : max;
}
};
int main(void)
{
Solution s;
cout << s.lengthOfLongestSubstring("abbaaa") << endl;
cout << s.lengthOfLongestSubstring("abcabcbb") << endl;
cout << s.lengthOfLongestSubstring("bbbbb") << endl;
cout << s.lengthOfLongestSubstring("") << endl;
cout << s.lengthOfLongestSubstring("abcdef") << endl;
cout << s.lengthOfLongestSubstring("aabacdebaaabbb") << endl;
return 0;
} | [
"sunrenchen@gmail.com"
] | sunrenchen@gmail.com |
44e901a61599e4d72109eaabbe20eb753c114628 | 3b5c65bde1ef327c2f229e7164f21238bd65cd43 | /Client.h | 6a2bd58c88dee1d4688c8acde05d20a031c2dcc1 | [] | no_license | SCube19/Robaki | 7195d12f6ed11ae177f1f214ee776b0f2c6f1ca7 | f70e2450416f4bb3daee26beafce0a194246c8fe | refs/heads/main | 2023-05-04T21:50:06.452718 | 2021-05-26T18:58:42 | 2021-05-26T18:58:42 | 371,034,705 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,158 | h | #ifndef CLIENT_H
#define CLIENT_H
#include <string>
#include <math.h>
struct __attribute__((packed)) ClientMessage
{
uint64_t session_id;
uint8_t turn_direction;
uint32_t next_expected_event_no;
char player_name[21];
};
enum TurningDirection
{
NONE,
RIGHT,
LEFT
};
using client_coord = std::pair<long double, long double>;
using coord_int = std::pair<uint32_t, uint32_t>;
class Client
{
private:
uint64_t session_id;
//last received turn_direction
TurningDirection lastTurningDirection;
//client flag due to -Wreorder
bool disconnected;
bool observer;
std::string name;
int turningAngle;
client_coord coords;
//client flags
bool alive;
bool sessionDiff;
bool wantsToStart;
public:
Client() = default;
Client(const Client &client) = default;
Client(Client *client);
Client(int sessionArg, TurningDirection turnArg, const std::string &nameArg);
Client(const ClientMessage &msg);
//getters
uint64_t getSessionId() const;
TurningDirection getTurningDirection() const;
int getAngle() const;
std::string getName() const;
coord_int getPixelCoord() const;
bool isObserver() const;
bool isDisconnected() const;
bool isAlive() const;
bool isSessionIdHigher() const;
bool willingToStart() const;
//setters
void disconnect();
void observe(bool x);
void sessionDiffDetected(bool x);
void die(bool x);
void will(bool x);
void setTurningDirection(TurningDirection direction);
void setAngle(int angle);
void setSessionId(uint64_t sessionArg);
void setName(std::string nameArg);
void setCoords(const client_coord &c);
void addAngle(int angle);
void changeClient(const ClientMessage &msg);
//moves client and return whether his integer coords have changed
bool move();
//comparator operators
bool operator==(Client const &o) const { return this->name.compare(o.name) == 0; }
bool operator<(Client const &o) const { return (this->observer < o.observer || (this->observer == o.observer && this->name.compare(o.name) < 0)); }
};
#endif // !CLIENT_H
| [
"kk418331@students.mimuw.edu.pl"
] | kk418331@students.mimuw.edu.pl |
f2dd14a2e58fa55b37c45276f1fccd2cba1e6581 | c32ee8ade268240a8064e9b8efdbebfbaa46ddfa | /Libraries/m2sdk/game/ai/C_BBRecord_WanderMainDir.h | 5692fe8cc7add105c30b38c5acf213f81aad3206 | [] | no_license | hopk1nz/maf2mp | 6f65bd4f8114fdeb42f9407a4d158ad97f8d1789 | 814cab57dc713d9ff791dfb2a2abeb6af0e2f5a8 | refs/heads/master | 2021-03-12T23:56:24.336057 | 2015-08-22T13:53:10 | 2015-08-22T13:53:10 | 41,209,355 | 19 | 21 | null | 2015-08-31T05:28:13 | 2015-08-22T13:56:04 | C++ | UTF-8 | C++ | false | false | 380 | h | // auto-generated file (rttidump-exporter by h0pk1nz)
#pragma once
#include <game/ai/C_BBRecord.h>
namespace game
{
namespace ai
{
/** game::ai::C_BBRecord_WanderMainDir (VTable=0x01E468E0) */
class C_BBRecord_WanderMainDir : public C_BBRecord
{
public:
virtual void vfn_0001_D07A90C8() = 0;
virtual void vfn_0002_D07A90C8() = 0;
};
} // namespace ai
} // namespace game
| [
"hopk1nz@gmail.com"
] | hopk1nz@gmail.com |
c2c38651bfd7a7a8523221827c31f3e948e2ca7e | 1bea45eb404581f3ba2314c61eddcb6926a747a7 | /AtCoder/arc/arc_006/3_arc006_c.cpp | 869ea80d0f5bc0b60cd4a52147a2bd888ed591db | [] | no_license | yokotech/competitive_programming | 9cf2b00c94a2381a00e3127e52fef19245245991 | 99502f661851dd53a41fa33d8267399cce6a4f6f | refs/heads/master | 2020-07-02T23:40:44.850521 | 2019-11-09T14:37:45 | 2019-11-09T14:37:45 | 201,705,416 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,507 | cpp | // 3_arc006_c
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
using namespace std;
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define SZ(x) ((int)(x).size())
#define INF (1e16)
#define MOD (1000000007)
typedef long long ll;
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
return 0;
}
| [
"yokoyama-ryo949@g.ecc.u-tokyo.ac.jp"
] | yokoyama-ryo949@g.ecc.u-tokyo.ac.jp |
a47b6890aa1eb935b2717d630807ec584f25e7ee | 23c524e47a96829d3b8e0aa6792fd40a20f3dd41 | /.history/Map_20210522201104.hpp | adccd557920c6eb98af85520a8f70ff472eb8baa | [] | no_license | nqqw/ft_containers | 4c16d32fb209aea2ce39e7ec25d7f6648aed92e8 | f043cf52059c7accd0cef7bffcaef0f6cb2c126b | refs/heads/master | 2023-06-25T16:08:19.762870 | 2021-07-23T17:28:09 | 2021-07-23T17:28:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,528 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Map.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dbliss <dbliss@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/19 17:14:29 by dbliss #+# #+# */
/* Updated: 2021/05/22 20:11:04 by dbliss ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MAP_HPP
#define MAP_HPP
#include "Algorithm.hpp"
#include "Identifiers.hpp"
#include "MapIterator.hpp"
#include <utility>
namespace ft
{
template <class Key, class T,
class Compare = less<Key>,
class Alloc = std::allocator<std::pair<const Key, T> > >
class map
{
private:
struct TreeNode
{
std::pair<const Key, T> val;
TreeNode *left;
TreeNode *right;
TreeNode *parent;
unsigned char height;
};
public:
typedef Key key_type;
typedef T mapped_type;
typedef std::pair<const key_type, mapped_type> value_type;
typedef less<key_type> key_compare;
typedef Alloc allocator_type;
typedef typename Alloc::reference reference;
typedef typename Alloc::const_reference const_reference;
typedef typename Alloc::pointer pointer;
typedef typename Alloc::const_pointer const_pointer;
typedef typename ft::MapIterator<pointer, TreeNode> iterator;
typedef typename ft::MapIterator<const pointer, TreeNode> const_iterator;
typedef typename ft::myReverseIterator<iterator> reverse_iterator;
typedef typename ft::myReverseIterator<const_iterator> const_reverse_iterator;
typedef ptrdiff_t difference_type;
typedef size_t size_type;
typedef typename Alloc::template rebind<TreeNode>::other node_allocator_type;
/*================================ 4 CONSTRUCTORS: ================================*/
/* EMPTY */
explicit map(const key_compare &comp = key_compare(),
const allocator_type &alloc = allocator_type()) : _node(NULL), _comp(comp), _allocator_type(alloc)
{
this->_last_node = allocate_tree_node();
}
/*RANGE*/
template <class InputIterator>
map(InputIterator first, InputIterator last,
const key_compare &comp = key_compare(),
const allocator_type &alloc = allocator_type());
/*COPY*/
map(const map &x);
/*================================ DESTRUCTOR: ================================*/
virtual ~map() {}
/*================================ OPERATOR=: ================================*/
map &operator=(const map &x);
/*================================ ITERATORS: ================================*/
iterator begin()
{
return (iterator(min_node(this->_node)));
}
const_iterator begin() const;
iterator end()
{
return (iterator(this->_last_node));
}
const_iterator end() const
{
return (const_iterator(this->_last_node));
}
reverse_iterator rbegin()
{
return (reverse_iterator(end()));
}
const_reverse_iterator rbegin() const
{
return (const_reverse_iterator(end()));
}
reverse_iterator rend()
{
return (reverse_iterator(begin()));
}
const_reverse_iterator rend() const
{
return (const_reverse_iterator(begin()));
}
/*================================ CAPACITY: ================================*/
bool empty() const;
size_type size() const;
size_type max_size() const;
/*================================ ELEMENT ACCESS: ================================*/
mapped_type &operator[](const key_type &k)
{
//return (*((this->insert(make_pair(k,mapped_type()))).first)).second);
}
/*================================ MODIFIERS: ================================*/
/* INSERT */
/* The single element versions (1) return a pair,
with its member pair::first set to an iterator pointing to either the newly inserted element
or to the element with an equivalent key in the map. The pair::second element in the pair
is set to true if a new element was inserted or false if an equivalent key already existed. */
std::pair<iterator, bool> insert(const value_type &val)
{
iterator iter;
if (!this->_node) // Insert the first node, if root is NULL.
{
this->_node = allocate_tree_node();
this->_allocator_type.construct(&_node->val, val);
this->_last_node->parent = this->_node;
this->_node->right = this->_last_node;
iter = this->_node;
return make_pair(iter, true);
}
else
{
TreeNode *new_node = construct_tree_node(val);
TreeNode *root = _node;
key_type key;
if (val.first <= _node->val.first)
{
while (root->left)
{
key = root->val.first;
if (key == val.first)
{
iter = root;
return (make_pair(iter, false));
}
root = root->left;
}
root->left = new_node;
new_node->right = NULL;
new_node->left = NULL;
new_node->parent = root;
iter = new_node;
}
else
{
while (root->right != _last_node)
{
key = root->val.first;
if (key == val.first)
{
iter = root;
return (make_pair(iter, false));
}
root = root->right;
}
root->right = new_node;
new_node->left = NULL;
new_node->right = _last_node;
_last_node->parent = new_node;
new_node->parent = root;
iter = _last_node;
}
return make_pair(iter, true);
}
}
// then add balancing function !
iterator insert(iterator position, const value_type &val);
template <class InputIterator>
void insert(InputIterator first, InputIterator last);
/* ERASE */
void erase(iterator position);
size_type erase(const key_type &k);
void erase(iterator first, iterator last);
/* SWAP */
void swap(map &x);
/* CLEAR */
void clear();
/*================================ OBSERVERS: ================================*/
key_compare key_comp() const;
// value_compare value_comp() const;
/*================================ OPERATIONS: ================================*/
iterator find(const key_type &k);
const_iterator find(const key_type &k) const;
size_type count(const key_type &k) const;
iterator lower_bound(const key_type &k);
const_iterator lower_bound(const key_type &k) const;
iterator upper_bound(const key_type &k);
const_iterator upper_bound(const key_type &k) const;
std::pair<const_iterator, const_iterator> equal_range(const key_type &k) const;
std::pair<iterator, iterator> equal_range(const key_type &k);
/*================================ HELPING FUNCTIONS : ================================*/
TreeNode *allocate_tree_node()
{
TreeNode *node;
node = this->_alloc_node.allocate(1);
node->right = NULL;
node->left = NULL;
node->parent = NULL;
std::memset(&node->val, 0, sizeof(node->val));
return node;
}
TreeNode *construct_tree_node(const_reference val)
{
TreeNode *node;
node = allocate_tree_node();
this->_allocator_type.construct(&node->val, val);
return (node);
}
unsigned char height(TreeNode *p)
{
if (p)
return p->height;
else
return 0;
}
int balanceFactor(TreeNode *p)
{
return height(p->right) - height(p->left);
}
void fixHeight(TreeNode *p)
{
unsigned char hl = height(p->left);
unsigned char hr = height(p->right);
p->height = (hl > hr ? hl : hr) + 1; // +1 for root
}
TreeNode *rotateright(TreeNode *p) // правый поворот вокруг p
{
TreeNode *q = p->left;
p->left = q->right;
q->right = p;
fixheight(p);
fixheight(q);
return q;
}
TreeNode *rotateleft(TreeNode *q) // левый поворот вокруг q
{
TreeNode *p = q->right;
q->right = p->left;
p->left = q;
fixheight(q);
fixheight(p);
return p;
}
TreeNode *min_node(TreeNode *node)
{
if (node)
{
while (node->left)
node = node->left;
}
return (node);
}
private:
TreeNode *_node;
TreeNode *_last_node;
Compare _comp;
allocator_type _allocator_type;
node_allocator_type _alloc_node;
};
}
#endif | [
"asleonova.1@gmail.com"
] | asleonova.1@gmail.com |
2a5faaa7b42bbfa4fbf32d900b3c284ecd58299b | e8d05dc3622c2aa60d9610548c7a671f11b6227e | /app/rdo_studio/src/dock/dock_chart_tree.cpp | 8302e496e64f17802d2f630cec47014c895e07ed | [
"MIT"
] | permissive | yarkeeb/rdo_studio | b69ec5a1e506e97dbd08f6233e298c5f0799e9ba | c7e21aa144bc2620d36b1c6c11eb8a99f64574ab | refs/heads/master | 2021-05-27T03:00:41.858923 | 2014-04-03T16:28:19 | 2014-04-03T16:28:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,155 | cpp | /*!
\copyright (c) RDO-Team, 2012-2012
\file dock_chart_tree.cpp
\author Урусов Андрей (rdo@rk9.bmstu.ru)
\date 06.10.2012
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "app/rdo_studio/pch/application_pch.h"
// ----------------------------------------------------------------------- INCLUDES
#include "utils/src/common/warning_disable.h"
#include <QAction>
#include "utils/src/common/warning_enable.h"
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio/src/dock/dock_chart_tree.h"
#include "app/rdo_studio/src/tracer/tracer.h"
// --------------------------------------------------------------------------------
DockChartTree::DockChartTree(QWidget* pParent)
: DockFocusable("Графики", pParent)
{
PTR(context_type) pWidget = new context_type(this);
pWidget->setMinimumSize(QSize(150, 200));
setWidget(pWidget);
toggleViewAction()->setIcon(QIcon(QString::fromUtf8(":/images/images/dock_chart.png")));
g_pTracer->setTree(pWidget);
}
DockChartTree::~DockChartTree()
{}
| [
"drobus@gmail.com"
] | drobus@gmail.com |
068fb78188f05f0ad76f319765733a5a3d580438 | d9c1c4ae9e03d9e2782d8a898e518a3b8bf6ff58 | /NewGDTS/GDTS_Server/WMV_TO_H264/VNMPDlg.h | 1c7eb51a9ebed465307ff2b2919a3e87f1ab8b85 | [] | no_license | zhaohongqiang/Codes | 753166b168a081d679e474ad0b0062d463a06096 | f28c860a65afc81ba19d1f49e1edbda719f44f03 | refs/heads/master | 2021-03-04T16:11:47.299084 | 2019-11-02T06:12:39 | 2019-11-02T06:12:39 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 956 | h | #pragma once
#include "H264Stream.h"
#include "vnmpLib.h"
#include "common.h"
// CVNMPDlg 对话框
class CVNMPDlg : public CDialog , public CCommon
{
DECLARE_DYNAMIC(CVNMPDlg)
public:
CVNMPDlg(CWnd* pParent = NULL); // 标准构造函数
virtual ~CVNMPDlg();
DEV_VNMP_PARAMS m_devParams[16];
//int SourceCount;
//CH264Stream *m_h264[16];
// 对话框数据
enum { IDD = IDD_VNMP_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
int GetInforFromIni4Company(void * pThisDir,int nIndex);
int GetInforFromIni(void* iniPath);
int SetDefaultParams(void * pParams);
int ParseRequest(char * pXmlBuf,CString *str);
CString CheckExit(CString str);
CString ChangeChannel(CString sId,int CH,CString str);
// 启动拉流函数
int SetParams(void *pStream,void * pParams);
int StartPull(void *pStream,void* pParams);
int ClosePull(void *pStream,void * pParams);
};
| [
"jc1402080216@163.com"
] | jc1402080216@163.com |
fc6602eb337df71827c8f17b474486552b09fdba | 41c678a8d10648fbfe09e8af6227f80b001b3c8e | /src/core/mesh.h | 30a59d015f93d9d77990aa4a755ca0c75ef6d529 | [] | no_license | bagobor/Beetle | b1fd1d76658d5bdd7870f461bf3f402e0da000b9 | 74be790ba2d0894f7e7604b02d2f363e296a8c8f | refs/heads/master | 2020-12-30T23:21:40.625167 | 2014-10-08T17:32:37 | 2014-10-08T17:32:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 414 | h | #ifndef MESH_H
#define MESH_H
#include <QVector>
#include <QVector2D>
#include <QVector3D>
class Mesh2D {
protected:
QVector<QVector2D> vertices;
QVector<QVector2D> texCoord;
QVector<unsigned int> indices;
};
class Mesh {
protected:
QVector<QVector3D> vertices;
QVector<QVector3D> normals;
QVector<QVector3D> tangetns;
QVector<QVector2D> texCoord;
QVector<unsigned int> indices;
};
#endif // MESH_H
| [
"torvald@torvald.(none)"
] | torvald@torvald.(none) |
06aa656eaa281c64bddb4baa9e4663c752ae6f0b | 64f778efc2e110adc199856e7850871ee00f142f | /TDT4102 Oving 8/Circle.cpp | 95a2e5d87c7219468b660504cd075c2b7ab15355 | [] | no_license | hanshell/TDT4102 | 14b0de7a12cc7e623d9c1b4ce3383ba39ca30808 | 104df6edeeb7839e4a3ae84b4b568247268b7ddf | refs/heads/master | 2021-01-22T03:05:02.240889 | 2013-06-23T12:07:17 | 2013-06-23T12:07:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,014 | cpp | #include "Circle.h"
#include <math.h>
#include <iostream>
#include <stdlib.h>
#include <time.h>
Circle::Circle(int x0, int y0, int radius, Color col) {
this->radius = radius;
this->x0 = x0;
this->y0 = y0;
setColor(col);
}
void Circle::Draw(Image& img) {
int x;
int y;
for (int i = x0 - radius; i < radius + x0; i++) {
y = y0 + sqrt(double(-pow(i - x0, 2) + pow(radius, 2)));
x = x0 + sqrt(double(-pow(y - y0, 2) + pow(radius, 2)));
int diff = y - y0;
img.SetColor(i, y, getColor());
img.SetColor(i, y0 - diff, getColor());
}
for (int i = y0 - radius; i < radius + y0; i++) {
x = x0 + sqrt(double(-pow(i - y0, 2) + pow(radius, 2)));
int diff=x-x0;
img.SetColor(x, i, getColor());
img.SetColor(x0-diff, i, getColor());
std::cout<<"y: "<<i<<" "<<"x: "<<x<<std::endl;
}
}
int Circle::getRadius() {
return radius;
}
Circle Circle::operator+(Circle circle){
} | [
"hanshmelby@gmail.com"
] | hanshmelby@gmail.com |
51dea1ddad8f3799c589b0e3206a9c0401026956 | 0e456e7610169365ad5d0304701a4939cbf230ef | /gfg/must do interview que/Hashing/IsSudokuValid.cpp | 78e4e4191968ec2f962132ec1ee27d4faf3c37fb | [] | no_license | rverma870/DSA-practice | 8674e75225fdb4396560e5d8cfd9c4a3fc6a3356 | f714d4887888dd774fa1c10192c59767074425e9 | refs/heads/main | 2023-06-11T02:12:52.447346 | 2021-06-19T17:16:32 | 2021-06-19T17:16:32 | 369,564,546 | 0 | 0 | null | 2021-05-21T14:54:53 | 2021-05-21T14:39:21 | C++ | UTF-8 | C++ | false | false | 1,015 | cpp | #include<bits/stdc++.h>
using namespace std;
int isValid(vector<vector<int>> mat)
{
set<string>st;
string row="",col="",box="";
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
if(mat[i][j]!=0)
{
row="Row" + to_string(i)+ "*" + to_string(mat[i][j]);
col="Col" + to_string(j)+ "*" + to_string(mat[i][j]);
int x= (i/3)*3+j/3;
box="Box" + to_string(x)+ "*" + to_string(mat[i][j]);
if(st.find(row)!=st.end() || st.find(col)!=st.end() || st.find(box)!=st.end())
{cout<<i<<" "<<j<<endl;
return 0;}
else
{
st.insert(row);
st.insert(col);
st.insert(box);
}
}
}
}
return 1;
}
int main()
{
vector<vector<int>>mat(9);
for(int i=0;i<9;i++)
{
vector<int>temp(9);
for(int j=0;j<9;j++)
{
cin>>temp[j];
}
mat[i]=temp;
}
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
cout<<isValid(mat);
}
| [
"rverma870@gmail.com"
] | rverma870@gmail.com |
bd482aa71a5c441564671c2c234f13d706bb8c51 | f7eab0e4b47d8484327056beeace689bc8d6adbb | /OpenGL_Project/src/Render/Renderer.cpp | c3708b0f2a7f6e587053fcb17acdc13c3a007eba | [] | no_license | Shturm0weak/OpenGL-2D-engine | f5d53fbd56c31043fdc1592acdb86a908ee80bb9 | 963811504cdc04f23acad45ef6f005541539bf96 | refs/heads/master | 2023-04-14T07:03:24.792664 | 2020-02-14T15:48:18 | 2020-02-14T15:48:18 | 213,491,490 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,862 | cpp | #include "../pch.h"
#include "Renderer.h"
#include <iostream>
void Renderer::Clear() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Renderer::DeleteAll() {
for (unsigned int i = 0; i < Renderer2DLayer::objects2d.size(); i++)
{
delete(&Renderer2DLayer::objects2d[i].get());
}
for (unsigned int i = 0; i < Renderer2DLayer::collision2d.size(); i++)
{
delete(&Renderer2DLayer::collision2d[i].get());
}
Renderer2DLayer::collision2d.clear();
Renderer2DLayer::objects2d.clear();
Renderer2DLayer::col_id = 0;
Renderer2DLayer::obj_id = 0;
}
void Renderer::DeleteObject(int id) {
if (Renderer2DLayer::objects2d[id].get().GetCollisionReference() != nullptr) {
int _id = Renderer2DLayer::objects2d[id].get().GetCollisionReference()->GetId();
Renderer2DLayer* col = Renderer2DLayer::objects2d[id].get().GetCollisionReference();
std::unique_ptr<Renderer2DLayer> my_p_col(new Renderer2DLayer(std::move(*col)));
Renderer2DLayer::collision2d.erase(_id + Renderer2DLayer::collision2d.begin());
Renderer2DLayer::col_id--;
int size = Renderer2DLayer::collision2d.size();
if (_id != size) {
for (unsigned int i = _id; i < size; i++)
{
Renderer2DLayer::collision2d[i].get().SetId(i);
}
}
}
Renderer2DLayer* go = &Renderer2DLayer::objects2d[id].get();
std::unique_ptr<Renderer2DLayer> my_p_obj(new Renderer2DLayer(std::move(*go)));
Renderer2DLayer::objects2d.erase(Renderer2DLayer::objects2d.begin() + id);
Renderer2DLayer::obj_id--;
int size = Renderer2DLayer::objects2d.size();
if (id != size) {
for (unsigned int i = 0; i < size; i++)
{
Renderer2DLayer::objects2d[i].get().SetId(i);
Renderer2DLayer::objects2d[i].get().GetLayer() = i;
}
}
}
void Renderer::Save(const std::string filename) {
std::ofstream out_file;
out_file.open(filename, std::ofstream::trunc);
if (out_file.is_open()) {
for (unsigned int i = 0; i < Renderer2DLayer::objects2d.size(); i++)
{
if (Renderer2DLayer::objects2d[i].get().type->c_str() == "GameObject")
continue;
double* pos = Renderer2DLayer::objects2d[i].get().GetPositions();
float* color = Renderer2DLayer::objects2d[i].get().GetColor();
float* scale = Renderer2DLayer::objects2d[i].get().GetScale();
out_file << *Renderer2DLayer::objects2d[i].get().name << "\n"
<< *Renderer2DLayer::objects2d[i].get().type << "\n"
<< Renderer2DLayer::objects2d[i].get().GetShaderType() << "\n"
<< pos[0] << " " << pos[1] << "\n"
<< Renderer2DLayer::objects2d[i].get().GetAngle() << "\n";
if (static_cast<ComponentManager*>(Renderer2DLayer::objects2d[i].get().GetComponentManager())->GetComponent<Collision>() != nullptr) {
out_file << 1 << "\n";
out_file << static_cast<ComponentManager*>(Renderer2DLayer::objects2d[i].get().GetComponentManager())->GetComponent<Collision>()->offsetX
<< " " << static_cast<ComponentManager*>(Renderer2DLayer::objects2d[i].get().GetComponentManager())->GetComponent<Collision>()->offsetY << "\n";
}
else {
out_file << 0 << "\n";
out_file << 0 << " " << 0 << "\n";
}
if (Renderer2DLayer::objects2d[i].get().GetShaderType() == 0){
out_file << *Renderer2DLayer::objects2d[i].get().GetPathToTexture() << "\n";
out_file << color[0] << " " << color[1] << " " << color[2] << " " << 255 << "\n";
}
else if (Renderer2DLayer::objects2d[i].get().GetShaderType() == 1) {
out_file << "None" << "\n";
out_file << color[0] << " " << color[1] << " " << color[2] << " " << color[3] << "\n";
}
out_file << scale[0] << " " << scale[1] << " " << scale[2];
if (i + 1 != Renderer2DLayer::objects2d.size())
out_file << "\n";
delete pos;
delete color;
}
}
else {
std::cout << "Error: filename doesn't exist";
}
out_file.close();
}
void Renderer::Load(const std::string filename)
{
DeleteAll();
std::string name = "";
std::string type = "";
std::string pathtotext = "";
bool hascollision = 0;
float angle = 0;
double pos[2];
float scale[3];
float color[4];
float offset[2];
int shadertype = 1;
std::ifstream in_file;
in_file.open(filename);
if (in_file.is_open()) {
while (in_file.peek() != EOF) {
in_file >> name;
//std::cout << name << std::endl;
in_file >> type;
//std::cout << type << std::endl;
in_file >> shadertype;
//std::cout << shadertype << std::endl;
in_file >> pos[0] >> pos[1];
//std::cout << pos[0] << " " << pos[1] << std::endl;
in_file >> angle;
//std::cout << angle << std::endl;
in_file >> hascollision;
//std::cout << hascollision << std::endl;
in_file >> offset[0] >> offset[1];
//std::cout << offset[0] << " " << offset[1] << std::endl;
in_file >> pathtotext;
//std::cout << pathtotext << std::endl;
in_file >> color[0] >> color[1] >> color[2] >> color[3];
//std::cout << color[0] << " " << color[1] << " " << color[2] << " " << color[3] << std::endl;
in_file >> scale[0] >> scale[1] >> scale[2];
//std::cout << scale[0] << " " << scale[1] << " " << scale[2] << std::endl;
if (type == "GameObject") {
LoadObj<GameObject>(name, pathtotext, angle, color, scale, pos, shadertype,hascollision,offset);
}
}
}
in_file.close();
}
void Renderer::Render(OrthographicCamera& camera)
{
for (unsigned int i = 0; i < Renderer2DLayer::objects2d.size(); i++) {
if(&Renderer2DLayer::objects2d[i].get() != nullptr)
Renderer2DLayer::objects2d[i].get().OnRunning(camera);
}
if (Collision::IsVisible == true) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
for (unsigned int i = 0; i < Renderer2DLayer::collision2d.size(); i++) {
if (Renderer2DLayer::collision2d[i].get().GetCollisionReference() != nullptr) {
if (Renderer2DLayer::collision2d[i].get().IsCollisionEnabled()) {
Renderer2DLayer::collision2d[i].get().OnRunning(camera);
}
}
}
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
} | [
"turlak01@mail.ru"
] | turlak01@mail.ru |
4691bd45b6a201a1a542ab2970f66fd357ed2929 | 3f9d0e536e6e3841768eeb4de43bca6e99064f7e | /Problem_Statement_1.cpp | 5044a132033375806ae88a3f367a37abf75d0ef6 | [] | no_license | allaudeen/VeeFix-Online-Challenge | 934f3812f737d7ce0050c14f5d76990f521a80c3 | 231786439cdca84d764bc821f1596878ad56c675 | refs/heads/master | 2021-01-10T14:24:40.671410 | 2016-01-06T11:52:22 | 2016-01-06T11:52:22 | 49,132,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | cpp | #include <iostream>
#include <set>
#include <string>
#include <conio.h>
using namespace std;
int main() {
int N;
cin>>N;
string input;
set<string> setOfString;
for(int i = 0; i < N; i++ ) {
cin>>input;
setOfString.insert(input);
}
int setSize = setOfString.size();
for(set<string>::iterator setIterator = setOfString.begin(); setIterator != setOfString.end(); setIterator++) {
cout<<*setIterator<<endl;
}
_getch();
return 0;
}
| [
"allaudeen.n@gmail.com"
] | allaudeen.n@gmail.com |
480043401e641475ceb134af135cf524ed00391b | 72af4ae88195e8b3ea3aa763a87d30b6e0602161 | /src/serialize.h | f754a22ece496bef535e508bd84828d91f811a07 | [
"MIT"
] | permissive | rivercoin/facilecoin-core | 2374f29acd6c692796a434b9a4b42a5355d58a82 | 0cb393087f2a8aa2122a6c9a2aca4d487a20c580 | refs/heads/master | 2021-01-09T06:35:11.827404 | 2016-05-25T19:32:03 | 2016-05-25T19:32:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,718 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The FacileCoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_SERIALIZE_H
#define BITCOIN_SERIALIZE_H
#include <algorithm>
#include <assert.h>
#include <ios>
#include <limits>
#include <map>
#include <set>
#include <stdint.h>
#include <string>
#include <string.h>
#include <utility>
#include <vector>
class CScript;
static const unsigned int MAX_SIZE = 0x02000000;
/**
* Used to bypass the rule against non-const reference to temporary
* where it makes sense with wrappers such as CFlatData or CTxDB
*/
template<typename T>
inline T& REF(const T& val)
{
return const_cast<T&>(val);
}
/**
* Used to acquire a non-const pointer "this" to generate bodies
* of const serialization operations from a template
*/
template<typename T>
inline T* NCONST_PTR(const T* val)
{
return const_cast<T*>(val);
}
/**
* Get begin pointer of vector (non-const version).
* @note These functions avoid the undefined case of indexing into an empty
* vector, as well as that of indexing after the end of the vector.
*/
template <class T, class TAl>
inline T* begin_ptr(std::vector<T,TAl>& v)
{
return v.empty() ? NULL : &v[0];
}
/** Get begin pointer of vector (const version) */
template <class T, class TAl>
inline const T* begin_ptr(const std::vector<T,TAl>& v)
{
return v.empty() ? NULL : &v[0];
}
/** Get end pointer of vector (non-const version) */
template <class T, class TAl>
inline T* end_ptr(std::vector<T,TAl>& v)
{
return v.empty() ? NULL : (&v[0] + v.size());
}
/** Get end pointer of vector (const version) */
template <class T, class TAl>
inline const T* end_ptr(const std::vector<T,TAl>& v)
{
return v.empty() ? NULL : (&v[0] + v.size());
}
/////////////////////////////////////////////////////////////////
//
// Templates for serializing to anything that looks like a stream,
// i.e. anything that supports .read(char*, size_t) and .write(char*, size_t)
//
enum
{
// primary actions
SER_NETWORK = (1 << 0),
SER_DISK = (1 << 1),
SER_GETHASH = (1 << 2),
};
#define READWRITE(obj) (::SerReadWrite(s, (obj), nType, nVersion, ser_action))
/**
* Implement three methods for serializable objects. These are actually wrappers over
* "SerializationOp" template, which implements the body of each class' serialization
* code. Adding "ADD_SERIALIZE_METHODS" in the body of the class causes these wrappers to be
* added as members.
*/
#define ADD_SERIALIZE_METHODS \
size_t GetSerializeSize(int nType, int nVersion) const { \
CSizeComputer s(nType, nVersion); \
NCONST_PTR(this)->SerializationOp(s, CSerActionSerialize(), nType, nVersion);\
return s.size(); \
} \
template<typename Stream> \
void Serialize(Stream& s, int nType, int nVersion) const { \
NCONST_PTR(this)->SerializationOp(s, CSerActionSerialize(), nType, nVersion);\
} \
template<typename Stream> \
void Unserialize(Stream& s, int nType, int nVersion) { \
SerializationOp(s, CSerActionUnserialize(), nType, nVersion); \
}
/*
* Basic Types
*/
#define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
#define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(signed long long a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(unsigned long long a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, signed long long a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, unsigned long long a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, signed long long& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, unsigned long long& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
/**
* Compact Size
* size < 253 -- 1 byte
* size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
* size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
* size > UINT_MAX -- 9 bytes (255 + 8 bytes)
*/
inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
{
if (nSize < 253) return sizeof(unsigned char);
else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
else return sizeof(unsigned char) + sizeof(uint64_t);
}
template<typename Stream>
void WriteCompactSize(Stream& os, uint64_t nSize)
{
if (nSize < 253)
{
unsigned char chSize = nSize;
WRITEDATA(os, chSize);
}
else if (nSize <= std::numeric_limits<unsigned short>::max())
{
unsigned char chSize = 253;
unsigned short xSize = nSize;
WRITEDATA(os, chSize);
WRITEDATA(os, xSize);
}
else if (nSize <= std::numeric_limits<unsigned int>::max())
{
unsigned char chSize = 254;
unsigned int xSize = nSize;
WRITEDATA(os, chSize);
WRITEDATA(os, xSize);
}
else
{
unsigned char chSize = 255;
uint64_t xSize = nSize;
WRITEDATA(os, chSize);
WRITEDATA(os, xSize);
}
return;
}
template<typename Stream>
uint64_t ReadCompactSize(Stream& is)
{
unsigned char chSize;
READDATA(is, chSize);
uint64_t nSizeRet = 0;
if (chSize < 253)
{
nSizeRet = chSize;
}
else if (chSize == 253)
{
unsigned short xSize;
READDATA(is, xSize);
nSizeRet = xSize;
if (nSizeRet < 253)
throw std::ios_base::failure("non-canonical ReadCompactSize()");
}
else if (chSize == 254)
{
unsigned int xSize;
READDATA(is, xSize);
nSizeRet = xSize;
if (nSizeRet < 0x10000u)
throw std::ios_base::failure("non-canonical ReadCompactSize()");
}
else
{
uint64_t xSize;
READDATA(is, xSize);
nSizeRet = xSize;
if (nSizeRet < 0x100000000ULL)
throw std::ios_base::failure("non-canonical ReadCompactSize()");
}
if (nSizeRet > (uint64_t)MAX_SIZE)
throw std::ios_base::failure("ReadCompactSize() : size too large");
return nSizeRet;
}
/**
* Variable-length integers: bytes are a MSB base-128 encoding of the number.
* The high bit in each byte signifies whether another digit follows. To make
* sure the encoding is one-to-one, one is subtracted from all but the last digit.
* Thus, the byte sequence a[] with length len, where all but the last byte
* has bit 128 set, encodes the number:
*
* (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
*
* Properties:
* * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
* * Every integer has exactly one encoding
* * Encoding does not depend on size of original integer type
* * No redundancy: every (infinite) byte sequence corresponds to a list
* of encoded integers.
*
* 0: [0x00] 256: [0x81 0x00]
* 1: [0x01] 16383: [0xFE 0x7F]
* 127: [0x7F] 16384: [0xFF 0x00]
* 128: [0x80 0x00] 16511: [0x80 0xFF 0x7F]
* 255: [0x80 0x7F] 65535: [0x82 0xFD 0x7F]
* 2^32: [0x8E 0xFE 0xFE 0xFF 0x00]
*/
template<typename I>
inline unsigned int GetSizeOfVarInt(I n)
{
int nRet = 0;
while(true) {
nRet++;
if (n <= 0x7F)
break;
n = (n >> 7) - 1;
}
return nRet;
}
template<typename Stream, typename I>
void WriteVarInt(Stream& os, I n)
{
unsigned char tmp[(sizeof(n)*8+6)/7];
int len=0;
while(true) {
tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
if (n <= 0x7F)
break;
n = (n >> 7) - 1;
len++;
}
do {
WRITEDATA(os, tmp[len]);
} while(len--);
}
template<typename Stream, typename I>
I ReadVarInt(Stream& is)
{
I n = 0;
while(true) {
unsigned char chData;
READDATA(is, chData);
n = (n << 7) | (chData & 0x7F);
if (chData & 0x80)
n++;
else
return n;
}
}
#define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
#define VARINT(obj) REF(WrapVarInt(REF(obj)))
#define LIMITED_STRING(obj,n) REF(LimitedString< n >(REF(obj)))
/**
* Wrapper for serializing arrays and POD.
*/
class CFlatData
{
protected:
char* pbegin;
char* pend;
public:
CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
template <class T, class TAl>
explicit CFlatData(std::vector<T,TAl> &v)
{
pbegin = (char*)begin_ptr(v);
pend = (char*)end_ptr(v);
}
char* begin() { return pbegin; }
const char* begin() const { return pbegin; }
char* end() { return pend; }
const char* end() const { return pend; }
unsigned int GetSerializeSize(int, int=0) const
{
return pend - pbegin;
}
template<typename Stream>
void Serialize(Stream& s, int, int=0) const
{
s.write(pbegin, pend - pbegin);
}
template<typename Stream>
void Unserialize(Stream& s, int, int=0)
{
s.read(pbegin, pend - pbegin);
}
};
template<typename I>
class CVarInt
{
protected:
I &n;
public:
CVarInt(I& nIn) : n(nIn) { }
unsigned int GetSerializeSize(int, int) const {
return GetSizeOfVarInt<I>(n);
}
template<typename Stream>
void Serialize(Stream &s, int, int) const {
WriteVarInt<Stream,I>(s, n);
}
template<typename Stream>
void Unserialize(Stream& s, int, int) {
n = ReadVarInt<Stream,I>(s);
}
};
template<size_t Limit>
class LimitedString
{
protected:
std::string& string;
public:
LimitedString(std::string& string) : string(string) {}
template<typename Stream>
void Unserialize(Stream& s, int, int=0)
{
size_t size = ReadCompactSize(s);
if (size > Limit) {
throw std::ios_base::failure("String length limit exceeded");
}
string.resize(size);
if (size != 0)
s.read((char*)&string[0], size);
}
template<typename Stream>
void Serialize(Stream& s, int, int=0) const
{
WriteCompactSize(s, string.size());
if (!string.empty())
s.write((char*)&string[0], string.size());
}
unsigned int GetSerializeSize(int, int=0) const
{
return GetSizeOfCompactSize(string.size()) + string.size();
}
};
template<typename I>
CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
/**
* Forward declarations
*/
/**
* string
*/
template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
/**
* vector
* vectors of unsigned char are a special case and are intended to be serialized as a single opaque blob.
*/
template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const unsigned char&);
template<typename T, typename A, typename V> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const V&);
template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const unsigned char&);
template<typename Stream, typename T, typename A, typename V> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const V&);
template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const unsigned char&);
template<typename Stream, typename T, typename A, typename V> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const V&);
template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
/**
* others derived from vector
*/
extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
/**
* pair
*/
template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
/**
* map
*/
template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion);
template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion);
/**
* set
*/
template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
/**
* If none of the specialized versions above matched, default to calling member function.
* "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
* The compiler will only cast int to long if none of the other templates matched.
* Thanks to Boost serialization for this idea.
*/
template<typename T>
inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
{
return a.GetSerializeSize((int)nType, nVersion);
}
template<typename Stream, typename T>
inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
{
a.Serialize(os, (int)nType, nVersion);
}
template<typename Stream, typename T>
inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
{
a.Unserialize(is, (int)nType, nVersion);
}
/**
* string
*/
template<typename C>
unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
{
return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
}
template<typename Stream, typename C>
void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
{
WriteCompactSize(os, str.size());
if (!str.empty())
os.write((char*)&str[0], str.size() * sizeof(str[0]));
}
template<typename Stream, typename C>
void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
{
unsigned int nSize = ReadCompactSize(is);
str.resize(nSize);
if (nSize != 0)
is.read((char*)&str[0], nSize * sizeof(str[0]));
}
/**
* vector
*/
template<typename T, typename A>
unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const unsigned char&)
{
return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
}
template<typename T, typename A, typename V>
unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const V&)
{
unsigned int nSize = GetSizeOfCompactSize(v.size());
for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
nSize += GetSerializeSize((*vi), nType, nVersion);
return nSize;
}
template<typename T, typename A>
inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
{
return GetSerializeSize_impl(v, nType, nVersion, T());
}
template<typename Stream, typename T, typename A>
void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const unsigned char&)
{
WriteCompactSize(os, v.size());
if (!v.empty())
os.write((char*)&v[0], v.size() * sizeof(T));
}
template<typename Stream, typename T, typename A, typename V>
void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const V&)
{
WriteCompactSize(os, v.size());
for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
::Serialize(os, (*vi), nType, nVersion);
}
template<typename Stream, typename T, typename A>
inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
{
Serialize_impl(os, v, nType, nVersion, T());
}
template<typename Stream, typename T, typename A>
void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const unsigned char&)
{
// Limit size per read so bogus size value won't cause out of memory
v.clear();
unsigned int nSize = ReadCompactSize(is);
unsigned int i = 0;
while (i < nSize)
{
unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
v.resize(i + blk);
is.read((char*)&v[i], blk * sizeof(T));
i += blk;
}
}
template<typename Stream, typename T, typename A, typename V>
void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const V&)
{
v.clear();
unsigned int nSize = ReadCompactSize(is);
unsigned int i = 0;
unsigned int nMid = 0;
while (nMid < nSize)
{
nMid += 5000000 / sizeof(T);
if (nMid > nSize)
nMid = nSize;
v.resize(nMid);
for (; i < nMid; i++)
Unserialize(is, v[i], nType, nVersion);
}
}
template<typename Stream, typename T, typename A>
inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
{
Unserialize_impl(is, v, nType, nVersion, T());
}
/**
* others derived from vector
*/
inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
{
return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
}
template<typename Stream>
void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
{
Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
}
template<typename Stream>
void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
{
Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
}
/**
* pair
*/
template<typename K, typename T>
unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
{
return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
}
template<typename Stream, typename K, typename T>
void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
{
Serialize(os, item.first, nType, nVersion);
Serialize(os, item.second, nType, nVersion);
}
template<typename Stream, typename K, typename T>
void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
{
Unserialize(is, item.first, nType, nVersion);
Unserialize(is, item.second, nType, nVersion);
}
/**
* map
*/
template<typename K, typename T, typename Pred, typename A>
unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
{
unsigned int nSize = GetSizeOfCompactSize(m.size());
for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
nSize += GetSerializeSize((*mi), nType, nVersion);
return nSize;
}
template<typename Stream, typename K, typename T, typename Pred, typename A>
void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
{
WriteCompactSize(os, m.size());
for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
Serialize(os, (*mi), nType, nVersion);
}
template<typename Stream, typename K, typename T, typename Pred, typename A>
void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
{
m.clear();
unsigned int nSize = ReadCompactSize(is);
typename std::map<K, T, Pred, A>::iterator mi = m.begin();
for (unsigned int i = 0; i < nSize; i++)
{
std::pair<K, T> item;
Unserialize(is, item, nType, nVersion);
mi = m.insert(mi, item);
}
}
/**
* set
*/
template<typename K, typename Pred, typename A>
unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
{
unsigned int nSize = GetSizeOfCompactSize(m.size());
for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
nSize += GetSerializeSize((*it), nType, nVersion);
return nSize;
}
template<typename Stream, typename K, typename Pred, typename A>
void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
{
WriteCompactSize(os, m.size());
for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
Serialize(os, (*it), nType, nVersion);
}
template<typename Stream, typename K, typename Pred, typename A>
void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
{
m.clear();
unsigned int nSize = ReadCompactSize(is);
typename std::set<K, Pred, A>::iterator it = m.begin();
for (unsigned int i = 0; i < nSize; i++)
{
K key;
Unserialize(is, key, nType, nVersion);
it = m.insert(it, key);
}
}
/**
* Support for ADD_SERIALIZE_METHODS and READWRITE macro
*/
struct CSerActionSerialize
{
bool ForRead() const { return false; }
};
struct CSerActionUnserialize
{
bool ForRead() const { return true; }
};
template<typename Stream, typename T>
inline void SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
{
::Serialize(s, obj, nType, nVersion);
}
template<typename Stream, typename T>
inline void SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
{
::Unserialize(s, obj, nType, nVersion);
}
class CSizeComputer
{
protected:
size_t nSize;
public:
int nType;
int nVersion;
CSizeComputer(int nTypeIn, int nVersionIn) : nSize(0), nType(nTypeIn), nVersion(nVersionIn) {}
CSizeComputer& write(const char *psz, size_t nSize)
{
this->nSize += nSize;
return *this;
}
template<typename T>
CSizeComputer& operator<<(const T& obj)
{
::Serialize(*this, obj, nType, nVersion);
return (*this);
}
size_t size() const {
return nSize;
}
};
#endif // BITCOIN_SERIALIZE_H
| [
"fcn@facilecoin.org"
] | fcn@facilecoin.org |
ab1ce89119b83878fed6d9551fa993b685eb5643 | 1ff055bf57f600d272209ffebb3d3979b4fd6f86 | /mexfiles/nuclear_proximal_gesdd_mex.cpp | baff79295d4a2c578213d4ba2149f5637ad217a0 | [] | no_license | zqaidwj1314/sparse_linear_model | 865bb43e1eb86a60eb8752a528cee5ff1eb3929d | 25a0b836ca430cc228aa21f0fd70141640277048 | refs/heads/master | 2020-12-11T06:06:53.030661 | 2013-10-14T16:23:17 | 2013-10-14T16:23:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,371 | cpp | /*
* nuclear_proximal_gesdd_mex.cpp
*
* Created on: Nov 11, 2011
* Author: igkiou
*/
#include "sparse_classification.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
/* Check number of input arguments */
if (nrhs != 2) {
ERROR("Two input arguments are required.");
}
/* Check number of output arguments */
if (nlhs > 2) {
ERROR("Too many output arguments.");
}
DOUBLE *X = (DOUBLE*) mxGetData(prhs[0]);
DOUBLE *tau = (DOUBLE*) mxGetData(prhs[1]);
INT M = (INT) mxGetM(prhs[0]);
INT N = (INT) mxGetN(prhs[0]);
plhs[0] = mxCreateNumericMatrix(M, N, MXPRECISION_CLASS, mxREAL);
DOUBLE *Xr = (DOUBLE *) mxGetData(plhs[0]);
DOUBLE *norm;
if (nlhs >= 2) {
plhs[1] = mxCreateNumericMatrix(1, 1, MXPRECISION_CLASS, mxREAL);
norm = (DOUBLE *) mxGetData(plhs[1]);
} else {
norm = NULL;
}
datacpy(Xr, X, M * N);
INT MINMN = IMIN(M, N);
INT MAXMN = IMAX(M, N);
DOUBLE *sv = (DOUBLE *) MALLOC(MINMN * 1 * sizeof(DOUBLE));
DOUBLE *svecsmall = (DOUBLE *) MALLOC(MINMN * MINMN * sizeof(DOUBLE));
DOUBLE *sveclarge = (DOUBLE *) MALLOC(MAXMN * MINMN * sizeof(DOUBLE));
INT *iwork = (INT *) malloc(16 * MINMN * sizeof(INT));
INT lwork = 0;
nuclear_proximal_gesdd(Xr, norm, *tau, M, N, sv, svecsmall, sveclarge, NULL, lwork, iwork);
FREE(sv);
FREE(svecsmall);
FREE(sveclarge);
FREE(iwork);
}
| [
"igkiou@17dedf92-65f5-4d44-bd7c-a9e8d8438006"
] | igkiou@17dedf92-65f5-4d44-bd7c-a9e8d8438006 |
dab660a895cc1e0aaafe06a492f21dc9aa9fd5b3 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /adb/include/alibabacloud/adb/model/ApplyAdviceByIdRequest.h | 204607d3bca748824b58b971f79535a954c6ebde | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,679 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_ADB_MODEL_APPLYADVICEBYIDREQUEST_H_
#define ALIBABACLOUD_ADB_MODEL_APPLYADVICEBYIDREQUEST_H_
#include <alibabacloud/adb/AdbExport.h>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <string>
#include <vector>
#include <map>
namespace AlibabaCloud {
namespace Adb {
namespace Model {
class ALIBABACLOUD_ADB_EXPORT ApplyAdviceByIdRequest : public RpcServiceRequest {
public:
ApplyAdviceByIdRequest();
~ApplyAdviceByIdRequest();
std::string getAdviceId() const;
void setAdviceId(const std::string &adviceId);
std::string getDBClusterId() const;
void setDBClusterId(const std::string &dBClusterId);
long getAdviceDate() const;
void setAdviceDate(long adviceDate);
std::string getRegionId() const;
void setRegionId(const std::string ®ionId);
private:
std::string adviceId_;
std::string dBClusterId_;
long adviceDate_;
std::string regionId_;
};
} // namespace Model
} // namespace Adb
} // namespace AlibabaCloud
#endif // !ALIBABACLOUD_ADB_MODEL_APPLYADVICEBYIDREQUEST_H_
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
91603d6a70af5eeb6924be89c67d196b9e2fd856 | e65200d0e35e5f7bf01f3b5514d39c648b5492aa | /work_video.cpp | 3796f00907a02a6f7dbad634e47bb16d04e2480f | [] | no_license | deClot/Video-YUV420-BMP | 855df1acd7d84ca5e2b3a6ab95656060d07d5aaa | 93c45257f7fa10fb890acfe2db51b5f12f3a96eb | refs/heads/master | 2020-03-26T08:57:33.514844 | 2018-10-02T05:38:15 | 2018-10-02T05:38:15 | 144,727,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,496 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include "work_video.h"
using namespace std;
int open_input_video (char* video_name, AVFormatContext** format_context, AVCodecContext** codec_context, int* video_stream) {
// file header and info about file format
int err; //error info, for av_strerror
err = avformat_open_input(format_context, video_name, 0, NULL);
if (err < 0) {
cout << "ffmpeg: Unable to open input file\n"<< endl;
/* char buf[128];
av_strerror(err, buf, sizeof(buf));
cout << buf<< endl;*/
return 0;
}
// Retrieve stream information
err = avformat_find_stream_info(*format_context, NULL);
if (err < 0) {
cout << "ffmpeg: Unable to find stream info\n"<< endl;
return 0;
}
av_dump_format(*format_context, 0, video_name, 0);
// Find the first video stream
AVCodec *dec;
err = av_find_best_stream(*format_context, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
if (err < 0) {
cout << "Cannot find a video stream in the input file\n" << endl;
return 0;
}
*video_stream = err;
// Create decoding context
AVCodecParameters* par = (*format_context)->streams[*video_stream]->codecpar;
// cout << "format bit_rate " << (*format_context)->bit_rate;
// AVCodecContext *ctx;
*codec_context = avcodec_alloc_context3(dec);
if (!*codec_context) {
cout << "Could not allocate a decoding context\n" << endl;
return 0;
}
err = avcodec_parameters_to_context (*codec_context, par);
if (err < 0) {
cout << "Could not convert parameters to context\n" << endl;
return 0;
}
// cout << "timebase " << (*codec_context)->time_base.den <<" "<< (*codec_context)->time_base.num <<endl;
// Init the video decoder
err = avcodec_open2(*codec_context, dec, NULL);
if (err < 0) {
cout << "ffmpeg: Unable to open codec\n" << endl;
return 0;
}
return 1;
}
int open_output_video(char *filename, AVCodecContext *input_codec_context,
AVFormatContext **output_format_context,
AVCodecContext **output_codec_context) {
AVCodecContext *avctx = NULL;
AVIOContext *output_io_context = NULL;
AVStream *stream = NULL;
AVCodec *output_codec = NULL;
int error;
/** Open the output file to write to it. */
if ((error = avio_open(&output_io_context, filename,
AVIO_FLAG_WRITE)) < 0) {
cout <<"Could not open output file" << endl;
return 0;
}
/** Create a new format context for the output container format. */
if (!(*output_format_context = avformat_alloc_context())) {
fprintf(stderr, "Could not allocate output format context\n");
return AVERROR(ENOMEM);
}
/** Associate the output file (pointer) with the container format context. */
(*output_format_context)->pb = output_io_context;
/** Guess the desired container format based on the file extension. */
if (!((*output_format_context)->oformat = av_guess_format(NULL, filename,
NULL))) {
fprintf(stderr, "Could not find output file format\n");
return 0;
}
// av_strlcpy((*output_format_context)->filename, filename,
// sizeof((*output_format_context)->filename));
/** Find the encoder to be used by its name. */ //input_codec_context->codec_id
if (!(output_codec = avcodec_find_encoder(AV_CODEC_ID_RAWVIDEO))) {
fprintf(stderr, "Could not find encoder.\n");
return 0;
}
/** Create a new stream in the output file container. */
if (!(stream = avformat_new_stream(*output_format_context, NULL))) {
fprintf(stderr, "Could not create new stream\n");
error = AVERROR(ENOMEM);
return 0;
}
avctx = avcodec_alloc_context3(output_codec);
if (!avctx) {
fprintf(stderr, "Could not allocate an encoding context\n");
error = AVERROR(ENOMEM);
return 0;
}
avctx->time_base = (AVRational){1, 25};
avctx->width = input_codec_context->width;
avctx->height = input_codec_context->height;
avctx->pix_fmt = AV_PIX_FMT_YUV420P;
avctx->codec_type = AVMEDIA_TYPE_VIDEO;
// if ((*output_format_context)->oformat->flags & AVFMT_GLOBALHEADER)
// avctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
/** Open the encoder for stream to use it later. */
if ((error = avcodec_open2(avctx, output_codec, NULL)) < 0) {
cout << "Could not open output codec " << error<< endl;
return 0;
}
error = avcodec_parameters_from_context(stream->codecpar, avctx);
if (error < 0) {
fprintf(stderr, "Could not initialize stream parameters\n");
return 0;
}
/** Save the encoder context for easier access later. */
*output_codec_context = avctx;
return 1;
}
/** Write the header of the output file container. */
int write_output_file_header(AVFormatContext *output_format_context)
{
int error;
if ((error = avformat_write_header(output_format_context, NULL)) < 0) {
cout << "Could not write output file header " << error << endl;
return error;
}
return 0;
}
int encode_frame(AVCodecContext *codec_context_out, AVFrame *frame_out, AVPacket *packet){
int err = 0;
frame_out->format = codec_context_out->pix_fmt;
frame_out->width = codec_context_out->width;
frame_out->height = codec_context_out->height;
err = av_frame_get_buffer(frame_out, 32);
if (err < 0) {
fprintf(stderr, "Could not allocate the video frame data\n");
return err;
}
/* make sure the frame data is writable */
if (err = av_frame_make_writable(frame_out)<0){
cout << "Could not allocate the video frame data" << endl;
return err;
}
err = avcodec_send_frame(codec_context_out, frame_out);
if (err < 0) {
fprintf(stderr, "Error sending a frame for encoding\n");
return err;
}
while (err >= 0) {
err = avcodec_receive_packet(codec_context_out, packet); ////!!!!!!!!!
if (err == AVERROR(EAGAIN) || err == AVERROR_EOF){
break;
}
else if (err < 0) {
fprintf(stderr, "Error during encoding\n");
return err;
}
av_frame_unref(frame_out);
}
return 0;
}
| [
"refenement@mail.ru"
] | refenement@mail.ru |
b171032cb989898d4e5e653457b854cf3f42817f | edfb38fa076edeb72b511d8c7a801f217ade83f4 | /wwiv-svn/.svn/pristine/b1/b171032cb989898d4e5e653457b854cf3f42817f.svn-base | 0ef4d168ed0733a78f6d697111b482d83720deab | [] | no_license | insidenothing/wwiv | b06e3e71265f8fe7ffa8c0e6ab37b2135bcdcf05 | 93f311305d36c07b363853707f64f4c53e43e0d4 | refs/heads/master | 2020-04-04T01:29:00.664801 | 2016-11-18T05:00:07 | 2016-11-18T05:00:07 | 9,230,690 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 40,569 | /**************************************************************************/
/* */
/* WWIV Version 5.0x */
/* Copyright (C)1998-2015, WWIV Software Services */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, */
/* software distributed under the License is distributed on an */
/* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, */
/* either express or implied. See the License for the specific */
/* language governing permissions and limitations under the License. */
/* */
/**************************************************************************/
#include <algorithm>
#include <memory>
#include <string>
#include "bbs/datetime.h"
#include "bbs/instmsg.h"
#include "bbs/input.h"
#include "bbs/subxtr.h"
#include "bbs/printfile.h"
#include "bbs/wwiv.h"
#include "bbs/keycodes.h"
#include "bbs/wstatus.h"
#include "core/strings.h"
#include "core/wwivassert.h"
void SetupThreadRecordsBeforeScan();
void HandleScanReadPrompt(int &nMessageNumber, int &nScanOptionType, int *nextsub, bool &bTitleScan, bool &done,
bool &quit, int &val);
void GetScanReadPrompts(int nMessageNumber, char *pszReadPrompt, char *szSubNamePrompt);
void HandleScanReadAutoReply(int &nMessageNumber, const char *pszUserInput, int &nScanOptionType);
void HandleScanReadFind(int &nMessageNumber, int &nScanOptionType);
void HandleListTitles(int &nMessageNumber, int &nScanOptionType);
void HandleMessageDownload(int nMessageNumber);
void HandleMessageMove(int &nMessageNumber);
void HandleMessageLoad();
void HandleMessageReply(int &nMessageNumber);
void HandleMessageDelete(int &nMessageNumber);
void HandleMessageExtract(int &nMessageNumber);
void HandleMessageHelp();
void HandleListReplies(int nMessageNumber);
static char s_szFindString[21];
using std::string;
using std::unique_ptr;
using wwiv::endl;
using namespace wwiv::strings;
void scan(int nMessageNumber, int nScanOptionType, int *nextsub, bool bTitleScan) {
irt[0] = '\0';
irt_name[0] = '\0';
int val = 0;
bool realexpress = express;
iscan(session()->GetCurrentMessageArea());
if (session()->GetCurrentReadMessageArea() < 0) {
bout.nl();
bout << "No subs available.\r\n\n";
return;
}
if (session()->IsMessageThreadingEnabled()) {
SetupThreadRecordsBeforeScan();
}
bool done = false;
bool quit = false;
do {
if (session()->IsMessageThreadingEnabled()) {
for (int nTempOuterMessageIterator = 0; nTempOuterMessageIterator <= session()->GetNumMessagesInCurrentMessageArea();
nTempOuterMessageIterator++) {
for (int nTempMessageIterator = 0; nTempMessageIterator <= session()->GetNumMessagesInCurrentMessageArea();
nTempMessageIterator++) {
if (IsEquals(thread[nTempOuterMessageIterator].parent_code, thread[nTempMessageIterator].message_code)) {
thread[nTempOuterMessageIterator].parent_num = thread[nTempMessageIterator].msg_num;
nTempMessageIterator = session()->GetNumMessagesInCurrentMessageArea() + 1;
}
}
}
}
session()->localIO()->tleft(true);
CheckForHangup();
set_net_num((xsubs[session()->GetCurrentReadMessageArea()].num_nets) ?
xsubs[session()->GetCurrentReadMessageArea()].nets[0].net_num : 0);
if (nScanOptionType != SCAN_OPTION_READ_PROMPT) {
resynch(&nMessageNumber, nullptr);
}
write_inst(INST_LOC_SUBS, usub[session()->GetCurrentMessageArea()].subnum, INST_FLAGS_NONE);
switch (nScanOptionType) {
case SCAN_OPTION_READ_PROMPT: { // Read Prompt
HandleScanReadPrompt(nMessageNumber, nScanOptionType, nextsub, bTitleScan, done, quit, val);
}
break;
case SCAN_OPTION_LIST_TITLES: { // List Titles
HandleListTitles(nMessageNumber, nScanOptionType);
}
break;
case SCAN_OPTION_READ_MESSAGE: { // Read Message
bool next = false;
if (nMessageNumber > 0 && nMessageNumber <= session()->GetNumMessagesInCurrentMessageArea()) {
if (forcescansub) {
incom = false;
}
read_message(nMessageNumber, &next, &val);
if (forcescansub) {
incom = true;
}
}
bout.Color(0);
bout.nl();
if (session()->IsMessageThreadingEnabled()) {
if (thread[nMessageNumber].used) {
bout << "|#9Current Message is a reply to Msg #|#2" << thread[nMessageNumber].parent_num << endl;
}
int nNumRepliesForThisThread = 0;
for (int nTempMessageIterator = 0; nTempMessageIterator <= session()->GetNumMessagesInCurrentMessageArea();
nTempMessageIterator++) {
if (IsEquals(thread[nTempMessageIterator].parent_code, thread[nMessageNumber].message_code) &&
nTempMessageIterator != nMessageNumber) {
nNumRepliesForThisThread++;
}
}
if (nNumRepliesForThisThread) {
bout << "|#9Current Message has |#6" << nNumRepliesForThisThread << "|#9"
<< ((nNumRepliesForThisThread == 1) ? " reply." : " replies.");
}
bout << endl;;
}
if (next) {
++nMessageNumber;
if (nMessageNumber > session()->GetNumMessagesInCurrentMessageArea()) {
done = true;
}
nScanOptionType = SCAN_OPTION_READ_MESSAGE;
} else {
nScanOptionType = SCAN_OPTION_READ_PROMPT;
}
if (expressabort) {
if (realexpress) {
done = true;
quit = true;
*nextsub = 0;
} else {
expressabort = false;
express = false;
nScanOptionType = SCAN_OPTION_READ_PROMPT;
}
}
}
break;
}
} while (!done && !hangup);
if (!realexpress) {
express = false;
expressabort = false;
}
if ((val & 1) && lcs() && !express) {
bout.nl();
bout << "|#5Validate messages here? ";
if (noyes()) {
open_sub(true);
for (int i = 1; i <= session()->GetNumMessagesInCurrentMessageArea(); i++) {
postrec* p3 = get_post(i);
if (p3->status & (status_unvalidated | status_delete)) {
p3->status &= (~(status_unvalidated | status_delete));
}
write_post(i, p3);
}
close_sub();
}
}
if ((val & 2) && lcs() && !express) {
bout.nl();
bout << "|#5Network validate here? ";
if (yesno()) {
int nNumMsgsSent = 0;
open_sub(true);
int nMsgToValidate = 0;
for (int i = 1; i <= session()->GetNumMessagesInCurrentMessageArea(); i++) {
if (get_post(i)->status & status_pending_net) {
nMsgToValidate++;
}
}
postrec* p3 = static_cast<postrec *>(BbsAllocA(nMsgToValidate * sizeof(postrec)));
if (p3) {
nMsgToValidate = 0;
for (int i = 1; i <= session()->GetNumMessagesInCurrentMessageArea(); i++) {
postrec *p4 = get_post(i);
if (p4->status & status_pending_net) {
p3[nMsgToValidate++] = *p4;
p4->status &= ~status_pending_net;
write_post(i, p4);
}
}
close_sub();
for (int j = 0; j < nMsgToValidate; j++) {
send_net_post(p3 + j, subboards[session()->GetCurrentReadMessageArea()].filename,
session()->GetCurrentReadMessageArea());
nNumMsgsSent++;
}
free(p3);
} else {
close_sub();
}
bout.nl();
bout << nNumMsgsSent << " messages sent.";
bout.nl(2);
}
}
if (!quit && !express) {
bout.nl();
if (!session()->user()->IsRestrictionPost() &&
(session()->user()->GetNumPostsToday() < getslrec(session()->GetEffectiveSl()).posts) &&
(session()->GetEffectiveSl() >= subboards[session()->GetCurrentReadMessageArea()].postsl)) {
bout << "|#5Post on " << subboards[session()->GetCurrentReadMessageArea()].name << "? ";
irt[0] = '\0';
irt_name[0] = '\0';
grab_quotes(nullptr, nullptr);
if (yesno()) {
post();
}
}
}
bout.nl();
if (thread) {
free(thread);
}
thread = nullptr;
}
void SetupThreadRecordsBeforeScan() {
if (thread) {
free(thread);
}
// We use +2 since if we post a message we'll need more than +1
thread = static_cast<threadrec *>(BbsAllocA((session()->GetNumMessagesInCurrentMessageArea() + 2) * sizeof(
threadrec)));
WWIV_ASSERT(thread != nullptr);
for (unsigned short tempnum = 1; tempnum <= session()->GetNumMessagesInCurrentMessageArea(); tempnum++) { // was 0.
strcpy(thread[tempnum].parent_code, "");
strcpy(thread[tempnum].message_code, "");
thread[tempnum].msg_num = tempnum;
thread[tempnum].parent_num = 0;
thread[tempnum].used = 0;
postrec *pPostRec1 = get_post(tempnum);
long lFileLen;
unique_ptr<char[]> b(readfile(&(pPostRec1->msg), (subboards[session()->GetCurrentReadMessageArea()].filename), &lFileLen));
for (long l1 = 0; l1 < lFileLen; l1++) {
if (b[l1] == 4 && b[l1 + 1] == '0' && b[l1 + 2] == 'P') {
l1 += 4;
strcpy(thread[tempnum].message_code, "");
char szTemp[ 81 ];
szTemp[0] = '\0';
while ((b[l1] != '\r') && (l1 < lFileLen)) {
sprintf(szTemp, "%c", b[l1]);
strcat(thread[tempnum].message_code, szTemp);
l1++;
}
l1 = lFileLen;
thread[tempnum].msg_num = tempnum;
}
}
for (long l2 = 0; l2 < lFileLen; l2++) {
if ((b[l2] == 4) && (b[l2 + 1] == '0') && (b[l2 + 2] == 'W')) {
l2 += 4;
strcpy(thread[tempnum].parent_code, "");
char szTemp[ 81 ];
szTemp[0] = '\0';
while ((b[l2] != '\r') && (l2 < lFileLen)) {
sprintf(szTemp, "%c", b[l2]);
strcat(thread[tempnum].parent_code, szTemp);
l2++;
}
l2 = lFileLen;
thread[tempnum].msg_num = tempnum;
thread[tempnum].used = 1;
}
}
}
}
void HandleScanReadPrompt(int &nMessageNumber, int &nScanOptionType, int *nextsub, bool &bTitleScan, bool &done,
bool &quit, int &val) {
bool bFollowThread = false;
char szReadPrompt[ 255 ];
char szSubNamePrompt[81];
session()->threadID = "";
resetnsp();
GetScanReadPrompts(nMessageNumber, szReadPrompt, szSubNamePrompt);
bout.nl();
char szUserInput[ 81 ];
if (express) {
szUserInput[0] = '\0';
szReadPrompt[0] = '\0';
szSubNamePrompt[0] = '\0';
bout.nl(2);
} else {
bout << szReadPrompt;
input(szUserInput, 5, true);
resynch(&nMessageNumber, nullptr);
while (szUserInput[0] == 32) {
char szTempBuffer[ 255 ];
strcpy(szTempBuffer, &(szUserInput[1]));
strcpy(szUserInput, szTempBuffer);
}
}
if (bTitleScan && szUserInput[0] == 0 && nMessageNumber < session()->GetNumMessagesInCurrentMessageArea()) {
nScanOptionType = SCAN_OPTION_LIST_TITLES;
szUserInput[0] = 'T';
szUserInput[1] = '\0';
} else {
bTitleScan = false;
nScanOptionType = SCAN_OPTION_READ_PROMPT;
}
int nUserInput = atoi(szUserInput);
if (szUserInput[0] == '\0') {
bFollowThread = false;
nUserInput = nMessageNumber + 1;
if (nUserInput >= session()->GetNumMessagesInCurrentMessageArea() + 1) {
done = true;
}
}
if (nUserInput != 0 && nUserInput <= session()->GetNumMessagesInCurrentMessageArea() && nUserInput >= 1) {
nScanOptionType = SCAN_OPTION_READ_MESSAGE;
nMessageNumber = nUserInput;
} else if (szUserInput[1] == '\0') {
if (forcescansub) {
return;
}
switch (szUserInput[0]) {
case '$': { // Last message in area.
nScanOptionType = SCAN_OPTION_READ_MESSAGE;
nMessageNumber = session()->GetNumMessagesInCurrentMessageArea();
}
break;
case 'F': { // Find addition
HandleScanReadFind(nMessageNumber, nScanOptionType);
}
break;
// End of find addition
case 'Q':
quit = true;
done = true;
*nextsub = 0;
break;
case 'B':
if (*nextsub != 0) {
bout.nl();
bout << "|#5Remove this sub from your Q-Scan? ";
if (yesno()) {
qsc_q[usub[session()->GetCurrentMessageArea()].subnum / 32] ^= (1L <<
(usub[session()->GetCurrentMessageArea()].subnum % 32));
} else {
bout.nl();
bout << "|#9Mark messages in " << subboards[usub[session()->GetCurrentMessageArea()].subnum].name <<
" as read? ";
if (yesno()) {
unique_ptr<WStatus> pStatus(application()->GetStatusManager()->GetStatus());
qsc_p[usub[session()->GetCurrentMessageArea()].subnum] = pStatus->GetQScanPointer() - 1L;
}
}
*nextsub = 1;
done = true;
quit = true;
}
break;
case 'T':
bTitleScan = true;
nScanOptionType = SCAN_OPTION_LIST_TITLES;
break;
case 'R':
nScanOptionType = SCAN_OPTION_READ_MESSAGE;
break;
case '@':
strcpy(irt_sub, subboards[usub[session()->GetCurrentMessageArea()].subnum].name);
case 'O':
case 'A': {
HandleScanReadAutoReply(nMessageNumber, szUserInput, nScanOptionType);
}
break;
case 'P':
irt[0] = '\0';
irt_name[0] = '\0';
session()->threadID = "";
post();
break;
case 'W':
HandleMessageReply(nMessageNumber);
break;
case 'Y':
HandleMessageDownload(nMessageNumber);
break;
case '?':
HandleMessageHelp();
break;
case '-':
if (nMessageNumber > 1 && (nMessageNumber - 1 < session()->GetNumMessagesInCurrentMessageArea())) {
--nMessageNumber;
nScanOptionType = SCAN_OPTION_READ_MESSAGE;
}
break;
case 'C':
express = true;
break;
case '*':
HandleListReplies(nMessageNumber);
break;
case '[':
if (session()->IsMessageThreadingEnabled()) {
if (forcescansub) {
printfile(MUSTREAD_NOEXT);
} else {
nMessageNumber = thread[nMessageNumber].parent_num;
nScanOptionType = SCAN_OPTION_READ_MESSAGE;
}
}
break;
case ']':
if (session()->IsMessageThreadingEnabled()) {
if (forcescansub) {
printfile(MUSTREAD_NOEXT);
} else {
for (int j = nMessageNumber; j <= session()->GetNumMessagesInCurrentMessageArea(); j++) {
if (IsEquals(thread[j].parent_code, thread[nMessageNumber].message_code) &&
j != nMessageNumber) {
nMessageNumber = j;
j = session()->GetNumMessagesInCurrentMessageArea();
nScanOptionType = SCAN_OPTION_READ_MESSAGE;
}
}
}
}
break;
case '>':
if (session()->IsMessageThreadingEnabled()) {
if (forcescansub) {
printfile(MUSTREAD_NOEXT);
} else {
int original = 0;
if (!bFollowThread) {
bFollowThread = true;
original = nMessageNumber;
}
int j = 0;
for (j = nMessageNumber; j <= session()->GetNumMessagesInCurrentMessageArea(); j++) {
if (IsEquals(thread[j].parent_code, thread[original].message_code) &&
j != nMessageNumber) {
nMessageNumber = j;
break;
}
}
if (j >= session()->GetNumMessagesInCurrentMessageArea()) {
nMessageNumber = original;
bFollowThread = false;
}
}
}
nScanOptionType = SCAN_OPTION_READ_MESSAGE;
break;
case 'V':
if (cs() && (get_post(nMessageNumber)->ownersys == 0) && (nMessageNumber > 0)
&& (nMessageNumber <= session()->GetNumMessagesInCurrentMessageArea())) {
valuser(get_post(nMessageNumber)->owneruser);
} else if (cs() && (nMessageNumber > 0) && (nMessageNumber <= session()->GetNumMessagesInCurrentMessageArea())) {
bout.nl();
bout << "|#6Post from another system.\r\n\n";
}
break;
case 'N':
if ((lcs()) && (nMessageNumber > 0) && (nMessageNumber <= session()->GetNumMessagesInCurrentMessageArea())) {
open_sub(true);
resynch(&nMessageNumber, nullptr);
postrec *p3 = get_post(nMessageNumber);
p3->status ^= status_no_delete;
write_post(nMessageNumber, p3);
close_sub();
bout.nl();
if (p3->status & status_no_delete) {
bout << "|#9Message will |#6NOT|#9 be auto-purged.\r\n";
} else {
bout << "|#9Message |#2CAN|#9 now be auto-purged.\r\n";
}
bout.nl();
}
break;
case 'X':
if (lcs() && nMessageNumber > 0 && nMessageNumber <= session()->GetNumMessagesInCurrentMessageArea() &&
subboards[session()->GetCurrentReadMessageArea()].anony & anony_val_net &&
xsubs[session()->GetCurrentReadMessageArea()].num_nets) {
open_sub(true);
resynch(&nMessageNumber, nullptr);
postrec *p3 = get_post(nMessageNumber);
p3->status ^= status_pending_net;
write_post(nMessageNumber, p3);
close_sub();
bout.nl();
if (p3->status & status_pending_net) {
val |= 2;
bout << "|#9Will be sent out on net now.\r\n";
} else {
bout << "|#9Not set for net pending now.\r\n";
}
bout.nl();
}
break;
case 'U':
if (lcs() && nMessageNumber > 0 && nMessageNumber <= session()->GetNumMessagesInCurrentMessageArea()) {
open_sub(true);
resynch(&nMessageNumber, nullptr);
postrec *p3 = get_post(nMessageNumber);
p3->anony = 0;
write_post(nMessageNumber, p3);
close_sub();
bout.nl();
bout << "|#9Message is not anonymous now.\r\n";
}
break;
case 'D':
HandleMessageDelete(nMessageNumber);
break;
case 'E':
HandleMessageExtract(nMessageNumber);
break;
case 'M':
HandleMessageMove(nMessageNumber);
break;
case 'L':
HandleMessageLoad();
break;
}
} else if (IsEquals(szUserInput, "cls")) {
bputch('\x0c');
}
}
void GetScanReadPrompts(int nMessageNumber, char *pszReadPrompt, char *pszSubNamePrompt) {
// TODO remove pszSubNamePrompt is decided to go to 1 line format.
char szLocalNetworkName[81];
if (forcescansub) {
if (nMessageNumber < session()->GetNumMessagesInCurrentMessageArea()) {
strcpy(pszReadPrompt, "|#1Press |#7[|#2ENTER|#7]|#1 to go to the next message...");
} else {
sprintf(pszReadPrompt, "|#1Press |#7[|#2ENTER|#7]|#1 to continue...");
}
} else {
if (xsubs[session()->GetCurrentReadMessageArea()].num_nets) {
sprintf(szLocalNetworkName, "%s", session()->GetNetworkName());
} else {
set_net_num(0);
sprintf(szLocalNetworkName, "%s", "Local");
}
sprintf(pszSubNamePrompt, "|#7[|#1%s|#7] [|#2%s|#7]", szLocalNetworkName,
subboards[session()->GetCurrentReadMessageArea()].name);
char szTemp[81];
if (session()->GetNumMessagesInCurrentMessageArea() > nMessageNumber) {
sprintf(szTemp, "%d", nMessageNumber + 1);
} else {
sprintf(szTemp, "\bExit Sub");
}
//sprintf(pszReadPrompt, "|#7(|#1Read |#21-%lu|#1, |#7[|#2ENTER|#7]|#1 = #|#2%s|#7) :|#0 ", session()->GetNumMessagesInCurrentMessageArea(), szTemp);
sprintf(pszReadPrompt, "%s |#7(|#1Read |#2%d |#1of |#2%d|#1|#7) : ", pszSubNamePrompt, nMessageNumber,
session()->GetNumMessagesInCurrentMessageArea());
}
}
void HandleScanReadAutoReply(int &nMessageNumber, const char *pszUserInput, int &nScanOptionType) {
if (!lcs() && get_post(nMessageNumber)->status & (status_unvalidated | status_delete)) {
return;
}
if (get_post(nMessageNumber)->ownersys && !get_post(nMessageNumber)->owneruser) {
grab_user_name(&(get_post(nMessageNumber)->msg), subboards[session()->GetCurrentReadMessageArea()].filename);
}
grab_quotes(&(get_post(nMessageNumber)->msg), subboards[session()->GetCurrentReadMessageArea()].filename);
if (okfsed() && session()->user()->IsUseAutoQuote() && nMessageNumber > 0 &&
nMessageNumber <= session()->GetNumMessagesInCurrentMessageArea() && pszUserInput[0] != 'O') {
long lMessageLen;
unique_ptr<char[]> b(readfile(&(get_post(nMessageNumber)->msg),
(subboards[session()->GetCurrentReadMessageArea()].filename), &lMessageLen));
if (pszUserInput[0] == '@') {
auto_quote(b.get(), lMessageLen, 1, get_post(nMessageNumber)->daten);
} else {
auto_quote(b.get(), lMessageLen, 3, get_post(nMessageNumber)->daten);
}
}
if (get_post(nMessageNumber)->status & status_post_new_net) {
set_net_num(get_post(nMessageNumber)->title[80]);
if (get_post(nMessageNumber)->title[80] == -1) {
bout << "|#6Deleted network.\r\n";
return;
}
}
if (pszUserInput[0] == 'O' && (so() || lcs())) {
irt_sub[0] = 0;
show_files("*.frm", syscfg.gfilesdir);
bout << "|#2Which form letter: ";
char szFileName[ MAX_PATH ];
input(szFileName, 8, true);
if (!szFileName[0]) {
return;
}
char szFullPathName[ MAX_PATH ];
sprintf(szFullPathName, "%s%s.frm", syscfg.gfilesdir, szFileName);
if (!File::Exists(szFullPathName)) {
sprintf(szFullPathName, "%sform%s.msg", syscfg.gfilesdir, szFileName);
}
if (File::Exists(szFullPathName)) {
LoadFileIntoWorkspace(szFullPathName, true);
email(get_post(nMessageNumber)->owneruser, get_post(nMessageNumber)->ownersys, false, get_post(nMessageNumber)->anony);
grab_quotes(nullptr, nullptr);
}
} else if (pszUserInput[0] == '@') {
bout.nl();
bout << "|#21|#7]|#9 Reply to Different Address\r\n";
bout << "|#22|#7]|#9 Forward Message\r\n";
bout.nl();
bout << "|#7(Q=Quit) Select [1,2] : ";
char chReply = onek("Q12\r", true);
switch (chReply) {
case '\r':
case 'Q':
nScanOptionType = SCAN_OPTION_READ_MESSAGE;
break;
case '1': {
bout.nl();
bout << "|#9Enter user name or number:\r\n:";
char szUserNameOrNumber[ 81 ];
input(szUserNameOrNumber, 75, true);
size_t nAtPos = strcspn(szUserNameOrNumber, "@");
if (nAtPos != strlen(szUserNameOrNumber) && isalpha(szUserNameOrNumber[ nAtPos + 1 ])) {
if (strstr(szUserNameOrNumber, "@32767") == nullptr) {
strlwr(szUserNameOrNumber);
strcat(szUserNameOrNumber, " @32767");
}
}
int nUserNumber, nSystemNumber;
parse_email_info(szUserNameOrNumber, &nUserNumber, &nSystemNumber);
if (nUserNumber || nSystemNumber) {
email(nUserNumber, nSystemNumber, false, 0);
}
nScanOptionType = SCAN_OPTION_READ_MESSAGE;
}
break;
case '2': {
if (nMessageNumber > 0 && nMessageNumber <= session()->GetNumMessagesInCurrentMessageArea()) {
long lMessageLen;
unique_ptr<char[]> b(readfile(&(get_post(nMessageNumber)->msg), (subboards[session()->GetCurrentReadMessageArea()].filename),
&lMessageLen));
string filename = "EXTRACT.TMP";
if (File::Exists(filename)) {
File::Remove(filename);
}
File fileExtract(filename);
if (!fileExtract.Open(File::modeBinary | File::modeCreateFile | File::modeReadWrite)) {
bout << "|#6Could not open file for writing.\r\n";
} else {
if (fileExtract.GetLength() > 0) {
fileExtract.Seek(-1L, File::seekEnd);
char chLastChar = CZ;
fileExtract.Read(&chLastChar, 1);
if (chLastChar == CZ) {
fileExtract.Seek(-1L, File::seekEnd);
}
}
char szBuffer[ 255 ];
sprintf(szBuffer, "ON: %s", subboards[session()->GetCurrentReadMessageArea()].name);
fileExtract.Write(szBuffer, strlen(szBuffer));
fileExtract.Write("\r\n\r\n", 4);
fileExtract.Write(get_post(nMessageNumber)->title, strlen(get_post(nMessageNumber)->title));
fileExtract.Write("\r\n", 2);
fileExtract.Write(b.get(), lMessageLen);
fileExtract.Close();
}
bout.nl();
bout << "|#5Allow editing? ";
if (yesno()) {
bout.nl();
LoadFileIntoWorkspace(filename.c_str(), false);
} else {
bout.nl();
LoadFileIntoWorkspace(filename.c_str(), true);
}
send_email();
filename = StringPrintf("%s%s", syscfgovr.tempdir, INPUT_MSG);
if (File::Exists(filename)) {
File::Remove(filename);
}
}
nScanOptionType = SCAN_OPTION_READ_MESSAGE;
}
break;
}
} else {
if (lcs() || (getslrec(session()->GetEffectiveSl()).ability & ability_read_post_anony)
|| get_post(nMessageNumber)->anony == 0) {
email(get_post(nMessageNumber)->owneruser, get_post(nMessageNumber)->ownersys, false, 0);
} else {
email(get_post(nMessageNumber)->owneruser, get_post(nMessageNumber)->ownersys, false, get_post(nMessageNumber)->anony);
}
irt_sub[0] = 0;
grab_quotes(nullptr, nullptr);
}
}
void HandleScanReadFind(int &nMessageNumber, int &nScanOptionType) {
bool abort = false;
char *pszTempFindString = nullptr;
if (!(g_flags & g_flag_made_find_str)) {
pszTempFindString = strupr(stripcolors(get_post(nMessageNumber)->title));
strncpy(s_szFindString, pszTempFindString, sizeof(s_szFindString) - 1);
g_flags |= g_flag_made_find_str;
} else {
pszTempFindString = &s_szFindString[0];
}
while (strncmp(pszTempFindString, "RE:", 3) == 0 || *pszTempFindString == ' ') {
if (*pszTempFindString == ' ') {
pszTempFindString++;
} else {
pszTempFindString += 3;
}
}
if (strlen(pszTempFindString) >= 20) {
pszTempFindString[20] = 0;
}
strncpy(s_szFindString, pszTempFindString, sizeof(s_szFindString) - 1);
bout.nl();
bout << "|#7Find what? (CR=\"" << pszTempFindString << "\")|#1";
char szFindString[ 81 ];
input(szFindString, 20);
if (!*szFindString) {
strncpy(szFindString, pszTempFindString, sizeof(szFindString) - 1);
} else {
strncpy(s_szFindString, szFindString, sizeof(s_szFindString) - 1);
}
bout.nl();
bout << "|#1Backwards or Forwards? ";
char szBuffer[ 10 ];
szBuffer[0] = 'Q';
szBuffer[1] = upcase(*"Backwards");
szBuffer[2] = upcase(*"Forwards");
strcpy(&szBuffer[3], "+-");
char ch = onek(szBuffer);
if (ch == 'Q') {
return;
}
bool fnd = false;
int nTempMsgNum = nMessageNumber;
bout.nl();
bout << "|#1Searching -> |#2";
// Store search direction and limit
bool bSearchForwards = true;
int nMsgNumLimit;
if (ch == '-' || ch == upcase(*"Backwards")) {
bSearchForwards = false;
nMsgNumLimit = 1;
} else {
bSearchForwards = true;
nMsgNumLimit = session()->GetNumMessagesInCurrentMessageArea();
}
while (nTempMsgNum != nMsgNumLimit && !abort && !hangup && !fnd) {
if (bSearchForwards) {
nTempMsgNum++;
} else {
nTempMsgNum--;
}
checka(&abort);
if (!(nTempMsgNum % 5)) {
bout.bprintf("%5.5d", nTempMsgNum);
for (int i1 = 0; i1 < 5; i1++) {
bout << "\b";
}
if (!(nTempMsgNum % 100)) {
session()->localIO()->tleft(true);
CheckForHangup();
}
}
long lMessageLen;
unique_ptr<char[]> b(readfile(&(get_post(nTempMsgNum)->msg), subboards[session()->GetCurrentReadMessageArea()].filename,
&lMessageLen));
if (b.get()) {
char* temp = strupr(b.get());
fnd = (strstr(strupr(stripcolors(get_post(nTempMsgNum)->title)), szFindString)
|| strstr(temp, szFindString)) ? true : false;
}
}
if (fnd) {
bout << "Found!\r\n";
nMessageNumber = nTempMsgNum;
nScanOptionType = SCAN_OPTION_READ_MESSAGE;
} else {
bout << "|#6Not found!\r\n";
nScanOptionType = SCAN_OPTION_READ_PROMPT;
}
}
void HandleListTitles(int &nMessageNumber, int &nScanOptionType) {
int i = 0;
bool abort = false;
if (nMessageNumber >= session()->GetNumMessagesInCurrentMessageArea()) {
abort = true;
} else {
bout.nl();
}
int nNumTitleLines = std::max<int>(session()->screenlinest - 6, 1);
while (!abort && !hangup && ++i <= nNumTitleLines) {
++nMessageNumber;
postrec *p3 = get_post(nMessageNumber);
char szPrompt[ 255 ];
char szTempBuffer[ 255 ];
if (p3->ownersys == 0 && p3->owneruser == session()->usernum) {
sprintf(szTempBuffer, "|#7[|#1%d|#7]", nMessageNumber);
} else if (p3->ownersys != 0) {
sprintf(szTempBuffer, "|#7<|#1%d|#7>", nMessageNumber);
} else {
sprintf(szTempBuffer, "|#7(|#1%d|#7)", nMessageNumber);
}
for (int i1 = 0; i1 < 7; i1++) {
szPrompt[i1] = SPACE;
}
if (p3->qscan > qsc_p[session()->GetCurrentReadMessageArea()]) {
szPrompt[0] = '*';
}
if (p3->status & (status_pending_net | status_unvalidated)) {
szPrompt[0] = '+';
}
strcpy(&szPrompt[9 - strlen(stripcolors(szTempBuffer))], szTempBuffer);
strcat(szPrompt, "|#1 ");
if ((get_post(nMessageNumber)->status & (status_unvalidated | status_delete)) && (!lcs())) {
strcat(szPrompt, "<<< NOT VALIDATED YET >>>");
} else {
// Need the StringTrim on post title since some FSEDs
// added \r in the title string, also gets rid of extra spaces
string title(get_post(nMessageNumber)->title);
StringTrim(&title);
strncat(szPrompt, stripcolors(title).c_str(), 60);
}
if (session()->user()->GetScreenChars() >= 80) {
if (strlen(stripcolors(szPrompt)) > 50) {
while (strlen(stripcolors(szPrompt)) > 50) {
szPrompt[strlen(szPrompt) - 1] = 0;
}
}
strcat(szPrompt, charstr(51 - strlen(stripcolors(szPrompt)), ' '));
if (okansi()) {
strcat(szPrompt, "|#7\xB3|#1");
} else {
strcat(szPrompt, "|");
}
strcat(szPrompt, " ");
if ((p3->anony & 0x0f) &&
((getslrec(session()->GetEffectiveSl()).ability & ability_read_post_anony) == 0)) {
strcat(szPrompt, ">UNKNOWN<");
} else {
long lMessageLen;
unique_ptr<char[]> b(readfile(&(p3->msg), (subboards[session()->GetCurrentReadMessageArea()].filename), &lMessageLen));
if (b) {
strncpy(szTempBuffer, b.get(), sizeof(szTempBuffer) - 1);
szTempBuffer[sizeof(szTempBuffer) - 1] = 0;
strcpy(b.get(), stripcolors(szTempBuffer));
long lTempBufferPos = 0;
strcpy(szTempBuffer, "");
while (b[lTempBufferPos] != RETURN && b[lTempBufferPos] && lTempBufferPos < lMessageLen
&& lTempBufferPos < (session()->user()->GetScreenChars() - 54)) {
szTempBuffer[lTempBufferPos] = b[lTempBufferPos];
lTempBufferPos++;
}
szTempBuffer[lTempBufferPos] = 0;
strcat(szPrompt, szTempBuffer);
}
}
}
bout.Color(2);
pla(szPrompt, &abort);
if (nMessageNumber >= session()->GetNumMessagesInCurrentMessageArea()) {
abort = true;
}
}
nScanOptionType = SCAN_OPTION_READ_PROMPT;
}
void HandleMessageDownload(int nMessageNumber) {
if (nMessageNumber > 0 && nMessageNumber <= session()->GetNumMessagesInCurrentMessageArea()) {
long lMessageLen;
unique_ptr<char[]> b(readfile(&(get_post(nMessageNumber)->msg), (subboards[session()->GetCurrentReadMessageArea()].filename),
&lMessageLen));
bout << "|#1Message Download -\r\n\n";
bout << "|#2Filename to use? ";
string filename;
input(&filename, 12);
if (!okfn(filename)) {
return;
}
File fileTemp(syscfgovr.tempdir, filename);
fileTemp.Delete();
fileTemp.Open(File::modeBinary | File::modeCreateFile | File::modeReadWrite);
fileTemp.Write(b.get(), lMessageLen);
fileTemp.Close();
bool bFileAbortStatus;
bool bStatus;
send_file(fileTemp.full_pathname().c_str(), &bStatus, &bFileAbortStatus, fileTemp.full_pathname().c_str(), -1,
lMessageLen);
bout << "|#1Message download... |#2" << (bStatus ? "successful" : "unsuccessful");
if (bStatus) {
sysoplog("Downloaded message");
}
}
}
void HandleMessageMove(int &nMessageNumber) {
if ((lcs()) && (nMessageNumber > 0) && (nMessageNumber <= session()->GetNumMessagesInCurrentMessageArea())) {
char *ss1 = nullptr;
tmp_disable_conf(true);
bout.nl();
do {
bout << "|#5Move to which sub? ";
ss1 = mmkey(0);
if (ss1[0] == '?') {
old_sublist();
}
} while (!hangup && ss1[0] == '?');
int nTempSubNum = -1;
if (ss1[0] == 0) {
tmp_disable_conf(false);
return;
}
bool ok = false;
for (int i1 = 0; (i1 < session()->num_subs && usub[i1].subnum != -1 && !ok); i1++) {
if (IsEquals(usub[i1].keys, ss1)) {
nTempSubNum = i1;
bout.nl();
bout << "|#9Copying to " << subboards[usub[nTempSubNum].subnum].name << endl;
ok = true;
}
}
if (nTempSubNum != -1) {
if (session()->GetEffectiveSl() < subboards[usub[nTempSubNum].subnum].postsl) {
bout.nl();
bout << "Sorry, you don't have post access on that sub.\r\n\n";
nTempSubNum = -1;
}
}
if (nTempSubNum != -1) {
open_sub(true);
resynch(&nMessageNumber, nullptr);
postrec p2 = *get_post(nMessageNumber);
postrec p1 = p2;
long lMessageLen;
unique_ptr<char[]> b(readfile(&(p2.msg), (subboards[session()->GetCurrentReadMessageArea()].filename), &lMessageLen));
bout.nl();
bout << "|#5Delete original post? ";
if (yesno()) {
delete_message(nMessageNumber);
if (nMessageNumber > 1) {
nMessageNumber--;
}
}
close_sub();
iscan(nTempSubNum);
open_sub(true);
p2.msg.storage_type = static_cast<unsigned char>(subboards[session()->GetCurrentReadMessageArea()].storage_type);
savefile(b.get(), lMessageLen, &(p2.msg), (subboards[session()->GetCurrentReadMessageArea()].filename));
WStatus* pStatus = application()->GetStatusManager()->BeginTransaction();
p2.qscan = pStatus->IncrementQScanPointer();
application()->GetStatusManager()->CommitTransaction(pStatus);
if (session()->GetNumMessagesInCurrentMessageArea() >=
subboards[session()->GetCurrentReadMessageArea()].maxmsgs) {
int nTempMsgNum = 1;
int nMsgToDelete = 0;
while (nMsgToDelete == 0 && nTempMsgNum <= session()->GetNumMessagesInCurrentMessageArea()) {
if ((get_post(nTempMsgNum)->status & status_no_delete) == 0) {
nMsgToDelete = nTempMsgNum;
}
++nTempMsgNum;
}
if (nMsgToDelete == 0) {
nMsgToDelete = 1;
}
delete_message(nMsgToDelete);
}
if ((!(subboards[session()->GetCurrentReadMessageArea()].anony & anony_val_net)) ||
(!xsubs[session()->GetCurrentReadMessageArea()].num_nets)) {
p2.status &= ~status_pending_net;
}
if (xsubs[session()->GetCurrentReadMessageArea()].num_nets) {
p2.status |= status_pending_net;
session()->user()->SetNumNetPosts(session()->user()->GetNumNetPosts() + 1);
send_net_post(&p2, subboards[session()->GetCurrentReadMessageArea()].filename,
session()->GetCurrentReadMessageArea());
}
add_post(&p2);
close_sub();
tmp_disable_conf(false);
iscan(session()->GetCurrentMessageArea());
bout.nl();
bout << "|#9Message moved.\r\n\n";
resynch(&nMessageNumber, &p1);
} else {
tmp_disable_conf(false);
}
}
}
void HandleMessageLoad() {
if (!so()) {
return;
}
bout.nl();
bout << "|#2Filename: ";
char szFileName[ MAX_PATH ];
input(szFileName, 50);
if (szFileName[0]) {
bout.nl();
bout << "|#5Allow editing? ";
if (yesno()) {
bout.nl();
LoadFileIntoWorkspace(szFileName, false);
} else {
bout.nl();
LoadFileIntoWorkspace(szFileName, true);
}
}
}
void HandleMessageReply(int &nMessageNumber) {
irt_sub[0] = 0;
if ((!lcs()) && (get_post(nMessageNumber)->status & (status_unvalidated | status_delete))) {
return;
}
postrec p2 = *get_post(nMessageNumber);
grab_quotes(&(p2.msg), subboards[session()->GetCurrentReadMessageArea()].filename);
if (okfsed() && session()->user()->IsUseAutoQuote() &&
nMessageNumber > 0 && nMessageNumber <= session()->GetNumMessagesInCurrentMessageArea()) {
long lMessageLen;
unique_ptr<char[]> b(readfile(&(get_post(nMessageNumber)->msg),
subboards[session()->GetCurrentReadMessageArea()].filename, &lMessageLen));
auto_quote(b.get(), lMessageLen, 1, get_post(nMessageNumber)->daten);
}
if (irt[0] == '\0') {
session()->threadID = "";
}
post();
resynch(&nMessageNumber, &p2);
grab_quotes(nullptr, nullptr);
}
void HandleMessageDelete(int &nMessageNumber) {
if (lcs()) {
if (nMessageNumber) {
open_sub(true);
resynch(&nMessageNumber, nullptr);
postrec p2 = *get_post(nMessageNumber);
delete_message(nMessageNumber);
close_sub();
if (p2.ownersys == 0) {
WUser tu;
application()->users()->ReadUser(&tu, p2.owneruser);
if (!tu.IsUserDeleted()) {
if (date_to_daten(tu.GetFirstOn()) < static_cast<time_t>(p2.daten)) {
bout.nl();
bout << "|#2Remove how many posts credit? ";
char szNumCredits[ 10 ];
input(szNumCredits, 3, true);
int nNumCredits = 1;
if (szNumCredits[0]) {
nNumCredits = (atoi(szNumCredits));
}
nNumCredits = std::min<int>(nNumCredits, tu.GetNumMessagesPosted());
if (nNumCredits) {
tu.SetNumMessagesPosted(tu.GetNumMessagesPosted() - static_cast<unsigned short>(nNumCredits));
}
bout.nl();
bout << "|#7Post credit removed = " << nNumCredits << endl;
tu.SetNumDeletedPosts(tu.GetNumDeletedPosts() - 1);
application()->users()->WriteUser(&tu, p2.owneruser);
application()->UpdateTopScreen();
}
}
}
resynch(&nMessageNumber, &p2);
}
}
}
void HandleMessageExtract(int &nMessageNumber) {
if (so()) {
if ((nMessageNumber > 0) && (nMessageNumber <= session()->GetNumMessagesInCurrentMessageArea())) {
long lMessageLen;
unique_ptr<char[]> b(readfile(&(get_post(nMessageNumber)->msg), (subboards[session()->GetCurrentReadMessageArea()].filename),
&lMessageLen));
if (b) {
extract_out(b.get(), lMessageLen, get_post(nMessageNumber)->title, get_post(nMessageNumber)->daten);
}
}
}
}
void HandleMessageHelp() {
if (forcescansub) {
printfile(MUSTREAD_NOEXT);
} else {
if (lcs()) {
printfile(SMBMAIN_NOEXT);
} else {
printfile(MBMAIN_NOEXT);
}
}
}
void HandleListReplies(int nMessageNumber) {
if (session()->IsMessageThreadingEnabled()) {
if (forcescansub) {
printfile(MUSTREAD_NOEXT);
} else {
bout.nl();
bout << "|#2Current Message has the following replies:\r\n";
int nNumRepliesForThisThread = 0;
for (int j = 0; j <= session()->GetNumMessagesInCurrentMessageArea(); j++) {
if (IsEquals(thread[j].parent_code, thread[nMessageNumber].message_code)) {
bout << " |#9Message #|#6" << j << ".\r\n";
nNumRepliesForThisThread++;
}
}
bout << "|#1 " << nNumRepliesForThisThread << " total replies.\r\n";
bout.nl();
pausescr();
}
}
}
| [
"ec2-user@nfs.mdwestserve.com"
] | ec2-user@nfs.mdwestserve.com | |
bfab540f570b78cf14885ac6e5c2dcd3a454e019 | 5d5673bafdb8def4aa504f6a19b0edb74d078d83 | /include/opencv.hpp | 715609b8533534c6e6635bbe5eaf4d38b6ea40c4 | [] | no_license | garychan/PickandPlace | c069783194450210e4bec99c654c2c75fd773a9e | c85d53a7cf3e83e0fa30ed0a660e73a0c52c5244 | refs/heads/master | 2021-01-25T05:58:09.382911 | 2012-03-11T20:30:33 | 2012-03-11T20:30:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,612 | hpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef __OPENCV_ALL_HPP__
#define __OPENCV_ALL_HPP__
#include "core/core_c.h"
#include "core/core.hpp"
#include "flann/miniflann.hpp"
#include "imgproc/imgproc_c.h"
#include "imgproc/imgproc.hpp"
#include "video/video.hpp"
#include "features2d/features2d.hpp"
#include "objdetect/objdetect.hpp"
#include "calib3d/calib3d.hpp"
#include "ml/ml.hpp"
#include "highgui/highgui_c.h"
#include "highgui/highgui.hpp"
#include "contrib/contrib.hpp"
#endif
| [
"einballimwasser@web.de"
] | einballimwasser@web.de |
5404f6a5a4622c0e5dbf00e577542b84cac41018 | e9753a85f0c77b7e1f82adfb01f52f64813f9d64 | /Huffman/源.cpp | 03450285635f5ef55d25219882e0c43a40d5d506 | [] | no_license | Hikyu/Huffman | 418bf602c914e93d9756c688db8ba78a0b2fc7b9 | dcfb26c7c801c24895f2d300a18fa45c0cf7abe8 | refs/heads/master | 2021-01-18T19:53:01.562127 | 2015-10-15T00:27:25 | 2015-10-15T00:27:25 | 44,283,741 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 324 | cpp | #include"scan.h"
#include"Huffman.h"
using namespace std;
int main()
{
string ifile("g:\\yu.txt");
string ofile("g:\\kai.txt");
scan a;
a.run(ifile);//扫描文件,统计字母频率
Huffman b(a.tmp);//建立霍夫曼树
b.encode(ifile,ofile);//编码
b.decode(ofile,"g:\\yukai.txt");
system("pause");
return 0;
} | [
"13116075090@sina.com"
] | 13116075090@sina.com |
2cbd4b2430eb00d2830a8a646d69e4237f11d7eb | 61d4e279bb59dab28e11ac17f99e466cf8aba3cc | /src/server/game/Entities/Corpse/Corpse.cpp | b73f4eb8db3ce45a06d1fc8e99c505622e8756db | [] | no_license | dufernst/5.4.8-Wow-source | a840af25441ec9c38622c16de40b2997d4605ad1 | 5511dffb1e9ad2e2e0b794288c4b9ea5041112d5 | refs/heads/master | 2021-01-16T22:12:12.568039 | 2015-08-19T22:55:05 | 2015-08-19T22:55:05 | 41,120,934 | 2 | 10 | null | 2015-08-20T22:03:56 | 2015-08-20T22:03:56 | null | UTF-8 | C++ | false | false | 7,563 | cpp | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "Common.h"
#include "Corpse.h"
#include "Player.h"
#include "UpdateMask.h"
#include "ObjectAccessor.h"
#include "DatabaseEnv.h"
#include "Opcodes.h"
#include "GossipDef.h"
#include "World.h"
Corpse::Corpse(CorpseType type) : WorldObject(type != CORPSE_BONES), m_type(type)
{
m_objectType |= TYPEMASK_CORPSE;
m_objectTypeId = TYPEID_CORPSE;
m_updateFlag = UPDATEFLAG_STATIONARY_POSITION;
m_valuesCount = CORPSE_END;
m_time = time(NULL);
lootForBody = false;
lootRecipient = NULL;
}
Corpse::~Corpse()
{
}
void Corpse::AddToWorld()
{
///- Register the corpse for guid lookup
if (!IsInWorld())
sObjectAccessor->AddObject(this);
Object::AddToWorld();
}
void Corpse::RemoveFromWorld()
{
///- Remove the corpse from the accessor
if (IsInWorld())
sObjectAccessor->RemoveObject(this);
Object::RemoveFromWorld();
}
bool Corpse::Create(uint32 guidlow, Map* map)
{
SetMap(map);
Object::_Create(guidlow, 0, HIGHGUID_CORPSE);
return true;
}
bool Corpse::Create(uint32 guidlow, Player* owner)
{
ASSERT(owner);
Relocate(owner->GetPositionX(), owner->GetPositionY(), owner->GetPositionZ(), owner->GetOrientation());
if (!IsPositionValid())
{
sLog->outError(LOG_FILTER_PLAYER, "Corpse (guidlow %d, owner %s) not created. Suggested coordinates isn't valid (X: %f Y: %f)",
guidlow, owner->GetName(), owner->GetPositionX(), owner->GetPositionY());
return false;
}
//we need to assign owner's map for corpse
//in other way we will get a crash in Corpse::SaveToDB()
SetMap(owner->GetMap());
WorldObject::_Create(guidlow, HIGHGUID_CORPSE, owner->GetPhaseMask());
SetObjectScale(1);
SetUInt64Value(CORPSE_FIELD_OWNER, owner->GetGUID());
_gridCoord = WoWSource::ComputeGridCoord(GetPositionX(), GetPositionY());
return true;
}
void Corpse::SaveToDB()
{
// prevent DB data inconsistence problems and duplicates
SQLTransaction trans = CharacterDatabase.BeginTransaction();
DeleteFromDB(trans);
uint16 index = 0;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CORPSE);
stmt->setUInt32(index++, GetGUIDLow()); // corpseGuid
stmt->setUInt32(index++, GUID_LOPART(GetOwnerGUID())); // guid
stmt->setFloat (index++, GetPositionX()); // posX
stmt->setFloat (index++, GetPositionY()); // posY
stmt->setFloat (index++, GetPositionZ()); // posZ
stmt->setFloat (index++, GetOrientation()); // orientation
stmt->setUInt16(index++, GetMapId()); // mapId
stmt->setUInt32(index++, GetUInt32Value(CORPSE_FIELD_DISPLAY_ID)); // displayId
stmt->setString(index++, _ConcatFields(CORPSE_FIELD_ITEM, EQUIPMENT_SLOT_END)); // itemCache
stmt->setUInt32(index++, GetUInt32Value(CORPSE_FIELD_BYTES_1)); // bytes1
stmt->setUInt32(index++, GetUInt32Value(CORPSE_FIELD_BYTES_2)); // bytes2
stmt->setUInt8 (index++, GetUInt32Value(CORPSE_FIELD_FLAGS)); // flags
stmt->setUInt8 (index++, GetUInt32Value(CORPSE_FIELD_DYNAMIC_FLAGS)); // dynFlags
stmt->setUInt32(index++, uint32(m_time)); // time
stmt->setUInt8 (index++, GetType()); // corpseType
stmt->setUInt32(index++, GetInstanceId()); // instanceId
stmt->setUInt16(index++, GetPhaseMask()); // phaseMask
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
}
void Corpse::DeleteBonesFromWorld()
{
ASSERT(GetType() == CORPSE_BONES);
Corpse* corpse = ObjectAccessor::GetCorpse(*this, GetGUID());
if (!corpse)
{
sLog->outError(LOG_FILTER_PLAYER, "Bones %u not found in world.", GetGUIDLow());
return;
}
AddObjectToRemoveList();
}
void Corpse::DeleteFromDB(SQLTransaction& trans)
{
PreparedStatement* stmt = NULL;
if (GetType() == CORPSE_BONES)
{
// Only specific bones
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CORPSE);
stmt->setUInt32(0, GetGUIDLow());
}
else
{
// all corpses (not bones)
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_CORPSES);
stmt->setUInt32(0, GUID_LOPART(GetOwnerGUID()));
}
trans->Append(stmt);
}
bool Corpse::LoadCorpseFromDB(uint32 guid, Field* fields)
{
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// SELECT posX, posY, posZ, orientation, mapId, displayId, itemCache, bytes1, bytes2, flags, dynFlags, time, corpseType, instanceId, phaseMask, corpseGuid, guid FROM corpse WHERE corpseType <> 0
uint32 ownerGuid = fields[16].GetUInt32();
float posX = fields[0].GetFloat();
float posY = fields[1].GetFloat();
float posZ = fields[2].GetFloat();
float o = fields[3].GetFloat();
uint32 mapId = fields[4].GetUInt16();
Object::_Create(guid, 0, HIGHGUID_CORPSE);
SetUInt32Value(CORPSE_FIELD_DISPLAY_ID, fields[5].GetUInt32());
_LoadIntoDataField(fields[6].GetCString(), CORPSE_FIELD_ITEM, EQUIPMENT_SLOT_END);
SetUInt32Value(CORPSE_FIELD_BYTES_1, fields[7].GetUInt32());
SetUInt32Value(CORPSE_FIELD_BYTES_2, fields[8].GetUInt32());
SetUInt32Value(CORPSE_FIELD_FLAGS, fields[9].GetUInt8());
SetUInt32Value(CORPSE_FIELD_DYNAMIC_FLAGS, fields[10].GetUInt8());
SetUInt64Value(CORPSE_FIELD_OWNER, MAKE_NEW_GUID(ownerGuid, 0, HIGHGUID_PLAYER));
m_time = time_t(fields[11].GetUInt32());
uint32 instanceId = fields[13].GetUInt32();
uint32 phaseMask = fields[14].GetUInt16();
// place
SetLocationInstanceId(instanceId);
SetLocationMapId(mapId);
SetPhaseMask(phaseMask, false);
Relocate(posX, posY, posZ, o);
if (!IsPositionValid())
{
sLog->outError(LOG_FILTER_PLAYER, "Corpse (guid: %u, owner: %u) is not created, given coordinates are not valid (X: %f, Y: %f, Z: %f)",
GetGUIDLow(), GUID_LOPART(GetOwnerGUID()), posX, posY, posZ);
return false;
}
_gridCoord = WoWSource::ComputeGridCoord(GetPositionX(), GetPositionY());
return true;
}
bool Corpse::IsExpired(time_t t) const
{
if (m_type == CORPSE_BONES)
return m_time < t - 5 * MINUTE;
else
return m_time < t - 3 * DAY;
}
| [
"andra778@yahoo.com"
] | andra778@yahoo.com |
9a64d26b6f937013e21db8a2da4dfa1322d4c6f9 | 6cfd73d4918ea055db30f6e3c3252e930234767a | /GameServer/MonsterItemMng.h | e4477140609fbd8839fd7e6c5ef0f1197085264d | [
"MIT"
] | permissive | neyma2379294/IGC.GameServer.SX | 138b1ff8019c9c2e83efebe75b8b2899be357255 | 44d77f47598b15c6adb297edba9035561c4fec74 | refs/heads/master | 2021-05-11T07:41:17.590766 | 2017-02-21T17:31:28 | 2017-02-21T17:31:28 | 118,029,462 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,691 | h | #ifndef MONSTERITEMMNG_H
#define MONSTERITEMMNG_H
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "zzzitem.h"
#define MAX_ITEM_IN_MONSTER 1000
#define MAX_LEVEL_MONSTER 255
#define MAX_MAGIC_IN_MONSTER 100
struct __tagMONSTER_ITEM_DROP_PRATE_
{
int m_Level;
int m_MagicBook;
int m_BlessRate;
int m_SoulRate;
int m_ChaosItemRate;
int m_LifeRate;
int m_CreationRate;
int m_NormalItemRate;
int m_TotalRate;
};
class CMonsterItemMng
{
public:
CMonsterItemMng();
virtual ~CMonsterItemMng();
void LoadMonsterItemDropRate();
void Init();
void Clear();
BYTE InsertItem(int monsterlevel, int type, int index, int itemlevel, int op1, int op2, int op3);
CItem * GetItem(int monsterlevel);
void gObjGiveItemSearch(int monsterlevel, int maxlevel);
void MakeJewelItem();
void gObjGiveItemSearchEx(int monsterlevel, int maxlevel);
void MagicBookGiveItemSearch(int monsterlevel, int maxlevel);
void NormalGiveItemSearch(int monsterlevel, int maxlevel);
int CheckMonsterDropItem(int type, int index);
CItem * GetItemEx(int monsterlevel);
void NormalGiveItemSearchEx(int monsterlevel, int maxlevel);
__tagMONSTER_ITEM_DROP_PRATE_ m_MonsterItemDropRate[MAX_LEVEL_MONSTER];
CItem *m_MonsterInvenItems[MAX_LEVEL_MONSTER];
int m_iMonsterInvenItemCount[MAX_LEVEL_MONSTER];
char MonsterName[255];
int m_bLoad;
int m_iMagicBookItmeCount[MAX_LEVEL_MONSTER];
CItem *m_MagicBookItems[MAX_LEVEL_MONSTER];
CItem *m_JewelOfBlessItem;
CItem *m_JewelOfSoulItem;
CItem *m_JewelOfChaosItem;
CItem *m_JewelOfLifeItem;
CItem *m_JewelOfCreationItem;
}; extern CMonsterItemMng g_MonsterItemMng;
#endif | [
"miller@mpdev.com.br"
] | miller@mpdev.com.br |
2cd81c3b8291c01b8f0523ce6c67552767dc374e | 5e0c8107113153eb68206f026038ed55ee079208 | /generate.cpp | ec8438eaf15eb34363fd5ea38fe3b68c158b2e34 | [] | no_license | Rac535/compP4 | 4ef98b9798c0069c219c863fc70250058c911a48 | 59e49491efb407026fedcee8b2c63d768ebded65 | refs/heads/master | 2020-04-11T10:23:46.032692 | 2018-12-14T00:59:01 | 2018-12-14T00:59:01 | 161,712,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,613 | cpp | // generate.c contains assembler generation routines //
// assembler routines are those from chapter2 of "Program Translation" by //
// P. Calingaert //
#include <stdio.h>
#include <string.h>
#include <vector>
#include <iostream>
#include "parser.h"
#include "token.h"
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
static int LabelCntr=0; // for unique labels //
static int VarCntr=0; // for unique variables //
typedef enum {VAR, LABEL} nameType;
static char Name[20]; // for creation of unique names //
static char *newName(nameType what)
{ if (what==VAR)
sprintf(Name,"V%d",VarCntr++); // generate a new label as V0, V1, etc //
else
sprintf(Name,"L%d",LabelCntr++); // new lables as L0, L1, etc //
return(Name);
}
static void recGen(Node *stats,FILE *out)
{ char label[20], label2[20], argR[20];
if (stats==NULL)
return;
if (stats->label== "program"){
recGen(&(stats->children[0]),out); // evaluate rhs //
recGen(&(stats->children[1]),out);
// evaluate rhs //
}else if(stats->label== "block"){
recGen(&(stats->children[0]),out); // evaluate rhs //
recGen(&(stats->children[1]),out); // evaluate rhs //
}
/* look into this one!
if (stats->label== "vars"){
if(!stats->children.empty{
strcpy(argR,newName(VAR)); //create a temporary variable
cout<<"\tREAD\t%s\n"<<argR;
cout<<"\tSTORE\t%s\n"<<argR;
cout<<"\tPUSH\t%s\n";
cout<<"\tSTACKW\t%s\n"<<argR;
}
recGen(&(stats->children[0]),out); // evaluate rhs //
} */
if (stats->label=="expr"){
recGen(&(stats->children[1]),out); // first evaluate rhs //
strcpy(argR,newName(VAR)); //create a temporary variable
cout<<"\tSTORE\t%s\n"<<argR;
recGen(&(stats->children[0]),out); // result is in ACC /
if (stats->tokens[0]=="/")
cout<<"\tDIV\t%s\n"<<argR;
else if (stats->tokens[0]=="*")
cout<<"\tMULT\t%s\n"<<argR;
else cout<<"Invalid tokenId in expression node";
}else if(stats->label=="A"){
recGen(&(stats->children[1]),out); // first evaluate rhs //
strcpy(argR,newName(VAR)); //create a temporary variable
cout<<"\tSTORE\t%s\n"<<argR;
recGen(&(stats->children[0]),out); // result is in ACC /
if (stats->tokens[0]=="+")
cout<<"\tADD\t%s\n"<<argR;
else if (stats->tokens[0]=="-")
cout<<"\tSUB\t%s\n"<<argR;
else cout<<"Invalid tokenId in expression node";
}else if (stats->label== "M"){
if(stats->children[0].label== "R"){
recGen(&(stats->children[0]),out);
}else{
cout<<"\tMULT -1\t%s\n";
}
} else if (stats->label== "R"){
if(!stats->children.empty()){
recGen(&(stats->children[0]),out);
}else if(stats->tokenstash[0].tokenID==ID_TKN){
cout<<"\tLOAD\t%s\n"<<stats->tokens[0];
}else if(stats->tokenstash[0].tokenID==INT_TKN){
cout<<"\tLOAD\t%s\n"<<stats->tokens[0];
}
////////////////
}else if(stats->label== "stats"){
recGen(&(stats->children[0]),out); // evaluate rhs //
cout<<"\tSTORE\t%s\n"<<stats->tokens[1];
/////////////
}else if(stats->label== "mstat"){
recGen(&(stats->children[0]),out); // evaluate rhs //
cout<<"\tSTORE\t%s\n"<<stats->tokens[1];
/////////////
}else if(stats->label== "stat"){
recGen(&(stats->children[0]),out); // evaluate rhs //
cout<<"\tSTORE\t%s\n"<<stats->tokens[1];
}else if(stats->label== "assign"){
recGen(&(stats->children[0]),out); // evaluate rhs //
cout<<"\tSTORE\t%s\n"<<stats->tokens[1];
}else if(stats->label== "in"){
cout<<"\tREAD\t%s\n"<<stats->tokens[1];
} else if (stats->label== "out"){
recGen(&(stats->children[0]),out); // evaluate rhs //
strcpy(argR,newName(VAR)); //create a temporary variable
cout<<"\tSTORE\t%s\n"<<argR;
cout<<"\tWRITE\t%s\n"<<argR;
////////
}else if(stats->label== "IF"){
recGen(&(stats->children[0]),out); // condition //
strcpy(label,Name); // memorize jump label //
recGen(&(stats->children[1]),out); // dependent statements //
cout<<"%s\tNOOP\n"<<label;
}else if(stats->label== "loop"){
recGen(&(stats->children[0]),out); // condition //
strcpy(label,Name); // memorize jump label //
recGen(&(stats->children[1]),out); // dependent statements //
cout<<"%s\tNOOP\n"<<label;
}else if(stats->label== "RO"){
recGen(&(stats->children[1]),out);
strcpy(argR,newName(VAR));
cout<<"\tSTORE\t%s\n"<<argR;
recGen(&(stats->children[0]),out);
cout<<"\tSUB\t%s\n"<<argR;
strcpy(label,newName(LABEL));
if (stats->tokens[0]=="<"){
if (stats->tokens[1]=="="){
cout<<"\tBRPOS\t%s\n"<<label;
}else{
cout<<"\tBRPOS\t%s\n",label;
cout<<"\tBRZERO\t%s\n",label;
}
}else if (stats->tokens[0]==">"){
if (stats->tokens[1]=="="){
cout<<"\tBRNEG\t%s\n"<<label;
}else{
cout<<"\tBRNEG\t%s\n"<<label;
cout<<"\tBRZERO\t%s\n"<<label;
}
}else if(stats->tokens[0]=="="){
if(stats->tokens[1]=="="){
}
}
/*
case EQUALtk: fprintf(out,"\tBRNONZ\t%s\n",label);
break;
default: fprintf(out,"\tBRZERO\t%s\n",label);
}
break;
/
default: recGen(*(stats->children[0]),out);
recGen(*(stats->children[1]),out);
recGen(&(stats->children[2]),out);
*/
}
}
// generate assembler code for parse tree pointed by prog, with variables //
// listed in st subtree //
/*
void generate(const Node *prog, Node *st, FILE *out)
{ int i;
if (prog==NULL || prog->label!=programNode || prog->children[0]==NULL ||
prog->children[0]->label!=programBlockNode)
error("something wrong with parse tree in generate",NULL,0);
recGen(prog->children[0]->children[1],out); // children[0]->children[1] points to statList //
fprintf(out,"\tSTOP\n");
while(st!=NULL) // allocate storage for program variables //
{ fprintf(out,"%s\tSPACE\n",st->tokenP->str);
st=st->children[0];
}
for (i=0;i<VarCntr; i++) // allocate space for temporary variables V* //
fprintf(out,"V%d\tSPACE\n",i);
}
*/
| [
"rac535@umsl.edu"
] | rac535@umsl.edu |
20dd58cf5ae5a5d87b84b1df185fc99ae10f21d4 | e9236095ea8706224892cd4ae310955f24f8e9d5 | /src/application.h | cca22b5a18d9c5295a6f67c8939d4c06e4ebea13 | [] | no_license | jgdevelopment/Shading | d71f75fa5b0bf8b72ebf8364fc9f13a4eb480eb7 | 8989be817740adffa90ccb3f544453ec33162399 | refs/heads/master | 2020-03-18T02:31:17.984101 | 2018-05-17T16:43:08 | 2018-05-17T16:43:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,536 | h | #ifndef CS248_APPLICATION_H
#define CS248_APPLICATION_H
// STL
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <vector>
// libCS248
#include "CS248/CS248.h"
#include "CS248/renderer.h"
#include "CS248/osdtext.h"
// COLLADA
#include "collada/collada.h"
#include "collada/light_info.h"
#include "collada/sphere_info.h"
#include "collada/polymesh_info.h"
#include "collada/material_info.h"
#include "collada/pattern_info.h"
// MeshEdit
#include "dynamic_scene/scene.h"
#include "dynamic_scene/widgets.h"
#include "halfEdgeMesh.h"
#include "meshEdit.h"
// PathTracer
#include "static_scene/scene.h"
#include "pathtracer.h"
#include "image.h"
// Animator
#include "timeline.h"
// Shared modules
#include "camera.h"
using namespace std;
namespace CS248 {
struct AppConfig {
AppConfig() {
pathtracer_ns_aa = 1;
pathtracer_max_ray_depth = 1;
pathtracer_ns_area_light = 4;
pathtracer_ns_diff = 1;
pathtracer_ns_glsy = 1;
pathtracer_ns_refr = 1;
pathtracer_num_threads = 1;
pathtracer_envmap = NULL;
pathtracer_result_path = "";
}
size_t pathtracer_ns_aa;
size_t pathtracer_max_ray_depth;
size_t pathtracer_ns_area_light;
size_t pathtracer_ns_diff;
size_t pathtracer_ns_glsy;
size_t pathtracer_ns_refr;
size_t pathtracer_num_threads;
HDRImageBuffer* pathtracer_envmap;
std::string pathtracer_result_path;
};
class Application : public Renderer {
public:
Application(AppConfig config);
~Application();
void init();
void render();
void resize(size_t w, size_t h);
std::string name();
std::string info();
std::string pattern_info();
void cursor_event(float x, float y);
void scroll_event(float offset_x, float offset_y);
void mouse_event(int key, int event, unsigned char mods);
void keyboard_event(int key, int event, unsigned char mods);
void char_event(unsigned int codepoint);
void load(Collada::SceneInfo* sceneInfo);
void writeScene(const char* filename);
void loadScene(const char* filename);
void writeSkeleton(const char* filename, const DynamicScene::Scene* scene);
void loadSkeleton(const char* filename, DynamicScene::Scene* scene);
void render_scene(std::string saveFileLocation);
private:
// Mode determines which type of data is visualized/
// which mode we're currently in (e.g., modeling vs. rendering vs. animation)
enum Mode { MODEL_MODE, RENDER_MODE, ANIMATE_MODE, VISUALIZE_MODE, SHADER_MODE };
Mode mode;
// Action determines which action will be taken when
// the user clicks/drags/etc.
enum class Action {
Navigate,
Edit,
Bevel,
CreateJoint,
BoneRadius,
IK,
Wave,
Object,
Pose,
Raytrace_Video,
Rasterize_Video,
Iterate_Pattern
};
Action action;
enum class Integrator { Forward_Euler, Symplectic_Euler };
Integrator integrator;
map<DynamicScene::Joint*, Vector3D> ikTargets;
void switch_modes(unsigned int key);
void to_model_mode();
void to_render_mode();
void to_animate_mode();
void to_visualize_mode();
void to_shader_mode();
void to_navigate_action();
void toggle_pattern_action();
void toggle_bevel_action();
void toggle_create_joint_action();
void to_wave_action();
void to_object_action();
void to_pose_action();
void cycle_edit_action();
void set_up_pathtracer();
void raytrace_video();
void rasterize_video();
DynamicScene::Scene* scene;
PathTracer* pathtracer;
// View Frustrum Variables.
// On resize, the aspect ratio is changed. On reset_camera, the position and
// orientation are reset but NOT the aspect ratio.
Camera camera;
Camera canonicalCamera;
size_t screenW;
size_t screenH;
double timestep;
double damping_factor;
// Length of diagonal of bounding box for the mesh.
// Guranteed to not have the camera occlude with the mes.
double canonical_view_distance;
// Rate of translation on scrolling.
double scroll_rate;
/*
Called whenever the camera fov or screenW/screenH changes.
*/
void set_projection_matrix();
/**
* Fills the DrawStyle structs.
*/
void initialize_style();
/**
* Update draw styles properly given the current view distance.
*/
void update_style();
/**
* Reads and combines the current modelview and projection matrices.
*/
Matrix4x4 get_world_to_3DH();
// Initialization functions to get the opengl cooking with oil.
std::string init_pattern(Collada::PatternInfo& pattern, vector<DynamicScene::PatternObject> &patterns);
void init_camera(Collada::CameraInfo& camera, const Matrix4x4& transform);
DynamicScene::SceneLight* init_light(Collada::LightInfo& light,
const Matrix4x4& transform);
DynamicScene::SceneObject* init_sphere(Collada::SphereInfo& polymesh,
const Matrix4x4& transform);
DynamicScene::SceneObject* init_polymesh(Collada::PolymeshInfo& polymesh,
const Matrix4x4& transform,
const std::string shader_prefix = "");
void init_material(Collada::MaterialInfo& material);
void set_scroll_rate();
// Resets the camera to the canonical initial view position.
void reset_camera();
// Rendering functions.
void update_gl_camera();
// style for elements that are neither hovered nor selected
DynamicScene::DrawStyle defaultStyle;
DynamicScene::DrawStyle hoverStyle;
DynamicScene::DrawStyle selectStyle;
// Internal event system //
float mouseX, mouseY;
enum e_mouse_button {
LEFT = MOUSE_LEFT,
RIGHT = MOUSE_RIGHT,
MIDDLE = MOUSE_MIDDLE
};
bool leftDown;
bool rightDown;
bool middleDown;
// Only draw the pick buffer so often
// as an optimization.
int pickDrawCountdown = 0;
int pickDrawInterval = 5;
// Event handling //
void mouse_pressed(e_mouse_button b); // Mouse pressed.
void mouse_released(e_mouse_button b); // Mouse Released.
void mouse1_dragged(float x, float y); // Left Mouse Dragged.
void mouse2_dragged(float x, float y); // Right Mouse Dragged.
void mouse_moved(float x, float y); // Mouse Moved.
/**
* If there is current selection and it's draggable, apply its drag method.
*/
void dragSelection(float x, float y, float dx, float dy,
const Matrix4x4& modelViewProj);
/**
* If the cursor is hovering over something, mark it as selected.
*/
void selectHovered();
void updateWidgets();
void setupElementTransformWidget();
// OSD text manager //
OSDText textManager;
Color text_color;
vector<int> messages;
// Coordinate System //
bool show_coordinates;
void draw_coordinates();
// 3D Transformation //
void setXFormWidget();
// HUD //
bool show_hud;
void draw_hud();
void draw_action();
inline void draw_string(float x, float y, string str, size_t size,
const Color& c);
bool lastEventWasModKey;
// Animator timeline
Timeline timeline;
bool draggingTimeline;
void enter_2D_GL_draw_mode();
void exit_2D_GL_draw_mode();
// Skeleton creation
DynamicScene::Joint* clickedJoint; // joint that is selected
// Intersects mouse position x, y in screen coordinates with a plane
// going through the origin, and returns the intersecting position
Vector3D getMouseProjection(double dist=std::numeric_limits<double>::infinity());
// File read/write --- since we don't have a proper implementation
// of undo/redo, we give the user 10 "buffers" they can write into
// and load out of. This way they can save their work before they
// try a dangerous edit, and restore it if they're unhappy with the
// result. These buffers actually just write files to disk (with
// labels 0-9) and load them back in as needed. To provide some
// protection against accidentally overwriting important data,
// the user has to press a sequence of keys to load and/or write,
// namely, they have to press 'w' and then a number 0-9 to write,
// or 'l' and a number 0-9 to load. If the file already exists
// during write, it will be overwritten. If the file does not
// exist during load, nothing will happen.
bool readyWrite, readyLoad;
void queueWrite();
void queueLoad();
void executeFileOp(int codepoint);
bool isGhosted;
void setGhosted(bool isGhosted);
void toggleGhosted();
bool useCapsuleRadius;
}; // class Application
} // namespace CS248
#endif // CS248_APPLICATION_H
| [
"mjlgg@stanford.edu"
] | mjlgg@stanford.edu |
3682c0bcbc15c56069c3f8b61194a51b9f4989fd | 6781f947994b016f97e9f471f40befbe7132b938 | /modules/ocl/test/test_api.cpp | 0b59fc6a55ccb2d2e82cbf912965f35767168829 | [] | no_license | expertdeveloperit/opencv | 5b8b070a6789f3e67ca3dafd6ae8597992c79809 | c5a65179021758835c31e79133c5796b281cbe16 | refs/heads/master | 2020-03-26T21:36:38.916848 | 2018-08-20T09:45:29 | 2018-08-20T09:45:29 | 145,398,103 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,199 | cpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other oclMaterials provided with the distribution.
//
// * The name of the copyright holders may not 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 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.
//
//M*/
#include "test_precomp.hpp"
#include "opencv2/ocl/cl_runtime/cl_runtime.hpp" // for OpenCL types: cl_mem
TEST(TestAPI, openCLExecuteKernelInterop)
{
cv::RNG rng;
Size sz(10000, 1);
cv::Mat cpuMat = cvtest::randomMat(rng, sz, CV_32FC4, -10, 10, false);
cv::ocl::oclMat gpuMat(cpuMat);
cv::ocl::oclMat gpuMatDst(sz, CV_32FC4);
const char* kernelStr =
"__kernel void test_kernel(__global float4* src, __global float4* dst) {\n"
" int x = get_global_id(0);\n"
" dst[x] = src[x];\n"
"}\n";
cv::ocl::ProgramSource program("test_interop", kernelStr);
using namespace std;
vector<pair<size_t , const void *> > args;
args.push_back( make_pair( sizeof(cl_mem), (void *) &gpuMat.data ));
args.push_back( make_pair( sizeof(cl_mem), (void *) &gpuMatDst.data ));
size_t globalThreads[3] = { sz.width, 1, 1 };
cv::ocl::openCLExecuteKernelInterop(
gpuMat.clCxt,
program,
"test_kernel",
globalThreads, NULL, args,
-1, -1,
"");
cv::Mat dst;
gpuMatDst.download(dst);
EXPECT_LE(checkNorm(cpuMat, dst), 1e-3);
}
| [
"expert.developer.it@gmail.com"
] | expert.developer.it@gmail.com |
152b9ba950ac3fb02312701d05ea0ca5b6fba8ea | 1005f450818900b923e345b73d77628f20d1875e | /thirdparty/asio/asio/experimental/detail/channel_handler.hpp | 04e3700dd287c4cda6c5d21cdac83869cdb97e90 | [
"MIT"
] | permissive | qicosmos/rest_rpc | c7ad37547a9dcb616832b32bc110a237977b8c74 | 93088a7e0f0ddb3786de40ed7b6311852644edbf | refs/heads/master | 2023-08-23T06:56:42.464323 | 2023-07-04T02:57:13 | 2023-07-04T02:57:13 | 162,215,656 | 1,504 | 354 | MIT | 2023-07-05T03:37:24 | 2018-12-18T02:01:52 | C++ | UTF-8 | C++ | false | false | 1,856 | hpp | //
// experimental/detail/channel_handler.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_EXPERIMENTAL_DETAIL_CHANNEL_HANDLER_HPP
#define ASIO_EXPERIMENTAL_DETAIL_CHANNEL_HANDLER_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/associator.hpp"
#include "asio/experimental/detail/channel_payload.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace experimental {
namespace detail {
template <typename Payload, typename Handler>
class channel_handler
{
public:
channel_handler(ASIO_MOVE_ARG(Payload) p, Handler& h)
: payload_(ASIO_MOVE_CAST(Payload)(p)),
handler_(ASIO_MOVE_CAST(Handler)(h))
{
}
void operator()()
{
payload_.receive(handler_);
}
//private:
Payload payload_;
Handler handler_;
};
} // namespace detail
} // namespace experimental
template <template <typename, typename> class Associator,
typename Payload, typename Handler, typename DefaultCandidate>
struct associator<Associator,
experimental::detail::channel_handler<Payload, Handler>,
DefaultCandidate>
: Associator<Handler, DefaultCandidate>
{
static typename Associator<Handler, DefaultCandidate>::type get(
const experimental::detail::channel_handler<Payload, Handler>& h,
const DefaultCandidate& c = DefaultCandidate()) ASIO_NOEXCEPT
{
return Associator<Handler, DefaultCandidate>::get(h.handler_, c);
}
};
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_EXPERIMENTAL_DETAIL_CHANNEL_HANDLER_HPP
| [
"qicosmos@163.com"
] | qicosmos@163.com |
6d2c703e3b0568fc4a22b9c961d39237e4825b3f | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_PrimalItem_RecipeNote_Kibble_Carbonemys_functions.cpp | 3df61d38fa5b1dcf4009c6b12f9cdd4968fa409a | [
"MIT"
] | permissive | git-Charlie/ARK-SDK | 75337684b11e7b9f668da1f15e8054052a3b600f | c38ca9925309516b2093ad8c3a70ed9489e1d573 | refs/heads/master | 2023-06-20T06:30:33.550123 | 2021-07-11T13:41:45 | 2021-07-11T13:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,258 | cpp | // ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PrimalItem_RecipeNote_Kibble_Carbonemys_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function PrimalItem_RecipeNote_Kibble_Carbonemys.PrimalItem_RecipeNote_Kibble_Carbonemys_C.ExecuteUbergraph_PrimalItem_RecipeNote_Kibble_Carbonemys
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UPrimalItem_RecipeNote_Kibble_Carbonemys_C::ExecuteUbergraph_PrimalItem_RecipeNote_Kibble_Carbonemys(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function PrimalItem_RecipeNote_Kibble_Carbonemys.PrimalItem_RecipeNote_Kibble_Carbonemys_C.ExecuteUbergraph_PrimalItem_RecipeNote_Kibble_Carbonemys");
UPrimalItem_RecipeNote_Kibble_Carbonemys_C_ExecuteUbergraph_PrimalItem_RecipeNote_Kibble_Carbonemys_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
d400b70b56773572bc01b7be82acecfec80457df | 217ce7c88681a6e5a723930a139133717e0a37a8 | /TemaT1/TemaT1/Schwefel.cpp | 794a4f3abbb7df026375cf1efe7a13707d8c88ec | [] | no_license | victorwenom123/AlgoritmiGenetici-Tema1 | 8850eafb418285ca8b1879d7f5d6e7639562b4d5 | bdcac43be6f96c17a209c6c37766ea1e5798057f | refs/heads/master | 2023-01-07T01:54:31.581530 | 2020-11-05T08:55:26 | 2020-11-05T08:55:26 | 310,235,448 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,308 | cpp | #define pi 3.14159
#include "Schwefel.h"
#include <time.h>
#include <iostream>
#include <random>
#include <cstdlib>
#include <algorithm>
#include <cmath>
using namespace std;
Schwefel::Schwefel()
{}
double Schwefel::SchwefelFunctie()
{
double s;
s = 10 * n;
double m = 10;
for (int i = 0; i < n; ++i)
s -= x_valori[i] * sin(sqrt(abs(x_valori[i])));
s = -s;
return s;
}
Schwefel::Schwefel(int dim)
{
n = dim;
a = -500;
b = 500;
d = 5;
zece_la_d = 10000;
n = dim;
}
void Schwefel::Random_v()
{
double N = double((b - a)) * double(zece_la_d);
nrbiti = ceil(log2(N));
//srand(time(NULL));
for (int i = 0; i < nrbiti * n; ++i)
v[i] = rand() % 2;
}
void Schwefel::Decodificare(bool sir[])
{
double xdecimal, xreal;
for (int i = 0; i < n; ++i)
{
xdecimal = 0;
for (int j = i * nrbiti; j < nrbiti * (i + 1); ++j)
xdecimal = 2 * xdecimal + sir[j];
xreal = a + double(double(xdecimal) * double((b - a))) / double(pow(2, nrbiti) - 1);
x_valori[i] = xreal;
}
}
void Schwefel::HillClimbingFirst()
{
bool local;
double min,potentialmin;
for (int iteratii = 0; iteratii < 200; ++iteratii)
{
Random_v();
/*for (int y = 0; y < n; y++)
cout << x_valori[y] << ' ';
cout << endl;*/
if (iteratii == 0)
copy(v, v + n * nrbiti, best);
copy(v, v + n * nrbiti, vc);
do
{
//Afisare();
copy(vc, vc + n * nrbiti, vn);
local = 0;
for (int i = 0; i < n * nrbiti; ++i)
{
Decodificare(vc);
min = SchwefelFunctie();
if (vn[i] == 1)
vn[i] = 0;
else
vn[i] = 1;
Decodificare(vn);
if (SchwefelFunctie() < min)
{
local = 1;
copy(vn, vn + n * nrbiti, vc);
break;
}
if (vn[i] == 1)
vn[i] = 0;
else
vn[i] = 1;
}
} while (local);
Decodificare(vc);
potentialmin = SchwefelFunctie();
Decodificare(best);
if (SchwefelFunctie() > potentialmin)
copy(vc, vc + n * nrbiti, best);
}
Decodificare(best);
}
void Schwefel::HillClimbingBest()
{
bool local;
double min,potentialmin;
//double vsave;
for (int iteratii = 0; iteratii < 200; ++iteratii)
{
Random_v();
if (iteratii == 0)
copy(v, v + n * nrbiti, best);
copy(v, v + n * nrbiti, vc);
do
{
copy(vc, vc + n * nrbiti, vn);
local = 0;
for (int i = 0; i < n * nrbiti; ++i)
{
Decodificare(vc);
min = SchwefelFunctie();
if (vn[i] == 1)
vn[i] = 0;
else
vn[i] = 1;
Decodificare(vn);
if (SchwefelFunctie() < min)
{
local = 1;
copy(vn, vn + n * nrbiti, vc);
//copy(vn, vn + n * nrbiti, vsave);
}
if (vn[i] == 1)
vn[i] = 0;
else
vn[i] = 1;
}
} while (local);
Decodificare(vc);
potentialmin = SchwefelFunctie();
Decodificare(best);
if (SchwefelFunctie() > potentialmin)
copy(vc, vc + n * nrbiti, best);
}
}
void Schwefel::SimulatedAnnealing()
{
double T = 10000;
bool local;
//srand(time(NULL));
Random_v();
copy(v, v + n * nrbiti, vc);
copy(v, v + n * nrbiti, best);
int nrveciniparcursi;
bool f[10001];
do
{
nrveciniparcursi = 0;
for (int param = 0; param < n*nrbiti; param++)
f[param] = 0;
do
{
local = false;
int poz = rand() % (n * nrbiti);
double min, Neighbor, Value;
copy(vc, vc + n * nrbiti, vn);
if (vn[poz] == 1)
vn[poz] = 0;
else
vn[poz] = 1;
Decodificare(vc);
Value = SchwefelFunctie();
min = Value;
Decodificare(vn);
Neighbor = SchwefelFunctie();
if (Neighbor < min)
{
local = 1;
copy(vn, vn + n * nrbiti, vc);
}
else
{
random_device r_d;
mt19937 m_t(r_d());
uniform_real_distribution<> d0(0, 1);
double prob = d0(m_t);
if (prob < exp(-abs( Neighbor-Value) / T))
{
local = 1;
copy(vn, vn + n * nrbiti, vc);
}
}
if (!local && !f[poz])
{
nrveciniparcursi++;
f[poz] = 1;
}
} while (!local && nrveciniparcursi < n*nrbiti); // cand am parcurs toti vecinii sau am gasit un vecin favorabil cautarii minimului
T = T * 0.91;
} while (T >= 0.0000000000000000001);
Decodificare(vc);
copy(vc, vc + n * nrbiti, best);
Decodificare(best);
}
void Schwefel::Afisare()
{
Decodificare(best);
for (int i = 0; i < n * nrbiti; ++i)
cout << best[i];
cout << '\n';
for (int i = 0; i < n; i++)
cout << x_valori[i] << ' ';
cout << '\n';
cout << SchwefelFunctie() << '\n';
} | [
"victornicolaestanciu@yahoo.com"
] | victornicolaestanciu@yahoo.com |
8aa6d9bb3993e325afd119b5e9036518da759fec | 33ce14af28db7b11914a388e0d5bda7ceeb6e518 | /logdevice/server/CleanedResponseRequest.h | 0886991840f3d55312b0b146ce1e227a1b49d948 | [
"BSD-3-Clause"
] | permissive | WolfgangBai/LogDevice | e1c025617c3efe06e67738f3c8143db290990b93 | c51c4fadbbf03bf6291628f240a009bf66943200 | refs/heads/master | 2020-03-28T23:05:49.187012 | 2018-09-18T09:57:48 | 2018-09-18T10:13:20 | 149,276,107 | 1 | 0 | null | 2018-09-18T11:18:40 | 2018-09-18T11:18:40 | null | UTF-8 | C++ | false | false | 2,952 | h | /**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include "logdevice/common/Address.h"
#include "logdevice/common/Request.h"
#include "logdevice/common/RequestType.h"
#include "logdevice/common/Seal.h"
#include "logdevice/common/WeakRefHolder.h"
#include "logdevice/common/protocol/CLEAN_Message.h"
namespace facebook { namespace logdevice {
/**
* @file CleanedResponseRequest is the request that handles sending CLEANED
* reply to the sequencer node which previously sent the CLEAN message
* during the recovery of a particular epoch. Before sending the CLEANED
* reply, it ensures that EpochRecoveryMetadata (derived from the CLEAN
* message) is persistently stored in the local log store if needed.
* This is important to guarantee when an epoch of a log finishes
* recovery (i.e., global LCE is advanced in epoch store), there must
* be at least f-majority of storage nodes that have
* EpochRecoveryMetadata for this epoch stored.
*
* One optimizatioin for storing EpochRecoveryMetadata is that we do
* *NOT* store EpochRecoveryMetadata if the epoch is known to be empty
* (i.e., last_known_good == last_digest_record == ESN_INVALID) according
* to the EpochRecovery state machine that sent us the CLEAN message.
*/
class EpochRecoveryMetadata;
class CleanedResponseRequest : public Request {
public:
CleanedResponseRequest(Status status,
std::unique_ptr<CLEAN_Message> clean_msg,
worker_id_t worker_id,
Address reply_to,
Seal preempted_seal,
shard_index_t shard);
int getThreadAffinity(int /* unused */) override {
return worker_id_.val_;
}
Execution execute() override;
// called when the storage task of writing EpochRecoveryMetadata
// finishes
void onWriteTaskDone(Status status);
private:
// status to be included in CLEANED message
Status status_;
// the orginal CLEAN message received
std::unique_ptr<CLEAN_Message> clean_msg_;
// index of worker that received the initial CLEAN message
const worker_id_t worker_id_;
// address of sequencer connection to send reply to
const Address reply_to_;
// if preempted, contains the Seal which preempted the original clean
// message
const Seal preempted_seal_;
// shard that was cleaned
const shard_index_t shard_;
// per epoch log metadata to be written
std::unique_ptr<EpochRecoveryMetadata> metadata_;
// for creating weakref to itself for storage tasks created.
WeakRefHolder<CleanedResponseRequest> ref_holder_;
void prepareMetadata();
void sendResponse();
void writeMetadata();
};
}} // namespace facebook::logdevice
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
b6749acc0d80846646bf0b18ff16844c948aaead | bf7e5ad39c76ffdaedfdc886ac707f4754dbaf46 | /LecturePractice/Lecture7AVL_OtherSorts.h | 5898556d22f31b9b25523ca63e6b91c31459491d | [] | no_license | rsrjohnson/CS5343 | c1a95b46d1069c40e7b6e2009242ad7dc3cbf9b6 | b1561bb6998b119562a4b5217e796059cd2eb2e3 | refs/heads/main | 2023-02-04T21:26:16.248408 | 2020-12-22T22:34:00 | 2020-12-22T22:34:00 | 323,744,157 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,966 | h | #pragma once
#include<algorithm>
#include "Lecture10QuickSort.h"
using namespace std;
struct AVLNode {
int val;
AVLNode* left;
AVLNode* right;
AVLNode* parent;
int ht;
};
AVLNode* insertBST(AVLNode* &root, AVLNode *n) {
if (n->val < root->val)
{
if (root->left == NULL)
{
root->left = n;
root->left->parent = root;
}
else return insertBST(root->left, n);
}
else
{
if (root->right == NULL)
{
root->right = n;
root->right->parent = root;
}
else return insertBST(root->right, n);
}
//root->ht =max(root->left->ht,root->right->ht)+1;
return n;
}
int height(AVLNode* root)
{
if (root == NULL)
return -1;
return 1 + max(height(root->left), height(root->right));
}
int getleftht(AVLNode* root)
{
return height(root->left);
}
int getrightht(AVLNode* root)
{
return height(root->right);
}
void balanceleftStline(AVLNode* &root,AVLNode* n1, AVLNode* n2, AVLNode* n3) {
AVLNode* par = n1->parent;
if (par != NULL)
par->left = n2;
n1->left = n2->right;
n1->parent = n2;
if(n2->right!=NULL)
n2->right->parent = n1;
n2->parent = par;
if(par==NULL){root=n2;}
n2->right = n1;
}
void balancerightStline(AVLNode* &root,AVLNode* n1, AVLNode* n2, AVLNode* n3)
{
AVLNode* par = n1->parent;
if (par != NULL)
par->right = n2;
n1->right = n2->left;
n1->parent = n2;
if(n2->left!=NULL)
n2->left->parent = n1;
n2->parent = par;
if(par==NULL){root=n2;}
n2->left = n1;
}
void balancezigzagleft(AVLNode*& root, AVLNode* n1, AVLNode* n2, AVLNode* n3)
{
n1->left = n3;
n3->parent = n1;
n2->right = n3->left;
if (n3->left != NULL)
n3->left->parent = n2;
n3->left = n2;
n2->parent = n3;
balanceleftStline(root, n1, n3, n2);
}
void balancezigzagright(AVLNode*& root,AVLNode* n1, AVLNode* n2, AVLNode* n3)
{
n1->right = n3;
n3->parent = n1;
n2->left = n3->right;
if(n3->right!=NULL)
n3->right->parent = n2;
n3->right = n2;
n2->parent = n3;
balancerightStline(root,n1, n3, n2);
}
void avlBalance(AVLNode* &root,AVLNode* n1, int ltht, int rtht) {
AVLNode* n2 = NULL;
AVLNode* n3 = NULL;
if (ltht > rtht) {
n2 = n1->left;
}
else {
n2 = n1->right;
}
int ltht3 = getleftht(n2);
int rtht3 = getrightht(n2);
if (ltht3 > rtht3) {
n3 = n2->left;
}
else {
n3 = n2->right;
}
if (n3 == n2->left && n2 == n1->left) {
balanceleftStline(root,n1, n2, n3);
}
if (n3 == n2->right && n2 == n1->right) {
balancerightStline(root,n1, n2, n3);
}
if (n3 == n2->left && n2 == n1->right) {
balancezigzagright(root,n1, n2, n3);
}
if (n3 == n2->right && n2 == n1->left) {
balancezigzagleft(root,n1, n2, n3);
}
n1->ht = height(n1);
n2->ht = height(n2);
n3->ht = height(n3);
}
void insertAVL(AVLNode* &root, AVLNode* n) {
n = insertBST(root, n);
bool flag = false;
AVLNode* par = n->parent;
int leftht, rightht;
while (flag == false && par!=NULL) {
if (par->left == NULL)
leftht = 0;
else
leftht = par->left->ht + 1;
if (par->right == NULL)
rightht = 0;
else
rightht = par->right->ht + 1;
par->ht = max(leftht, rightht);
if (abs(leftht - rightht) == 2) {
avlBalance(root,par, leftht, rightht);
flag = true;
}
par = par->parent;
}
}
//Bubble Sort
void bubblesort(int* a, int len) {
int i, tmp;
bool swapped = true;
while (swapped == true) {
swapped = false;
for (i = 0; i < len - 1; i++) {//starting int j=0 and doing len - j - 1, j++
if (a[i] < a[i + 1]) {//>for descending
tmp = a[i];
a[i] = a[i + 1];
a[i + 1] = tmp;
swapped = true;
}
}
}
}
struct link {
int data;
link* next;
};
class linklist
{
public:
link* first;
};
void bubblesortli(linklist *li) {
link* current;
link* current2;
int tmp;
bool swap = true;
while (swap == true) {
swap = false;
current =li->first;
current2 = current->next;
while (current2 != NULL) {
if (current->data < current2->data) {//> for descending
tmp = current->data;
current->data = current2->data;
current2->data = tmp;
swap = true;
}
//cout << "st3" << current2->data << endl;
//cout << "min" << min->data << endl;
current = current2;
current2 = current2->next;
}
//current = current->next;
}
}
void merge(vector<int>& A, int left, int mid, int right)
{
vector<int> tmp(right - left + 1, 0);
int i, j, k;
i = left; j = mid + 1;
for (k = 0; k < right - left + 1; k++)
{
if (i == mid + 1)
{
tmp[k] = A[j];
j++;
continue;
}
if (j == right + 1)
{
tmp[k] = A[i];
i++;
continue;
}
if (A[i] < A[j])//> for descending
{
tmp[k] = A[i];
i++;
}
else
{
tmp[k] = A[j];
j++;
}
}
// copy tmp back to A[] at left to right index
//copy(begin(tmp), end(tmp), begin(A)+left);
copy(tmp.begin(), tmp.end(), A.begin()+left);
printArray(A, A.size());
}
void mergesort(vector<int>&A, int l, int r)
{
if (r <= l)
return;
int mid = (l + r) / 2;
mergesort(A, l, mid);
mergesort(A, mid + 1, r);
merge(A, l, mid, r);
}
| [
"rsrjohnson@gmail.com"
] | rsrjohnson@gmail.com |
5dbbf9560571c544e8abcb510eb959dd60c43d01 | 4026628e96d3024bd1e79779a0b1790f8a5d352a | /OpenGLTemplate/Camera/camera.cpp | 517a4c3214646cf45035eb92062fede54769d302 | [
"BSD-3-Clause"
] | permissive | koralexa/raytracer | 2a1e99452e7563dd3a58edb915ab87a53dccd5a1 | 969e711d451de7ebfeac0838b4bce1b49619beac | refs/heads/main | 2023-03-24T14:54:23.138209 | 2021-03-25T12:30:49 | 2021-03-25T12:30:49 | 350,742,182 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,900 | cpp | #include "camera.h"
#include <vector>
#include "../Application/application.h"
static vector<CameraPtr> cameras;
void Camera::set_orthographic(float width, float height, float zNear, float zFar)
{
const float aspectRatio = width / height;
projection = ortho(-1.f, 1.f,-1.f * aspectRatio, 1.f * aspectRatio, zNear, zFar);
}
void Camera::set_perspective(float fieldOfView, float aspectRatio, float zNear, float zFar)
{
projection = perspective(fieldOfView, aspectRatio, zNear, zFar);
}
void Camera::set_perspective(float fieldOfView, float zNear, float zFar)
{
const float aspectRatio = (float)Application::get_context().get_width() / Application::get_context().get_height();
projection = perspective(fieldOfView, aspectRatio, zNear, zFar);
}
const mat4x4& Camera::get_projection() const
{
return projection;
}
Transform& Camera::get_transform()
{
return transform;
}
mat4x4 Camera::get_transform_matrix() const
{
return transform.get_transform();
}
void Camera::set_priority(int priority)
{
this->priority = priority;
}
int Camera::get_priority() const
{
return priority;
}
void Camera::set_to_shader(const Shader& shader, bool sky_box) const
{
vec3 cameraPosition = transform.get_position();
mat4 view = inverse(transform.get_transform());
mat4x4 viewProjection = projection * (sky_box ? mat4(mat3(view)): view);
shader.set_mat4x4("ViewProjection", viewProjection);
shader.set_vec3("CameraPosition", cameraPosition);
}
void add_camera(CameraPtr camera)
{
cameras.emplace_back(camera);
}
CameraPtr main_camera()
{
CameraPtr camera;
if (cameras.size() > 0)
{
int max_priority = cameras[0]->get_priority();
camera = cameras[0];
for (auto camera_ptr : cameras)
{
if (camera_ptr->get_priority() > max_priority)
{
max_priority = camera_ptr->get_priority();
camera = camera_ptr;
}
}
}
return camera;
}
| [
"koralexa@ispras.ru"
] | koralexa@ispras.ru |
dc3f5a88cf16fee556d07ab54aff0b1e1749e901 | 28d68af73c56375314efd07eaf6a1a9241a51ce3 | /aws-cpp-sdk-swf/include/aws/swf/model/FailWorkflowExecutionFailedCause.h | cfe2b01d95dc67a318d6e6a0612f6cd797ad6f2e | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | zeliard/aws-sdk-cpp | 93b560791fa359be25b201e9a6513bc3cb415046 | 14119f1f5bc159ce00a1332f86e117362afd3cb6 | refs/heads/master | 2021-01-16T22:49:18.731977 | 2016-01-04T01:54:38 | 2016-01-04T01:54:38 | 41,892,393 | 0 | 1 | null | 2015-09-04T01:35:43 | 2015-09-04T01:35:43 | null | UTF-8 | C++ | false | false | 1,226 | h | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/swf/SWF_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace SWF
{
namespace Model
{
enum class FailWorkflowExecutionFailedCause
{
NOT_SET,
UNHANDLED_DECISION,
OPERATION_NOT_PERMITTED
};
namespace FailWorkflowExecutionFailedCauseMapper
{
AWS_SWF_API FailWorkflowExecutionFailedCause GetFailWorkflowExecutionFailedCauseForName(const Aws::String& name);
AWS_SWF_API Aws::String GetNameForFailWorkflowExecutionFailedCause(FailWorkflowExecutionFailedCause value);
} // namespace FailWorkflowExecutionFailedCauseMapper
} // namespace Model
} // namespace SWF
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
b313d36d5506efcbac515dd0a975b7ec840136ff | 542b94e96e477c8f8373fa21a2ac76ff58bb57ce | /020_valid_parentheses.cpp | bec9c6a1b99e912ab45183b5576bccec37c72c88 | [] | no_license | CharellKing/leetcode | 73d7aad8383aaf4cfc7f3332fdb8551781001f64 | 94d9e614cd897f5318aa1b17654faca4f945b14d | refs/heads/master | 2020-03-10T10:37:34.981191 | 2018-04-13T02:42:34 | 2018-04-13T02:42:34 | 129,337,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 670 | cpp | class Solution {
public:
bool isValid(const string& s) {
stack<char> ss;
for(int i = 0; i < s.size(); i ++) {
if ('(' == s[i]) {
ss.push(s[i]);
} else if ('[' == s[i]) {
ss.push(s[i]);
} else if ('{' == s[i]) {
ss.push(s[i]);
} else if (')' == s[i]) {
if (ss.size() > 0 && '(' == ss.top()) {
ss.pop();
} else {
return false;
}
} else if (']' == s[i]) {
if (ss.size() > 0 && '[' == ss.top()) {
ss.pop();
} else {
return false;
}
} else if ('}' == s[i]) {
if (ss.size() > 0 && '{' == ss.top()) {
ss.pop();
} else {
return false;
}
}
}
return ss.size() == 0;
}
};
| [
"CharellkingQu@163.com"
] | CharellkingQu@163.com |
676f7a69d271902ced807ae3488826771c06f55d | 7217d7ba75389316520cc823b36fcba565021afe | /searchingAlgo/breadthFirstSearch/BreadthFirstSearch.cpp | 930902f79b9e868e0474d2a963747537a628c296 | [] | no_license | deutranium/Algorithms | eee6271340ccecb941d23b4b71846d6704b2ebca | 8adb8ff5140e641e96f854cdecefc5d2106ab2f7 | refs/heads/master | 2023-02-04T11:51:16.542960 | 2022-12-01T14:16:10 | 2022-12-01T14:16:10 | 196,196,487 | 47 | 127 | null | 2023-01-30T19:29:00 | 2019-07-10T11:55:44 | C++ | UTF-8 | C++ | false | false | 1,953 | cpp | #include<iostream>
#include <list>
using namespace std;
// This class represents a directed graph using
// adjacency list representation
class Graph
{
int V; // No. of vertices
// Pointer to an array containing adjacency
// lists
list<int> *adj;
public:
Graph(int V); // Constructor
// function to add an edge to graph
void addEdge(int v, int w);
// prints BFS traversal from a given source s
void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::BFS(int s)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
// 'i' will be used to get all adjacent
// vertices of a vertex
list<int>::iterator i;
while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();
// Get all adjacent vertices of the dequeued
// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
// Driver program to test methods of graph class
int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Breadth First Traversal "
<< "(starting from vertex 2) \n";
g.BFS(2);
return 0;
}
| [
"anamikak266@gmail.com"
] | anamikak266@gmail.com |
99bac8036cfaa518026fdba8755e04943be181f1 | a8719083b1859d645da054f0f11b3577e537f4b1 | /proj2-harness/code/userprog/pcb.cc | e5b1106dd7e02a099f0ab9410f2a178932198aac | [
"MIT-Modern-Variant"
] | permissive | Kevcheezy/NACHOSsyscall | 1be67b5e4e0bed8788937b8a6128b909d2e8a199 | 88d29ef6bce01abd333058f2e686e52442aa18da | refs/heads/master | 2021-01-21T19:13:04.484139 | 2017-05-25T04:28:40 | 2017-05-25T04:28:40 | 92,126,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,124 | cc | // pcb.cc
/*
* PCB implementation
*
* A process control block stores all the necessary information about a process.
*/
#include "pcb.h"
#include "utility.h"
#include "openfilemanager.h"
#include "system.h"
//-----------------------------------------------------------------------------
// PCB::PCB
//
// Constructor
//-----------------------------------------------------------------------------
PCB::PCB(int pid1, int parentPID1) : openFilesBitMap(MAX_NUM_FILES_OPEN) {
this->pid = pid1;
this->parentPID = parentPID1;
this->process = NULL;
//openFilesBitMap maintains what has been opened.
// Account for files that are already opened, including descriptor 0 and 1
// Child process should inherit the file descriptors openned in the parent process
openFilesBitMap.Mark(0);
openFilesBitMap.Mark(1);
//openFilesBitMap.Mark(2);
// Copy parent's openFilesBitMap
/*
PCB* parentPCB = processManager->getPCB(parentPID);
BitMap* parentBitMap = parentPCB->getOpenFilesBitMap();
// Copy parent's userOpenFileList
UserOpenFile* parentUserFileOpenList = parentPCB->getUserOpenFileList();
for(int i = 0; i < MAX_NUM_FILES_OPEN ; i++){
if(parentBitMap->Test(i) == TRUE){
openFilesBitMap.Mark(1);
}
else{
openFilesBitMap.Mark(0);
}
this->userOpenFileList[i] = parentUserFileOpenList[i];
}
*/
}
//-----------------------------------------------------------------------------
// PCB::~PCB
//
// Destructor
//-----------------------------------------------------------------------------
PCB::~PCB() {}
//-----------------------------------------------------------------------------
// PCB::getPID
//
// Returns the process ID assocated with this PCB.
//-----------------------------------------------------------------------------
int PCB::getPID() {
return this->pid;
}
//-----------------------------------------------------------------------------
// PCB::addFile
//
// Adds an open file to this PCB's open file list.
//-----------------------------------------------------------------------------
int PCB::addFile(UserOpenFile file) {
int fileIndex = openFilesBitMap.Find();
if (fileIndex == -1) {
printf("No more room for open files.\n");
return -1;
} else {
userOpenFileList[fileIndex] = file;
return fileIndex;
}
}
//-----------------------------------------------------------------------------
// PCB::getFile
//
// Returns the open file associated with this PCB with the specified fileID.
//-----------------------------------------------------------------------------
UserOpenFile* PCB::getFile(int fileID) {
if (openFilesBitMap.Test(fileID)) {
return userOpenFileList + fileID;
} else {
return NULL;
}
}
//-----------------------------------------------------------------------------
// PCB::removeFile
//
// Removes the open file associated with this PCB with the specified fileID.
//-----------------------------------------------------------------------------
void PCB::removeFile(int fileID) {
openFilesBitMap.Clear(fileID);
}
| [
"kevinchan@umail.ucsb.edu"
] | kevinchan@umail.ucsb.edu |
eae8ded87bb61502179eb70c2683de4485f623ce | bcc51e7c82640d749fd231de3a00e5f26ae9f52f | /code/Server/Operation.h | fe5738a7ddc0acaf16fd72bb21fff7c38bf3c011 | [
"BSD-3-Clause"
] | permissive | eamonhsiun/gStoreD | c7312ceda0eefb9412b4af38e5c019df1b9b5ce9 | ef2b7a8a1cc73db762f72decf8f151819f00b718 | refs/heads/master | 2021-01-11T06:20:18.212470 | 2016-10-06T07:38:57 | 2016-10-06T07:38:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,186 | h | /*
* Operation.h
*
* Created on: 2014-10-16
* Author: hanshuo
*/
#ifndef OPERATION_H_
#define OPERATION_H_
#include<string>
#include<vector>
#include"../Bstr/Bstr.h"
enum CommandType {CMD_CONNECT, CMD_EXIT, CMD_LOAD, CMD_UNLOAD, CMD_CREATE_DB, CMD_DELETE_DB,
CMD_IMPORT, CMD_QUERY, CMD_SHOW, CMD_INSERT, CMD_OTHER}; // extend the operation command type here.
class Operation
{
public:
Operation();
Operation(std::string _usr, std::string _pwd, CommandType _cmd, const std::vector<std::string>& _para);
Operation(CommandType _cmd, const std::vector<std::string>& _para);
~Operation();
Bstr encrypt();
Bstr deencrypt();
CommandType getCommand();
std::string getParameter(int _idx);
void setCommand(CommandType _cmd);
void setParameter(const std::vector<std::string>& _para);
private:
/*
* attention: the username and password is not used to verify permissions of connection by now...
* this part of functions should be implemented later.
*/
std::string username;
std::string password;
CommandType command;
std::vector<std::string> parameters;
};
#endif /* OPERATION_H_ */
| [
"bnu05pp@gmail.com"
] | bnu05pp@gmail.com |
003418644bdb5429e2985ca2f9e7fb8c8b20fb9f | b7b747979fdb97ed2bc79806fd0b706e8bbdd61d | /hw5/token.cc | d18788b9b5b08d269bb9f4d6a2007729bd16f9f4 | [] | no_license | luop/ee590 | 14204c63504b825121cfff7669266c91b43ba100 | 29299bba4489266ce8f155769798fdf0ef8ad746 | refs/heads/master | 2021-03-27T11:59:54.003394 | 2016-12-20T00:58:31 | 2016-12-20T00:58:31 | 69,709,543 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,265 | cc | #include <string>
#include <iostream>
#include "token.hh"
std::string Token::to_s ( void ) {
switch ( token_type ) {
case PUNCTUATION: {
std::string s("");
s += punctuation;
return s;
}
case STRING:
return str;
case BOOLEAN:
return boolean ? std::string("true") : std::string("false");
case NUMBER:
return std::to_string(is_integer ? ((int) number) : number);
case EXPONENTS:
return std::to_string(is_integer ? ((int) number) : number) + "E" + std::to_string(exponents);
case NULLTOK:
return std::string("null");
default:
return std::string("UNKNOWN TOKEN");
}
}
std::ostream& operator<<(std::ostream& os, const Token &tok) {
switch ( tok.type() ) {
case Token::NULLTOK:
os << "NULLTOK: null";
break;
case Token::NUMBER:
os << "NUMBER: " << tok.number;
break;
case Token::EXPONENTS:
os << "NUMBER: " << tok.number << "E" << tok.exponents;
break;
case Token::STRING:
os << "STRING: " << tok.str;
break;
case Token::BOOLEAN:
os << "BOOLEAN: " << ( tok.boolean ? "true" : "false" );
break;
case Token::PUNCTUATION:
os << "PUNCTUATION: " << tok.punctuation;
break;
default:
os << "!UNKNOWN TOKEN!";
break;
}
return os;
}
| [
"lpan@linux-lab-001.ee.washington.edu"
] | lpan@linux-lab-001.ee.washington.edu |
9afc50159ac6bd9aaaebf8960584d75290f4c8ca | ce7a1741a43d496f1700a3675c7edc5a9e83c979 | /Screen.cpp | 184fc9ae7b220d077b26135316053446a42320d4 | [] | no_license | ajdm05/Progra3-Examen1 | c673c2c73b2593fe8b30f98dea990bfe74300da8 | e311b0a48e279f7100c1732f2bf2e6327d6df446 | refs/heads/master | 2021-05-27T16:57:24.094078 | 2013-05-11T05:01:24 | 2013-05-11T05:01:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 863 | cpp | #include "Screen.h"
Screen::Screen()
{
pantalla = NULL;
//ctor
}
Screen::~Screen()
{
delete this->pantalla;
}
bool Screen::init()
{
//Initialize all SDL subsystems
if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
{
return false;
}
//Set up the screen
pantalla = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
//Set the window caption
SDL_WM_SetCaption( "SDL Runner Lab Progra 3", NULL );
//If everything initialized fine
return true;
}
void Screen::frameCap()
{
int frames_per_seccond = 15;
if(update->get_ticks() < 1000 / frames_per_seccond)
{
//Sleep the remaining frame time
SDL_Delay( ( 1000 / frames_per_seccond ) - update->get_ticks() );
}
update->start();
}
SDL_Surface* Screen::getScreen()
{
return this->pantalla;
}
| [
"angela.delgado@unitec.edu"
] | angela.delgado@unitec.edu |
5420b5db049358c614592f6d57bb116897ae7cb7 | 0a438bbdd7dda35efa060ca3c978d91035c61cbf | /lab2_scheduler_DES/src/state.h | 07762b7c801b72c6da38bedf1554c19b8abc22c5 | [] | no_license | flying-potato/OS | ffef008be9281a4790acfc6a860184da70d75c51 | be4085df6bf5ff10503d2a527ba48fa68524b981 | refs/heads/master | 2021-01-22T20:45:40.962375 | 2017-04-19T07:10:28 | 2017-04-19T07:10:28 | 85,359,629 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 379 | h | #ifndef __STATE__
#define __STATE__
using namespace std;
enum TRANSITION{
TRANS_TO_READY,TRANS_TO_RUN,
TRANS_TO_BLOCK, TRANS_TO_PREEMPT, TRANS_TO_DONE
};
enum STATE{
CREATED, READY, RUNNG, BLOCK, Done
};
string TRAN[4] ={ "TRANS_TO_READY","TRANS_TO_RUN", "TRANS_TO_BLOCK", "TRANS_TO_PREEMPT"};
string STA[5] ={"CREATED", "READY", "RUNNG", "BLOCK", "Done"};
#endif
| [
"cl4056@nyu.edu"
] | cl4056@nyu.edu |
9591025f766c79c231f8b4e85d1f8b04cb3645de | f71a56667058c547b06b97eaf0844de337d575ec | /WingLoft/Wing.cpp | 7fc674d49ee643843571c99bc9d43f7d78ea781e | [] | no_license | nappij/WingLoft | 9b5e181f5442c9a9fc00ba609c2dd60ba5e9ddba | 4b183aa748a5552e5f4e9e5df1a4c1bb4a3794c4 | refs/heads/master | 2020-05-02T18:28:03.737761 | 2019-04-12T20:47:14 | 2019-04-12T20:47:14 | 177,926,585 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,040 | cpp | // ***************************
// * Introduction to C++ *
// ***************************
// Author: John Nappi
// Assignment: Final Project
// Date Due: Apr. 5, 2019
#include "Wing.h"
// *****************************************************************************
// Grid and connectivity setter
// *****************************************************************************
// Set the grid table and connectivity table together
void Wing::setGridsAndConnectivity(const std::vector<Vector3>& grids,
const std::vector<std::vector<int>>& connectivity)
{
this->grids = grids;
this->connectivity = connectivity;
}
// *****************************************************************************
// Grid and connectivity getters
// *****************************************************************************
// Return grid table
const std::vector<Vector3>& Wing::getGrids() const
{
return grids;
}
// Return connectivity table
const std::vector<std::vector<int>>& Wing::getConnectivity() const
{
return connectivity;
} | [
"nappij@gmail.com"
] | nappij@gmail.com |
f8fbb4b8b5675d95874a30b4ab4f300aeb64940a | 4c3b00dad2548e8041cee612be66b33c7800c66d | /ACMP/669.cpp | 01efb921990b1bdaeb955727f2e6c3d7f0f9fdec | [] | no_license | MuctepK/Olympiad | 21a083818e07c4414a30042d0d739a87cb676bdb | f037e56a8f58d4d89e538bd5a13636855f28e61d | refs/heads/master | 2020-07-25T12:37:20.590729 | 2020-06-04T17:00:45 | 2020-06-04T17:00:45 | 208,291,690 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,724 | cpp | // Произведение цифр - 3
// (Время: 1 сек. Память: 16 Мб Сложность: 39%)
// Найти наименьшее и наибольшее натуральные числа, произведение цифр в которых равно заданному натуральному числу M или сообщить, что таких чисел не существует. Для записи искомых чисел нельзя использовать цифры 0 и 1.
// Входные данные
// В единственной строке входного файла INPUT.TXT записано натуральное число M (2 ≤ M ≤ 1000).
// Выходные данные
// В единственную строку выходного файла OUTPUT.TXT нужно вывести два натуральных числа в неубывающем порядке. Если таких чисел не существует, то вывести -1 -1.
#include <bits/stdc++.h>
using namespace std;
int first[10];
int second[10];
int main() {
long N;
cin >> N;
long temp = N;
for (int i =9;i>1;i--){
while (temp%i==0){
temp/=i;
first[i]++;
}
}
for (int i =2;i<10;i++){
while (N%i==0){
N/=i;
second[i]++;
}
}
if (N!=1){
cout << -1 << " " << -1;
return 0;
}
else{
for (int i =2;i<10;i++){
while (first[i]){
cout << i;
first[i]--;
}
}
cout << " ";
for (int i =9;i>1;i--){
while (second[i]){
cout << i;
second[i]--;
}
}
}
}
| [
"muctep.k@gmail.com"
] | muctep.k@gmail.com |
e68a9d1a55269c5417b47fefa43879ee80737292 | 5ed2c620083bfdacd3a2cd69e68401f6e4519152 | /Cpp/Design-Pattern/Strategy/Strategy/Strategy.h | 3dab0c59651e17e8b6abb76ef8669a1ee1b0f779 | [] | no_license | plinx/CodePractices | 03a4179a8bbb9653a40faf683676bc884b72bf75 | 966af4bf2bd5e69d7e5cfbe8ed67c13addcb61b9 | refs/heads/master | 2021-01-01T05:40:02.159404 | 2015-08-30T20:16:44 | 2015-08-30T20:16:44 | 33,318,262 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 518 | h | #ifndef Strategy_h
#define Strategy_h
class Strategy
{
public:
Strategy() = default;
virtual ~Strategy() = default;
virtual void AlgInterface() = 0;
};
class ConcreteStrategy1 : public Strategy
{
public:
ConcreteStrategy1() = default;
void AlgInterface() { std::cout << "ConcreteStrategy1 AlgInterface ..." << std::endl; }
};
class ConcreteStrategy2 : public Strategy
{
public:
ConcreteStrategy2() = default;
void AlgInterface() { std::cout << "ConcreteStrategy2 AlgInterface ..." << std::endl; }
};
#endif
| [
"plinux@qq.com"
] | plinux@qq.com |
c147dc24904a90cc74f3b4f02cf630f5bfbdb7fc | 2a347390a0abbb5872628bf3a067a2be9581d669 | /leetcode 217 Contains Duplicate.cpp | f24aaeefcc401e533914cb2cdade1177a5a1bf93 | [] | no_license | sean1125/Leetcode_cpp | 126d0319e5351512c5237c79b267dca1e311fced | 603e2f0bd28d9199ea497a472e9ceb5f657d4a55 | refs/heads/master | 2021-01-22T21:12:53.764576 | 2015-10-04T20:10:55 | 2015-10-04T20:10:55 | 33,286,337 | 1 | 1 | null | 2015-11-12T02:42:24 | 2015-04-02T03:03:52 | C++ | UTF-8 | C++ | false | false | 347 | cpp | // leetcode 217 Contains Duplicate.cpp
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int i, size = nums.size();
unordered_set<int> s;
for (i = 0; i < size; i++) {
if (s.find(nums[i]) != s.end()) return true;
s.insert(nums[i]);
}
return false;
}
};
| [
"shixiaoran1989@gmail.com"
] | shixiaoran1989@gmail.com |
82257eaf8fbf200f6fc34d716db528f636c42f56 | 15662778233fc0cca3e88e888a193d5c56bc1a4b | /frontend/gen_tree_visitor.h | 8896e2f4fd50d80c9711da2ab6148d105a075c75 | [] | no_license | voidii/CS160 | 52dba9bf11bb4beabe473cbb919de8234e277a87 | 5ae9a4f1dfd1d864da5e400f476fc0abb27084c2 | refs/heads/master | 2023-01-23T14:50:57.526577 | 2020-12-08T03:54:30 | 2020-12-08T03:54:30 | 319,486,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,770 | h |
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
#include "ast_visitor.h"
namespace cs160::frontend {
class genTreeVisitor : public AstVisitor {
public:
genTreeVisitor() {}
~genTreeVisitor() {}
const std::string GetOutput() const { return output_.str(); }
void visitInteger(const Integer& exp) override {
output_ << exp.value();
}
void visitNil(const NilExpr& exp) override {
output_ << "nil";
}
void visitAccessPath(const AccessPath& path) override {
path.root().Visit(this);
for (auto const & f : path.fieldAccesses()) {
output_ << "." << f;
}
}
void visitTypeExpr(const TypeExpr& exp) override { output_ << exp.name(); }
void visitAddExpr(const AddExpr& exp) override {
output_ << "(+ ";
exp.lhs().visit(this);
output_ << " ";
exp.rhs().visit(this);
output_ << ")";
}
void visitSubtractExpr(const SubtractExpr& exp) override {
output_ << "(- ";
exp.lhs().visit(this);
output_ << " ";
exp.rhs().visit(this);
output_ << ")";
}
void visitMultiplyExpr(const MultiplyExpr& exp) override {
output_ << "(* ";
exp.lhs().visit(this);
output_ << " ";
exp.rhs().visit(this);
output_ << ")";
}
void visitVariableExpr(const VariableExpr& exp) override {
output_ << exp.name();
}
void visitNewExpr(const NewExpr& exp) override {
output_ << "new " << exp.type();
}
void visitLessThanExpr(const LessThanExpr& exp) override {
output_ << "(< ";
exp.lhs().visit(this);
output_ << " ";
exp.rhs().visit(this);
output_ << ")";
}
void visitLessThanEqualToExpr(const LessThanEqualToExpr& exp) override {
output_ << "(<= ";
exp.lhs().visit(this);
output_ << " ";
exp.rhs().visit(this);
output_ << ")";
}
void visitEqualToExpr(const EqualToExpr& exp) override {
output_ << "(= ";
exp.lhs().visit(this);
output_ << " ";
exp.rhs().visit(this);
output_ << ")";
}
void visitLogicalAndExpr(const LogicalAndExpr& exp) override {
output_ << "(&& ";
exp.lhs().visit(this);
output_ << " ";
exp.rhs().visit(this);
output_ << ")";
}
void visitLogicalOrExpr(const LogicalOrExpr& exp) override {
output_ << "(|| ";
exp.lhs().visit(this);
output_ << " ";
exp.rhs().visit(this);
output_ << ")";
}
void visitLogicalNotExpr(const LogicalNotExpr& exp) override {
output_ << "(!";
exp.operand().visit(this);
output_ << ")";
}
void visitIntType(const IntType& exp) override { output_ << exp.value(); }
void visitIntTypeExpr(const IntType& exp) override { output_ << exp.value(); }
void visitBlockExpr(const BlockExpr& exp) override {
for (auto it = exp.decls().begin(); it != exp.decls().end(); ++it) {
(*it)->visit(this);
}
output_ << " ";
for (auto it = exp.stmts().begin(); it != exp.stmts().end(); ++it) {
(*it)->visit(this);
}
}
void visitDeclaration(const Declaration& exp) override {
output_ << "";
exp.type().visit(this);
output_ << " ";
exp.id().visit(this);
output_ << "; ";
}
void visitAssignment(const Assignment& exp) override {
output_ << "";
exp.lhs().visit(this);
output_ << " := ";
exp.rhs().visit(this);
output_ << "; ";
}
void visitConditional(const Conditional& exp) override {
output_ << "if ";
exp.guard().visit(this);
output_ << " {";
exp.true_branch().visit(this);
output_ << "} else {";
exp.false_branch().visit(this);
output_ << "}";
}
void visitWhileLoop(const Loop& exp) override {
output_ << "while ";
exp.guard().visit(this);
output_ << " {";
exp.body().visit(this);
output_ << "}";
}
void visitFunctionCallExpr(const FunctionCall& exp) override {
output_ << exp.callee_name() << "(";
for (auto it = exp.arguments().begin(); it != exp.arguments().end(); ++it) {
(*it)->visit(this);
}
output_ << ")";
}
void visitFunctionDef(const FunctionDef& exp) override {
output_ << "def " << exp.function_name();
output_ << "(";
for (auto it = exp.parameters().begin(); it != exp.parameters().end();
++it) {
(*it).first->visit(this);
output_ << " ";
(*it).second->visit(this);
if (std::next(it) != exp.parameters().end()) {
output_ << ", ";
}
}
output_ << ") : ";
exp.type().visit(this);
output_ << " {";
exp.function_body().visit(this);
output_ << "return ";
exp.retval().visit(this);
output_ << "; }";
}
void visitProgram(const Program& exp) override {
output_ << "Program(";
for (auto it = exp.function_defs().begin(); it != exp.function_defs().end();
++it) {
(*it)->visit(this);
}
exp.statements().visit(this);
output_ << "output ";
exp.arithmetic_exp().visit(this);
output_ << ");";
}
void visitTypeDef(const TypeDef & typeDef) override {
output_ << "struct " << typeDef.type_name() << " {\n";
for (auto & decl : typeDef.fields()) {
decl.visit(this);
}
output_ << "\n};";
}
private:
std::stringstream output_;
// map of productions
std::unordered_map<AstNode, std::vector<AstNode>> productions(
{{AExpPrime, VariableExpr}});
}; // namespace cs160::frontend
} // namespace cs160::frontend
| [
"ruoqian@umail.ucsb.edu"
] | ruoqian@umail.ucsb.edu |
7744caa70d47b4fd770de6eb3fa11cbb41e8dcc4 | 175cb710901f613caf919bc34fd1d3699aa2458e | /CppPractice/codeforces/cf104/e104b.cpp | 99b18c21dc835d6f7002d512224af6cb20838386 | [] | no_license | harshit977/CP_Solutions | 0df1cd3ddbebdf0fd840c3a35f876c5ce7d3e3a1 | b83e70f10229da6c2005f12b653ed6aa5eb74a07 | refs/heads/main | 2023-08-12T06:48:50.721317 | 2021-10-01T11:43:18 | 2021-10-01T11:43:18 | 412,458,588 | 1 | 0 | null | 2021-10-01T12:29:36 | 2021-10-01T12:29:35 | null | UTF-8 | C++ | false | false | 498 | cpp | #include<bits/stdc++.h>
#define boost ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define ll long long
#define fi for(ll i=0;i<n;i++)
#define pb push_back
using namespace std;
int main()
{
boost;
ll tc;
cin>>tc;
while(tc--)
{
ll n,k;
cin>>n>>k;
ll a=(n-1)/2;
ll b=k%n;
ll c;
if(a!=0)
{
c=(k-1)/a;
}
else
{
c=0;
}
ll ans;
if(b==0 && c==0)
ans=n;
else
ans=c+b;
cout<<ans<<"\n";
}
return 0;
}
| [
"nayanmanojgupta@gmail.com"
] | nayanmanojgupta@gmail.com |
2b71352c022fd9618da8eb9e7b773926e4b1f5fa | addef918477eb71f9be2afe9558e1b98f5aa74c1 | /Codeforecs/1102E.cpp | aab658efd7b8e91196c85ddbba298c7f5269ae6a | [] | no_license | iammarajul/competitive_programming | 3977b9e1c15808d3a7084af7d1dd64c40a5dccb8 | 4d48578e48b3392bedf82b22281bb16c82ed2a1b | refs/heads/master | 2020-06-04T08:26:05.568287 | 2020-03-08T19:38:18 | 2020-03-08T19:38:18 | 191,943,679 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,148 | cpp |
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
int sc1(){int x; scanf("%d",&x); return x;}
long long sc2(){long long x;scanf("%lld",&x);return x;}
#define gcd(a,b) __gcd(a,b)
#define lcm(a,b) (a*b)/gcd(a,b)
#define Int sc1()
#define LL sc2()
#define For(n) for(int i=0;i<n;i++)
#define Forj(n) for(int j=0;j<n;j++)
#define Fork(n) for(int k=0;k<n;k++)
#define For1(n) for(int i=1;i<=n;i++)
#define ll long long
#define vi std::vector<int>
#define vll std::vector<ll>
#define qui qu
#define pb push_back
#define mpsi std::map<string, int>
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int n=Int;
int mx=0,my=0;
while(n--)
{
char ch;
int a,b;
scanf(" %c",&ch);
scanf("%d%d",&a,&b);
if(ch=='+')
{
mx=max(mx,max(a,b));
my=max(my,min(a,b));
}
else
{
if(max(a,b)>=mx && min(a,b)>=my)
{
cout<<"YES"<<endl;
}
else
cout<<"NO"<<endl;
}
}
return 0;
}
| [
"m.marajul@gmail.com"
] | m.marajul@gmail.com |
82097770b6e5db3117d074a69e39c8d87c5c8942 | 0abc971a7bd85bf6efeedd765298f04dc01387a9 | /Search Engine Pt. 2/classes/database.cpp | d85928b72ceeb5c78170bf080dcff2a92aa87dc5 | [] | no_license | Lucaster13/USC_Coursework | 106af19b89748ac49aece6a6af1627e4e1c668f1 | f50414fdbdfda572464eef5de2fd259718e32f11 | refs/heads/master | 2020-04-01T11:53:59.892819 | 2018-10-15T21:41:56 | 2018-10-15T21:41:56 | 153,182,388 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,009 | cpp | #include "database.h"
#include <iostream>
#include <sstream>
#include <queue>
#include <cctype>
#include <algorithm>
using namespace std;
/*
pageRank Comparator:
compares the pagerank values of each webpage
comp(p1,p2) = true if p1.pagerank < p2.pagerank
*/
struct PageRankComp
{
bool operator()(Webpage* p1, Webpage* p2)
{
return p1->getPageRank() > p2->getPageRank();
}
};
/*
Constructor:
allocates memory for each webpage
parses all webpages
adds all incoming links to each webpage
*/
Database::Database(ifstream& index)
{
//create all webpages
while(!index.fail())
{
string linkName;
index >> linkName;
if(!index.fail())
{
Webpage* newPage = new Webpage(linkName);
webpages[linkName] = newPage;
}
}
//parse all webpages
map<string, Webpage*>::iterator it;
for(it = webpages.begin(); it != webpages.end(); ++it)
{
it->second->parse(WordBank);
}
//add the incoming links to webpages and initialize in and out degree
for(it = webpages.begin(); it != webpages.end(); ++it)
{
it->second->addIncomingAndOutgoing(webpages);
it->second->setDegree();
}
}
/*
Destructor:
Deallocates all memory for webpages
*/
Database::~Database()
{
map<string, Webpage*>::iterator it = webpages.begin();
while(it != webpages.end())
{
Webpage* temp = it->second;
++it;
delete temp;
}
}
/*
processQueries:
Takes the queries from query.txt
processes the commands and then
performs the necessary functions
to carry out the query
*/
void Database::processQueries(ifstream& queries, ofstream& ofile,
double& restartProb, int& stepNum)
{
while(!queries.fail())
{
string queryLine;
getline(queries, queryLine);
stringstream ss(queryLine);
vector<string> queryVec;
string query;
ss >> query;
if(ss.fail())break;
if(query == "PRINT" || query == "INCOMING" || query == "OUTGOING")
{
string fileName;
ss >> fileName;
if(ss.fail())
{
queryVec.push_back(query);
}
else
{
queryVec.push_back(query);
queryVec.push_back(fileName);
}
}
else if(query == "AND" || query == "OR")
{
queryVec.push_back(query);
while(!ss.fail())
{
string word;
ss >> word;
if(ss.fail())break;
for(size_t i = 0; i < word.size(); i++)
{
if(!isdigit(word[i]))
{
word[i] = tolower(word[i]);
}
}
queryVec.push_back(word);
}
}
else if(query == "")
{
ofile << "Invalid query\n" << endl;
continue;
}
else
{
for(size_t i = 0; i < query.size(); i++)
{
if(!isdigit(query[i]))
{
query[i] = tolower(query[i]);
}
}
queryVec.push_back(query);
while(!ss.fail())
{
string word;
ss >> word;
if(ss.fail())break;
queryVec.push_back(word);
}
}
if(queryVec.size() == 1)
{
vector<string>::iterator it = queryVec.begin();
for(size_t i = 0; i < it->size(); i++)
{
if(!isdigit(it->at(i)))
{
it->at(i) = tolower(it->at(i));
}
}
queryStrings.insert(*it);
OR(ofile, restartProb, stepNum);
}
else if(queryVec.size() > 1)
{
vector<string>::iterator it = queryVec.begin();
queryVec.erase(it);
for(it = queryVec.begin(); it != queryVec.end(); ++it)
{
queryStrings.insert(*it);
}
if(query == "AND")
{
AND(ofile, restartProb, stepNum);
}
else if(query == "OR")
{
OR(ofile, restartProb, stepNum);
}
else if(query == "PRINT")
{
it = queryVec.begin();
PRINT(*it, ofile);
}
else if(query == "INCOMING")
{
it = queryVec.begin();
INCOMING(*it, ofile);
}
else if(query == "OUTGOING")
{
it = queryVec.begin();
OUTGOING(*it, ofile);
}
else
{
ofile << "Invalid query\n" << endl;
}
}
queryStrings.clear();
}
ofile.close();
}
/*
PRINT:
finds the webpage with given name
calls printPage function on that webpage
*/
void Database::PRINT(const string& pageName, ofstream& ofile)
{
map<string, Webpage*>::iterator it = webpages.find(pageName);
if(it != webpages.end())
{
ofile << pageName << endl;
it->second->printPage(ofile);
return;
}
//if file does not exist
ofile << "Invalid query\n" << endl;
}
/*
INCOMING:
finds webpage w given name
calls printIncoming on webpage
*/
void Database::INCOMING(const string& pageName, ofstream& ofile)
{
map<string, Webpage*>::iterator it = webpages.find(pageName);
if(it != webpages.end())
{
ofile << it->second->numIncoming() << endl;
it->second->printIncoming(ofile);
return;
}
//if file does not exist
ofile << "Invalid query\n" << endl;
}
/*
OUTGOING:
finds webpage w given name
calls printOutgoing on webpage
*/
void Database::OUTGOING(const string& pageName, ofstream& ofile)
{
map<string, Webpage*>::iterator it = webpages.find(pageName);
if(it != webpages.end())
{
ofile << it->second->numOutgoing() << endl;
it->second->printOutgoing(ofile);
return;
}
//if file does not exist
ofile << "Invalid query\n" << endl;
}
/*
AND:
calls searchAnd on every webpage for a given query word
then adds those that contain the words to Intersection set
then prints all webpages to ofile
*/
void Database::AND(ofstream& ofile, double& restartProb, int& stepNum)
{
set<Webpage*> Intersection;
set<string>::iterator queryWord;
for(queryWord = queryStrings.begin(); queryWord != queryStrings.end(); ++queryWord)
{
set<Webpage*> pages = WordBank[*queryWord];
//if no pages contain word
if(!pages.size())
{
Intersection.clear();
break;
}
if(queryWord == queryStrings.begin())
{
Intersection = pages;
}
else
{
Intersection = setIntersection(Intersection, pages);
}
}
//expanding the Candidate Set
set<Webpage*> expandedSet = candidateExpand(Intersection);
//calculate PageRanks and order vector
vector<Webpage*> rankedPages = PageRank(expandedSet, restartProb, stepNum);
//output the newly Ranked pages
ofile << rankedPages.size() << endl;
for(vector<Webpage*>::iterator it = rankedPages.begin(); it != rankedPages.end(); ++it)
{
ofile << (*it)->getName() << endl;
}
ofile << endl;
}
/*
OR:
calls searchOr on every webpage for a given query word
then adds those that contain the words to Union set
then prints all webpages to ofile
*/
void Database::OR(ofstream& ofile, double& restartProb, int& stepNum)
{
set<Webpage*> Union;
set<string>::iterator queryWord;
for(queryWord = queryStrings.begin(); queryWord != queryStrings.end(); ++queryWord)
{
set<Webpage*> pages = WordBank[*queryWord];
Union = setUnion(Union, pages);
}
//expanding the Candidate Set
set<Webpage*> expandedSet = candidateExpand(Union);
//calculate PageRanks and order vector
vector<Webpage*> rankedPages = PageRank(expandedSet, restartProb, stepNum);
//output the newly Ranked pages
ofile << rankedPages.size() << endl;
for(vector<Webpage*>::iterator it = rankedPages.begin(); it != rankedPages.end(); ++it)
{
ofile << (*it)->getName() << endl;
}
ofile << endl;
}
/*
candidateExpand:
expands candidate set by iterating through
all incoming and outgoing links of currentPages
*/
set<Webpage*> Database::candidateExpand(set<Webpage*>& currentPages)
{
set<Webpage*> expandedPages;
set<Webpage*>::iterator it;
for(it = currentPages.begin(); it != currentPages.end(); it++)
{
expandedPages.insert(*it);
set<Webpage*> outgoing = (*it)->getOutgoingLinks();
set<Webpage*> incoming = (*it)->getIncomingLinks();
set<Webpage*>::iterator itOut;
for(itOut = outgoing.begin(); itOut != outgoing.end(); ++itOut)
{
expandedPages.insert(*itOut);
}
set<Webpage*>::iterator itIn;
for(itIn = incoming.begin(); itIn != incoming.end(); ++itIn)
{
expandedPages.insert(*itIn);
}
}
return expandedPages;
}
/*
PageRank:
calculates pagerank for a set of pages
*/
vector<Webpage*> Database::PageRank(set<Webpage*>& candidates, double& restartProb, int& stepNum)
{
double n = (double)candidates.size(); //num candidates = n
//initialize pagerank values
for(set<Webpage*>::iterator it = candidates.begin(); it != candidates.end(); ++it)
{
(*it)->setPageRank(1/n);//set val to 1/n
}
// the first and last terms of the formula that are constant
const double term1 = 1 - restartProb;
const double term3 = restartProb * (1/n);
for(int i = 0; i < stepNum; i++)
{
//keeps track of the previous iteration's incoming link
map<Webpage*, queue<double> > previousIncomingRanks;
for(set<Webpage*>::iterator it = candidates.begin(); it != candidates.end(); ++it)
{
set<Webpage*> incoming = (*it)->getIncomingLinks();
for(set<Webpage*>::iterator it2 = incoming.begin(); it2 != incoming.end(); ++it2)
{
previousIncomingRanks[*it].push((*it2)->getPageRank());
}
}
//calculate new ranks for pages
for(set<Webpage*>::iterator it = candidates.begin(); it != candidates.end(); ++it)
{
double summation = (*it)->getPageRank() * 1/(*it)->getOutDegree(); //accounts for the self loop
set<Webpage*> incoming = (*it)->getIncomingLinks();
queue<double> incomingRanks = previousIncomingRanks[*it];
//iterate through all incoming links adding the (pagerank*1/outdegree) of each incoming link
for(set<Webpage*>::iterator itSet = incoming.begin(); itSet != incoming.end(); ++itSet)
{
summation += incomingRanks.front() * 1/(*itSet)->getOutDegree();
incomingRanks.pop();
}
//PAGERANK FORMULA
double newPageRank = term1 * summation + term3;
(*it)->setPageRank(newPageRank);
}
}
//copy pages to vector
vector<Webpage*> rankedPages;
for(set<Webpage*>::iterator it = candidates.begin(); it != candidates.end(); ++it)
{
rankedPages.push_back(*it);
}
//sort ranked pages
PageRankComp comp;
sort(rankedPages.begin(), rankedPages.end(), comp);
return rankedPages;
}
/*
resetPageRank:
reverts all of the candidates' pageRanks back to 0
when the query is over
*/
void resetPageRank(vector<Webpage*>& rankedPages)
{
for(vector<Webpage*>::iterator it = rankedPages.begin(); it != rankedPages.end(); ++it)
{
(*it)->setPageRank(0);
}
}
| [
"terr@usc.edu"
] | terr@usc.edu |
04d3b0d1eb96026d4fe7a1cd0ede5287c66b20f3 | d98764a2c2dfd32bfb86f17aeb43546ea89345bc | /dalvik/vm/mterp/out/InterpC-armv5te.cpp | 93ade2b2088486ad1f5ea9f467819f1590b123bf | [
"Apache-2.0"
] | permissive | mdsalman729/droidtrack | 4c17e9ae417425c25d0bf08b8c3fbe8cc707b536 | 2e535f81468da8d96c22303fc4f2592eb712b71a | refs/heads/master | 2021-01-10T07:31:40.041008 | 2015-12-23T19:45:52 | 2015-12-23T19:45:52 | 48,508,301 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 77,294 | cpp | /*
* This file was generated automatically by gen-mterp.py for 'armv5te'.
*
* --> DO NOT EDIT <--
*/
/* File: c/header.cpp */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* common includes */
#include "Dalvik.h"
#include "interp/InterpDefs.h"
#include "mterp/Mterp.h"
#include <math.h> // needed for fmod, fmodf
#include "mterp/common/FindInterface.h"
/*
* Configuration defines. These affect the C implementations, i.e. the
* portable interpreter(s) and C stubs.
*
* Some defines are controlled by the Makefile, e.g.:
* WITH_INSTR_CHECKS
* WITH_TRACKREF_CHECKS
* EASY_GDB
* NDEBUG
*/
#ifdef WITH_INSTR_CHECKS /* instruction-level paranoia (slow!) */
# define CHECK_BRANCH_OFFSETS
# define CHECK_REGISTER_INDICES
#endif
/*
* Some architectures require 64-bit alignment for access to 64-bit data
* types. We can't just use pointers to copy 64-bit values out of our
* interpreted register set, because gcc may assume the pointer target is
* aligned and generate invalid code.
*
* There are two common approaches:
* (1) Use a union that defines a 32-bit pair and a 64-bit value.
* (2) Call memcpy().
*
* Depending upon what compiler you're using and what options are specified,
* one may be faster than the other. For example, the compiler might
* convert a memcpy() of 8 bytes into a series of instructions and omit
* the call. The union version could cause some strange side-effects,
* e.g. for a while ARM gcc thought it needed separate storage for each
* inlined instance, and generated instructions to zero out ~700 bytes of
* stack space at the top of the interpreter.
*
* The default is to use memcpy(). The current gcc for ARM seems to do
* better with the union.
*/
#if defined(__ARM_EABI__)
# define NO_UNALIGN_64__UNION
#endif
//#define LOG_INSTR /* verbose debugging */
/* set and adjust ANDROID_LOG_TAGS='*:i jdwp:i dalvikvm:i dalvikvmi:i' */
/*
* Export another copy of the PC on every instruction; this is largely
* redundant with EXPORT_PC and the debugger code. This value can be
* compared against what we have stored on the stack with EXPORT_PC to
* help ensure that we aren't missing any export calls.
*/
#if WITH_EXTRA_GC_CHECKS > 1
# define EXPORT_EXTRA_PC() (self->currentPc2 = pc)
#else
# define EXPORT_EXTRA_PC()
#endif
/*
* Adjust the program counter. "_offset" is a signed int, in 16-bit units.
*
* Assumes the existence of "const u2* pc" and "const u2* curMethod->insns".
*
* We don't advance the program counter until we finish an instruction or
* branch, because we do want to have to unroll the PC if there's an
* exception.
*/
#ifdef CHECK_BRANCH_OFFSETS
# define ADJUST_PC(_offset) do { \
int myoff = _offset; /* deref only once */ \
if (pc + myoff < curMethod->insns || \
pc + myoff >= curMethod->insns + dvmGetMethodInsnsSize(curMethod)) \
{ \
char* desc; \
desc = dexProtoCopyMethodDescriptor(&curMethod->prototype); \
LOGE("Invalid branch %d at 0x%04x in %s.%s %s", \
myoff, (int) (pc - curMethod->insns), \
curMethod->clazz->descriptor, curMethod->name, desc); \
free(desc); \
dvmAbort(); \
} \
pc += myoff; \
EXPORT_EXTRA_PC(); \
} while (false)
#else
# define ADJUST_PC(_offset) do { \
pc += _offset; \
EXPORT_EXTRA_PC(); \
} while (false)
#endif
/*
* If enabled, log instructions as we execute them.
*/
#ifdef LOG_INSTR
# define ILOGD(...) ILOG(LOG_DEBUG, __VA_ARGS__)
# define ILOGV(...) ILOG(LOG_VERBOSE, __VA_ARGS__)
# define ILOG(_level, ...) do { \
char debugStrBuf[128]; \
snprintf(debugStrBuf, sizeof(debugStrBuf), __VA_ARGS__); \
if (curMethod != NULL) \
LOG(_level, LOG_TAG"i", "%-2d|%04x%s", \
self->threadId, (int)(pc - curMethod->insns), debugStrBuf); \
else \
LOG(_level, LOG_TAG"i", "%-2d|####%s", \
self->threadId, debugStrBuf); \
} while(false)
void dvmDumpRegs(const Method* method, const u4* framePtr, bool inOnly);
# define DUMP_REGS(_meth, _frame, _inOnly) dvmDumpRegs(_meth, _frame, _inOnly)
static const char kSpacing[] = " ";
#else
# define ILOGD(...) ((void)0)
# define ILOGV(...) ((void)0)
# define DUMP_REGS(_meth, _frame, _inOnly) ((void)0)
#endif
/* get a long from an array of u4 */
static inline s8 getLongFromArray(const u4* ptr, int idx)
{
#if defined(NO_UNALIGN_64__UNION)
union { s8 ll; u4 parts[2]; } conv;
ptr += idx;
conv.parts[0] = ptr[0];
conv.parts[1] = ptr[1];
return conv.ll;
#else
s8 val;
memcpy(&val, &ptr[idx], 8);
return val;
#endif
}
/* store a long into an array of u4 */
static inline void putLongToArray(u4* ptr, int idx, s8 val)
{
#if defined(NO_UNALIGN_64__UNION)
union { s8 ll; u4 parts[2]; } conv;
ptr += idx;
conv.ll = val;
ptr[0] = conv.parts[0];
ptr[1] = conv.parts[1];
#else
memcpy(&ptr[idx], &val, 8);
#endif
}
/* get a double from an array of u4 */
static inline double getDoubleFromArray(const u4* ptr, int idx)
{
#if defined(NO_UNALIGN_64__UNION)
union { double d; u4 parts[2]; } conv;
ptr += idx;
conv.parts[0] = ptr[0];
conv.parts[1] = ptr[1];
return conv.d;
#else
double dval;
memcpy(&dval, &ptr[idx], 8);
return dval;
#endif
}
/* store a double into an array of u4 */
static inline void putDoubleToArray(u4* ptr, int idx, double dval)
{
#if defined(NO_UNALIGN_64__UNION)
union { double d; u4 parts[2]; } conv;
ptr += idx;
conv.d = dval;
ptr[0] = conv.parts[0];
ptr[1] = conv.parts[1];
#else
memcpy(&ptr[idx], &dval, 8);
#endif
}
/*
* If enabled, validate the register number on every access. Otherwise,
* just do an array access.
*
* Assumes the existence of "u4* fp".
*
* "_idx" may be referenced more than once.
*/
#ifdef CHECK_REGISTER_INDICES
# define GET_REGISTER(_idx) \
( (_idx) < curMethod->registersSize ? \
(fp[(_idx)]) : (assert(!"bad reg"),1969) )
# define SET_REGISTER(_idx, _val) \
( (_idx) < curMethod->registersSize ? \
(fp[(_idx)] = (u4)(_val)) : (assert(!"bad reg"),1969) )
# define GET_REGISTER_AS_OBJECT(_idx) ((Object *)GET_REGISTER(_idx))
# define SET_REGISTER_AS_OBJECT(_idx, _val) SET_REGISTER(_idx, (s4)_val)
# define GET_REGISTER_INT(_idx) ((s4) GET_REGISTER(_idx))
# define SET_REGISTER_INT(_idx, _val) SET_REGISTER(_idx, (s4)_val)
# define GET_REGISTER_WIDE(_idx) \
( (_idx) < curMethod->registersSize-1 ? \
getLongFromArray(fp, (_idx)) : (assert(!"bad reg"),1969) )
# define SET_REGISTER_WIDE(_idx, _val) \
( (_idx) < curMethod->registersSize-1 ? \
(void)putLongToArray(fp, (_idx), (_val)) : assert(!"bad reg") )
# define GET_REGISTER_FLOAT(_idx) \
( (_idx) < curMethod->registersSize ? \
(*((float*) &fp[(_idx)])) : (assert(!"bad reg"),1969.0f) )
# define SET_REGISTER_FLOAT(_idx, _val) \
( (_idx) < curMethod->registersSize ? \
(*((float*) &fp[(_idx)]) = (_val)) : (assert(!"bad reg"),1969.0f) )
# define GET_REGISTER_DOUBLE(_idx) \
( (_idx) < curMethod->registersSize-1 ? \
getDoubleFromArray(fp, (_idx)) : (assert(!"bad reg"),1969.0) )
# define SET_REGISTER_DOUBLE(_idx, _val) \
( (_idx) < curMethod->registersSize-1 ? \
(void)putDoubleToArray(fp, (_idx), (_val)) : assert(!"bad reg") )
#else
# define GET_REGISTER(_idx) (fp[(_idx)])
# define SET_REGISTER(_idx, _val) (fp[(_idx)] = (_val))
# define GET_REGISTER_AS_OBJECT(_idx) ((Object*) fp[(_idx)])
# define SET_REGISTER_AS_OBJECT(_idx, _val) (fp[(_idx)] = (u4)(_val))
# define GET_REGISTER_INT(_idx) ((s4)GET_REGISTER(_idx))
# define SET_REGISTER_INT(_idx, _val) SET_REGISTER(_idx, (s4)_val)
# define GET_REGISTER_WIDE(_idx) getLongFromArray(fp, (_idx))
# define SET_REGISTER_WIDE(_idx, _val) putLongToArray(fp, (_idx), (_val))
# define GET_REGISTER_FLOAT(_idx) (*((float*) &fp[(_idx)]))
# define SET_REGISTER_FLOAT(_idx, _val) (*((float*) &fp[(_idx)]) = (_val))
# define GET_REGISTER_DOUBLE(_idx) getDoubleFromArray(fp, (_idx))
# define SET_REGISTER_DOUBLE(_idx, _val) putDoubleToArray(fp, (_idx), (_val))
#endif
/*
* Get 16 bits from the specified offset of the program counter. We always
* want to load 16 bits at a time from the instruction stream -- it's more
* efficient than 8 and won't have the alignment problems that 32 might.
*
* Assumes existence of "const u2* pc".
*/
#define FETCH(_offset) (pc[(_offset)])
/*
* Extract instruction byte from 16-bit fetch (_inst is a u2).
*/
#define INST_INST(_inst) ((_inst) & 0xff)
/*
* Replace the opcode (used when handling breakpoints). _opcode is a u1.
*/
#define INST_REPLACE_OP(_inst, _opcode) (((_inst) & 0xff00) | _opcode)
/*
* Extract the "vA, vB" 4-bit registers from the instruction word (_inst is u2).
*/
#define INST_A(_inst) (((_inst) >> 8) & 0x0f)
#define INST_B(_inst) ((_inst) >> 12)
/*
* Get the 8-bit "vAA" 8-bit register index from the instruction word.
* (_inst is u2)
*/
#define INST_AA(_inst) ((_inst) >> 8)
/*
* The current PC must be available to Throwable constructors, e.g.
* those created by the various exception throw routines, so that the
* exception stack trace can be generated correctly. If we don't do this,
* the offset within the current method won't be shown correctly. See the
* notes in Exception.c.
*
* This is also used to determine the address for precise GC.
*
* Assumes existence of "u4* fp" and "const u2* pc".
*/
#define EXPORT_PC() (SAVEAREA_FROM_FP(fp)->xtra.currentPc = pc)
/*
* Check to see if "obj" is NULL. If so, throw an exception. Assumes the
* pc has already been exported to the stack.
*
* Perform additional checks on debug builds.
*
* Use this to check for NULL when the instruction handler calls into
* something that could throw an exception (so we have already called
* EXPORT_PC at the top).
*/
static inline bool checkForNull(Object* obj)
{
if (obj == NULL) {
dvmThrowNullPointerException(NULL);
return false;
}
#ifdef WITH_EXTRA_OBJECT_VALIDATION
if (!dvmIsHeapAddressObject(obj)) {
LOGE("Invalid object %p", obj);
dvmAbort();
}
#endif
#ifndef NDEBUG
if (obj->clazz == NULL || ((u4) obj->clazz) <= 65536) {
/* probable heap corruption */
LOGE("Invalid object class %p (in %p)", obj->clazz, obj);
dvmAbort();
}
#endif
return true;
}
/*
* Check to see if "obj" is NULL. If so, export the PC into the stack
* frame and throw an exception.
*
* Perform additional checks on debug builds.
*
* Use this to check for NULL when the instruction handler doesn't do
* anything else that can throw an exception.
*/
static inline bool checkForNullExportPC(Object* obj, u4* fp, const u2* pc)
{
if (obj == NULL) {
EXPORT_PC();
dvmThrowNullPointerException(NULL);
return false;
}
#ifdef WITH_EXTRA_OBJECT_VALIDATION
if (!dvmIsHeapAddress(obj)) {
LOGE("Invalid object %p", obj);
dvmAbort();
}
#endif
#ifndef NDEBUG
if (obj->clazz == NULL || ((u4) obj->clazz) <= 65536) {
/* probable heap corruption */
LOGE("Invalid object class %p (in %p)", obj->clazz, obj);
dvmAbort();
}
#endif
return true;
}
/* File: cstubs/stubdefs.cpp */
/*
* In the C mterp stubs, "goto" is a function call followed immediately
* by a return.
*/
#define GOTO_TARGET_DECL(_target, ...) \
extern "C" void dvmMterp_##_target(Thread* self, ## __VA_ARGS__);
/* (void)xxx to quiet unused variable compiler warnings. */
#define GOTO_TARGET(_target, ...) \
void dvmMterp_##_target(Thread* self, ## __VA_ARGS__) { \
u2 ref, vsrc1, vsrc2, vdst; \
u2 inst = FETCH(0); \
const Method* methodToCall; \
StackSaveArea* debugSaveArea; \
(void)ref; (void)vsrc1; (void)vsrc2; (void)vdst; (void)inst; \
(void)methodToCall; (void)debugSaveArea;
#define GOTO_TARGET_END }
/*
* Redefine what used to be local variable accesses into Thread struct
* references. (These are undefined down in "footer.cpp".)
*/
#define retval self->interpSave.retval
#define pc self->interpSave.pc
#define fp self->interpSave.curFrame
#define curMethod self->interpSave.method
#define methodClassDex self->interpSave.methodClassDex
#define debugTrackedRefStart self->interpSave.debugTrackedRefStart
/* ugh */
#define STUB_HACK(x) x
#if defined(WITH_JIT)
#define JIT_STUB_HACK(x) x
#else
#define JIT_STUB_HACK(x)
#endif
/*
* InterpSave's pc and fp must be valid when breaking out to a
* "Reportxxx" routine. Because the portable interpreter uses local
* variables for these, we must flush prior. Stubs, however, use
* the interpSave vars directly, so this is a nop for stubs.
*/
#define PC_FP_TO_SELF()
#define PC_TO_SELF()
/*
* Opcode handler framing macros. Here, each opcode is a separate function
* that takes a "self" argument and returns void. We can't declare
* these "static" because they may be called from an assembly stub.
* (void)xxx to quiet unused variable compiler warnings.
*/
#define HANDLE_OPCODE(_op) \
extern "C" void dvmMterp_##_op(Thread* self); \
void dvmMterp_##_op(Thread* self) { \
u4 ref; \
u2 vsrc1, vsrc2, vdst; \
u2 inst = FETCH(0); \
(void)ref; (void)vsrc1; (void)vsrc2; (void)vdst; (void)inst;
#define OP_END }
/*
* Like the "portable" FINISH, but don't reload "inst", and return to caller
* when done. Further, debugger/profiler checks are handled
* before handler execution in mterp, so we don't do them here either.
*/
#if defined(WITH_JIT)
#define FINISH(_offset) { \
ADJUST_PC(_offset); \
if (self->interpBreak.ctl.subMode & kSubModeJitTraceBuild) { \
dvmCheckJit(pc, self); \
} \
return; \
}
#else
#define FINISH(_offset) { \
ADJUST_PC(_offset); \
return; \
}
#endif
/*
* The "goto label" statements turn into function calls followed by
* return statements. Some of the functions take arguments, which in the
* portable interpreter are handled by assigning values to globals.
*/
#define GOTO_exceptionThrown() \
do { \
dvmMterp_exceptionThrown(self); \
return; \
} while(false)
#define GOTO_returnFromMethod() \
do { \
dvmMterp_returnFromMethod(self); \
return; \
} while(false)
#define GOTO_invoke(_target, _methodCallRange, _jumboFormat) \
do { \
dvmMterp_##_target(self, _methodCallRange, _jumboFormat); \
return; \
} while(false)
#define GOTO_invokeMethod(_methodCallRange, _methodToCall, _vsrc1, _vdst) \
do { \
dvmMterp_invokeMethod(self, _methodCallRange, _methodToCall, \
_vsrc1, _vdst); \
return; \
} while(false)
/*
* As a special case, "goto bail" turns into a longjmp.
*/
#define GOTO_bail() \
dvmMterpStdBail(self, false);
/*
* Periodically check for thread suspension.
*
* While we're at it, see if a debugger has attached or the profiler has
* started.
*/
#define PERIODIC_CHECKS(_pcadj) { \
if (dvmCheckSuspendQuick(self)) { \
EXPORT_PC(); /* need for precise GC */ \
dvmCheckSuspendPending(self); \
} \
}
/* File: c/opcommon.cpp */
/* forward declarations of goto targets */
GOTO_TARGET_DECL(filledNewArray, bool methodCallRange, bool jumboFormat);
GOTO_TARGET_DECL(invokeVirtual, bool methodCallRange, bool jumboFormat);
GOTO_TARGET_DECL(invokeSuper, bool methodCallRange, bool jumboFormat);
GOTO_TARGET_DECL(invokeInterface, bool methodCallRange, bool jumboFormat);
GOTO_TARGET_DECL(invokeDirect, bool methodCallRange, bool jumboFormat);
GOTO_TARGET_DECL(invokeStatic, bool methodCallRange, bool jumboFormat);
GOTO_TARGET_DECL(invokeVirtualQuick, bool methodCallRange, bool jumboFormat);
GOTO_TARGET_DECL(invokeSuperQuick, bool methodCallRange, bool jumboFormat);
GOTO_TARGET_DECL(invokeMethod, bool methodCallRange, const Method* methodToCall,
u2 count, u2 regs);
GOTO_TARGET_DECL(returnFromMethod);
GOTO_TARGET_DECL(exceptionThrown);
/*
* ===========================================================================
*
* What follows are opcode definitions shared between multiple opcodes with
* minor substitutions handled by the C pre-processor. These should probably
* use the mterp substitution mechanism instead, with the code here moved
* into common fragment files (like the asm "binop.S"), although it's hard
* to give up the C preprocessor in favor of the much simpler text subst.
*
* ===========================================================================
*/
#define HANDLE_NUMCONV(_opcode, _opname, _fromtype, _totype) \
HANDLE_OPCODE(_opcode /*vA, vB*/) \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); \
ILOGV("|%s v%d,v%d", (_opname), vdst, vsrc1); \
SET_REGISTER##_totype(vdst, \
GET_REGISTER##_fromtype(vsrc1)); \
FINISH(1);
#define HANDLE_FLOAT_TO_INT(_opcode, _opname, _fromvtype, _fromrtype, \
_tovtype, _tortype) \
HANDLE_OPCODE(_opcode /*vA, vB*/) \
{ \
/* spec defines specific handling for +/- inf and NaN values */ \
_fromvtype val; \
_tovtype intMin, intMax, result; \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); \
ILOGV("|%s v%d,v%d", (_opname), vdst, vsrc1); \
val = GET_REGISTER##_fromrtype(vsrc1); \
intMin = (_tovtype) 1 << (sizeof(_tovtype) * 8 -1); \
intMax = ~intMin; \
result = (_tovtype) val; \
if (val >= intMax) /* +inf */ \
result = intMax; \
else if (val <= intMin) /* -inf */ \
result = intMin; \
else if (val != val) /* NaN */ \
result = 0; \
else \
result = (_tovtype) val; \
SET_REGISTER##_tortype(vdst, result); \
} \
FINISH(1);
#define HANDLE_INT_TO_SMALL(_opcode, _opname, _type) \
HANDLE_OPCODE(_opcode /*vA, vB*/) \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); \
ILOGV("|int-to-%s v%d,v%d", (_opname), vdst, vsrc1); \
SET_REGISTER(vdst, (_type) GET_REGISTER(vsrc1)); \
FINISH(1);
/* NOTE: the comparison result is always a signed 4-byte integer */
#define HANDLE_OP_CMPX(_opcode, _opname, _varType, _type, _nanVal) \
HANDLE_OPCODE(_opcode /*vAA, vBB, vCC*/) \
{ \
int result; \
u2 regs; \
_varType val1, val2; \
vdst = INST_AA(inst); \
regs = FETCH(1); \
vsrc1 = regs & 0xff; \
vsrc2 = regs >> 8; \
ILOGV("|cmp%s v%d,v%d,v%d", (_opname), vdst, vsrc1, vsrc2); \
val1 = GET_REGISTER##_type(vsrc1); \
val2 = GET_REGISTER##_type(vsrc2); \
if (val1 == val2) \
result = 0; \
else if (val1 < val2) \
result = -1; \
else if (val1 > val2) \
result = 1; \
else \
result = (_nanVal); \
ILOGV("+ result=%d", result); \
SET_REGISTER(vdst, result); \
} \
FINISH(2);
#define HANDLE_OP_IF_XX(_opcode, _opname, _cmp) \
HANDLE_OPCODE(_opcode /*vA, vB, +CCCC*/) \
vsrc1 = INST_A(inst); \
vsrc2 = INST_B(inst); \
if ((s4) GET_REGISTER(vsrc1) _cmp (s4) GET_REGISTER(vsrc2)) { \
int branchOffset = (s2)FETCH(1); /* sign-extended */ \
ILOGV("|if-%s v%d,v%d,+0x%04x", (_opname), vsrc1, vsrc2, \
branchOffset); \
ILOGV("> branch taken"); \
if (branchOffset < 0) \
PERIODIC_CHECKS(branchOffset); \
FINISH(branchOffset); \
} else { \
ILOGV("|if-%s v%d,v%d,-", (_opname), vsrc1, vsrc2); \
FINISH(2); \
}
#define HANDLE_OP_IF_XXZ(_opcode, _opname, _cmp) \
HANDLE_OPCODE(_opcode /*vAA, +BBBB*/) \
vsrc1 = INST_AA(inst); \
if ((s4) GET_REGISTER(vsrc1) _cmp 0) { \
int branchOffset = (s2)FETCH(1); /* sign-extended */ \
ILOGV("|if-%s v%d,+0x%04x", (_opname), vsrc1, branchOffset); \
ILOGV("> branch taken"); \
if (branchOffset < 0) \
PERIODIC_CHECKS(branchOffset); \
FINISH(branchOffset); \
} else { \
ILOGV("|if-%s v%d,-", (_opname), vsrc1); \
FINISH(2); \
}
#define HANDLE_UNOP(_opcode, _opname, _pfx, _sfx, _type) \
HANDLE_OPCODE(_opcode /*vA, vB*/) \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); \
ILOGV("|%s v%d,v%d", (_opname), vdst, vsrc1); \
SET_REGISTER##_type(vdst, _pfx GET_REGISTER##_type(vsrc1) _sfx); \
FINISH(1);
#define HANDLE_OP_X_INT(_opcode, _opname, _op, _chkdiv) \
HANDLE_OPCODE(_opcode /*vAA, vBB, vCC*/) \
{ \
u2 srcRegs; \
vdst = INST_AA(inst); \
srcRegs = FETCH(1); \
vsrc1 = srcRegs & 0xff; \
vsrc2 = srcRegs >> 8; \
ILOGV("|%s-int v%d,v%d", (_opname), vdst, vsrc1); \
if (_chkdiv != 0) { \
s4 firstVal, secondVal, result; \
firstVal = GET_REGISTER(vsrc1); \
secondVal = GET_REGISTER(vsrc2); \
if (secondVal == 0) { \
EXPORT_PC(); \
dvmThrowArithmeticException("divide by zero"); \
GOTO_exceptionThrown(); \
} \
if ((u4)firstVal == 0x80000000 && secondVal == -1) { \
if (_chkdiv == 1) \
result = firstVal; /* division */ \
else \
result = 0; /* remainder */ \
} else { \
result = firstVal _op secondVal; \
} \
SET_REGISTER(vdst, result); \
} else { \
/* non-div/rem case */ \
SET_REGISTER(vdst, \
(s4) GET_REGISTER(vsrc1) _op (s4) GET_REGISTER(vsrc2)); \
} \
} \
FINISH(2);
#define HANDLE_OP_SHX_INT(_opcode, _opname, _cast, _op) \
HANDLE_OPCODE(_opcode /*vAA, vBB, vCC*/) \
{ \
u2 srcRegs; \
vdst = INST_AA(inst); \
srcRegs = FETCH(1); \
vsrc1 = srcRegs & 0xff; \
vsrc2 = srcRegs >> 8; \
ILOGV("|%s-int v%d,v%d", (_opname), vdst, vsrc1); \
SET_REGISTER(vdst, \
_cast GET_REGISTER(vsrc1) _op (GET_REGISTER(vsrc2) & 0x1f)); \
} \
FINISH(2);
#define HANDLE_OP_X_INT_LIT16(_opcode, _opname, _op, _chkdiv) \
HANDLE_OPCODE(_opcode /*vA, vB, #+CCCC*/) \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); \
vsrc2 = FETCH(1); \
ILOGV("|%s-int/lit16 v%d,v%d,#+0x%04x", \
(_opname), vdst, vsrc1, vsrc2); \
if (_chkdiv != 0) { \
s4 firstVal, result; \
firstVal = GET_REGISTER(vsrc1); \
if ((s2) vsrc2 == 0) { \
EXPORT_PC(); \
dvmThrowArithmeticException("divide by zero"); \
GOTO_exceptionThrown(); \
} \
if ((u4)firstVal == 0x80000000 && ((s2) vsrc2) == -1) { \
/* won't generate /lit16 instr for this; check anyway */ \
if (_chkdiv == 1) \
result = firstVal; /* division */ \
else \
result = 0; /* remainder */ \
} else { \
result = firstVal _op (s2) vsrc2; \
} \
SET_REGISTER(vdst, result); \
} else { \
/* non-div/rem case */ \
SET_REGISTER(vdst, GET_REGISTER(vsrc1) _op (s2) vsrc2); \
} \
FINISH(2);
#define HANDLE_OP_X_INT_LIT8(_opcode, _opname, _op, _chkdiv) \
HANDLE_OPCODE(_opcode /*vAA, vBB, #+CC*/) \
{ \
u2 litInfo; \
vdst = INST_AA(inst); \
litInfo = FETCH(1); \
vsrc1 = litInfo & 0xff; \
vsrc2 = litInfo >> 8; /* constant */ \
ILOGV("|%s-int/lit8 v%d,v%d,#+0x%02x", \
(_opname), vdst, vsrc1, vsrc2); \
if (_chkdiv != 0) { \
s4 firstVal, result; \
firstVal = GET_REGISTER(vsrc1); \
if ((s1) vsrc2 == 0) { \
EXPORT_PC(); \
dvmThrowArithmeticException("divide by zero"); \
GOTO_exceptionThrown(); \
} \
if ((u4)firstVal == 0x80000000 && ((s1) vsrc2) == -1) { \
if (_chkdiv == 1) \
result = firstVal; /* division */ \
else \
result = 0; /* remainder */ \
} else { \
result = firstVal _op ((s1) vsrc2); \
} \
SET_REGISTER(vdst, result); \
} else { \
SET_REGISTER(vdst, \
(s4) GET_REGISTER(vsrc1) _op (s1) vsrc2); \
} \
} \
FINISH(2);
#define HANDLE_OP_SHX_INT_LIT8(_opcode, _opname, _cast, _op) \
HANDLE_OPCODE(_opcode /*vAA, vBB, #+CC*/) \
{ \
u2 litInfo; \
vdst = INST_AA(inst); \
litInfo = FETCH(1); \
vsrc1 = litInfo & 0xff; \
vsrc2 = litInfo >> 8; /* constant */ \
ILOGV("|%s-int/lit8 v%d,v%d,#+0x%02x", \
(_opname), vdst, vsrc1, vsrc2); \
SET_REGISTER(vdst, \
_cast GET_REGISTER(vsrc1) _op (vsrc2 & 0x1f)); \
} \
FINISH(2);
#define HANDLE_OP_X_INT_2ADDR(_opcode, _opname, _op, _chkdiv) \
HANDLE_OPCODE(_opcode /*vA, vB*/) \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); \
ILOGV("|%s-int-2addr v%d,v%d", (_opname), vdst, vsrc1); \
if (_chkdiv != 0) { \
s4 firstVal, secondVal, result; \
firstVal = GET_REGISTER(vdst); \
secondVal = GET_REGISTER(vsrc1); \
if (secondVal == 0) { \
EXPORT_PC(); \
dvmThrowArithmeticException("divide by zero"); \
GOTO_exceptionThrown(); \
} \
if ((u4)firstVal == 0x80000000 && secondVal == -1) { \
if (_chkdiv == 1) \
result = firstVal; /* division */ \
else \
result = 0; /* remainder */ \
} else { \
result = firstVal _op secondVal; \
} \
SET_REGISTER(vdst, result); \
} else { \
SET_REGISTER(vdst, \
(s4) GET_REGISTER(vdst) _op (s4) GET_REGISTER(vsrc1)); \
} \
FINISH(1);
#define HANDLE_OP_SHX_INT_2ADDR(_opcode, _opname, _cast, _op) \
HANDLE_OPCODE(_opcode /*vA, vB*/) \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); \
ILOGV("|%s-int-2addr v%d,v%d", (_opname), vdst, vsrc1); \
SET_REGISTER(vdst, \
_cast GET_REGISTER(vdst) _op (GET_REGISTER(vsrc1) & 0x1f)); \
FINISH(1);
#define HANDLE_OP_X_LONG(_opcode, _opname, _op, _chkdiv) \
HANDLE_OPCODE(_opcode /*vAA, vBB, vCC*/) \
{ \
u2 srcRegs; \
vdst = INST_AA(inst); \
srcRegs = FETCH(1); \
vsrc1 = srcRegs & 0xff; \
vsrc2 = srcRegs >> 8; \
ILOGV("|%s-long v%d,v%d,v%d", (_opname), vdst, vsrc1, vsrc2); \
if (_chkdiv != 0) { \
s8 firstVal, secondVal, result; \
firstVal = GET_REGISTER_WIDE(vsrc1); \
secondVal = GET_REGISTER_WIDE(vsrc2); \
if (secondVal == 0LL) { \
EXPORT_PC(); \
dvmThrowArithmeticException("divide by zero"); \
GOTO_exceptionThrown(); \
} \
if ((u8)firstVal == 0x8000000000000000ULL && \
secondVal == -1LL) \
{ \
if (_chkdiv == 1) \
result = firstVal; /* division */ \
else \
result = 0; /* remainder */ \
} else { \
result = firstVal _op secondVal; \
} \
SET_REGISTER_WIDE(vdst, result); \
} else { \
SET_REGISTER_WIDE(vdst, \
(s8) GET_REGISTER_WIDE(vsrc1) _op (s8) GET_REGISTER_WIDE(vsrc2)); \
} \
} \
FINISH(2);
#define HANDLE_OP_SHX_LONG(_opcode, _opname, _cast, _op) \
HANDLE_OPCODE(_opcode /*vAA, vBB, vCC*/) \
{ \
u2 srcRegs; \
vdst = INST_AA(inst); \
srcRegs = FETCH(1); \
vsrc1 = srcRegs & 0xff; \
vsrc2 = srcRegs >> 8; \
ILOGV("|%s-long v%d,v%d,v%d", (_opname), vdst, vsrc1, vsrc2); \
SET_REGISTER_WIDE(vdst, \
_cast GET_REGISTER_WIDE(vsrc1) _op (GET_REGISTER(vsrc2) & 0x3f)); \
} \
FINISH(2);
#define HANDLE_OP_X_LONG_2ADDR(_opcode, _opname, _op, _chkdiv) \
HANDLE_OPCODE(_opcode /*vA, vB*/) \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); \
ILOGV("|%s-long-2addr v%d,v%d", (_opname), vdst, vsrc1); \
if (_chkdiv != 0) { \
s8 firstVal, secondVal, result; \
firstVal = GET_REGISTER_WIDE(vdst); \
secondVal = GET_REGISTER_WIDE(vsrc1); \
if (secondVal == 0LL) { \
EXPORT_PC(); \
dvmThrowArithmeticException("divide by zero"); \
GOTO_exceptionThrown(); \
} \
if ((u8)firstVal == 0x8000000000000000ULL && \
secondVal == -1LL) \
{ \
if (_chkdiv == 1) \
result = firstVal; /* division */ \
else \
result = 0; /* remainder */ \
} else { \
result = firstVal _op secondVal; \
} \
SET_REGISTER_WIDE(vdst, result); \
} else { \
SET_REGISTER_WIDE(vdst, \
(s8) GET_REGISTER_WIDE(vdst) _op (s8)GET_REGISTER_WIDE(vsrc1));\
} \
FINISH(1);
#define HANDLE_OP_SHX_LONG_2ADDR(_opcode, _opname, _cast, _op) \
HANDLE_OPCODE(_opcode /*vA, vB*/) \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); \
ILOGV("|%s-long-2addr v%d,v%d", (_opname), vdst, vsrc1); \
SET_REGISTER_WIDE(vdst, \
_cast GET_REGISTER_WIDE(vdst) _op (GET_REGISTER(vsrc1) & 0x3f)); \
FINISH(1);
#define HANDLE_OP_X_FLOAT(_opcode, _opname, _op) \
HANDLE_OPCODE(_opcode /*vAA, vBB, vCC*/) \
{ \
u2 srcRegs; \
vdst = INST_AA(inst); \
srcRegs = FETCH(1); \
vsrc1 = srcRegs & 0xff; \
vsrc2 = srcRegs >> 8; \
ILOGV("|%s-float v%d,v%d,v%d", (_opname), vdst, vsrc1, vsrc2); \
SET_REGISTER_FLOAT(vdst, \
GET_REGISTER_FLOAT(vsrc1) _op GET_REGISTER_FLOAT(vsrc2)); \
} \
FINISH(2);
#define HANDLE_OP_X_DOUBLE(_opcode, _opname, _op) \
HANDLE_OPCODE(_opcode /*vAA, vBB, vCC*/) \
{ \
u2 srcRegs; \
vdst = INST_AA(inst); \
srcRegs = FETCH(1); \
vsrc1 = srcRegs & 0xff; \
vsrc2 = srcRegs >> 8; \
ILOGV("|%s-double v%d,v%d,v%d", (_opname), vdst, vsrc1, vsrc2); \
SET_REGISTER_DOUBLE(vdst, \
GET_REGISTER_DOUBLE(vsrc1) _op GET_REGISTER_DOUBLE(vsrc2)); \
} \
FINISH(2);
#define HANDLE_OP_X_FLOAT_2ADDR(_opcode, _opname, _op) \
HANDLE_OPCODE(_opcode /*vA, vB*/) \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); \
ILOGV("|%s-float-2addr v%d,v%d", (_opname), vdst, vsrc1); \
SET_REGISTER_FLOAT(vdst, \
GET_REGISTER_FLOAT(vdst) _op GET_REGISTER_FLOAT(vsrc1)); \
FINISH(1);
#define HANDLE_OP_X_DOUBLE_2ADDR(_opcode, _opname, _op) \
HANDLE_OPCODE(_opcode /*vA, vB*/) \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); \
ILOGV("|%s-double-2addr v%d,v%d", (_opname), vdst, vsrc1); \
SET_REGISTER_DOUBLE(vdst, \
GET_REGISTER_DOUBLE(vdst) _op GET_REGISTER_DOUBLE(vsrc1)); \
FINISH(1);
#define HANDLE_OP_AGET(_opcode, _opname, _type, _regsize) \
HANDLE_OPCODE(_opcode /*vAA, vBB, vCC*/) \
{ \
ArrayObject* arrayObj; \
u2 arrayInfo; \
EXPORT_PC(); \
vdst = INST_AA(inst); \
arrayInfo = FETCH(1); \
vsrc1 = arrayInfo & 0xff; /* array ptr */ \
vsrc2 = arrayInfo >> 8; /* index */ \
ILOGV("|aget%s v%d,v%d,v%d", (_opname), vdst, vsrc1, vsrc2); \
arrayObj = (ArrayObject*) GET_REGISTER(vsrc1); \
if (!checkForNull((Object*) arrayObj)) \
GOTO_exceptionThrown(); \
if (GET_REGISTER(vsrc2) >= arrayObj->length) { \
dvmThrowArrayIndexOutOfBoundsException( \
arrayObj->length, GET_REGISTER(vsrc2)); \
GOTO_exceptionThrown(); \
} \
/*Android bug-checker \
abcAddObjectAccessToTrace(arrayObj, GET_REGISTER(vsrc2), self, 2); \
Android bug-checker*/ \
SET_REGISTER##_regsize(vdst, \
((_type*)(void*)arrayObj->contents)[GET_REGISTER(vsrc2)]); \
ILOGV("+ AGET[%d]=%#x", GET_REGISTER(vsrc2), GET_REGISTER(vdst)); \
} \
FINISH(2);
#define HANDLE_OP_APUT(_opcode, _opname, _type, _regsize) \
HANDLE_OPCODE(_opcode /*vAA, vBB, vCC*/) \
{ \
ArrayObject* arrayObj; \
u2 arrayInfo; \
EXPORT_PC(); \
vdst = INST_AA(inst); /* AA: source value */ \
arrayInfo = FETCH(1); \
vsrc1 = arrayInfo & 0xff; /* BB: array ptr */ \
vsrc2 = arrayInfo >> 8; /* CC: index */ \
ILOGV("|aput%s v%d,v%d,v%d", (_opname), vdst, vsrc1, vsrc2); \
arrayObj = (ArrayObject*) GET_REGISTER(vsrc1); \
if (!checkForNull((Object*) arrayObj)) \
GOTO_exceptionThrown(); \
if (GET_REGISTER(vsrc2) >= arrayObj->length) { \
dvmThrowArrayIndexOutOfBoundsException( \
arrayObj->length, GET_REGISTER(vsrc2)); \
GOTO_exceptionThrown(); \
} \
/*Android bug-checker \
abcAddObjectAccessToTrace(arrayObj, GET_REGISTER(vsrc2), self, 1); \
Android bug-checker*/ \
ILOGV("+ APUT[%d]=0x%08x", GET_REGISTER(vsrc2), GET_REGISTER(vdst));\
((_type*)(void*)arrayObj->contents)[GET_REGISTER(vsrc2)] = \
GET_REGISTER##_regsize(vdst); \
} \
FINISH(2);
/*
* It's possible to get a bad value out of a field with sub-32-bit stores
* because the -quick versions always operate on 32 bits. Consider:
* short foo = -1 (sets a 32-bit register to 0xffffffff)
* iput-quick foo (writes all 32 bits to the field)
* short bar = 1 (sets a 32-bit register to 0x00000001)
* iput-short (writes the low 16 bits to the field)
* iget-quick foo (reads all 32 bits from the field, yielding 0xffff0001)
* This can only happen when optimized and non-optimized code has interleaved
* access to the same field. This is unlikely but possible.
*
* The easiest way to fix this is to always read/write 32 bits at a time. On
* a device with a 16-bit data bus this is sub-optimal. (The alternative
* approach is to have sub-int versions of iget-quick, but now we're wasting
* Dalvik instruction space and making it less likely that handler code will
* already be in the CPU i-cache.)
*/
#define HANDLE_IGET_X(_opcode, _opname, _ftype, _regsize) \
HANDLE_OPCODE(_opcode /*vA, vB, field@CCCC*/) \
{ \
InstField* ifield; \
Object* obj; \
EXPORT_PC(); \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); /* object ptr */ \
ref = FETCH(1); /* field ref */ \
ILOGV("|iget%s v%d,v%d,field@0x%04x", (_opname), vdst, vsrc1, ref); \
obj = (Object*) GET_REGISTER(vsrc1); \
if (!checkForNull(obj)) \
GOTO_exceptionThrown(); \
ifield = (InstField*) dvmDexGetResolvedField(methodClassDex, ref); \
if (ifield == NULL) { \
ifield = dvmResolveInstField(curMethod->clazz, ref); \
if (ifield == NULL) \
GOTO_exceptionThrown(); \
} \
/*Android bug-checker*/ \
abcAddObjectAccessToTrace(obj, ref, self, 2); \
/*Android bug-checker*/ \
SET_REGISTER##_regsize(vdst, \
dvmGetField##_ftype(obj, ifield->byteOffset)); \
ILOGV("+ IGET '%s'=0x%08llx", ifield->field.name, \
(u8) GET_REGISTER##_regsize(vdst)); \
} \
FINISH(2);
#define HANDLE_IGET_X_JUMBO(_opcode, _opname, _ftype, _regsize) \
HANDLE_OPCODE(_opcode /*vBBBB, vCCCC, class@AAAAAAAA*/) \
{ \
InstField* ifield; \
Object* obj; \
EXPORT_PC(); \
ref = FETCH(1) | (u4)FETCH(2) << 16; /* field ref */ \
vdst = FETCH(3); \
vsrc1 = FETCH(4); /* object ptr */ \
ILOGV("|iget%s/jumbo v%d,v%d,field@0x%08x", \
(_opname), vdst, vsrc1, ref); \
obj = (Object*) GET_REGISTER(vsrc1); \
if (!checkForNull(obj)) \
GOTO_exceptionThrown(); \
ifield = (InstField*) dvmDexGetResolvedField(methodClassDex, ref); \
if (ifield == NULL) { \
ifield = dvmResolveInstField(curMethod->clazz, ref); \
if (ifield == NULL) \
GOTO_exceptionThrown(); \
} \
/*Android bug-checker*/ \
abcAddObjectAccessToTrace(obj, ref, self, 2); \
/*Android bug-checker*/ \
SET_REGISTER##_regsize(vdst, \
dvmGetField##_ftype(obj, ifield->byteOffset)); \
ILOGV("+ IGET '%s'=0x%08llx", ifield->field.name, \
(u8) GET_REGISTER##_regsize(vdst)); \
} \
FINISH(5);
#define HANDLE_IGET_X_QUICK(_opcode, _opname, _ftype, _regsize) \
HANDLE_OPCODE(_opcode /*vA, vB, field@CCCC*/) \
{ \
Object* obj; \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); /* object ptr */ \
ref = FETCH(1); /* field offset */ \
ILOGV("|iget%s-quick v%d,v%d,field@+%u", \
(_opname), vdst, vsrc1, ref); \
obj = (Object*) GET_REGISTER(vsrc1); \
if (!checkForNullExportPC(obj, fp, pc)) \
GOTO_exceptionThrown(); \
/*Android bug-checker*/ \
abcAddObjectAccessToTrace(obj, ref, self, 2); \
/*Android bug-checker*/ \
SET_REGISTER##_regsize(vdst, dvmGetField##_ftype(obj, ref)); \
ILOGV("+ IGETQ %d=0x%08llx", ref, \
(u8) GET_REGISTER##_regsize(vdst)); \
} \
FINISH(2);
#define HANDLE_IPUT_X(_opcode, _opname, _ftype, _regsize) \
HANDLE_OPCODE(_opcode /*vA, vB, field@CCCC*/) \
{ \
InstField* ifield; \
Object* obj; \
EXPORT_PC(); \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); /* object ptr */ \
ref = FETCH(1); /* field ref */ \
ILOGV("|iput%s v%d,v%d,field@0x%04x", (_opname), vdst, vsrc1, ref); \
obj = (Object*) GET_REGISTER(vsrc1); \
if (!checkForNull(obj)) \
GOTO_exceptionThrown(); \
ifield = (InstField*) dvmDexGetResolvedField(methodClassDex, ref); \
if (ifield == NULL) { \
ifield = dvmResolveInstField(curMethod->clazz, ref); \
if (ifield == NULL) \
GOTO_exceptionThrown(); \
} \
/*Android bug-checker*/ \
abcAddObjectAccessToTrace(obj, ref, self, 1); \
/*Android bug-checker*/ \
dvmSetField##_ftype(obj, ifield->byteOffset, \
GET_REGISTER##_regsize(vdst)); \
ILOGV("+ IPUT '%s'=0x%08llx", ifield->field.name, \
(u8) GET_REGISTER##_regsize(vdst)); \
} \
FINISH(2);
#define HANDLE_IPUT_X_JUMBO(_opcode, _opname, _ftype, _regsize) \
HANDLE_OPCODE(_opcode /*vBBBB, vCCCC, class@AAAAAAAA*/) \
{ \
InstField* ifield; \
Object* obj; \
EXPORT_PC(); \
ref = FETCH(1) | (u4)FETCH(2) << 16; /* field ref */ \
vdst = FETCH(3); \
vsrc1 = FETCH(4); /* object ptr */ \
ILOGV("|iput%s/jumbo v%d,v%d,field@0x%08x", \
(_opname), vdst, vsrc1, ref); \
obj = (Object*) GET_REGISTER(vsrc1); \
if (!checkForNull(obj)) \
GOTO_exceptionThrown(); \
ifield = (InstField*) dvmDexGetResolvedField(methodClassDex, ref); \
if (ifield == NULL) { \
ifield = dvmResolveInstField(curMethod->clazz, ref); \
if (ifield == NULL) \
GOTO_exceptionThrown(); \
} \
/*Android bug-checker*/ \
abcAddObjectAccessToTrace(obj, ref, self, 1); \
/*Android bug-checker*/ \
dvmSetField##_ftype(obj, ifield->byteOffset, \
GET_REGISTER##_regsize(vdst)); \
ILOGV("+ IPUT '%s'=0x%08llx", ifield->field.name, \
(u8) GET_REGISTER##_regsize(vdst)); \
} \
FINISH(5);
#define HANDLE_IPUT_X_QUICK(_opcode, _opname, _ftype, _regsize) \
HANDLE_OPCODE(_opcode /*vA, vB, field@CCCC*/) \
{ \
Object* obj; \
vdst = INST_A(inst); \
vsrc1 = INST_B(inst); /* object ptr */ \
ref = FETCH(1); /* field offset */ \
ILOGV("|iput%s-quick v%d,v%d,field@0x%04x", \
(_opname), vdst, vsrc1, ref); \
obj = (Object*) GET_REGISTER(vsrc1); \
if (!checkForNullExportPC(obj, fp, pc)) \
GOTO_exceptionThrown(); \
/*Android bug-checker*/ \
abcAddObjectAccessToTrace(obj, ref, self, 1); \
/*Android bug-checker*/ \
dvmSetField##_ftype(obj, ref, GET_REGISTER##_regsize(vdst)); \
ILOGV("+ IPUTQ %d=0x%08llx", ref, \
(u8) GET_REGISTER##_regsize(vdst)); \
} \
FINISH(2);
/*
* The JIT needs dvmDexGetResolvedField() to return non-null.
* Because the portable interpreter is not involved with the JIT
* and trace building, we only need the extra check here when this
* code is massaged into a stub called from an assembly interpreter.
* This is controlled by the JIT_STUB_HACK maco.
*/
#define HANDLE_SGET_X(_opcode, _opname, _ftype, _regsize) \
HANDLE_OPCODE(_opcode /*vAA, field@BBBB*/) \
{ \
StaticField* sfield; \
vdst = INST_AA(inst); \
ref = FETCH(1); /* field ref */ \
ILOGV("|sget%s v%d,sfield@0x%04x", (_opname), vdst, ref); \
sfield = (StaticField*)dvmDexGetResolvedField(methodClassDex, ref); \
if (sfield == NULL) { \
EXPORT_PC(); \
sfield = dvmResolveStaticField(curMethod->clazz, ref); \
if (sfield == NULL) \
GOTO_exceptionThrown(); \
if (dvmDexGetResolvedField(methodClassDex, ref) == NULL) { \
JIT_STUB_HACK(dvmJitEndTraceSelect(self,pc)); \
} \
} \
/*Android bug-checker*/ \
abcAddStaticFieldAccessToTrace(curMethod->clazz->descriptor, \
sfield->name, ref, self, 2); \
/*Android bug-checker*/ \
SET_REGISTER##_regsize(vdst, dvmGetStaticField##_ftype(sfield)); \
ILOGV("+ SGET '%s'=0x%08llx", \
sfield->field.name, (u8)GET_REGISTER##_regsize(vdst)); \
} \
FINISH(2);
#define HANDLE_SGET_X_JUMBO(_opcode, _opname, _ftype, _regsize) \
HANDLE_OPCODE(_opcode /*vBBBB, class@AAAAAAAA*/) \
{ \
StaticField* sfield; \
ref = FETCH(1) | (u4)FETCH(2) << 16; /* field ref */ \
vdst = FETCH(3); \
ILOGV("|sget%s/jumbo v%d,sfield@0x%08x", (_opname), vdst, ref); \
sfield = (StaticField*)dvmDexGetResolvedField(methodClassDex, ref); \
if (sfield == NULL) { \
EXPORT_PC(); \
sfield = dvmResolveStaticField(curMethod->clazz, ref); \
if (sfield == NULL) \
GOTO_exceptionThrown(); \
if (dvmDexGetResolvedField(methodClassDex, ref) == NULL) { \
JIT_STUB_HACK(dvmJitEndTraceSelect(self,pc)); \
} \
} \
/*Android bug-checker*/ \
abcAddStaticFieldAccessToTrace(curMethod->clazz->descriptor, \
sfield->name, ref, self, 2); \
/*Android bug-checker*/ \
SET_REGISTER##_regsize(vdst, dvmGetStaticField##_ftype(sfield)); \
ILOGV("+ SGET '%s'=0x%08llx", \
sfield->field.name, (u8)GET_REGISTER##_regsize(vdst)); \
} \
FINISH(4);
#define HANDLE_SPUT_X(_opcode, _opname, _ftype, _regsize) \
HANDLE_OPCODE(_opcode /*vAA, field@BBBB*/) \
{ \
StaticField* sfield; \
vdst = INST_AA(inst); \
ref = FETCH(1); /* field ref */ \
ILOGV("|sput%s v%d,sfield@0x%04x", (_opname), vdst, ref); \
sfield = (StaticField*)dvmDexGetResolvedField(methodClassDex, ref); \
if (sfield == NULL) { \
EXPORT_PC(); \
sfield = dvmResolveStaticField(curMethod->clazz, ref); \
if (sfield == NULL) \
GOTO_exceptionThrown(); \
if (dvmDexGetResolvedField(methodClassDex, ref) == NULL) { \
JIT_STUB_HACK(dvmJitEndTraceSelect(self,pc)); \
} \
} \
/*Android bug-checker*/ \
abcAddStaticFieldAccessToTrace(curMethod->clazz->descriptor, \
sfield->name, ref, self, 1); \
/*Android bug-checker*/ \
dvmSetStaticField##_ftype(sfield, GET_REGISTER##_regsize(vdst)); \
ILOGV("+ SPUT '%s'=0x%08llx", \
sfield->field.name, (u8)GET_REGISTER##_regsize(vdst)); \
} \
FINISH(2);
#define HANDLE_SPUT_X_JUMBO(_opcode, _opname, _ftype, _regsize) \
HANDLE_OPCODE(_opcode /*vBBBB, class@AAAAAAAA*/) \
{ \
StaticField* sfield; \
ref = FETCH(1) | (u4)FETCH(2) << 16; /* field ref */ \
vdst = FETCH(3); \
ILOGV("|sput%s/jumbo v%d,sfield@0x%08x", (_opname), vdst, ref); \
sfield = (StaticField*)dvmDexGetResolvedField(methodClassDex, ref); \
if (sfield == NULL) { \
EXPORT_PC(); \
sfield = dvmResolveStaticField(curMethod->clazz, ref); \
if (sfield == NULL) \
GOTO_exceptionThrown(); \
if (dvmDexGetResolvedField(methodClassDex, ref) == NULL) { \
JIT_STUB_HACK(dvmJitEndTraceSelect(self,pc)); \
} \
} \
/*Android bug-checker*/ \
abcAddStaticFieldAccessToTrace(curMethod->clazz->descriptor, \
sfield->name, ref, self, 1); \
/*Android bug-checker*/ \
dvmSetStaticField##_ftype(sfield, GET_REGISTER##_regsize(vdst)); \
ILOGV("+ SPUT '%s'=0x%08llx", \
sfield->field.name, (u8)GET_REGISTER##_regsize(vdst)); \
} \
FINISH(4);
/* File: cstubs/enddefs.cpp */
/* undefine "magic" name remapping */
#undef retval
#undef pc
#undef fp
#undef curMethod
#undef methodClassDex
#undef self
#undef debugTrackedRefStart
/* File: armv5te/debug.cpp */
#include <inttypes.h>
/*
* Dump the fixed-purpose ARM registers, along with some other info.
*
* This function MUST be compiled in ARM mode -- THUMB will yield bogus
* results.
*
* This will NOT preserve r0-r3/ip.
*/
void dvmMterpDumpArmRegs(uint32_t r0, uint32_t r1, uint32_t r2, uint32_t r3)
{
register uint32_t rPC asm("r4");
register uint32_t rFP asm("r5");
register uint32_t rSELF asm("r6");
register uint32_t rINST asm("r7");
register uint32_t rIBASE asm("r8");
register uint32_t r9 asm("r9");
register uint32_t r10 asm("r10");
//extern char dvmAsmInstructionStart[];
printf("REGS: r0=%08x r1=%08x r2=%08x r3=%08x\n", r0, r1, r2, r3);
printf(" : rPC=%08x rFP=%08x rSELF=%08x rINST=%08x\n",
rPC, rFP, rSELF, rINST);
printf(" : rIBASE=%08x r9=%08x r10=%08x\n", rIBASE, r9, r10);
//Thread* self = (Thread*) rSELF;
//const Method* method = self->method;
printf(" + self is %p\n", dvmThreadSelf());
//printf(" + currently in %s.%s %s\n",
// method->clazz->descriptor, method->name, method->shorty);
//printf(" + dvmAsmInstructionStart = %p\n", dvmAsmInstructionStart);
//printf(" + next handler for 0x%02x = %p\n",
// rINST & 0xff, dvmAsmInstructionStart + (rINST & 0xff) * 64);
}
/*
* Dump the StackSaveArea for the specified frame pointer.
*/
void dvmDumpFp(void* fp, StackSaveArea* otherSaveArea)
{
StackSaveArea* saveArea = SAVEAREA_FROM_FP(fp);
printf("StackSaveArea for fp %p [%p/%p]:\n", fp, saveArea, otherSaveArea);
#ifdef EASY_GDB
printf(" prevSave=%p, prevFrame=%p savedPc=%p meth=%p curPc=%p\n",
saveArea->prevSave, saveArea->prevFrame, saveArea->savedPc,
saveArea->method, saveArea->xtra.currentPc);
#else
printf(" prevFrame=%p savedPc=%p meth=%p curPc=%p fp[0]=0x%08x\n",
saveArea->prevFrame, saveArea->savedPc,
saveArea->method, saveArea->xtra.currentPc,
*(u4*)fp);
#endif
}
/*
* Does the bulk of the work for common_printMethod().
*/
void dvmMterpPrintMethod(Method* method)
{
/*
* It is a direct (non-virtual) method if it is static, private,
* or a constructor.
*/
bool isDirect =
((method->accessFlags & (ACC_STATIC|ACC_PRIVATE)) != 0) ||
(method->name[0] == '<');
char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
printf("<%c:%s.%s %s> ",
isDirect ? 'D' : 'V',
method->clazz->descriptor,
method->name,
desc);
free(desc);
}
| [
"md.salman729@gmail.com"
] | md.salman729@gmail.com |
56c7d5e222a1434b18bf6adc7d25d483741f2265 | c6cbe7d208ac0a659c28ba665840baab7d86fcb2 | /build-BMSGUI-Desktop_Qt_5_11_1_MinGW_32bit-Debug/debug/moc_mainwindow.cpp | 7a7e430dd0a663976340b8e2ce0b49627e8dc5bb | [] | no_license | HyperloopatVCU/HyperloopGUI | 49c5f6cb3afa0f7854878593d6f805e6e98fd751 | bfed1a3580477ac1b31197533a6bec51f09db95c | refs/heads/master | 2020-03-22T02:17:05.193139 | 2018-08-03T23:12:24 | 2018-08-03T23:12:24 | 139,361,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,649 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../BMSGUI/mainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.11.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
QByteArrayData data[1];
char stringdata0[11];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 0, 10) // "MainWindow"
},
"MainWindow"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject MainWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data,
qt_meta_data_MainWindow, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(this);
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"34044280+jonescb5@users.noreply.github.com"
] | 34044280+jonescb5@users.noreply.github.com |
85713ffe08384e1a5bb3a7303a0c2191b6f37eb1 | f9a82c5090c6136993438cbb20cb7bedc5c67cb4 | /209.cpp | 503bc9ce866dcedfa38d24fa7172a102c3af7d3e | [] | no_license | JarvisZhang/Leetcode | 78d1dab0e8dda79aa00f3a8f76897432813cc108 | ed7d2975b0719ae2ce25bedb23ca57b62e74a58d | refs/heads/master | 2020-06-03T19:18:58.503493 | 2015-09-23T13:17:49 | 2015-09-23T13:17:49 | 38,595,044 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 834 | cpp | //
// 209.cpp
// LeetCode
//
// Created by 张佐玮 on 15/6/2.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: Minimum Size Subarray Sum
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int minSubArrayLen(int s, vector<int>& nums) {
if (nums.empty()) {
return 0;
}
int maxLength = INT_MAX, start = 0, end = 0, sum = 0;
while (end < nums.size() || sum >= s) {
if (sum >= s) {
int currentLength = end - start;
maxLength = (currentLength < maxLength) ? currentLength : maxLength;
sum -= nums[start++];
}
else {
sum += nums[end++];
}
}
return (maxLength == INT_MAX) ? 0 : maxLength;
}
}; | [
"zuowzhang@buaa.edu.cn"
] | zuowzhang@buaa.edu.cn |
8366b21f57ba3ef725b9c79a4dc633e0d2cb6d8c | 443a77967733786dace6c8d67bae940d1b8bfdbc | /physicsEngine/src/collision/narrowphase/CollisionObjectWrapper.cpp | 7fb2016557a135715e4ec6b87f4f3b4f3f9fd826 | [
"MIT"
] | permissive | whztt1989/UrchinEngine | c3f754d075e2c2ff8f85cf775fcca27eaa2dcb11 | f90ba990b09f3792899db63fb1cbd8adfe514373 | refs/heads/master | 2021-01-13T08:17:59.441361 | 2016-10-23T18:33:11 | 2016-10-23T18:33:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 545 | cpp | #include "collision/narrowphase/CollisionObjectWrapper.h"
namespace urchin
{
CollisionObjectWrapper::CollisionObjectWrapper(const CollisionShape3D &shape, const PhysicsTransform &shapeWorldTransform) :
shape(shape),
shapeWorldTransform(shapeWorldTransform)
{
}
CollisionObjectWrapper::~CollisionObjectWrapper()
{
}
const CollisionShape3D &CollisionObjectWrapper::getShape() const
{
return shape;
}
const PhysicsTransform &CollisionObjectWrapper::getShapeWorldTransform() const
{
return shapeWorldTransform;
}
}
| [
"petitg1987@gmail.com"
] | petitg1987@gmail.com |
1009f858695b014afb39b60b6511fd5d1aeabb8f | 415a1f6841edfb27d1f902d4617708bd84771d5d | /BST.h | 8e75fdeb8bf8975d4effd8782ce40fb1181619eb | [] | no_license | m3h3d1/English-Vocabulary-Program-using-BST | fa88f6cec44a73fb7d2b79f4afd2baa5cfe2f1bb | e6410825e643adb33be3cca70d1bba58a46b0220 | refs/heads/master | 2023-02-28T18:07:58.961719 | 2021-02-09T13:19:37 | 2021-02-09T13:19:37 | 197,061,484 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | h | #ifndef BST_H
#define BST_H
#include<iostream>
#include<fstream>
#include<algorithm>
#include<ctime>
using namespace std;
struct Dict {
string Word, syn, ant;
};
struct Node {
string Word, syn, ant;
Node *left, *right, *parent;
Node() {
left = right = parent = NULL;
Word = syn = ant = "";
}
};
class bst {
Node *root;
public:
bst();
Node* Root();
Dict inputData();
void insertWord(Dict data);
Node* insertWord(Node *curr, Node *par, Dict data);
void inorder(Node *curr);
Node* search(Node* curr, string key);
Node* minimum(Node* curr);
Node* maximum(Node* curr);
Node* successor(Node* curr);
Dict copyData(Node* tmp);
Node* deleteWord(Node* curr, Dict data);
void editWord();
};
#endif | [
"hasanmehedi185@gmail.com"
] | hasanmehedi185@gmail.com |
d92f79f1e51a0176e12ac5a7571ee17793cd0844 | 9a1629e05468ec73b4e4bb0937a3511087addfa6 | /Tests/testXLFormula.cpp | e05043f5a7fa98ad9ec72a7d0ec3ce9b4b792ace | [
"BSD-3-Clause"
] | permissive | senliontec/OpenXLSX | 09a74b58102a2fc7f886228d57392bd166e4dbfa | 5e3ef1e3abdf7dbc7f888ec3be35ee37643b8aa6 | refs/heads/master | 2023-08-15T20:41:49.577769 | 2021-09-19T14:44:10 | 2021-09-19T14:44:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,380 | cpp | //
// Created by Kenneth Balslev on 27/08/2021.
//
#include <OpenXLSX.hpp>
#include <catch.hpp>
#include <fstream>
using namespace OpenXLSX;
TEST_CASE("XLFormula Tests", "[XLFormula]")
{
SECTION("Default Constructor")
{
XLFormula formula;
REQUIRE(formula.get().empty());
}
SECTION("String Constructor")
{
XLFormula formula1("BLAH1");
REQUIRE(formula1.get() == "BLAH1");
std::string s = "BLAH2";
XLFormula formula2(s);
REQUIRE(formula2.get() == "BLAH2");
}
SECTION("Copy Constructor")
{
XLFormula formula1("BLAH1");
REQUIRE(formula1.get() == "BLAH1");
XLFormula formula2 = formula1;
REQUIRE(formula2.get() == "BLAH1");
}
SECTION("Move Constructor")
{
XLFormula formula1("BLAH1");
REQUIRE(formula1.get() == "BLAH1");
XLFormula formula2 = std::move(formula1);
REQUIRE(formula2.get() == "BLAH1");
}
SECTION("Copy assignment")
{
XLFormula formula1("BLAH1");
REQUIRE(formula1.get() == "BLAH1");
XLFormula formula2;
formula2 = formula1;
REQUIRE(formula2.get() == "BLAH1");
}
SECTION("Move assignment")
{
XLFormula formula1("BLAH1");
REQUIRE(formula1.get() == "BLAH1");
XLFormula formula2;
formula2 = std::move(formula1);
REQUIRE(formula2.get() == "BLAH1");
}
SECTION("Clear")
{
XLFormula formula1("BLAH1");
REQUIRE(formula1.get() == "BLAH1");
formula1.clear();
REQUIRE(formula1.get().empty());
}
SECTION("String assignment")
{
XLFormula formula1;
formula1 = "BLAH1";
REQUIRE(formula1.get() == "BLAH1");
XLFormula formula2;
formula2 = std::string("BLAH2");
REQUIRE(formula2.get() == "BLAH2");
}
SECTION("String setter")
{
XLFormula formula1;
formula1.set("BLAH1");
REQUIRE(formula1.get() == "BLAH1");
XLFormula formula2;
formula2.set(std::string("BLAH2"));
REQUIRE(formula2.get() == "BLAH2");
}
SECTION("Implicit conversion")
{
XLFormula formula1;
formula1.set("BLAH1");
REQUIRE(formula1.get() == "BLAH1");
auto result = std::string(formula1);
REQUIRE(result == "BLAH1");
}
} | [
"kenneth.balslev@gmail.com"
] | kenneth.balslev@gmail.com |
e361f410a9d1fe662c04afbd86a67f6faf99ad4e | 738d3de21b64c1c66905821a723d27cd9b7833e3 | /sample.cc | 5e5d71ea135bb7dfc36bf43c9daed9367d627da8 | [] | no_license | KUNPL/NFADC400 | bf86b829b5ee0143b27f4b763c16771fdb4b11a9 | 0c5c1bda7d5504b90a3ff05e158a982604b220dc | refs/heads/master | 2021-01-13T01:28:07.841338 | 2015-03-19T06:09:04 | 2015-03-19T06:09:04 | 22,037,632 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | cc | void sample() {
gSystem -> Load("libNFADC400");
TFile *file = new TFile("sample.root");
TClonesArray *events = NULL;
TTree *tree = (TTree *) file -> Get(Form("Mod%dCh%d", 2, 1));
tree -> SetBranchAddress("events", &events);
tree -> GetEntry(0);
NFADC400Event4 *anEvent = NULL;
Int_t numEvents = events -> GetEntries();
for (Int_t i = 0; i < numEvents; i++) {
anEvent = (NFADC400Event4 *) events -> At(i);
Int_t numData = anEvent -> GetNumData();
for (Int_t j = 0; j < numData; j++)
cout << setw(5) << i << setw(5) << j << setw(5) << anEvent -> GetADC(j) << endl;
}
}
| [
"geniejhang@majimak.com"
] | geniejhang@majimak.com |
e65b6a8fb148107826e3467f1a1356774a761acb | 5521a03064928d63cc199e8034e4ea76264f76da | /fboss/agent/hw/sai/tracer/UdfApiTracer.cpp | bb1c7e993548524c575e8bf3f82c2bdc33fde022 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | facebook/fboss | df190fd304e0bf5bfe4b00af29f36b55fa00efad | 81e02db57903b4369200eec7ef22d882da93c311 | refs/heads/main | 2023-09-01T18:21:22.565059 | 2023-09-01T15:53:39 | 2023-09-01T15:53:39 | 31,927,407 | 925 | 353 | NOASSERTION | 2023-09-14T05:44:49 | 2015-03-09T23:04:15 | C++ | UTF-8 | C++ | false | false | 2,782 | cpp | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/agent/hw/sai/tracer/UdfApiTracer.h"
#include <typeindex>
#include <utility>
#include "fboss/agent/hw/sai/api/UdfApi.h"
#include "fboss/agent/hw/sai/tracer/Utils.h"
using folly::to;
namespace {
std::map<int32_t, std::pair<std::string, std::size_t>> _UdfMap{
SAI_ATTR_MAP(Udf, UdfMatchId),
SAI_ATTR_MAP(Udf, UdfGroupId),
SAI_ATTR_MAP(Udf, Base),
SAI_ATTR_MAP(Udf, Offset),
};
std::map<int32_t, std::pair<std::string, std::size_t>> _UdfMatchMap {
SAI_ATTR_MAP(UdfMatch, L2Type), SAI_ATTR_MAP(UdfMatch, L3Type),
#if SAI_API_VERSION >= SAI_VERSION(1, 12, 0)
SAI_ATTR_MAP(UdfMatch, L4DstPortType),
#endif
};
std::map<int32_t, std::pair<std::string, std::size_t>> _UdfGroupMap{
SAI_ATTR_MAP(UdfGroup, Type),
SAI_ATTR_MAP(UdfGroup, Length),
};
} // namespace
namespace facebook::fboss {
WRAP_CREATE_FUNC(udf, SAI_OBJECT_TYPE_UDF, udf);
WRAP_REMOVE_FUNC(udf, SAI_OBJECT_TYPE_UDF, udf);
WRAP_SET_ATTR_FUNC(udf, SAI_OBJECT_TYPE_UDF, udf);
WRAP_GET_ATTR_FUNC(udf, SAI_OBJECT_TYPE_UDF, udf);
WRAP_CREATE_FUNC(udf_match, SAI_OBJECT_TYPE_UDF_MATCH, udf);
WRAP_REMOVE_FUNC(udf_match, SAI_OBJECT_TYPE_UDF_MATCH, udf);
WRAP_SET_ATTR_FUNC(udf_match, SAI_OBJECT_TYPE_UDF_MATCH, udf);
WRAP_GET_ATTR_FUNC(udf_match, SAI_OBJECT_TYPE_UDF_MATCH, udf);
WRAP_CREATE_FUNC(udf_group, SAI_OBJECT_TYPE_UDF_GROUP, udf);
WRAP_REMOVE_FUNC(udf_group, SAI_OBJECT_TYPE_UDF_GROUP, udf);
WRAP_SET_ATTR_FUNC(udf_group, SAI_OBJECT_TYPE_UDF_GROUP, udf);
WRAP_GET_ATTR_FUNC(udf_group, SAI_OBJECT_TYPE_UDF_GROUP, udf);
sai_udf_api_t* wrappedUdfApi() {
static sai_udf_api_t udfWrappers;
udfWrappers.create_udf = &wrap_create_udf;
udfWrappers.remove_udf = &wrap_remove_udf;
udfWrappers.set_udf_attribute = &wrap_set_udf_attribute;
udfWrappers.get_udf_attribute = &wrap_get_udf_attribute;
udfWrappers.create_udf_match = &wrap_create_udf_match;
udfWrappers.remove_udf_match = &wrap_remove_udf_match;
udfWrappers.set_udf_match_attribute = &wrap_set_udf_match_attribute;
udfWrappers.get_udf_match_attribute = &wrap_get_udf_match_attribute;
udfWrappers.create_udf_group = &wrap_create_udf_group;
udfWrappers.remove_udf_group = &wrap_remove_udf_group;
udfWrappers.set_udf_group_attribute = &wrap_set_udf_group_attribute;
udfWrappers.get_udf_group_attribute = &wrap_get_udf_group_attribute;
return &udfWrappers;
}
SET_SAI_ATTRIBUTES(Udf)
SET_SAI_ATTRIBUTES(UdfMatch)
SET_SAI_ATTRIBUTES(UdfGroup)
} // namespace facebook::fboss
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
e9664eec6e17908e73451f7cffaea50db14d37f6 | 1942a0d16bd48962e72aa21fad8d034fa9521a6c | /aws-cpp-sdk-apigateway/source/model/GetDocumentationPartRequest.cpp | aad4b5f5db225696addd681b4058f11aa8cca68d | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | yecol/aws-sdk-cpp | 1aff09a21cfe618e272c2c06d358cfa0fb07cecf | 0b1ea31e593d23b5db49ee39d0a11e5b98ab991e | refs/heads/master | 2021-01-20T02:53:53.557861 | 2018-02-11T11:14:58 | 2018-02-11T11:14:58 | 83,822,910 | 0 | 1 | null | 2017-03-03T17:17:00 | 2017-03-03T17:17:00 | null | UTF-8 | C++ | false | false | 1,039 | cpp | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/apigateway/model/GetDocumentationPartRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::APIGateway::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
GetDocumentationPartRequest::GetDocumentationPartRequest() :
m_restApiIdHasBeenSet(false),
m_documentationPartIdHasBeenSet(false)
{
}
Aws::String GetDocumentationPartRequest::SerializePayload() const
{
return "";
}
| [
"henso@amazon.com"
] | henso@amazon.com |
fe56b8a39aa471aac0d3e3b9f9b9d0a0f28680e6 | cfbbeff5af88c2d8004f2030d7f500742e0f13c1 | /src/qt/coinuint_treemodel.h | d60ed7dd3ea1c3cc12f06e7206d284eaa8a7ad2d | [
"MIT"
] | permissive | jeanstony/asset_bitcoin | 5a2f2ab0456b4fd574d7995258a42c7bd7313cb3 | ff4e497da2fa64ac9efa7e806047d0eb44fdfd64 | refs/heads/master | 2020-09-21T23:13:00.968760 | 2019-12-02T01:14:48 | 2019-12-02T01:14:48 | 224,965,826 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,227 | h | #ifndef TREEMODEL_H
#define TREEMODEL_H
#include <QAbstractItemModel>
#include <QModelIndex>
#include <QVariant>
#include <amount.h>
class CoinUintTreeItem;
//! [0]
class CoinUintTreeModel : public QAbstractItemModel
{
Q_OBJECT
public:
CoinUintTreeModel(const QStringList &headers, QObject *parent = 0);
~CoinUintTreeModel();
//! [0] //! [1]
Q_INVOKABLE virtual QVariant data(const QModelIndex &index, int role) const override;
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const override;
Q_INVOKABLE virtual QModelIndexList match(const QModelIndex &start, int role,
const QVariant &value, int hits = 1,
Qt::MatchFlags flags =
Qt::MatchFlags(Qt::MatchStartsWith|Qt::MatchWrap)) const override;
QModelIndex index(int row, int column,
const QModelIndex &parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex &index) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
//! [1]
//! [2]
Qt::ItemFlags flags(const QModelIndex &index) const override;
bool setData(const QModelIndex &index, const QVariant &value,
int role = Qt::EditRole) override;
bool setHeaderData(int section, Qt::Orientation orientation,
const QVariant &value, int role = Qt::EditRole) override;
bool insertColumns(int position, int columns,
const QModelIndex &parent = QModelIndex()) override;
bool removeColumns(int position, int columns,
const QModelIndex &parent = QModelIndex()) override;
bool removeRows(int position, int rows,
const QModelIndex &parent = QModelIndex()) override;
void ReadAllBalanceData(void);
void UpdateAssetBalance(QMap<int, CAmount> &amounts);
private:
CoinUintTreeItem *getItem(const QModelIndex &index) const;
CoinUintTreeItem *rootItem;
};
//! [2]
#endif // TREEMODEL_H
| [
"zjtzvvip@163.com"
] | zjtzvvip@163.com |
d5fd6dad349693781e43c2859a3b10899326df43 | 0694c644b97c7c6d723435e534d18825d4b6d296 | /projects/command/command.cpp | ad974713cfc26fc76e6441728c089e6983b42e53 | [] | no_license | shellyweiss/projects | 4faea75da72cb57afe6f85e7fff19d44d10c942b | 5fc897ed6f059b1fcc8dee96e43a00ee8ce1fccc | refs/heads/master | 2022-11-25T20:36:26.277730 | 2020-08-04T14:53:53 | 2020-08-04T14:53:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,160 | cpp | /*******************************
Yonatan Zaken
Command
CPP
ILRD - RD8081
*******************************/
#include <cstring>
#include <boost/make_shared.hpp>
#include "command.hpp"
namespace ilrd
{
/************************************ Read *********************************/
Read::Read(RequestMessage& message):
m_message(message)
{
}
int Read::Operation(const boost::shared_ptr<Storage>& storage, uint8_t *buffer)
{
return storage->Read(buffer, m_message.GetBlockID());
}
boost::shared_ptr<Read> Read::CreateRead(RequestMessage& message)
{
return (boost::shared_ptr<Read>(new Read(message)));
}
/************************************ Write *********************************/
Write::Write(RequestMessage& message):
m_message(message)
{
//memcpy(m_data, message.DataBlock(), protocol::BLOCK_SIZE);
}
int Write::Operation(const boost::shared_ptr<Storage>& storage, uint8_t *buffer)
{
return storage->Write(buffer, m_message.GetBlockID());
}
boost::shared_ptr<Write> Write::CreateWrite(RequestMessage& message)
{
return (boost::shared_ptr<Write>(new Write(message)));
}
} // namespace ilrd
| [
"yonatan.zaken@gmail.com"
] | yonatan.zaken@gmail.com |
44d64191ca46e5c3542c4906e7d6c828a276f01f | c6ffcfbccc4799ceb13414ba21d609274728b027 | /old/pepper1/src/test/samples/overload_function/overload_function.cpp | 886be65cdbf2c956543c7e613194b943ffcb424c | [
"MIT"
] | permissive | andybalaam/pepper | 6ac69c56ea8e3a5b5328b623b301de21d4722be1 | f0d12379c7c6e2d82003c0c1d6130bfac685e1c3 | refs/heads/master | 2020-04-02T01:10:04.065726 | 2019-02-07T20:55:06 | 2019-02-07T20:55:06 | 1,834,766 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 127 | cpp | #include <stdio.h>
int main( int argc, char* argv[] )
{
printf( "%d\n", 12 );
printf( "%f\n", 2.4 );
return 0;
}
| [
"andybalaam@artificialworlds.net"
] | andybalaam@artificialworlds.net |
814ceeb6c74895a108a75c549ba882126a6cda85 | bce9f873ed573257f6a8ed9eaaac1166ec6c48f8 | /lab2/fromD4_comb_first_enc_pas/main_WITH_ENCRYPTION.cpp | ebbd1ad439f664289869a387e6d33b8cbafd8de0 | [] | no_license | spresley/compnetworksSAV | 0b47aa77d81fc7795a0858a5e037c97d54646620 | dd02d8d066429e3f37fee96888c7e2c43ffc684c | refs/heads/master | 2021-01-10T03:38:32.752246 | 2015-11-13T17:22:32 | 2015-11-13T17:22:32 | 45,035,639 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,589 | cpp | #include <avr/io.h>
#include <stdio.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <string.h>
#include "tft.h"
#include "tone.h"
#include "keypad.h"
#include "rgbconv.h"
#include "rfm12.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//#include "encryption.h"
#define freq0 96 //the different frequency the rfm12 can change
#define freq1 519
#define freq2 942
#define freq3 1365
#define freq4 1788
#define freq5 2211
#define freq6 2634
#define freq7 3057
#define freq8 3480
#define freq9 3903
#define NUM_MENU 6
class tft_t tft;
uint8_t *bufptr; //the pointer the buffer will return
char str[100]; //the string want to send
uint16_t p = 0; //the position of string
void init_sys(void); //initial the system
void text(void); //founction for text
void main_menu(void); //display and go to the main menu
void read(void); //founction for read data from sd card
void help(void); //founction for description the device
void about(void); //device information
void play(void); //get audio message from sd card
uint8_t detect(void); //dectect whether receive messages
void sync(void); //make host and slave sync.
uint8_t decrypt(uint8_t var, int key_no);//decrypt the message
void password(); //the password get into the device
void text_password(); //founction for typing password
void talk(void); //push to talk
void init(void)
{
tft.init(); //init the TFT screen
tft.setOrient(tft.Landscape); //set the orientation
tft.setBackground(conv::c32to16(0xFFFFFF)); //background colar white
tft.setForeground(0x0000); //forground colar black
tft.clean(); //clean the TFT screen
stdout = tftout(&tft);
tft.setBGLight(true);
}
int main(void)
{
init_sys();
DDRB |= 0x08; //buzzer
DDRB |= _BV(0); //the flag give to the other ilmatto (push to talk)
PORTB |= _BV(3);
PORTB |= _BV(0);
_delay_ms(500);
PORTB &= ~_BV(3);
while(keypad::scan() == (uint8_t)-1);
password();
_delay_ms(100); //little delay for the rfm12 to initialize properly
rfm12_init(); //init the RFM12
_delay_ms(100);
sei(); //interrupts on
menu:
_delay_ms(100);
main_menu();
uint8_t scan;
rescan: while(( scan = keypad::scan()) == (uint8_t)-1);
switch(scan)
{
case 0:
goto send;
case 1:
goto read;
case 2:
goto play;
case 4:
goto help;
case 5:
goto sync;
case 6:
goto about;
case 11:
goto menu;
case 15:
goto talk;
default:
goto rescan;
}
send:
text();
goto menu;
read:
read();
while(keypad::scan() != 11);
goto menu;
play:
play();
while(keypad::scan() != 11);
goto menu;
help:
help();
while(keypad::scan() != 11);
goto menu;
sync:
sync();
while(keypad::scan() != 11);
goto menu;
about:
about();
while(keypad::scan() != 11);
goto menu;
talk:
talk();
goto menu;
return 1;
}
static const char transform[10][5] = {
{' ', '0', '!', 'L', '+'},
{',', '.', '1', '-', '*'},
{'a', 'b', 'c', '2', 'A'},
{'d', 'e', 'f', '3', 'B'},
{'g', 'h', 'i', '4', 'C'},
{'j', 'k', 'l', '5', 'D'},
{'m', 'n', 'o', '6', 'E'},
{'p', 'q', 'r', 's', '7'},
{'t', 'u', 'v', '8', 'O'},
{'w', 'x', 'y', 'z', '9'},
};
static const char menu[6][10] = {
"send",
"read",
"play",
"help",
"sync",
"about"
};
void init_sys(void)
{
init();
init_tone();
keypad::init(); //init the keypad
keypad::init_timer();
tft.clean();
tft.setZoom(3);
tft.setBackground(conv::c32to16(0xFF0000));
tft.clean();
tft.setForeground(conv::c32to16(0x00FF00));
puts(" *Welcome to use*");
puts("");
puts(" ***Group O***");
puts(" **Smart Talk**");
tft.setZoom(1);
puts("supported by OOS(Oblivion OS) version 1.0.0");
puts("press any key to continue....");
}
void main_menu (void)
{
tft.setBackground(conv::c32to16(0xFFFFFF)); //main menu gui part
tft.setForeground(0x0000);
tft.clean();
tft.setZoom(2);
uint8_t i = 0;
uint32_t rec_c[] = {0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, 0x123456, 0x654321, 0x765432, 0xFEDCBA};
uint16_t rec_p[2] = {0,0};
uint16_t rec_width = tft.width() / (NUM_MENU / 2);
uint16_t rec_height = tft.height() / 2;
uint16_t text_p[2] = {(rec_width - 5*FONT_WIDTH * tft.zoom())/2, rec_height/2}; //calculate the rectangle position and size, and the position of the words
do{ //draw the rectangle
for(uint8_t j = 0;j < NUM_MENU / 2; j++)
{
tft.rectangle(rec_p[0], rec_p[1], rec_width, rec_height, conv::c32to16(rec_c[i]));
tft.setXY(rec_p[0] + text_p[0], rec_p[1] + text_p[1]);
tft.setBackground(conv::c32to16(rec_c[i]));
printf("%u",i+1);
tft.setXY(rec_p[0] + text_p[0], rec_p[1] + text_p[1] + FONT_HEIGHT * tft.zoom());
puts(menu[i]);
rec_p[0] += rec_width;
i++;
}
rec_p[0] = 0;
rec_p[1] += rec_height;
}while(i < NUM_MENU);
while(keypad::scan() == (uint8_t) - 1) //if get message, just goto display the messages
{
i = detect();
if(i == 1)
{
while(keypad::scan() != 11);
break;
}
}
return;
}
void text(void)
{
tft.setBackground(conv::c32to16(0xFFFFFF));
tft.clean();
tft.setZoom(2);
tft.setForeground(conv::c32to16(0x00FF00));
puts("***Enter the message***");
puts("***********************");
tft.setForeground(conv::c32to16(0x000000));
tft.setZoom(2);
while(1){
uint8_t tem = keypad::scan(); //follwoing founction will be explained in keypad.cpp
if(tem != -1)
{
if(tem == 3)
{
keypad::send(str);
for(uint16_t k = 0; k < p; k++)
str[k] = '\0';
p = 0;
}
else if(tem == 7)
keypad::del(str, &p);
else if(tem == 11)
return;
else if(tem == 14)
keypad::buzzer();
else if(tem < 3)
keypad::num(tem + 1, 1, &p, str);
else if (tem >=4 && tem < 7)
keypad::num(tem, 0, &p, str);
else if (tem >=8 && tem < 11)
keypad::num(tem - 1, -1, &p, str);
else if(tem == 13)
keypad::num(0, -13, &p, str);
else if(tem == 12)
keypad::pre_rec(str, &p);
}
}
}
void read(void)
{
tft.clean();
tft.setZoom(3);
puts("read message!");
}
void play(void)
{
tft.clean();
tft.setZoom(3);
puts("Choose file to play");
}
void help(void) //help founction, keys description
{
h_menu: tft.clean();
tft.setZoom(3);
puts("***Welcome to Use***");
tft.setZoom(2);
puts("The document helps users to use the device:");
puts("press the number on the menu to enter the help document for specific function:");
puts("1: send function");
puts("2: read function");
puts("3: play function");
puts("4: sync function");
puts("5: about function");
while(keypad::scan() == (uint8_t)-1);
rescan: uint8_t help_s = keypad::scan();
switch(help_s)
{
case 0:
tft.clean();
puts("key description in send");
puts("1: , . 1 - +");
puts("2: a b c 2 A");
puts("3: d e f 3 B");
puts("4: g h i 4 C");
puts("5: j k l 5 D");
puts("6: m n o 6 E");
puts("7: p q r s 7");
puts("8: t u v 8 O");
puts("9: w x y z 9");
puts("0: 0 ! L +");
puts("press 1 go to the next page");
while(keypad::scan() != 0);
tft.clean();
puts("A: pre recoded message");
puts("B: Buzzer");
puts("C: Push to talk");
puts("D: go back to main menu");
puts("E: back space");
puts("F: send messages");
puts("press D go back to the help menu");
while(keypad::scan() != 11);
goto h_menu;
case 1:
tft.clean();
puts("key description in read");
puts("press D go back to the help menu");
while(keypad::scan() != 11);
goto h_menu;
case 2:
tft.clean();
tft.setZoom(3);
puts("key description in play");
puts("press D go back to the help menu");
while(keypad::scan() != 11);
goto h_menu;
case 4:
tft.clean();
tft.setZoom(3);
puts("key description in ***");
puts("press D go back to the help menu");
while(keypad::scan() != 11);
goto h_menu;
case 5:
tft.clean();
tft.setZoom(3);
puts("key description in about");
tft.setZoom(2);
puts("the device is build by group O");
puts("press D go back to the help menu");
while(keypad::scan() != 11);
goto h_menu;
case 11:
return;
default:
goto rescan;
}
}
void sync(void)
{
tft.clean();
tft.setZoom(2);
puts("the device sync function");
puts("press 1 sync");
puts("press 2 to choose freq");
re_sync: while(keypad::scan() == (uint8_t)-1);
uint8_t tem = keypad::scan();
switch(tem)
{
case 0:
{
puts("wait the device until see the commend");
uint8_t tv[] = "connected, press D go back";
tft.clean();
while(keypad::scan() != 11)
{
if (rfm12_rx_status() == STATUS_COMPLETE)
{
bufptr = rfm12_rx_buffer(); //get the address of the current rx buffer
// dump buffer contents to uart
for (uint8_t i=0;i<rfm12_rx_len();i++)
{
putchar(bufptr[i]);
}
// puts("\"\r\n");
// tell the implementation that the buffer
// can be reused for the next data.
rfm12_rx_clear();
}
puts(".");
// printf("%d", sizeof(tv));
rfm12_tx (sizeof(tv), 0, tv);
// }
//rfm12 needs to be called from your main loop periodically.
//it checks if the rf channel is free (no one else transmitting), and then
//sends packets, that have been queued by rfm12_tx above.
rfm12_tick();
_delay_ms(1000); //small delay so loop doesn't run as fast
}
return;
}
case 1:
{
puts("press a number to choose a frequency band");
while(keypad::scan() == (uint8_t)-1);
uint8_t freq = keypad::scan();
while(keypad::scan() == freq);
switch(freq)
{
case 13:
rfm12_livectrl(RFM12_LIVECTRL_FREQUENCY, freq0);
puts("carrier frequency 0 selected");
goto end;
case 0:
rfm12_livectrl(RFM12_LIVECTRL_FREQUENCY, freq1);
puts("carrier frequency 1 selected");
goto end;
case 1:
rfm12_livectrl(RFM12_LIVECTRL_FREQUENCY, freq2);
puts("carrier frequency 2 selected");
goto end;
case 2:
rfm12_livectrl(RFM12_LIVECTRL_FREQUENCY, freq3);
puts("carrier frequency 3 selected");
goto end;
case 4:
rfm12_livectrl(RFM12_LIVECTRL_FREQUENCY, freq4);
puts("carrier frequency 4 selected");
goto end;
case 5:
rfm12_livectrl(RFM12_LIVECTRL_FREQUENCY, freq5);
puts("carrier frequency 5 selected");
goto end;
case 6:
rfm12_livectrl(RFM12_LIVECTRL_FREQUENCY, freq6);
puts("carrier frequency 6 selected");
goto end;
case 8:
rfm12_livectrl(RFM12_LIVECTRL_FREQUENCY, freq7);
puts("carrier frequency 7 selected");
goto end;
case 9:
rfm12_livectrl(RFM12_LIVECTRL_FREQUENCY, freq8);
puts("carrier frequency 8 selected");
goto end;
case 10:
rfm12_livectrl(RFM12_LIVECTRL_FREQUENCY, freq9);
puts("carrier frequency 9 selected");
goto end;
}
end: puts("press D go back");
while(keypad::scan() != 11);
goto re_sync;
}
case 11:
return;
default:
goto re_sync;
}
}
void about(void)
{
tft.clean();
tft.setZoom(3);
puts("key description in about");
tft.setZoom(2);
puts("the device is build by group O");
puts("press D go back to the help menu");
// while(keypad::scan() != 11);
}
uint8_t detect(void)
{
if (rfm12_rx_status() == STATUS_COMPLETE)
{
tft.clean();
PORTB |= _BV(3);
bufptr = rfm12_rx_buffer(); //get the address of the current rx buffer
// dump buffer contents to uart
uint8_t decrypted_data;
for (uint16_t i=0;i<rfm12_rx_len();i++)
{
/**********************************************************DECRYPTION************************************************/
decrypted_data = decrypt(bufptr[i], i);
putchar(decrypted_data);
/*******************************************************************************************************************/
}
//puts("\"\r\n");
puts(" ");
puts("press D go back");
// tell the implementation that the buffer
// can be reused for the next data.
rfm12_rx_clear();
_delay_ms(500);
PORTB &= ~_BV(3);
return 1;
}
return 0;
}
void password(void)
{
re_pas: char password[20] = {"a"};
text_password();
int wow = strcmp(password, str);
if(!wow)
{
for(uint16_t k = 0; k < p; k++)
str[k] = '\0';
p = 0;
return;
}
else
{
for(uint16_t k = 0; k < p; k++)
str[k] = '\0';
p = 0;
puts("the password is wrong, press D to go back and re-enter the password");
while(keypad::scan() != 11);
goto re_pas;
}
}
void text_password(void)
{
//uint8_t p;
tft.setBackground(conv::c32to16(0xFFFFFF));
tft.clean();
tft.setZoom(2);
tft.setForeground(conv::c32to16(0x00FF00));
puts("***Enter the password, and press F to confirm***");
puts("***********************");
tft.setForeground(conv::c32to16(0x000000));
tft.setZoom(2);
while(1){
uint8_t tem = keypad::scan();
if(tem != -1)
{
if(tem == 3)
return;
else if(tem == 7)
keypad::del(str, &p);
else if(tem < 3)
keypad::num(tem + 1, 1, &p, str);
else if (tem >=4 && tem < 7)
keypad::num(tem, 0, &p, str);
else if (tem >=8 && tem < 11)
keypad::num(tem - 1, -1, &p, str);
else if(tem == 13)
keypad::num(0, -13, &p, str);
}
// printf ("%d\n",tem);
}
}
void talk(void)
{
while(keypad::scan() == 15)
{
PORTB &= ~_BV(0);
}
PORTB |= _BV(0);
}
void test_tft(void) //for testing the TFT
{
tft.clean();
tft.setZoom(1);
puts("*** TFT library testing ***");
puts("STDOUT output, orientation, FG/BG colour, BG light");
tft.setZoom(3);
puts("Font size test");
tft.setZoom(1);
tft.setXY(300, 38);
puts("Change text position & word warp test");
tft.frame(115, 56, 200, 10, 2, 0xF800);
puts("Draw frame test");
tft.rectangle(118, 68, 180, 6, 0x07E0);
puts("Draw rectangle test");
tft.point(120, 76, 0x001F);
tft.point(122, 76, 0x001F);
tft.point(124, 76, 0x001F);
tft.point(126, 76, 0x001F);
tft.point(128, 76, 0x001F);
tft.point(130, 76, 0x001F);
puts("Draw points test");
tft.line(200, 100, 300, 200, 0xF800);
tft.line(300, 210, 200, 110, 0x001F);
tft.line(200, 200, 300, 100, 0xF800);
tft.line(300, 110, 200, 210, 0x001F);
tft.line(100, 100, 300, 200, 0xF800);
tft.line(300, 210, 100, 110, 0x001F);
tft.line(100, 200, 300, 100, 0xF800);
tft.line(300, 110, 100, 210, 0x001F);
tft.line(200, 0, 300, 200, 0xF800);
tft.line(300, 210, 200, 10, 0x001F);
tft.line(200, 200, 300, 0, 0xF800);
tft.line(300, 10, 200, 210, 0x001F);
tft.line(100, 150, 300, 150, 0xF800);
tft.line(300, 160, 100, 160, 0x001F);
tft.line(250, 0, 250, 200, 0xF800);
tft.line(260, 200, 260, 0, 0x001F);
puts("Draw lines test");
}
uint8_t decrypt(uint8_t var, int key_no)
{
uint8_t key[3] = {0x36, 0x5A, 0xEB};
return var ^ key[key_no % 3];
}
| [
"huw.percival@btinternet.com"
] | huw.percival@btinternet.com |
44df1295457d558b70df323f98bcea20a5ef27aa | cb5c6d9dd01a938db01c4b29f11c8d0aceec17ec | /ParticleEmitter/stdafx.h | 6ffc896c4d42074e66519a9512cd3c6b6cbf1a96 | [] | no_license | fofo2313/ParticleEmitter | 69d3e56ada286e1b4b287560f03f7cc48d94eb08 | 30e66e9767447c33b55d61f2eab3c6b6f860eb97 | refs/heads/master | 2020-12-14T08:42:36.365628 | 2020-01-18T06:04:11 | 2020-01-18T06:04:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,272 | h | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently.
#pragma once
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers.
#endif
#include <windows.h>
#include <dxgi1_4.h>
#include <D3Dcompiler.h>
#include <DirectXMath.h>
#include "d3dx12.h"
// C RunTime Header Files
#include <iostream>
#include <sstream>
#include <fstream>
#include <codecvt>
#include <iomanip>
#include <algorithm>
#include <string>
#include <vector>
#include <unordered_map>
#include <functional>
#include <wrl.h>
#include <shellapi.h>
#if defined(DEBUG) | defined(_DEBUG)
#ifndef DBG_NEW
#define DBG_NEW new (_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DBG_NEW
#endif
#endif // _DEBUG
| [
"TianchenX@outlook.com"
] | TianchenX@outlook.com |
20f0ce944c6de49fefbbf5b4ce8449b7c6e57647 | d6723b2e1547d1eddd5a120c8fa4edbf4cddbacb | /silkopter/gs/src/stream_viewers/Video_Stream_Viewer_Widget.h | 0b3b7d0eac5163d1cf16ef484589e7d0be4ef25f | [
"BSD-3-Clause"
] | permissive | gonzodepedro/silkopter | 2d16e10bd46affe4ca319e3db3f7dbc54283ca23 | cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8 | refs/heads/master | 2022-01-04T20:46:51.893287 | 2019-01-07T22:43:40 | 2019-01-07T22:43:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 830 | h | #pragma once
#include "IStream_Viewer_Widget.h"
#include "video/Video_Decoder.h"
#include "boost/signals2.hpp"
#include <QPainter>
namespace silk
{
class Comms;
}
class Video_Stream_Viewer_Widget : public IStream_Viewer_Widget
{
public:
Video_Stream_Viewer_Widget(QWidget* parent);
~Video_Stream_Viewer_Widget();
void init(silk::Comms& comms, std::string const& stream_path, uint32_t stream_rate, silk::stream::Type stream_type) override;
private:
void paintEvent(QPaintEvent* ev);
silk::Comms* m_comms = nullptr;
std::string m_stream_path;
uint32_t m_stream_rate;
silk::stream::Type m_stream_type;
boost::signals2::scoped_connection m_connection;
Video_Decoder m_decoder;
QPainter m_painter;
QImage m_image;
QImage m_image_flipped;
std::vector<uint8_t> m_data;
};
| [
"catalin.vasile@gmail.com"
] | catalin.vasile@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.