blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f83135122b269e9d883233ef8f9a9fbe1b44efde | 898c114cfe33dfbc6410c1bd793b47e079d0596a | /lab3/smarttree/SmartTree.cpp | 65f96997f4848e4ad92802a0bd848a6547d75180 | [] | no_license | piowik/jimp | 284c7dae1443015d2fa71a4c472feb5923d03509 | 22a7a7e9435dbf884d501502325c1508ef4741bf | refs/heads/master | 2021-01-19T04:19:59.196309 | 2017-06-21T15:42:33 | 2017-06-21T15:42:33 | 84,430,676 | 0 | 0 | null | 2017-06-21T15:42:34 | 2017-03-09T10:43:16 | C++ | UTF-8 | C++ | false | false | 4,980 | cpp | SmartTree.cpp | //
// Created by Piotrek on 19.03.2017.
//
#include <ostream>
#include <memory>
#include <sstream>
#include <regex>
#include <cmath>
#include <iostream>
#include "SmartTree.h"
using std::unique_ptr;
using std::make_unique;
using std::string;
namespace datastructures {
unique_ptr<SmartTree> CreateLeaf(int value) {
unique_ptr<SmartTree> leaf = make_unique<SmartTree>();
leaf->left = nullptr;
leaf->right = nullptr;
leaf->value = value;
return leaf;
}
unique_ptr<SmartTree> InsertLeftChild(unique_ptr<SmartTree> tree, unique_ptr<SmartTree> left_subtree) {
tree->left = move(left_subtree);
return tree;
}
unique_ptr<SmartTree> InsertRightChild(unique_ptr<SmartTree> tree, unique_ptr<SmartTree> right_subtree) {
tree->right = move(right_subtree);
return tree;
}
void PrintTreeInOrder(const unique_ptr<SmartTree> &unique_ptr, std::ostream *out) {
if (unique_ptr->left != nullptr)
PrintTreeInOrder(unique_ptr->left, out);
*out << unique_ptr->value << ", ";
if (unique_ptr->right != nullptr)
PrintTreeInOrder(unique_ptr->right, out);
}
string DumpTree(const unique_ptr<SmartTree> &tree) {
if (tree == nullptr)
return "[none]";
std::stringstream ret;
ret << "[";
ret << tree->value;
ret << " " + DumpTree(tree->left);
ret << " " + DumpTree(tree->right);
ret << "]";
return ret.str();
}
std::size_t FindCharInString(string str, char wantedChar, std::size_t startingPos = 0) {
std::size_t foundPosition = str.find(wantedChar, startingPos);
if (foundPosition != std::string::npos)
return foundPosition;
else
foundPosition = 1;
return foundPosition;
}
unique_ptr<SmartTree> RestoreTree(const string &tree) {
if (tree == "[none]")
return nullptr;
unique_ptr<SmartTree> root = nullptr;
std::size_t currentIndex = 0;
int depth = 0;
string path = "";
int depthIterator = 0;
bool leftNow = true;
while (currentIndex < tree.length() - 1) {
std::size_t openingPos = FindCharInString(tree, '[', currentIndex);
if (openingPos == -1) // done
break;
std::size_t closingPos = FindCharInString(tree, ']', currentIndex);
if (openingPos < closingPos) {
currentIndex = openingPos + 1;
} else if (openingPos > closingPos) {
depthIterator++;
if (depthIterator == 2) { // 2x none
depth--;
depthIterator = 0;
}
currentIndex = closingPos + 1;
}
char chAt = tree.at(currentIndex);
while (chAt == '[' || chAt == ']' || chAt == ' ') { // rare, skip to next digit/none
currentIndex++;
chAt = tree.at(currentIndex);
if (chAt == ']')
depth--;
}
std::size_t spacePos = FindCharInString(tree, ' ', currentIndex);
std::size_t closingPPos = FindCharInString(tree, ']', currentIndex);
if (closingPPos < spacePos) { // none
leftNow = false;
currentIndex += 4;
} else {
int wart = stoi(tree.substr(currentIndex, spacePos));
depth += 1;
if ((path.length() == 1) && (depth == 1))
path = "";
else
path = path.substr(0, depth - 2);
if (root == nullptr) {
root = CreateLeaf(wart);
leftNow = true;
} else {
if (leftNow) {
if (path.length() > 0) {
if (path.at(0) == 'L')
root->left = InsertLeftChild(move(root->left), CreateLeaf(wart));
else
root->right = InsertLeftChild(move(root->right), CreateLeaf(wart));
} else
root = InsertLeftChild(move(root), CreateLeaf(wart));
path += "L";
} else {
leftNow = true;
if (path.length() > 0) {
if (path.at(0) == 'L')
root->left = InsertRightChild(move(root->left), CreateLeaf(wart));
else
root->right = InsertRightChild(move(root->right), CreateLeaf(wart));
} else
root = InsertRightChild(move(root), CreateLeaf(wart));
path += "R";
}
}
}
}
return root;
}
}
|
db1ae7b95b573f2a178dbc32bbebe45d3796588a | e70ca0649b25acd73005f0b6c8e96c20025dd02b | /LSM303DLH.h | e9e9d125d7aba0a61e17449073c2a4ae713d9ea2 | [] | no_license | benoitclem/PYRN | 0f3a0ce850e27c79c22869b9b63845666eeac95c | bfe6a16b92d996c51b1ad8518dffece6a3cbf508 | refs/heads/master | 2020-05-30T22:11:27.060481 | 2016-07-29T14:47:40 | 2016-07-29T14:47:40 | 38,675,414 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,864 | h | LSM303DLH.h | #ifndef __LSM303DLH_H
#define __LSM303DLH_H
#include "mbed.h"
// CONSTS
#define WRITE_BUFF_MAX 16
#define LSM303DH_ID 0x49
// I2C Addresses (SAO -> 1)
#define LSM303D_ADDR_R 0x3B
#define LSM303D_ADDR_W 0x3A
// REGISTERS
#define LSM303D_CTRL0 0x1F
#define LSM303D_CTRL1 0x20
#define LSM303D_CTRL2 0x21
#define LSM303D_CTRL3 0x22
#define LSM303D_CTRL4 0x23
#define LSM303D_CTRL5 0x24
#define LSM303D_CTRL6 0x25
#define LSM303D_CTRL7 0x26
#define LSM303D_WHO_AM_I 0x0F
#define LSM303D_TEMP_OUT_L 0x05
#define LSM303D_TEMP_OUT_H 0x06
#define LSM303D_STATUS_M 0x07
#define LSM303D_OUT_X_L_M 0x08
#define LSM303D_OUT_X_H_M 0x09
#define LSM303D_OUT_Y_L_M 0x0A
#define LSM303D_OUT_Y_H_M 0x0B
#define LSM303D_OUT_Z_L_M 0x0C
#define LSM303D_OUT_Z_H_M 0x0D
#define LSM303D_STATUS_A 0x27
#define LSM303D_OUT_X_L_A 0x28
#define LSM303D_OUT_X_H_A 0x29
#define LSM303D_OUT_Y_L_A 0x2A
#define LSM303D_OUT_Y_H_A 0x2B
#define LSM303D_OUT_Z_L_A 0x2C
#define LSM303D_OUT_Z_H_A 0x2D
class LSM303DLH {
private:
float accLSB;
float magLSB;
I2C *dev;
uint8_t dataBuff[WRITE_BUFF_MAX]; // Who read more than WRITE_BUFF_MAX(16)?
uint8_t devRead(const uint8_t reg, uint8_t *data, uint8_t size);
uint8_t devReadSingle(const uint8_t reg, uint8_t byte);
uint8_t devWrite(const uint8_t reg, uint8_t *data, uint8_t size);
uint8_t devWriteSingle(const uint8_t reg, uint8_t byte);
public:
LSM303DLH(I2C *i2cDevice);
void basicConfig(void);
void readRawAcc(int16_t *x, int16_t *y, int16_t *z);
void readRawMag(int16_t *x, int16_t *y, int16_t *z);
void readAcc(float *x, float *y, float *z);
void readMag(float *x, float *y, float *z);
};
#endif |
564bf1fb5ecdc0d6f09245a169e663935225a696 | 3e31dd6650704888458b8b26ae7812de4313164f | /examples/555example/example.cpp | f09e68e44f184c7c7b85c423f5eab74327e1d03b | [] | no_license | hippymulehead/RA595 | 547c2e147ab7f19be846a3fe9d9efba18d529d2d | f9ec24bf0e6fd14015ca0c3f0a5cd8601abde3a9 | refs/heads/master | 2021-09-11T09:57:01.453614 | 2018-04-06T17:23:07 | 2018-04-06T17:23:07 | 103,848,902 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,981 | cpp | example.cpp | #include <Arduino.h>
#include <RA595.h>
/*
Demo of the RA595 lib from Romans Audio
Show off some of the simple things that you can do with a shift register
using the lib.
The hardware is set up with an LED and a 220 off each output. The rest of
the 595 is set up as you would expect.
*/
// Setup your object
// RA595(int latchPin, int clockPin, int dataPin);
RA595 demoReg(10,11,12);
// Make a counter
unsigned long counter = 0;
void setup() {
// Set the 0 bit high
demoReg.allOff();
demoReg.setBit(0,1);
demoReg.write();
// Set A6 as the pin to read from for a random seed
demoReg.setRandomReadPin(A6);
}
void loop() {
for(int i = 0; i < 100; i++) {
demoReg.wrapRight(1);
demoReg.write();
delay(100);
}
// wrapRight()
for(int i = 0; i < 100; i++) {
demoReg.wrapLeft(1);
demoReg.write();
delay(100);
}
for(int i = 0; i < 10; i++) {
for(int x = 0; x < 7; x++) {
demoReg.wrapRight(1);
demoReg.write();
delay(100);
}
for(int x = 0; x < 7; x++) {
demoReg.wrapLeft(1);
demoReg.write();
delay(100);
}
}
// allOn()
demoReg.allOn();
demoReg.write();
delay(700);
// allOff()
demoReg.allOff();
demoReg.write();
// setRandomBit()
for(size_t i = 0; i < 100; i++) {
demoReg.setRandomBit();
demoReg.write();
delay(100);
}
demoReg.allOff();
// setBit()
demoReg.setBit(0,1);
demoReg.setBit(2,1);
demoReg.setBit(4,1);
demoReg.setBit(6,1);
demoReg.write();
for(int i = 0; i < 100; i++) {
demoReg.wrapRight(1);
demoReg.write();
delay(100);
}
for(int i = 0; i < 100; i++) {
demoReg.wrapLeft(1);
demoReg.write();
delay(100);
}
// Reset for the loop to start over
demoReg.allOff();
demoReg.setBit(0,1);
demoReg.write();
}
|
4867b214c70ffb7cd2e18011d38259319b9eed15 | c4fea6f4c353c91df780354936a17fae4c5501c2 | /CH2_BinaryTree/BinarySearchTree/BinarySearchTree.cpp | cf7b10e4bc9cc644758410ce6a2137cd56079f6a | [] | no_license | selfsongs/Data-Structures-And-Algorithm | fb561bc21812739217cef7fa7934dd8cd69865cc | 6fd36b32de04714f44f03f455cca9651791e53d4 | refs/heads/master | 2020-04-28T22:08:49.821463 | 2019-05-10T13:08:56 | 2019-05-10T13:08:56 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,350 | cpp | BinarySearchTree.cpp | //BinarySearchTree
//查找:尾递归方式 ,效率不高
Position Find(ElementType X,BinTree BST)
{
if(!BST) return NULL;//空树,返回NULL
if(X>BST->Data)
return Find(X,BST->Right);//在右子树上查找
else if(X<BST->Data)
return Find(X,BST->Left);//在左子树上查找
else
return BST;//查找成功,返回节点的地址
}
//查找:非递归函数实现,采用迭代的方式,效率比递归方式好
Position IterFind(ElementType X,BinTree BST)
{
while(BST){
if(X>BST->Data)
BST=BST->Right;
else if(X<BST->Data)
BST=BST->Left;
else
return BST;
}
return NULL;//查找失败
}
//递归查找最小值,返回其地址
Position FindMin(BinTree BST)
{
if(!BST)
return NULL;
else if(!BST->Left)
return BST;
else
return FindMin(BST->Left);
}
//迭代查找最大值,返回其地址
Position FindMax(BinTree BST)
{
if(BST)
while(BST->Right)
BST=BST->Right;
return BST;
}
// 插入:递归方式
BinTree Insert(ElementType X,BinTree BST)
{
if(!BST){
//若原树为空,生成并返回一个结点的二叉搜索树
BST=malloc(sizeof(struct TreeNode));
BST->Data=X;
BST->Left=BST->Right=NULL;
}else{//开始找要插入元素的位置
if(X<BST->Data)
BST->Left=Insert(X,BST->Left);//递归插入左子树
else if(X>BST->Data)
BST->Right=Insert(X,BST->Right);//递归插入右子树
}
return BST;
}
//删除:
BinTree Delete(ElementType X,BinTree BST)
{
Position Tmp;
if(!BST)
printf("要删除的元素未找到");
else{
if(X<BST->Data)
BST->Left=Delete(X,BST->Left);//左子树递归删除
else if(X>BST->Data)
BST->Right=Delete(X,BST->Right);//右子树递归删除
else{//找到要删除的结点
if(BST->Left&&BST->Right){//被删除结点有左右两个子结点
Tmp=FindMin(BST->Right);//在右子树中找最小的元素填充删除结点
BST->Data=Tmp->Data;
BST->Right=Delete(BST->Data,BST->Right);
}else{//被删除结点有一个或无子结点
Tmp=BST;
if(!BST->Left)//有右孩子或无子结点
BST=BST->Right;
else if(!BST->Right)//有左孩子或无子结点
BST=BST->Left;
free(Tmp);
}
}
}
return BST;
}
|
8997a57b49b906fa62dcabe0870c9f66fa61caa2 | 3166d800f87fc8e020ae65c638fe3d86b7b0b792 | /apprepo/i-team-video_segment/video_framework/video_pool.h | 5f76209b44b242a67f40f9627a675e2359932f9d | [] | no_license | TTgogogo/Android-App-Profiling | b8fe745980a1b50037075fa71bd15daa9e9a185a | 4dc615839f67da092c3d9e3100f4bed2a1fb9b69 | refs/heads/master | 2021-01-14T13:06:18.219317 | 2012-12-09T04:10:34 | 2012-12-09T04:10:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,289 | h | video_pool.h | /*
* video_pool.h
* video_framework
*
* Created by Matthias Grundmann on 9/20/10.
* Copyright 2010 Matthias Grundmann. All rights reserved.
*
*/
#ifndef VIDEO_POOL_H__
#define VIDEO_POOL_H__
#include "video_unit.h"
namespace VideoFramework {
// Joins several VideoUnits as input, by buffering incoming frames until input sources are
// exhausted and calls processing functions on the pool of frames.
// It acts as a sink for multiple incoming units, does joint processing of all frames and
// act as new output source.
// Derive implementation units from it, implementing OpenPoolStreams and ProcessAllPoolFrames.
// TODO: Reject all feedback streams for this unit! Implement if needed.
class VideoPool : public VideoUnit {
public:
VideoPool() : num_input_units_(0) {
}
// Interface to for deriving classes.
typedef vector< vector<FrameSetPtr> > FrameSetPtrPool;
virtual void OpenPoolStreams(const vector<StreamSet>& stream_sets) = 0;
virtual void ProcessAllPoolFrames(const FrameSetPtrPool& frame_sets) = 0;
// Same as for VideoUnit but renamed to act additionally as root.
// Invoked after OpenPoolStreams.
virtual bool OpenRootStream(StreamSet* set) {
return true;
}
virtual void RootPostProcess(list<FrameSetPtr>* append) { }
virtual bool OpenStreamsFromSender(StreamSet* set, const VideoUnit* sender);
virtual void ProcessFrameFromSender(FrameSetPtr input,
list<FrameSetPtr>* output,
const VideoUnit* sender);
virtual void PostProcessFromSender(list<FrameSetPtr>* append, const VideoUnit* sender);
int InputUnits() const { return num_input_units_; }
protected:
// Overrides default behavior, does not open streams for children, as it acts as a sink.
virtual bool OpenStreamsImpl(StreamSet* set, const VideoUnit* sender);
virtual void PostProcessImpl(const VideoUnit* sender);
// Use if you don't want to buffer output in ProcessAllPoolFrames in output on
// RootPostProcess but push output immediately to children.
virtual void ImmediatePushToChildren(list<FrameSetPtr>* append);
private:
// Maps sender pointer to index in StreamSet via the map declared below.
// Resizes vectors for StreamSet and FrameSets accordingly.
int SenderToId(const VideoUnit* sender, bool dont_insert);
// Returns true if input_unit_exhausted_ is set to true for all indices.
bool AllInputsExhausted() const;
vector<const VideoUnit*> video_unit_map_;
int num_input_units_;
protected:
vector<StreamSet> stream_sets_;
vector< vector<FrameSetPtr> > frame_sets_;
vector<bool> input_unit_exhausted_;
};
// Can act as root unit for several input units, e.g. if a VideoPool is present in a
// Filter tree.
class MultiSource {
public:
// Specifies how frames are fetched.
enum PullMethod {
ROUND_ROBIN, // One frame at a time from each unit
DRAIN_SOURCE // Process all frames from one unit until it is drained, then go
}; // to next one.
MultiSource(PullMethod pull_method) : pull_method_(pull_method) {
}
void AddSource(VideoUnit* unit);
bool Run();
private:
bool pull_method_;
vector<VideoUnit*> root_units_;
};
}
#endif // VIDEO_POOL_H__ |
f56474e5f6a3983d076dbe0b878aae2a2952c8f1 | 4e8e126344d3aa5fbde7b0c477e43faac8949794 | /build/custom_msg/rosidl_generator_cpp/custom_msg/msg/num__traits.hpp | 4b86d20fb794dbc011506fa15abf9273c7cbdd56 | [] | no_license | Vishnu-Vijay95/Ros2_ws | 0f8c84900b8e61fba7d638a04d7a0315ca7a78c3 | 27e60ad06eae5e7dc9609f9c4178e26b4f22d4dc | refs/heads/main | 2023-01-14T16:05:27.901287 | 2020-11-25T05:13:09 | 2020-11-25T05:13:09 | 315,832,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 804 | hpp | num__traits.hpp | // generated from rosidl_generator_cpp/resource/idl__traits.hpp.em
// with input from custom_msg:msg/Num.idl
// generated code does not contain a copyright notice
#ifndef CUSTOM_MSG__MSG__NUM__TRAITS_HPP_
#define CUSTOM_MSG__MSG__NUM__TRAITS_HPP_
#include "custom_msg/msg/num__struct.hpp"
#include <rosidl_generator_cpp/traits.hpp>
#include <stdint.h>
#include <type_traits>
namespace rosidl_generator_traits
{
template<>
inline const char * data_type<custom_msg::msg::Num>()
{
return "custom_msg::msg::Num";
}
template<>
struct has_fixed_size<custom_msg::msg::Num>
: std::integral_constant<bool, true> {};
template<>
struct has_bounded_size<custom_msg::msg::Num>
: std::integral_constant<bool, true> {};
} // namespace rosidl_generator_traits
#endif // CUSTOM_MSG__MSG__NUM__TRAITS_HPP_
|
deeeaac877203dc7a3e0cbd7e7e39d4add101091 | e6237bdc6e7ef92fbdcd8c0b0e9ea48201ceed81 | /C++/Day16/Zones/main.cpp | 5cbd509d734bf8d7abd30ba7ceb448706a8ccf78 | [] | no_license | Epaggelia/VGD_Personal | 45ac91c4f2c8bd34d07641eda987856be01b90b5 | 9809014c62ad5cd257d2913805868daaf64b2118 | refs/heads/master | 2020-05-21T21:03:27.025592 | 2016-10-28T02:39:50 | 2016-10-28T02:39:50 | 64,180,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,823 | cpp | main.cpp | #include <iostream>
#include "zoneType.h"
#include "worldType.h"
using std::cout;
using std::endl;
using std::cin;
void buildWorld(WorldType& world);
void changePosition(ZoneType::DIRECTIONS whichway, WorldType& world);
int main()
{
WorldType dungeon;
buildWorld (dungeon);
char choice = 'q';
do
{
cout << endl << dungeon.showCurrentZone() << endl << endl;
cout << "which way would you like to go? ";
cin >> choice;
switch (choice)
{
case 'n':
case 'N':
changePosition(ZoneType::NORTH, dungeon);
break;
case 'e':
case 'E':
changePosition(ZoneType::EAST, dungeon);
break;
case 's':
case 'S':
changePosition(ZoneType::SOUTH, dungeon);
break;
case 'w':
case 'W':
changePosition(ZoneType::WEST, dungeon);
break;
}
} while (choice!= 'q');
return 0;
}
void buildWorld(WorldType& world)
{
world.addZone("GROOM", new ZoneType("A gaurd room."));
world.addZone("HALL", new ZoneType("A dark hallway."));
world.addZone("DEND", new ZoneType("A dead end. It looks like a storage room."));
world.addZone("CELL", new ZoneType("A dirty cell."));
world.addZone("COURTYARD", new ZoneType("A courtyard."));
world["CELL"]->setExit(ZoneType::NORTH, world["HALL"]);
world["HALL"]->setExit(ZoneType::SOUTH, world["CELL"]);
world["HALL"]->setExit(ZoneType::EAST, world["DEND"]);
world["HALL"]->setExit(ZoneType::WEST, world["GROOM"]);
world["DEND"]->setExit(ZoneType::WEST, world["HALL"]);
world["GROOM"]->setExit(ZoneType::EAST, world["HALL"]);
world["GROOM"]->setExit(ZoneType::WEST, world["COURTYARD"]);
world["COURTYARD"]->setExit(ZoneType::EAST, world["GROOM"]);
world.setPosition(world["CELL"]);
}
void changePosition(ZoneType::DIRECTIONS whichWay, WorldType& world)
{
if (world.move(whichWay) == false)
{
cout << "You can't go that way!" << endl;
}
}
|
703946d499e762c365ef6272b4c4f56b8a3ba731 | 02365b900afa3d9c8e0d10881916329e5aed13a6 | /merkle.h | ea4459e18521d94981208f0b18ad2082aac67b31 | [] | no_license | hypoactiv/pdp | 6ae8963022950e351df035a9ee85486bcf458bb9 | b6a1c491ca82925428d8689b0772f5a7b7909960 | refs/heads/master | 2021-08-07T11:51:01.958574 | 2017-11-08T03:58:04 | 2017-11-08T03:58:04 | 109,918,341 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,414 | h | merkle.h | #ifndef MERKLE_H
#define MERKLE_H
#include "SdFat.h"
#include "message.h"
#include "usha256.h"
namespace PDP {
typedef enum {
MERKLE_HASH_KNOWN = (1 << 0),
MERKLE_CHUNK_COMPLETE = (1 << 1),
} MerkleBlockFlags_t;
class MerkleFile {
public:
MerkleFile();
// Opens merkleFilename.
//
// If merkleFilename exists, its rootHash is compared to HashChainMessage. If
// they do not match Error is set to ERROR_MERKLE_ROOT_MISMATCH
//
// If merkleFilename does not exist, creates a blank merkle file from
// HashChainMessage
void Open(FatFileSystem &fs, const char *merkleFilename,
HashChainMessage &msg);
// Opens merkleFilename.
//
// If merkleFilename does not exist, or has invalid header, creates it from
// the data in FatFile
void Open(FatFileSystem &fs, const char *merkleFilename, FatFile &src);
void ReadHashBlock(uint16_t n);
void WriteHashBlock(
uint16_t n); // TODO private? only expose Save(HashChainMessage&)
void ReadHeaderBlock();
void ReadRootHashBlock();
bool HashKnown(uint16_t chunk);
void SetHash(uint16_t chunk, uint8_t *hash);
bool ChunkComplete(uint16_t chunk);
void SetChunkComplete(uint16_t chunk);
// load the hash chain for the specified chunk into 'msg'
void Load(HashChainMessage &msg, uint16_t chunk);
// save the hash chain specified in 'msg'
void Save(HashChainMessage &msg);
// verify msg is a valid hash chain
bool Verify(HashChainMessage &msg);
// verify msg is a valid chunk. returns false if the correct hash for this
// chunk is not yet known.
bool Verify(DataChunkMessage &msg);
// Check that the contents of f match this merkle file's hashes
void Check(FatFile &f);
// Fill in unknown hashes in this merkle file, if their children are known
void Fill();
struct {
uint8_t type;
union {
struct {
uint8_t flags;
uint8_t hash[32];
} HashBlock;
struct {
uint32_t fileSize;
uint32_t chunkSize;
uint16_t numChunks, numLeafs, numNodes;
uint8_t treeDepth;
} HeaderBlock;
};
} Block;
Error_t Error;
private:
void createFrom(FatFile &src, const uint32_t chunkSize);
void scanChunks(FatFile &src, bool writeHashes, Sha256Context &ctx);
void fill(Sha256Context &ctx);
void readBlock(uint16_t n);
void writeBlock(uint16_t n);
void reset();
FatFile m;
};
} // namespace PDP
#endif // MERKLE_H
|
cf5bae6913c1a99861344eb6ecacc4126345b242 | acbed85aedb961af8b5d216f6962e3d8a2c0812a | /leptonica/.svn/text-base/colormap.inc.svn-base | 553999e440db066407ba9a52c35374d68b9ac177 | [] | no_license | moctes/pascalsane | 739d562c798de091b5220bd78c9dbdebf9a279c1 | 9d38fb9fe787162177fa7496e7090f925ac76591 | refs/heads/master | 2020-05-04T02:29:04.861235 | 2019-04-01T19:03:08 | 2019-04-01T19:03:08 | 178,927,431 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,939 | colormap.inc.svn-base | {*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
*====================================================================*}
{*
* colormap.c PASCAL
*
* Colormap creation, copy, destruction, addition
* PIXCMAP *pixcmapCreate()
* PIXCMAP *pixcmapCreateRandom()
* PIXCMAP *pixcmapCreateLinear()
* PIXCMAP *pixcmapCopy()
* void pixcmapDestroy()
* l_int32 pixcmapAddColor()
* l_int32 pixcmapAddNewColor()
* l_int32 pixcmapAddNearestColor()
* l_int32 pixcmapUsableColor()
* l_int32 pixcmapAddBlackOrWhite()
* l_int32 pixcmapSetBlackAndWhite()
* l_int32 pixcmapGetCount()
* l_int32 pixcmapGetDepth()
* l_int32 pixcmapGetMinDepth()
* l_int32 pixcmapGetFreeCount()
* l_int32 pixcmapClear()
*
* Colormap random access and test
* l_int32 pixcmapGetColor()
* l_int32 pixcmapGetColor32()
* l_int32 pixcmapResetColor() X
* l_int32 pixcmapGetIndex()
* l_int32 pixcmapHasColor()
* l_int32 pixcmapCountGrayColors()
* l_int32 pixcmapGetRankIntensity()
* l_int32 pixcmapGetNearestIndex()
* l_int32 pixcmapGetNearestGrayIndex()
* l_int32 pixcmapGetComponentRange()
* l_int32 pixcmapGetExtremeValue()
*
* Colormap conversion
* PIXCMAP *pixcmapGrayToColor()
* PIXCMAP *pixcmapColorToGray()
*
* Colormap I/O
* l_int32 pixcmapReadStream()
* l_int32 pixcmapWriteStream()
*
* Extract colormap arrays and serialization
* l_int32 pixcmapToArrays()
* l_int32 pixcmapToRGBTable()
* l_int32 pixcmapSerializeToMemory()
* PIXCMAP *pixcmapDeserializeFromMemory()
* char *pixcmapConvertToHex()
*
* Colormap transforms
* l_int32 pixcmapGammaTRC()
* l_int32 pixcmapContrastTRC()
* l_int32 pixcmapShiftIntensity()
* l_int32 pixcmapShiftByComponent()
*}
{*!
* pixcmapResetColor()
*
* Input: cmap
* index
* rval, gval, bval (colormap entry to be reset; each number
* is in range [0, ... 255])
* Return: 0 if OK, 1 if not accessable (caller should check)
*
* Notes:
* (1) This resets sets the color of an entry that has already
* been set and included in the count of colors.
*}
function pixcmapResetColor( cmap: PPixCmap; index, rval, gval, bval: Longint ): Longint; cdecl; external LIBLEPT;
| |
eafa164c4a2da73c1843cb6df4935cdecd19cca6 | f0b7bcc41298354b471a72a7eeafe349aa8655bf | /codebase/apps/radar/src/TsAscope/_AscopeReader.hh | 937a833237a987a75d8d0f5ea3599ffbc1516f88 | [
"BSD-3-Clause"
] | permissive | NCAR/lrose-core | 23abeb4e4f1b287725dc659fb566a293aba70069 | be0d059240ca442883ae2993b6aa112011755688 | refs/heads/master | 2023-09-01T04:01:36.030960 | 2023-08-25T00:41:16 | 2023-08-25T00:41:16 | 51,408,988 | 90 | 53 | NOASSERTION | 2023-08-18T21:59:40 | 2016-02-09T23:36:25 | C++ | UTF-8 | C++ | false | false | 4,188 | hh | _AscopeReader.hh | // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
// ** Copyright UCAR (c) 1990 - 2016
// ** University Corporation for Atmospheric Research (UCAR)
// ** National Center for Atmospheric Research (NCAR)
// ** Boulder, Colorado, USA
// ** BSD licence applies - redistribution and use in source and binary
// ** forms, with or without modification, are permitted provided that
// ** the following conditions are met:
// ** 1) If the software is modified to produce derivative works,
// ** such modified software should be clearly marked, so as not
// ** to confuse it with the version available from UCAR.
// ** 2) Redistributions of source code must retain the above copyright
// ** notice, this list of conditions and the following disclaimer.
// ** 3) 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.
// ** 4) Neither the name of UCAR nor the names of its contributors,
// ** if any, may be used to endorse or promote products derived from
// ** this software without specific prior written permission.
// ** DISCLAIMER: THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS
// ** OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
// ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
#ifndef ASCOPEREADER_H_
#define ASCOPEREADER_H_
#include <QObject>
#include <QMetaType>
#include <string>
#include <toolsa/Socket.hh>
#include <toolsa/MemBuf.hh>
#include <radar/iwrf_data.h>
#include <radar/IwrfTsInfo.hh>
#include <radar/IwrfTsPulse.hh>
#include <radar/IwrfTsBurst.hh>
#include "AScope.h"
/// A Time series reader for the AScope. It reads IWRF data and translates
/// DDS samples to AScope::TimeSeries.
Q_DECLARE_METATYPE(AScope::TimeSeries)
class AScopeReader : public QObject
{
Q_OBJECT
public:
/// Constructor
/// @param host The server host
/// @param port The server port
AScopeReader(const std::string &host, int port,
AScope &scope, int debugLevel);
/// Destructor
virtual ~AScopeReader();
signals:
/// This signal provides an item that falls within
/// the desired bandwidth specification.
/// @param pItem A pointer to the item.
/// It must be returned via returnItem().
void newItem(AScope::TimeSeries pItem);
public slots:
/// Use this slot to return an item
/// @param pItem the item to be returned.
void returnItemSlot(AScope::TimeSeries pItem);
// respond to timer events
void timerEvent(QTimerEvent *event);
protected:
private:
int _debugLevel;
std::string _serverHost;
int _serverPort;
AScope &_scope;
// communication via socket
Socket _sock;
time_t _lastTryConnectTime;
int _sockTimerId;
bool _timedOut;
// pulse stats
int _nSamples;
int _pulseCount;
int _pulseCountSinceSync;
// info and pulses
IwrfTsInfo _info;
IwrfTsBurst _burst;
vector<IwrfTsPulse *> _pulsesH; // when H/V flag is 1
vector<IwrfTsPulse *> _pulsesV; // when H/V flag is 0
// xmit mode
typedef enum {
XMIT_MODE_H_ONLY,
XMIT_MODE_V_ONLY,
XMIT_MODE_ALTERNATING
} xmitMode_t;
xmitMode_t _xmitMode;
// sequence number for time series to ascope
size_t _tsSeqNum;
// methods
int _readFromServer();
int _readPacket(int &id, int &len, MemBuf &buf);
int _peekAtBuffer(void *buf, int nbytes);
void _addPulse(const MemBuf &buf);
void _setBurst(const MemBuf &buf);
void _sendDataToAScope();
void _loadTs(int nGates,
int channelIn,
const vector<IwrfTsPulse *> &pulses,
int channelOut,
AScope::FloatTimeSeries &ts);
};
#endif /*ASCOPEREADER_H_*/
|
b333a3f9c1b5011ef1999c51ef43bb259fb2cbda | 8421732a35cadaecb28ad5043887ea1414890ef7 | /Basics/NearestLuckyNo.cpp | 97339010ce0d5d022196b6e319179cc5386bfce4 | [] | no_license | sonambharti/Basic-Code | 6e7e8e1dcf76f9f9fb675090adb5ef9cffa2dc54 | 8dfea6a93a30440501f654e138ad8925234e7af7 | refs/heads/master | 2023-01-28T04:40:21.129965 | 2023-01-17T06:27:57 | 2023-01-17T06:27:57 | 145,596,947 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 332 | cpp | NearestLuckyNo.cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
string s,a;
cin>>s;
int n,i,j=0,k;
n=s.size();
for(i=0;i<n;i++)
{
a[0]=s[i];
k = stoi(a);
if(k==4 || k==7){
j+=1;
}
}
if(j==4 || j==7)
cout<<"YES";
else
cout<<"NO";
return 0;
} |
e9182fc5f66fad53ddbb4354674ce8262a114174 | 560a3eaef59c9ae381edb0a5f0bc77a10c974d6c | /master/sensors.ino | 505927b11b731555653dd8871a2d69632d8401fa | [] | no_license | agemery/ParkUF-Hardware-Solution | 3314b1fd12a87e6b5c00a3838507008480454431 | 27667f3ad95a048a980ed07e0256a83d2697f859 | refs/heads/master | 2020-04-06T03:44:00.697503 | 2014-12-02T19:20:53 | 2014-12-02T19:20:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,651 | ino | sensors.ino | //Sonar stuff
const int sonarPin = 8; //the io pin we are using
const float threshold = 265; //distance threshold in centimeters
//anything under threshold counts as a car
//PIR stuff
const int pirPin = 11;
const int calibrationTime = 10; //seconds to allow calibration
//miliseconds sensor has to be low before all motion has stopped
const int detectionWindow = 4; //duration to poll range finder
void setupSensors() {
setupPir();
setupSonar();
}
void setupSonar() {
//not too much to do here
pinMode(sonarPin, OUTPUT);
}
void setupPir() {
pinMode(pirPin, INPUT);
digitalWrite(pirPin, LOW);
Serial.println("Allowing PIR to calibrate");
for(int i=0; i<calibrationTime; i++) {
delay(1000); //delay is in miliseconds
}
Serial.println("Calibration finished");
delay(50);
}
int carsDetected() {
//instead of returning a boolena value indicating at maximum a single car,
//count the number of cars that have passed in a timining interval
//based upon the spaces that exist between cars in a chain of cars
//for example, if three cars pass in an interval, we count the number
//of times the distance goes back to ~265(cm).
//so something like [168,165,268,190,191,192,189,268,267,268,140,141..]
//we can see that there are two breaks there, thus three cars
if(digitalRead(pirPin == HIGH)) {
Serial.println("Motion detected @ " + String(millis()/1000) + " seconds");
int cars = countCars();
Serial.println(String(cars) + " cars detected");
return (cars);
}
else {
return 0;
}
}
int expandWindow(int w, unsigned long t, unsigned long start) {
if ((t - start)/1000 > (w-2)) {
Serial.println("Window expanded. window= " + String(w));
return (w +2); //extend the window so we do not miss a car
}
else
Serial.println("Window unchanged. window= " + String(w));
return w;
}
int countCars() {
unsigned long startTime = millis();
boolean isFirstCarPassed = false;
boolean isCarBreak = false;
int numCars = 0;
int window = detectionWindow;
//adjustable window extends when there is a car chain so we do not miss a
//car at the edge of the window
//s is the length of time we will poll the range finder, in seconds
for(unsigned long time = millis(); (time - startTime)/1000 < window; time=millis()) {
turnOnRangeFinder();
//the duration of the pulse is converted into the distance
float duration = pulseIn(sonarPin, HIGH);
// convert to centimeters
float range = ((duration / 29.412) / 2);
if (!isFirstCarPassed && (range < threshold)) {
//if the first car has not passed previously, and range is
//now below threshold, then this car is the first car in the chain
isFirstCarPassed = true;
numCars=1;
window = expandWindow(window, time, startTime);
isCarBreak = false;
}
else if(isFirstCarPassed && !isCarBreak && (range >= (threshold))) {
//if the first car has already passed, and we see the range go
//higher than 265, and we are not already on a car break, then
//this is a break in the chain of cars
isCarBreak = true;
window = expandWindow(window, time, startTime);
}
else if(isFirstCarPassed && isCarBreak && (range < threshold)) {
//if the first car has already passed, and we have recorded that
//we were on a break in the chain, and if the range is now below threshold
//then this is a new car. increment numCars
numCars++;
isCarBreak = false; //not on a car break anymore
window = expandWindow(window, time, startTime);
}
else if(!isCarBreak && (range < threshold) ) {
window = expandWindow(window, time, startTime);
}
Serial.println(range);
delay(100); //wait before turning the sensor back on
}
return numCars;
}
boolean isCarDetected() {
//call this method to poll the PIR & check the range finder
//if the range finder returns a value under the threshold, that is
//interpreted as a car (when no car is present, range finder reads max dist)
//return true if car is present.
//if the PIR goes high, check the range finder
if(digitalRead(pirPin) == HIGH) {
Serial.println("Motion detected @ " + String(millis()/1000) + " seconds");
float dist = getMinRange();
Serial.println("Distance detected: " + String(dist) + " cm");
if(dist < threshold)
return true;
else
return false;
}
return false;
}
//returns minimum range found over the given interval
float getMinRange() {
//if we get this number back, something is wrong
float minRange = 10000.0;
unsigned long startTime = millis();
//s is the length of time we will poll the range finder, in seconds
while((millis() - startTime)/1000 < detectionWindow) {
turnOnRangeFinder();
//the duration of the pulse is converted into the distance
float duration = pulseIn(sonarPin, HIGH);
// convert to centimeters
float range = ((duration / 29.412) / 2);
if (range < minRange)
minRange = range;
delay(30); //wait before turning the sensor back on
}
return minRange;
}
void turnOnRangeFinder() {
pinMode(sonarPin, OUTPUT);
//this sequences turns on the sonar range finder
digitalWrite(sonarPin, LOW); //send low pulse
delayMicroseconds(2); //wait 2 uS
digitalWrite(sonarPin, HIGH); //high pulse brah
delayMicroseconds(5); //5 uS wait
digitalWrite(sonarPin, LOW); //back off again
pinMode(sonarPin, INPUT); // make it an input pin
digitalWrite(sonarPin, HIGH); //turn on pullup resistor
//making pin active low
}
|
658c6e9ebac313f6f3403ebd0f6c7e264174e3d2 | 75106c3a7a7d16f643e6ebe54fcbfe636b2da174 | /LinkedList/37_zigZagList.cpp | 4ec0e985f85dd67e07b967abe6b2ee7f4b2df59d | [] | no_license | i7sharath/geeks4geeks | b7f604189111c6ba45008d6d5ac5491533a7576e | 9c02e45dc2b73a007db2c2bba96a9491538818c7 | refs/heads/master | 2021-05-01T17:00:36.132885 | 2016-09-17T17:44:08 | 2016-09-17T17:44:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,733 | cpp | 37_zigZagList.cpp | /*
Given a linked list, rearrange it such that converted list should be of the form a < b > c < d > e < f .. where a, b, c.. are consecutive data node of linked list. Examples :
Input: 1->2->3->4
Output: 1->3->2->4
Input: 11->15->20->5->10
Output: 11->20->5->15->10
*/
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
void insert(node* &head,int val)
{
node *newnode=(node*)malloc(sizeof(node));
newnode->data=val;
newnode->next=NULL;
node *start=head;
if(start==NULL)
{
head=newnode;
return ;
}
while(start->next)
start=start->next;
start->next=newnode;
return ;
}
void printList(node *head)
{
while(head)
{
cout<<head->data;
head=head->next;
if(head)
cout<<"->";
}
cout<<endl;
return;
}
node *zigZack(node* head)
{
if(head==NULL || head->next==NULL)
return head;
node *currhead=head;
int flaggreater=0;
while(currhead && currhead->next)
{
if(flaggreater==0)
{
if(currhead->data > currhead->next->data)
swap(currhead->data,currhead->next->data);
flaggreater=1;
}
else
{
if(currhead->data < currhead->next->data)
swap(currhead->data,currhead->next->data);
flaggreater=0;
}
currhead=currhead->next;
}
return head;
}
int main()
{
struct node *head=NULL;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int val;
cin>>val;
insert(head,val);
}
printList(head);
head=zigZack(head);
printList(head);
return 0;
}
|
5d9a2c8c7bcba27829084f5e868afed5b3bb100f | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /chrome/browser/sync/test/integration/two_client_typed_urls_sync_test.cc | e9a8a296727dce39301bee39c5b907d2c572fe5b | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 38,260 | cc | two_client_typed_urls_sync_test.cc | // Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include "base/big_endian.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/uuid.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/sync/test/integration/bookmarks_helper.h"
#include "chrome/browser/sync/test/integration/sync_service_impl_harness.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "chrome/browser/sync/test/integration/typed_urls_helper.h"
#include "chrome/browser/sync/test/integration/updated_progress_marker_checker.h"
#include "components/history/core/browser/history_types.h"
#include "components/sync/base/client_tag_hash.h"
#include "components/sync/base/features.h"
#include "components/sync/model/metadata_batch.h"
#include "components/sync/protocol/entity_metadata.pb.h"
#include "content/public/test/browser_test.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "ash/constants/ash_features.h"
#include "chromeos/ash/components/standalone_browser/feature_refs.h"
#endif
using base::ASCIIToUTF16;
using bookmarks::BookmarkNode;
using typed_urls_helper::AddUrlToHistory;
using typed_urls_helper::AddUrlToHistoryWithTimestamp;
using typed_urls_helper::AddUrlToHistoryWithTransition;
using typed_urls_helper::AreVisitsEqual;
using typed_urls_helper::AreVisitsUnique;
using typed_urls_helper::CheckSyncHasMetadataForURLID;
using typed_urls_helper::CheckSyncHasURLMetadata;
using typed_urls_helper::CheckURLRowVectorsAreEqualForTypedURLs;
using typed_urls_helper::DeleteUrlFromHistory;
using typed_urls_helper::ExpireHistoryBefore;
using typed_urls_helper::ExpireHistoryBetween;
using typed_urls_helper::GetAllSyncMetadata;
using typed_urls_helper::GetTypedUrlsFromClient;
using typed_urls_helper::GetUrlFromClient;
using typed_urls_helper::GetVisitsFromClient;
using typed_urls_helper::WriteMetadataToClient;
namespace {
const char kDummyUrl[] = "http://dummy-history.google.com/";
} // namespace
// TODO(crbug.com/1365291): Evaluate which of these tests should be kept after
// kSyncEnableHistoryDataType is enabled and HISTORY has replaced TYPED_URLS.
class TwoClientTypedUrlsSyncTest : public SyncTest {
public:
TwoClientTypedUrlsSyncTest() : SyncTest(TWO_CLIENT) {}
TwoClientTypedUrlsSyncTest(const TwoClientTypedUrlsSyncTest&) = delete;
TwoClientTypedUrlsSyncTest& operator=(const TwoClientTypedUrlsSyncTest&) =
delete;
~TwoClientTypedUrlsSyncTest() override = default;
::testing::AssertionResult CheckClientsEqual() {
history::URLRows urls = GetTypedUrlsFromClient(0);
history::URLRows urls2 = GetTypedUrlsFromClient(1);
if (!CheckURLRowVectorsAreEqualForTypedURLs(urls, urls2)) {
return ::testing::AssertionFailure() << "URLVectors are not equal";
}
// Now check the visits.
for (size_t i = 0; i < urls.size() && i < urls2.size(); i++) {
history::VisitVector visit1 = GetVisitsFromClient(0, urls[i].id());
history::VisitVector visit2 = GetVisitsFromClient(1, urls2[i].id());
if (!AreVisitsEqual(visit1, visit2)) {
return ::testing::AssertionFailure() << "Visits are not equal";
}
}
return ::testing::AssertionSuccess();
}
bool CheckNoDuplicateVisits() {
for (int i = 0; i < num_clients(); ++i) {
history::URLRows urls = GetTypedUrlsFromClient(i);
for (const history::URLRow& url : urls) {
history::VisitVector visits = GetVisitsFromClient(i, url.id());
if (!AreVisitsUnique(visits)) {
return false;
}
}
}
return true;
}
int GetVisitCountForFirstURL(int index) {
history::URLRows urls = GetTypedUrlsFromClient(index);
if (urls.empty()) {
return 0;
} else {
return urls[0].visit_count();
}
}
};
class TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest
: public TwoClientTypedUrlsSyncTest {
public:
TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest() {
features_.InitAndDisableFeature(syncer::kSyncEnableHistoryDataType);
}
~TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest() override = default;
private:
base::test::ScopedFeatureList features_;
};
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, E2E_ENABLED(Add)) {
ResetSyncForPrimaryAccount();
// Use a randomized URL to prevent test collisions.
const std::u16string kHistoryUrl = ASCIIToUTF16(base::StringPrintf(
"http://www.add-history.google.com/%s",
base::Uuid::GenerateRandomV4().AsLowercaseString().c_str()));
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
size_t initial_count = GetTypedUrlsFromClient(0).size();
// Populate one client with a URL, wait for it to sync to the other.
GURL new_url(kHistoryUrl);
AddUrlToHistory(0, new_url);
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
// Assert that the second client has the correct new URL.
history::URLRows urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(initial_count + 1, urls.size());
ASSERT_EQ(new_url, urls.back().url());
}
// Doesn't work with HISTORY because of CheckSyncHasURLMetadata().
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest,
AddExpired) {
const std::u16string kHistoryUrl(u"http://www.add-one-history.google.com/");
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Populate one client with a URL, should sync to the other.
GURL new_url(kHistoryUrl);
// Create a URL with a timestamp 1 year before today.
base::Time timestamp = base::Time::Now() - base::Days(365);
AddUrlToHistoryWithTimestamp(0, new_url, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED, timestamp);
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(new_url, urls[0].url());
// Let sync finish.
// Add a dummy url and sync it.
AddUrlToHistory(0, GURL(kDummyUrl));
urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(2U, urls.size());
ASSERT_TRUE(TypedURLChecker(1, kDummyUrl).Wait());
// Second client should only have dummy URL since kHistoryUrl is expired.
urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(GURL(kDummyUrl), urls.back().url());
EXPECT_TRUE(CheckSyncHasURLMetadata(1, GURL(kDummyUrl)));
// Sync on both clients should not receive expired visits.
EXPECT_FALSE(CheckSyncHasURLMetadata(0, new_url));
EXPECT_FALSE(CheckSyncHasURLMetadata(1, new_url));
}
// Doesn't work with HISTORY because of CheckSyncHasURLMetadata().
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest,
AddExpiredThenUpdate) {
const std::u16string kHistoryUrl(u"http://www.add-one-history.google.com/");
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Populate one client with a URL, should sync to the other.
GURL new_url(kHistoryUrl);
// Create a URL with a timestamp 1 year before today.
base::Time timestamp = base::Time::Now() - base::Days(365);
AddUrlToHistoryWithTimestamp(0, new_url, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED, timestamp);
std::vector<history::URLRow> urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(new_url, urls[0].url());
// Let sync finish.
// Add a dummy url and sync it.
AddUrlToHistory(0, GURL(kDummyUrl));
urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(2U, urls.size());
ASSERT_TRUE(TypedURLChecker(1, kDummyUrl).Wait());
// Second client should only have dummy URL since kHistoryUrl is expired.
urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(1U, urls.size());
EXPECT_TRUE(CheckSyncHasURLMetadata(0, GURL(kDummyUrl)));
// Sync should not receive expired visits.
EXPECT_FALSE(CheckSyncHasURLMetadata(0, new_url));
// Now drive an update on the first client.
AddUrlToHistory(0, new_url);
// Let sync finish again.
ASSERT_TRUE(TypedURLChecker(1, new_url.spec()).Wait());
// Second client should have kHistoryUrl now.
urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(2U, urls.size());
// Sync should receive the new visit.
EXPECT_TRUE(CheckSyncHasURLMetadata(0, new_url));
EXPECT_TRUE(CheckSyncHasURLMetadata(1, new_url));
}
// Doesn't work with HISTORY because of CheckSyncHasURLMetadata().
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest,
AddThenExpireOnSecondClient) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
base::Time now = base::Time::Now();
// Populate one client with a URL, should sync to the other.
GURL url("http://www.add-one-history.google.com/");
base::Time insertion_time = now - base::Days(1);
AddUrlToHistoryWithTimestamp(0, url, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED, insertion_time);
std::vector<history::URLRow> urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(url, urls[0].url());
history::URLID url_id_on_first_client = urls[0].id();
// Wait for sync to finish.
ASSERT_TRUE(TypedURLChecker(1, url.spec()).Wait());
// Second client should have the url.
ASSERT_EQ(1U, GetTypedUrlsFromClient(1).size());
EXPECT_TRUE(CheckSyncHasURLMetadata(1, url));
// Expire the url on the second client.
ExpireHistoryBefore(1, insertion_time + base::Seconds(1));
// The data and the metadata should be gone on the second client.
ASSERT_EQ(0U, GetTypedUrlsFromClient(1).size());
EXPECT_FALSE(CheckSyncHasURLMetadata(1, url));
// Let sync finish; Add a dummy url to the second client and sync it.
AddUrlToHistory(1, GURL(kDummyUrl));
ASSERT_EQ(1U, GetTypedUrlsFromClient(1).size());
ASSERT_TRUE(TypedURLChecker(0, kDummyUrl).Wait());
// The expiration should not get synced up, the first client still has the
// URL (and also the dummy URL)
ASSERT_EQ(2U, GetTypedUrlsFromClient(0).size());
EXPECT_TRUE(CheckSyncHasMetadataForURLID(0, url_id_on_first_client));
}
// Doesn't work with HISTORY because of CheckSyncHasURLMetadata().
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest,
AddThenExpireThenAddAgain) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
base::Time now = base::Time::Now();
// Populate one client with a URL, should sync to the other.
GURL url("http://www.add-one-history.google.com/");
base::Time insertion_time = now - base::Days(1);
AddUrlToHistoryWithTimestamp(0, url, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED, insertion_time);
std::vector<history::URLRow> urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(url, urls[0].url());
history::URLID url_id_on_first_client = urls[0].id();
// Wait for sync to finish.
ASSERT_TRUE(TypedURLChecker(1, url.spec()).Wait());
// Second client should have the url.
urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(1U, urls.size());
EXPECT_TRUE(CheckSyncHasURLMetadata(0, url));
// Expire the url on the first client.
ExpireHistoryBefore(0, insertion_time + base::Seconds(1));
// The data and the metadata should be gone on the first client.
ASSERT_EQ(0U, GetTypedUrlsFromClient(0).size());
EXPECT_FALSE(CheckSyncHasMetadataForURLID(0, url_id_on_first_client));
// Let sync finish.
// Add a dummy url and sync it.
AddUrlToHistory(0, GURL(kDummyUrl));
urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_TRUE(TypedURLChecker(1, kDummyUrl).Wait());
// The expiration should not get synced up, the second client still has the
// URL.
urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(2U, urls.size());
EXPECT_TRUE(CheckSyncHasURLMetadata(1, url));
// The first client can add the URL again (regression test for
// https://crbug.com/827111).
AddUrlToHistoryWithTransition(0, url, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED);
urls = GetTypedUrlsFromClient(0);
EXPECT_EQ(2U, urls.size());
EXPECT_TRUE(CheckSyncHasURLMetadata(0, url));
}
// Doesn't work with HISTORY because of CheckSyncHasURLMetadata().
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest,
AddThenExpireVisitByVisit) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
base::Time now = base::Time::Now();
// Populate one client with a URL (with three visits), should sync to the
// other. First non-typed, then typed, then non-typed again.
GURL url("http://www.add-one-history.google.com/");
base::Time insertion_time = now - base::Days(6);
base::Time second_typed_visit_time = now - base::Days(5);
base::Time third_link_visit_time = now - base::Days(4);
base::Time dummy_visit_1 = now - base::Days(3);
base::Time dummy_visit_2 = now - base::Days(2);
base::Time dummy_visit_3 = now - base::Days(1);
AddUrlToHistoryWithTimestamp(0, url, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED, insertion_time);
AddUrlToHistoryWithTimestamp(0, url, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED,
second_typed_visit_time);
AddUrlToHistoryWithTimestamp(0, url, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED, third_link_visit_time);
std::vector<history::URLRow> urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(url, urls[0].url());
history::URLID url_id_on_first_client = urls[0].id();
// Wait for sync to finish.
ASSERT_TRUE(TypedURLChecker(1, url.spec()).Wait());
// Second client should have the url.
ASSERT_EQ(1U, GetTypedUrlsFromClient(1).size());
EXPECT_TRUE(CheckSyncHasURLMetadata(1, url));
// Expire the first (non-typed) visit on the first client and assert both data
// and metadata are intact.
ExpireHistoryBefore(0, insertion_time + base::Seconds(1));
ASSERT_EQ(1U, GetTypedUrlsFromClient(0).size());
EXPECT_TRUE(CheckSyncHasMetadataForURLID(0, url_id_on_first_client));
// Force a sync cycle (add a dummy typed url and sync it) and check the second
// client still has the original URL (plus the dummy one).
AddUrlToHistoryWithTimestamp(0, GURL(kDummyUrl), ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED, dummy_visit_1);
ASSERT_EQ(2U, GetTypedUrlsFromClient(0).size());
ASSERT_TRUE(TypedURLChecker(1, kDummyUrl).Wait());
ASSERT_EQ(2U, GetTypedUrlsFromClient(1).size());
EXPECT_TRUE(CheckSyncHasURLMetadata(1, url));
// Expire the second (typed) visit on the first client and assert both data
// and metadata for the URL are gone.
ExpireHistoryBefore(0, second_typed_visit_time + base::Seconds(1));
std::vector<history::URLRow> pruned_urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, pruned_urls.size());
ASSERT_EQ(GURL(kDummyUrl), pruned_urls[0].url());
EXPECT_FALSE(CheckSyncHasMetadataForURLID(0, url_id_on_first_client));
// Force a sync cycle (add another visit to the dummy url and sync it).
AddUrlToHistoryWithTimestamp(0, GURL(kDummyUrl), ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED, dummy_visit_2);
ASSERT_TRUE(TypedURLChecker(1, kDummyUrl).Wait());
// The expiration should not get synced up, the second client still has the
// URL (and also the dummy one).
ASSERT_EQ(2U, GetTypedUrlsFromClient(1).size());
EXPECT_TRUE(CheckSyncHasURLMetadata(1, url));
// Now expire also the last non-typed visit (make sure it has no impact).
ExpireHistoryBefore(0, third_link_visit_time + base::Seconds(1));
ASSERT_EQ(1U, GetTypedUrlsFromClient(0).size());
EXPECT_FALSE(CheckSyncHasMetadataForURLID(0, url_id_on_first_client));
// Force a sync cycle (add another visit to the dummy url and sync it) and
// check the second client still has the same state.
AddUrlToHistoryWithTimestamp(0, GURL(kDummyUrl), ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED, dummy_visit_3);
ASSERT_TRUE(TypedURLChecker(1, kDummyUrl).Wait());
ASSERT_EQ(2U, GetTypedUrlsFromClient(1).size());
EXPECT_TRUE(CheckSyncHasURLMetadata(1, url));
}
// Doesn't work with HISTORY because DeleteUrlFromHistory() deletes only
// locally (doesn't send a delete directive).
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest,
E2E_ENABLED(AddThenDelete)) {
ResetSyncForPrimaryAccount();
// Use a randomized URL to prevent test collisions.
const std::u16string kHistoryUrl = ASCIIToUTF16(base::StringPrintf(
"http://www.add-history.google.com/%s",
base::Uuid::GenerateRandomV4().AsLowercaseString().c_str()));
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
size_t initial_count = GetTypedUrlsFromClient(0).size();
// Populate one client with a URL, wait for it to sync to the other.
GURL new_url(kHistoryUrl);
AddUrlToHistory(0, new_url);
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
// Assert that the second client has the correct new URL.
history::URLRows urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(initial_count + 1, urls.size());
ASSERT_EQ(new_url, urls.back().url());
// Delete from first client, and wait for them to sync.
DeleteUrlFromHistory(0, new_url);
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
// Assert that it's deleted from the second client.
ASSERT_EQ(initial_count, GetTypedUrlsFromClient(1).size());
}
// Doesn't work with HISTORY because it uses ExpireHistoryBetween() (rather than
// DeleteLocalAndRemoteHistoryBetween()).
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest,
AddMultipleVisitsThenDeleteAllTypedVisits) {
const std::u16string kHistoryUrl(u"http://history1.google.com/");
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
base::Time now = base::Time::Now();
base::Time insertion_time = now - base::Days(2);
base::Time visit_time = now - base::Days(1);
// Populate one client with a URL with multiple visits, wait for it to sync to
// the other.
GURL new_url(kHistoryUrl);
AddUrlToHistoryWithTimestamp(0, new_url, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED, insertion_time);
AddUrlToHistoryWithTimestamp(0, new_url, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED, visit_time);
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
// Assert that the second client has the correct new URL.
history::URLRows urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(1u, urls.size());
ASSERT_EQ(new_url, urls[0].url());
// Delete the only typed visit from the first client, and wait for them to
// sync.
ExpireHistoryBetween(0, insertion_time - base::Seconds(1),
insertion_time + base::Seconds(1));
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
// Assert that it's deleted from the second client.
ASSERT_EQ(0u, GetTypedUrlsFromClient(1).size());
}
// Doesn't work with HISTORY because that doesn't sync retroactively.
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest,
DisableEnableSync) {
ResetSyncForPrimaryAccount();
const std::u16string kUrl1(u"http://history1.google.com/");
const std::u16string kUrl2(u"http://history2.google.com/");
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Disable history sync for one client, leave it active for the other.
ASSERT_TRUE(
GetClient(0)->DisableSyncForType(syncer::UserSelectableType::kHistory));
// Add one URL to non-syncing client, add a different URL to the other,
// wait for sync cycle to complete. No data should be exchanged.
GURL url1(kUrl1);
GURL url2(kUrl2);
AddUrlToHistory(0, url1);
AddUrlToHistory(1, url2);
ASSERT_TRUE(UpdatedProgressMarkerChecker(GetSyncService(1)).Wait());
// Make sure that no data was exchanged.
history::URLRows post_sync_urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, post_sync_urls.size());
ASSERT_EQ(url1, post_sync_urls[0].url());
post_sync_urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(1U, post_sync_urls.size());
ASSERT_EQ(url2, post_sync_urls[0].url());
// Enable history sync, make both URLs are synced to each client.
ASSERT_TRUE(
GetClient(0)->EnableSyncForType(syncer::UserSelectableType::kHistory));
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
}
// Doesn't work with HISTORY because DeleteUrlFromHistory() deletes only
// locally (doesn't send a delete directive).
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest,
AddOneDeleteOther) {
const std::u16string kHistoryUrl(
u"http://www.add-one-delete-history.google.com/");
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Populate one client with a URL, should sync to the other.
GURL new_url(kHistoryUrl);
AddUrlToHistory(0, new_url);
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(new_url, urls[0].url());
// Both clients should have this URL.
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
// Now, delete the URL from the second client.
DeleteUrlFromHistory(1, new_url);
urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
// Both clients should have this URL removed.
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
}
// Doesn't work with HISTORY because DeleteUrlFromHistory() deletes only
// locally (doesn't send a delete directive).
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest,
AddOneDeleteOtherAddAgain) {
const std::u16string kHistoryUrl(
u"http://www.add-delete-add-history.google.com/");
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Populate one client with a URL, should sync to the other.
GURL new_url(kHistoryUrl);
AddUrlToHistory(0, new_url);
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(new_url, urls[0].url());
// Both clients should have this URL.
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
// Now, delete the URL from the second client.
DeleteUrlFromHistory(1, new_url);
urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
// Both clients should have this URL removed.
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
// Add it to the first client again, should succeed (tests that the deletion
// properly disassociates that URL).
AddUrlToHistory(0, new_url);
// Both clients should have this URL added again.
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
}
// Doesn't work with HISTORY because that doesn't sync retroactively.
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest,
MergeTypedWithNonTypedDuringAssociation) {
ASSERT_TRUE(SetupClients());
GURL new_url("http://history.com");
base::Time timestamp = base::Time::Now();
// Put a non-typed URL in both clients with an identical timestamp.
// Then add a typed URL to the second client - this test makes sure that
// we properly merge both sets of visits together to end up with the same
// set of visits on both ends.
AddUrlToHistoryWithTimestamp(0, new_url, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED, timestamp);
AddUrlToHistoryWithTimestamp(1, new_url, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED, timestamp);
AddUrlToHistoryWithTimestamp(1, new_url, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED,
timestamp + base::Seconds(1));
// Now start up sync - URLs should get merged. Fully sync client 1 first,
// before syncing client 0, so we have both of client 1's URLs in the sync DB
// at the time that client 0 does model association.
ASSERT_TRUE(GetClient(1)->SetupSync()) << "SetupSync() failed";
ASSERT_TRUE(UpdatedProgressMarkerChecker(GetSyncService(1)).Wait());
ASSERT_TRUE(GetClient(0)->SetupSync()) << "SetupSync() failed";
ASSERT_TRUE(TypedURLChecker(1, new_url.spec()).Wait());
ASSERT_TRUE(CheckClientsEqual());
// At this point, we should have no duplicates (total visit count should be
// 2). We only need to check client 0 since we already verified that both
// clients are identical above.
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(new_url, urls[0].url());
ASSERT_TRUE(CheckNoDuplicateVisits());
ASSERT_EQ(2, GetVisitCountForFirstURL(0));
}
// Tests transitioning a URL from non-typed to typed when both clients
// have already seen that URL (so a merge is required).
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest,
MergeTypedWithNonTypedDuringChangeProcessing) {
ASSERT_TRUE(SetupClients());
GURL new_url("http://history.com");
base::Time timestamp = base::Time::Now();
AddUrlToHistoryWithTimestamp(0, new_url, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED, timestamp);
AddUrlToHistoryWithTimestamp(1, new_url, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED, timestamp);
// Now start up sync. Neither URL should get synced as they do not look like
// typed URLs.
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(CheckClientsEqual());
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(0U, urls.size());
// Now, add a typed visit to the first client.
AddUrlToHistoryWithTimestamp(0, new_url, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED,
timestamp + base::Seconds(1));
ASSERT_TRUE(TypedURLChecker(1, new_url.spec()).Wait());
ASSERT_TRUE(CheckClientsEqual());
ASSERT_TRUE(CheckNoDuplicateVisits());
urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(2, GetVisitCountForFirstURL(0));
ASSERT_EQ(2, GetVisitCountForFirstURL(1));
}
// Tests transitioning a URL from non-typed to typed when one of the clients
// has never seen that URL before (so no merge is necessary).
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, UpdateToNonTypedURL) {
const std::u16string kHistoryUrl(
u"http://www.add-delete-add-history.google.com/");
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Populate one client with a non-typed URL, should not be synced.
GURL new_url(kHistoryUrl);
AddUrlToHistoryWithTransition(0, new_url, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED);
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(0U, urls.size());
// Both clients should have 0 typed URLs.
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(0U, urls.size());
// Now, add a typed visit to this URL.
AddUrlToHistory(0, new_url);
// Let sync finish.
ASSERT_TRUE(TypedURLChecker(1, new_url.spec()).Wait());
// Both clients should have this URL as typed and have two visits synced up.
ASSERT_TRUE(CheckClientsEqual());
urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(new_url, urls[0].url());
ASSERT_EQ(2, GetVisitCountForFirstURL(0));
}
// Doesn't work with HISTORY because that *does* sync non-typed visits.
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest,
E2E_ENABLED(DontSyncUpdatedNonTypedURLs)) {
ResetSyncForPrimaryAccount();
// Checks if a non-typed URL that has been updated (modified) doesn't get
// synced. This is a regression test after fixing a bug where adding a
// non-typed URL was guarded against but later modifying it was not. Since
// "update" is "update or create if missing", non-typed URLs were being
// created.
const GURL kNonTypedURL("http://link.google.com/");
const GURL kTypedURL("http://typed.google.com/");
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
AddUrlToHistoryWithTransition(0, kNonTypedURL, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED);
AddUrlToHistoryWithTransition(0, kTypedURL, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED);
// Modify the non-typed URL. It should not get synced.
typed_urls_helper::SetPageTitle(0, kNonTypedURL, "Welcome to Non-Typed URL");
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
history::VisitVector visits;
// First client has both visits.
visits = typed_urls_helper::GetVisitsForURLFromClient(0, kNonTypedURL);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_LINK));
visits = typed_urls_helper::GetVisitsForURLFromClient(0, kTypedURL);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_TYPED));
// Second client has only the typed visit.
visits = typed_urls_helper::GetVisitsForURLFromClient(1, kNonTypedURL);
ASSERT_EQ(0U, visits.size());
visits = typed_urls_helper::GetVisitsForURLFromClient(1, kTypedURL);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_TYPED));
}
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest,
E2E_ENABLED(SyncTypedRedirects)) {
ResetSyncForPrimaryAccount();
const std::u16string kHistoryUrl(u"http://typed.google.com/");
const std::u16string kRedirectedHistoryUrl(u"http://www.typed.google.com/");
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Simulate a typed address that gets redirected by the server to a different
// address.
GURL initial_url(kHistoryUrl);
const ui::PageTransition initial_transition = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_CHAIN_START);
AddUrlToHistoryWithTransition(0, initial_url, initial_transition,
history::SOURCE_BROWSED);
GURL redirected_url(kRedirectedHistoryUrl);
const ui::PageTransition redirected_transition = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_CHAIN_END |
ui::PAGE_TRANSITION_SERVER_REDIRECT);
// This address will have a typed_count == 0 because it's a redirection.
// It should still be synced.
AddUrlToHistoryWithTransition(0, redirected_url, redirected_transition,
history::SOURCE_BROWSED);
// Both clients should have both URLs.
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
history::VisitVector visits =
typed_urls_helper::GetVisitsForURLFromClient(0, initial_url);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_TYPED));
visits = typed_urls_helper::GetVisitsForURLFromClient(0, redirected_url);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_TYPED));
visits = typed_urls_helper::GetVisitsForURLFromClient(1, initial_url);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_TYPED));
visits = typed_urls_helper::GetVisitsForURLFromClient(1, redirected_url);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_TYPED));
}
// Doesn't work with HISTORY because that doesn't sync retroactively.
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest,
SkipImportedVisits) {
GURL imported_url("http://imported_url.com");
GURL browsed_url("http://browsed_url.com");
GURL browsed_and_imported_url("http://browsed_and_imported_url.com");
ASSERT_TRUE(SetupClients());
// Create 3 items in our first client - 1 imported, one browsed, one with
// both imported and browsed entries.
AddUrlToHistoryWithTransition(0, imported_url, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_FIREFOX_IMPORTED);
AddUrlToHistoryWithTransition(0, browsed_url, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED);
AddUrlToHistoryWithTransition(0, browsed_and_imported_url,
ui::PAGE_TRANSITION_TYPED,
history::SOURCE_FIREFOX_IMPORTED);
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(TypedURLChecker(1, browsed_url.spec()).Wait());
history::URLRows urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(browsed_url, urls[0].url());
// Now browse to 3rd URL - this should cause it to be synced, even though it
// was initially imported.
AddUrlToHistoryWithTransition(0, browsed_and_imported_url,
ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED);
ASSERT_TRUE(TypedURLChecker(1, browsed_and_imported_url.spec()).Wait());
urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(2U, urls.size());
// Make sure the imported URL didn't make it over.
for (const history::URLRow& url : urls) {
ASSERT_NE(imported_url, url.url());
}
}
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, BookmarksWithTypedVisit) {
GURL bookmark_url("http://www.bookmark.google.com/");
GURL bookmark_icon_url("http://www.bookmark.google.com/favicon.ico");
ASSERT_TRUE(SetupClients());
// Create a bookmark.
const BookmarkNode* node = bookmarks_helper::AddURL(
0, bookmarks_helper::IndexedURLTitle(0), bookmark_url);
bookmarks_helper::SetFavicon(0, node, bookmark_icon_url,
bookmarks_helper::CreateFavicon(SK_ColorWHITE),
bookmarks_helper::FROM_UI);
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// A row in the DB for client 1 should have been created as a result of the
// sync.
history::URLRow row;
ASSERT_TRUE(GetUrlFromClient(1, bookmark_url, &row));
// Now, add a typed visit for client 0 to the bookmark URL and sync it over
// - this should not cause a crash.
AddUrlToHistory(0, bookmark_url);
ASSERT_TRUE(ProfilesHaveSameTypedURLsChecker().Wait());
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(bookmark_url, urls[0].url());
ASSERT_EQ(1, GetVisitCountForFirstURL(0));
}
// ResetWithDuplicateMetadata doesn't work with HISTORY because it manually
// writes to the TypedURL metadata DB.
class TwoClientTypedUrlsSyncTestWithoutLacrosSupport
: public TwoClientTypedUrlsWithoutNewHistoryTypeSyncTest {
public:
TwoClientTypedUrlsSyncTestWithoutLacrosSupport() {
#if BUILDFLAG(IS_CHROMEOS_ASH)
// TODO(crbug.com/1263014): Update test to pass with Lacros enabled.
feature_list_.InitWithFeatures(
/*enabled_features=*/{},
/*disabled_features=*/ash::standalone_browser::GetFeatureRefs());
#endif
}
~TwoClientTypedUrlsSyncTestWithoutLacrosSupport() override = default;
private:
base::test::ScopedFeatureList feature_list_;
};
// Regression test for one part crbug.com/1075573. The fix for the issue was
// general, so typed_urls is somewhat arbitrary choice (typed_urls were the most
// affected by the issue).
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTestWithoutLacrosSupport,
PRE_ResetWithDuplicateMetadata) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Populate one client with a URL, should sync to the other.
const GURL url(kDummyUrl);
AddUrlToHistory(0, url);
EXPECT_TRUE(TypedURLChecker(1, kDummyUrl).Wait());
EXPECT_TRUE(CheckSyncHasURLMetadata(1, GURL(kDummyUrl)));
// Write a duplicate metadata entity. Duplicates appear on clients due to
// different reasons / bugs, this test is not realistic in this sense. It is
// just the simplest way to get to the desired state.
sync_pb::EntityMetadata duplicate_metadata;
duplicate_metadata.set_client_tag_hash(
syncer::ClientTagHash::FromUnhashed(syncer::TYPED_URLS, kDummyUrl)
.value());
duplicate_metadata.set_creation_time(0);
history::URLID arbitrary_id(5438392);
std::string storage_key(sizeof(arbitrary_id), 0);
base::WriteBigEndian<history::URLID>(&storage_key[0], arbitrary_id);
WriteMetadataToClient(1, storage_key, duplicate_metadata);
}
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTestWithoutLacrosSupport,
ResetWithDuplicateMetadata) {
base::HistogramTester histogram_tester;
// SetupSync() can't be used since it relies on an additional sync cycle (via
// UpdateProgressMarkerChecker which checks non-empty progress markers).
ASSERT_TRUE(SetupClients());
ASSERT_TRUE(GetClient(0)->AwaitSyncSetupCompletion());
ASSERT_TRUE(GetClient(1)->AwaitSyncSetupCompletion());
// On startup, client 1 should reset its metadata and perform initial sync
// once again. Sync one more url across the clients to be sure client 1
// finishes its initial sync.
const std::string kFurtherURL("http://www.typed.google.com/");
AddUrlToHistory(0, GURL(kFurtherURL));
EXPECT_TRUE(TypedURLChecker(1, kFurtherURL).Wait());
// Check that client 1 has all the metadata without the duplicate.
syncer::MetadataBatch batch = GetAllSyncMetadata(1);
syncer::EntityMetadataMap metadata_map(batch.TakeAllMetadata());
size_t count_for_dummy = 0;
const syncer::ClientTagHash kClientTagHash =
syncer::ClientTagHash::FromUnhashed(syncer::TYPED_URLS, kDummyUrl);
for (const auto& [storage_key, metadata] : metadata_map) {
if (metadata->client_tag_hash() == kClientTagHash.value()) {
++count_for_dummy;
}
}
EXPECT_EQ(count_for_dummy, 1u);
histogram_tester.ExpectBucketCount(
"Sync.ModelTypeOrphanMetadata.ModelReadyToSync",
/*sample=*/ModelTypeHistogramValue(syncer::TYPED_URLS),
/*expected_count=*/1);
}
|
923e6c2b27a094d2bea7d8167246b5074e18d951 | 67e24dd384bdf75beb0f4d21eec362da0af6d89d | /OOP/Classes/person_definition.h | 545b1493f3cda877f2cfe8210d13b800299d3398 | [] | no_license | OdessaRadio/CPP-From-Beginner-to-Expert | 0b8cc32eaa0179b7b161645d870a789df9e926cb | 18a46624e9c41f626533562b5daa0d4e1c30bc56 | refs/heads/master | 2022-12-28T23:27:34.094170 | 2020-10-13T08:48:57 | 2020-10-13T08:48:57 | 296,020,264 | 0 | 0 | null | 2020-10-07T06:46:50 | 2020-09-16T12:04:40 | C++ | UTF-8 | C++ | false | false | 724 | h | person_definition.h | #ifndef PERSON_DEFINITION_H_INCLUDED
#define PERSON_DEFINITION_H_INCLUDED
#include <iostream>
using namespace std;
class PersonalData
{
private: // private means it can be used only inside class
int age;
string name;
int *p;
public: //public means that attributes and methods are available outside
// constructor is not returning anything
PersonalData(); // constructor
PersonalData(short); // constructor
~PersonalData() ; // destructor
void setName (string);
string getName () {return name;}
/*These functions are set age*/
void setAge (int);
int getAge () {return age;}
};
#endif // PERSON_DEFINITION_H_INCLUDED
|
a0fd8d80753ffed4404056f1da15c622e8b403e0 | 06ed081966adfbcd212eb57050f8cceb4f8faea7 | /MaximumGap.cpp | 6d4c16f48a99d046a50ae4150a2ce652389a5985 | [] | no_license | ak638/leetcode | 8ccc5c1509dce4e1de52216ce1031327f5fb0a74 | 8a1829041718c3849150ad2fe30dde795289d635 | refs/heads/master | 2021-06-07T13:32:37.569282 | 2019-03-20T03:58:12 | 2019-03-20T03:58:12 | 26,021,910 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,451 | cpp | MaximumGap.cpp | #include <stdio.h>
#include <stdlib.h>
#include <string>
#include <stack>
#include <queue>
#include <vector>
#include <set>
//#include <unordered_set>
#include <map>
#include <bitset>
//#include <unordered_map>
//#include "unordered_set"
//#include "unordered_map"
#include <string.h>
#include <cmath>
//https://leetcode.com/problems/maximum-gap/
using namespace std;
class Solution {
public:
int maximumGap(vector<int> &num)
{
//bucket sort
int n = (int)num.size();
if (n < 2) return 0;
int iMax = num[0];
int iMin = num[0];
for (int i = 0; i < n; ++i)
{
iMax = max(iMax, num[i]);
iMin = min(iMin, num[i]);
}
//利用一个特性,免除在bucket里面进行sort
//这样就可以不用存同一个bucket里面的元素,只需要记录bucket的最大和最小值就可以
//准确来说应该是(只有n-1个间隔):
//max_gap的low bound应该为low_bound = (iMax - iMin) / (n - 1) + ((iMax - iMin) % (n - 1) ? 1 : 0);
//low_bound >= old_iInterval,所以用old_iInterval作为max_gap的最小值是没问题的!
//int old_iInterval = 1 + (iMax - iMin) / n; //桶中元素的max_gap,必定小于等于全部元素的max_gap的最小值, safe!
int iInterval = (iMax - iMin) / (n - 1) + ((iMax - iMin) % (n - 1) ? 1 : 0);
vector<int> vecMin(n, INT_MAX);
vector<int> vecMax(n, -1);
int max_gap = iInterval;
for (int i = 0; i < n; ++i)
{
int idx = (num[i] - iMin) / iInterval;
vecMin[idx] = min(num[i], vecMin[idx]);
vecMax[idx] = max(num[i], vecMax[idx]);
}
int last_max = -1;
for (int i = 0; i < n; ++i)
{
//cmp last max with this min
//可能中间有些bucket是空的,需要跳过
if (vecMin[i] == INT_MAX) continue;
if (last_max == -1) last_max = vecMax[i];
max_gap = max(max_gap, vecMin[i] - last_max);
last_max = vecMax[i];
}
return max_gap;
}
int maximumGap_v1(vector<int> &num)
{
//bucket sort
int n = (int)num.size();
if (n < 2) return 0;
int iMax = num[0];
int iMin = num[0];
for (int i = 0; i < n; ++i)
{
iMax = max(iMax, num[i]);
iMin = min(iMin, num[i]);
}
int iBkSize = n;
int iInterval = (iMax - iMin) / iBkSize + 1; //each bucket range size
vector<vector<int> > vecBucket(iBkSize, vector<int>());
for (int i = 0; i < n; ++i)
{
vecBucket[(num[i]-iMin) / iInterval].push_back(num[i]);
}
int last_num = -1;
int max_gap = 0;
//sort each bucket
for (int i = 0; i < iBkSize; ++i)
{
sort(vecBucket[i].begin(), vecBucket[i].end());
for (int j = 0; j < vecBucket[i].size(); ++j)
{
if (last_num == -1) last_num = vecBucket[i][j];
max_gap = max(max_gap, vecBucket[i][j] - last_num);
last_num = vecBucket[i][j];
}
}
return max_gap;
}
};
int main(int argc, char *argv[])
{
freopen("./input.txt", "r", stdin);
//freopen("./tmp2.txt", "r", stdin);
Solution poSolution;
int testcase = 0;
scanf("%d", &testcase);
while (testcase--)
{
int n;
scanf("%d", &n);
//printf("nnnn %d\n", n);
vector<int> num;
while (n--)
{
int a;
scanf("%d", &a);
num.push_back(a);
//printf("asdf%d %d\n", a, num[num.size()-1]);
}
//printf("len %u\n", num.size());
int res = poSolution.maximumGap(num);
printf("RES: %d\n", res);
}
return 0;
}
/*
5
6
1 199 189 3 4 2
6
100 4 200 1 3 2
3
1000 1 100000
10
1 2 3 5 2 1 5 6 2 4
2
1 10000000
*/
|
f54c49249dd0183ed5269192d2498af98032dc7d | 4154ca38100f91a42a4d3ba875e7b76c03cb7dba | /detours/server_player_counts.cpp | 6bce336a36201f1ebc0872558b47fbbb4f7b6123 | [] | no_license | Attano/Left4Downtown2 | 8e27f2a9de2b57db0172c4ec42f7679e10bda2a0 | 944994f916617201680c100d372c1074c5f6ae42 | refs/heads/master | 2021-01-18T22:57:38.963577 | 2019-02-01T10:08:01 | 2019-02-01T10:08:01 | 9,821,427 | 27 | 28 | null | 2019-02-01T10:08:02 | 2013-05-02T19:57:30 | C++ | UTF-8 | C++ | false | false | 2,382 | cpp | server_player_counts.cpp | /**
* vim: set ts=4 :
* =============================================================================
* Left 4 Downtown SourceMod Extension
* Copyright (C) 2009-2011 Downtown1, ProdigySim; 2012-2015 Visor
* =============================================================================
*
* 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 "server_player_counts.h"
#include "player_slots.h"
#include "extension.h"
namespace Detours
{
/*
On Windows overwriting maxPlayers makes the server browser display that value
On Linux overwriting maxPlayers only makes 'status' show that value as the max
*/
int ServerPlayerCounts::OnGetMasterServerPlayerCounts(int* currentPlayers, int* maxPlayers, int* unknownArg)
{
int arg1, arg2, arg3;
int results = (this->*(GetTrampoline()))(&arg1, &arg2, &arg3);
//spams log every 2 seconds
//L4D_DEBUG_LOG("CServer::GetMasterServerPlayerCounts returned %d, args(%d, %d, %d) / MaxSlots = %d", results, arg1, arg2, arg3, ::PlayerSlots::MaxSlots);
*currentPlayers = arg1;
*maxPlayers = arg2;
*unknownArg = arg3; //always 0 in brief testing
if(::PlayerSlots::MaxSlots != -1)
{
*maxPlayers = ::PlayerSlots::MaxSlots;
}
return results;
}
};
|
9dc6568ae63185edbddf8f64088e719b26d76367 | 4bcf0d6e8cd5c7722dd45a24a57a2586b308b597 | /include/replier.h | 850c437905673bc4809cc6bd4d335d0a652a44e3 | [] | no_license | ababo/syncer | 8da2eeb0b99930dbbe1c39be49970b1d27c37e50 | 4d454e1777dbe6e177dade9d9b35ceecf96b0642 | refs/heads/master | 2021-05-15T16:16:20.513433 | 2017-10-03T18:56:31 | 2017-10-03T19:11:40 | 107,448,139 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,635 | h | replier.h | /**
* @file replier.h
* @author Simon Prykhodko
* @brief Generic replier implementation.
*/
#ifndef SYNCER_REPLIER_H_
#define SYNCER_REPLIER_H_
#include <atomic>
#include <functional>
#include <thread>
#include "common.h"
#include "socket.h"
namespace syncer {
/**
* @brief Generic replier.
* @details It creates and binds a REPLIER-socket at time of construction.
* Then it allows to process incoming requests via provided callback, sending
* the corresponding replies. The callback will be called sequentially in a
* dedicated thread.
*/
template <typename Socket = DefaultSocket> class Replier {
public:
/** @brief Alias for socket parameters. */
using Params = typename Socket::Params;
/** @brief Alias for socket message. */
using Message = typename Socket::Message;
/** @brief Callback to handle requests. */
using Callback = std::function<Message(const Message&)>;
/**
* @brief Constructor.
* @param params socket parameters.
* @param cb a callback for request processing.
*/
Replier(const Params& params, Callback cb)
: exit_(false)
, thr_(&Replier::Process, this, params, cb) { }
/** @brief Destructor. */
~Replier() {
exit_ = true;
thr_.join();
}
private:
void Process(const Params& params, Callback cb) {
Message msg;
msg.reserve(Message::MAX_SIZE);
Socket skt(SocketType::REPLIER, params);
while (!exit_) {
if (skt.WaitToReceive()) {
skt.Receive(msg);
skt.Send(cb(msg));
}
}
}
// the field order is important!
std::atomic_bool exit_;
std::thread thr_;
};
}
#endif // SYNCER_REPLIER_H_
|
ba0f90d2c660f8d17965544ae2cfcaaa2d5deded | 52bcada7e6ccc55adb2896e9960dcc70d7c9942c | /120. Triangle.cpp | 3a254d01a91b48ebfa24c009b5995a76e4058340 | [] | no_license | RockyYan1994/Algorithm | fab75db170ab59446bf478ad2f9b76bd0d8c4b43 | 1d0edb009ec566cc917ee732c5d7b3ac281f3a61 | refs/heads/master | 2021-10-02T18:53:12.273993 | 2018-11-30T08:16:35 | 2018-11-30T08:16:35 | 114,224,825 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 599 | cpp | 120. Triangle.cpp | /*
查看discussion之后,发现可以通过从下往上的方法,不断找出经过每个节点的最短路径,最后到达顶点。
最基本的方法是从头向下,把每条路径计算出来,然后遍历找出最短的路径。
*/
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int row = triangle.size();
vector<int> temp(triangle.back());
for(int i=row-2;i>=0;i--){
for(int j=0;j<=i;j++){
temp[j] = triangle[i][j] + min(temp[j],temp[j+1]);
}
}
return temp[0];
}
}; |
47424e953eec485bb6515f222acff7b3e03d6026 | e73121fcfcc4df2e7092a82f4810ce9615e9dd83 | /UVa/uva_884.cpp | 80e12556de041c4cef63dee22678ad83d746d103 | [] | no_license | Redwanuzzaman/Online-Judge-Problem-Solutions | 1aba5eda26a03ed8cafaf6281618bf13bea7699b | f2f4ccac708bd49e825f2788da886bf434523d3c | refs/heads/master | 2022-08-29T04:10:31.084874 | 2022-08-14T18:20:30 | 2022-08-14T18:20:30 | 142,601,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,027 | cpp | uva_884.cpp | va#include <bits/stdc++.h>
using namespace std;
#define MAX 100005
typedef long long ll;
bool marked[MAX];
ll arr[1000010];
vector <int> prime;
void sieve()
{
for(int i = 3; i * i <= MAX; i += 2)
{
if(marked[i] == false)
{
for(int j = i * i; j <= MAX; j += i+i)
marked[j] = true;
}
}
prime.push_back(2);
for(int i = 3; i < MAX; i += 2)
{
if(marked[i] == false)
{
prime.push_back(i);
}
}
}
ll divCount(ll n)
{
ll cnt = 0;
for(int i = 0; prime[i] * prime[i] <= n; i++)
{
while(n % prime[i] == 0)
{
cnt++;
n /= prime[i];
}
}
if(n > 1) cnt++;
return cnt;
}
int main()
{
sieve();
ll n;
arr[0] = 0;
arr[1] = 0;
for(ll i = 2; i < 1000005; i++)
{
arr[i] = arr[i-1] + divCount(i);
}
while(cin >> n)
{
printf("%lld\n", arr[n]);
}
}
|
d712a7a50ac03cbd01c00ad052220a32b3b7cfa9 | ff7268092ecb0f97a61cf0b4e735ef83446d481b | /mydialog.cpp | 4a070d5e4e47f05075e601dcf2617bc52bca8072 | [] | no_license | haorenhl007/QT_dataGathing_embeddedSystem | 9e9776b2c614bb440eb7930bc4fe1dddf1c6929f | 936e3d7ec11ca785d7e4d5a8eaf1d8307a84f708 | refs/heads/master | 2020-03-20T03:30:28.447952 | 2017-03-07T10:07:18 | 2017-03-07T10:07:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,926 | cpp | mydialog.cpp | #include "mydialog.h"
#include "qgridlayout.h"
#include "qlabel.h"
#include "qtextcodec.h"
#include "qcheckbox.h"
#include "qradiobutton.h"
#include "qcombobox.h"
#include "qlineedit.h"
#include "qmessagebox.h"
#include "qpushbutton.h"
mydialog::mydialog(QWidget*parent):QDialog(parent)
{
QGridLayout *grid=new QGridLayout;
grid->setRowStretch(0,1);
grid->setRowStretch(8,1);
grid->setColumnStretch(0,1);
grid->setColumnStretch(4,1);
QTextCodec *code=QTextCodec::codecForLocale();
QLabel *ll1=new QLabel(code->toUnicode("用户名"));
QLabel *ll2=new QLabel(code->toUnicode("密码"));
QLabel *ll3=new QLabel(code->toUnicode("性别"));
QLabel *ll4=new QLabel(code->toUnicode("班级"));
QLabel *ll5=new QLabel(code->toUnicode("爱好"));
grid->addWidget(ll1,1,1);
grid->addWidget(ll2,2,1);
grid->addWidget(ll3,3,1);
grid->addWidget(ll4,4,1);
grid->addWidget(ll5,5,1);
name=new QLineEdit();
password=new QLineEdit();
password->setEchoMode(QLineEdit::Password);
grid->addWidget(name,1,2,1,2);
grid->addWidget(password,2,2,1,2);
QComboBox *com=new QComboBox;
com->addItem("iot-1-class");
com->addItem("iot-2-class");
com->addItem("iot-2-class");
grid->addWidget(com,4,2,1,2);
banji="iot-1-class";
connect(com,SIGNAL(currentIndexChanged(QString)),
this,SLOT(on_combo_changed(QString)));
QRadioButton *r1=new QRadioButton(code->toUnicode("男"));
QRadioButton *r2=new QRadioButton(code->toUnicode("女"));
grid->addWidget(r1,3,2);
grid->addWidget(r2,3,3);
connect(r1,SIGNAL(clicked()),this,SLOT(on_radio_clicked()));
connect(r2,SIGNAL(clicked()),this,SLOT(on_radio_clicked()));
r1->setChecked(true);
sex="男";
//xing qu aihao
char *name[]={"洗澡","打球","打斗斗","玩蛇"};
for(int i=0;i<4;i++){
ck[i]=new QCheckBox(code->toUnicode(name[i]));
connect(ck[i],SIGNAL(clicked()),
this,SLOT(on_check_clicked()));
}
grid->addWidget(ck[0],5,2);
grid->addWidget(ck[1],5,3);
grid->addWidget(ck[2],6,2);
grid->addWidget(ck[3],6,3);
fav="";
QPushButton *ok=new QPushButton(code->toUnicode("确定"));
QPushButton *cancel=new QPushButton(code->toUnicode("取消"));
grid->addWidget(ok,7,1);
grid->addWidget(cancel,7,3);
connect(ok,SIGNAL(clicked()),this,
SLOT(on_Yes_clicked()));
connect(cancel,SIGNAL(clicked()),this,
SLOT(close()));
flag =0;
this->setLayout(grid);
}
void mydialog::on_Yes_clicked(){
if(name->text().isEmpty() | password->text().isEmpty()||
fav.isEmpty())
QMessageBox::information(this,"tishi",
"please input completely");
else{
flag = 1;
this->close();
}
}
//void mydialog::close(){
//
//}
QString mydialog::exec(){ //
QDialog::exec();
if(this->flag==1){
QString ss=name->text()+"-"+password->text()+"-"+sex
+"-"+banji+"-"+fav;
// return name->text()+"-"+pass->text()+"-"+sex
// +"-"+banji+"-"+fav;
emit(sig(ss));
return ss;
}
return QString(NULL);
}
void mydialog::on_radio_clicked(){
QString ss=((QRadioButton*)sender())->text();
this->sex=ss;
}
void mydialog::on_check_clicked(){
QString ss;
for(int i=0;i<4;i++){
if(ck[i]->isChecked()){
ss+= ck[i]->text()+"-";
}
}
fav=ss;
// //chai fen zi fuchuang
// QStringList mm=ss.split("-");
// for(int i=0;i<mm.size();i++)
// qDebug()<<mm.at(i);
}
void mydialog::on_combo_changed(QString ss){
banji=ss;
}
|
d41815276b6852a78e011f7ee851386c26fe9dc0 | 99e1afbd2f150775f95eacfb9e4f10038a1b0c40 | /src/animation/PaintingLight.h | b7f2ff0b0bd1112f740c66291ef8a2979b68f921 | [] | no_license | team-carbon-bee/smartLeaf_backend | 108c50c2302b3d7695631d4bbb934750274afc49 | 4004ede2a3ef2a879b65426545a46d4f3cf7c5ec | refs/heads/master | 2022-07-09T08:21:01.148267 | 2022-03-31T19:52:52 | 2022-03-31T19:52:52 | 207,617,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,486 | h | PaintingLight.h | #pragma once
#include <Arduino.h>
#include <LinkedList.h>
#include "IAnimation.h"
#include "referenceSystem/LinearReferenceSystem.h"
#include "PixelHelper.h"
#include "tools/DividedCounter.h"
namespace animation
{
class PaintingLight : public IAnimation
{
public:
PaintingLight()
{
}
virtual ~PaintingLight()
{
}
String name() const
{
return "Painting lights";
}
uint8_t id() const
{
return 14;
}
void setup()
{
}
//Called each time before starting animation
void initialize()
{
referenceSystem::LinearRef.clear();
referenceSystem::LinearRef.driveLeds();
_foreColor = PixelHelper::getRandomFullColor();
_backgroundColor = PixelHelper::getRandomFullColorExcept(_foreColor);
_curPos = 0;
_divider.configure(random(1, 3));
}
//Called at the end of the animation
virtual void deinitialize()
{
}
//Determine if the animation can be ended by itself
virtual bool canFinish() const
{
return false;
}
//Check if the animation has finished if it can false otherwise
virtual bool isFinished() const
{
return false;
}
void loop()
{
if (_divider.step())
{
//we draw the painted part
for (int i = 0; i < _curPos; ++i)
referenceSystem::LinearRef.setPixel(i, _foreColor);
//we draw the background
for (int i = _curPos; i < referenceSystem::LinearRef.ledCount(); ++i)
referenceSystem::LinearRef.setPixel(i, _backgroundColor);
_curPos++;
if (_curPos >= referenceSystem::LinearRef.ledCount())
{
_curPos = 0;
_backgroundColor = _foreColor;
_foreColor = PixelHelper::getRandomFullColorExcept(_backgroundColor);
}
referenceSystem::LinearRef.driveLeds();
}
}
private:
Color _foreColor;
Color _backgroundColor;
int _curPos;
DividedCounter _divider;
};
} |
cb9286e77b99a71dad1a971cb9a8c70495e61ec9 | 9e02c151f257584592d7374b0045196a3fd2cf53 | /AtCoder/ARC/008/B.cpp | 278d9ac94f472ecba38963634a7381865dd1d88f | [] | no_license | robertcal/cpp_competitive_programming | 891c97f315714a6b1fc811f65f6be361eb642ef2 | 0bf5302f1fb2aa8f8ec352d83fa6281f73dec9b5 | refs/heads/master | 2021-12-13T18:12:31.930186 | 2021-09-29T00:24:09 | 2021-09-29T00:24:09 | 173,748,291 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 887 | cpp | B.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 1e9;
const int MOD = 1e9 + 7;
const ll LINF = 1e18;
int main() {
int n, m; cin >> n >> m;
string name; cin >> name;
string k; cin >> k;
int name_cnt[26] = {};
int k_cnt[26] = {};
for (int i = 0; i < name.length(); ++i) {
name_cnt[name[i] - 'A']++;
}
for (int i = 0; i < k.length(); ++i) {
k_cnt[k[i] - 'A']++;
}
int ma = 0;
for (int i = 0; i < 26; ++i) {
int t;
if (name_cnt[i] > 0 && k_cnt[i] == 0) {
cout << -1 << endl;
return 0;
}
if (k_cnt[i] == 0) continue;
if (name_cnt[i] % k_cnt[i] == 0) {
t = name_cnt[i] / k_cnt[i];
} else {
t = name_cnt[i] / k_cnt[i] + 1;
}
ma = max(ma, t);
}
cout << ma << endl;
} |
e3908f20c670e34c98c3242cb2e697bca0e17a94 | f15c036b4b06357a1371c1c1e6cfbb1116563ba3 | /component/rbtree_sim.cpp | 9818b89ebd69c17215ec7815e16f3baa0eb5d325 | [] | no_license | dayu521/mimic | 4d3316abf5ffa0b48cc8c3e65298839fd38f8909 | d78d3d278c7bab200d7d33687b4d58ebd3cf5622 | refs/heads/master | 2023-04-12T08:21:25.769493 | 2020-05-19T06:13:07 | 2020-05-19T06:13:07 | 264,967,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 835 | cpp | rbtree_sim.cpp | #include "rbtree_sim.h"
#include "animation/rbtree_model.h"
#include "datasource/rbdata.h"
#include<QRandomGenerator>
Rbtree::Rbtree():rbtreeModel(std::make_shared<RbtreeModel>()),rbData(std::make_shared<RbData>())
{
dataSource=rbData;
animation=rbtreeModel;
}
Rbtree::~Rbtree()
{
}
void Rbtree::convertInput(const std::vector<int> &v)
{
Input a={RbData::Insert,100};
for(int i=0;i<a.dataLength;i++)
a.data[i]=QRandomGenerator::global()->generate()%500;
rbData->prepareWorks();
rbData->setInput({a});
// rbtreeModel->pullOriginInput({a});
}
void Rbtree::prepareReplay()
{
rbtreeModel->initModelData();
}
void Rbtree::produceModelData()
{
Simulator::produceModelData();
rbtreeModel->setXYNodeNumber(rbData->treeMaxNumberX(),rbData->treeMaxNumberY());
st=Status::HasModelData;
}
|
1d03eb8923d550f5286c3a12dec170ffeb542a76 | 819506e59300756d657a328ce9418825eeb2c9cc | /CQU/chuangchun15网赛/i.cpp | b58bbae22bd5a331cf3f2bcab5c91bf9d6d7a257 | [] | no_license | zerolxf/zero | 6a996c609e2863503b963d6798534c78b3c9847c | d8c73a1cc00f8a94c436dc2a40c814c63f9fa132 | refs/heads/master | 2021-06-27T04:13:00.721188 | 2020-10-08T07:45:46 | 2020-10-08T07:45:46 | 48,839,896 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,592 | cpp | i.cpp | /*************************************************************************
> File Name: i.cpp
> Author: Zeroxf
> Mail: 641587852@qq.com
> Created Time: 2016年04月30日 星期六 15时31分08秒
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<stack>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<string>
#include<cmath>
using namespace std;
#define ll long long
#define rep(i,n) for(int i =0; i < n; ++i)
#define CLR(x) memset(x,0,sizeof x)
#define MEM(a,b) memset(a,b,sizeof a)
#define pr(x) cout << #x << " = " << x << " ";
#define prln(x) cout << #x << " = " << x << endl;
const int maxn = 4e5+100;
const int INF = 0x3f3f3f3f;
int x[maxn], y[maxn], z[maxn], a[maxn], b[maxn], c[maxn];
int dp[1234567];
int getdp2 (int p, int m, int *v, int *cost, int *num){
int ma = 0;
ma = 50000;
for(int i = 0; i <= ma+200; ++i) dp[i] = 0;
dp[0] = 0;
for(int i = 0; i < m; ++i){
int base = 1;
while(base <= num[i]){
for(int j = ma+110; j >= base*cost[i]; --j){
dp[j] = max(dp[j], dp[j-base*cost[i]] + base*v[i]);
}
num[i] -= base;
base <<=1;
}
if(num[i] > 0){
for(int j = ma+110; j >= num[i]*cost[i]; --j){
dp[j] = max(dp[j], (dp[j-num[i]*cost[i]] + num[i]*v[i]));
}
}
}
int ans = INF;
for(int i = 0; i <= ma+110; ++i){
if(dp[i] >= p) ans = min(i,ans);
}
return ans;
}
int getdp(int p, int m, int *v, int *cost, int *num){
int ma = 0;
ma = p;
for(int i = 0; i <= ma+200; ++i) dp[i] = INF;
dp[0] = 0;
for(int i = 0; i < m; ++i){
int base = 1;
while(base <= num[i]){
for(int j = ma+110; j >= base*v[i]; --j){
dp[j] = min(dp[j], dp[j-base*v[i]] + base*cost[i]);
}
num[i] -= base;
base <<=1;
}
if(num[i] > 0){
for(int j = ma+110; j >= num[i]*v[i]; --j){
dp[j] = min(dp[j], (dp[j-num[i]*v[i]] + num[i]*cost[i]));
}
}
}
int ans = INF;
for(int i = ma; i <= ma+110; ++i){
ans = min(ans,dp[i]);
}
return ans;
}
int main(){
#ifdef LOCAL
freopen("/home/zeroxf/桌面/in.txt","r",stdin);
#endif
int n, m, p;
int kase = 0;
scanf("%d", &kase);
while(kase--){
scanf("%d%d%d", &n, &m, &p);
for(int i = 0; i < n; ++i){
scanf("%d%d%d", &x[i], &y[i], &z[i]);
}
for(int i = 0; i < m; ++i){
scanf("%d%d%d", &a[i], &b[i], &c[i]);
}
bool ok = true;
p = getdp(p, n, x, y, z);
if(p >= INF) ok = false;
if(ok) p = getdp2(p, m, a, b, c);
if(p >= INF) ok = false;
if(ok) printf("%d\n",p);
else printf("TAT\n");
}
return 0;
}
|
a1dbd5d8e17ddf806eef564163f483e6925b850d | 508efd553572f28ebeb93bac77d913b514094256 | /codeforces/560B.cpp | 564b8f1649ad4b1ba7b090bca66c5633f45ca487 | [] | no_license | pimukthee/competitive-prog | 4eaa917c27ddd02c8e4ff56502fa53eb7f884011 | 0a40e9fe8b229ce3534ad6e6e316e0b94c028847 | refs/heads/master | 2021-05-23T05:59:02.243040 | 2018-06-08T08:54:03 | 2018-06-08T08:54:03 | 94,750,445 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 539 | cpp | 560B.cpp | #include <bits/stdc++.h>
using namespace std;
int a1[5][5];
int main() {
int aa, bb, a, b;
scanf("%d %d", &a, &b);
for(int i = 0; i < 2; ++i) scanf("%d %d", &a1[i][0], &a1[i][1]);
for(int i = 0; i < 2; ++i) {
for(int j = 0; j < 2; ++j) {
aa = a1[0][i] + a1[1][j];
bb = max(a1[0][i ^ 1], a1[1][j ^ 1]);
if((aa<=a && bb<=b) || (aa<=b && bb<=a)) {
printf("YES\n");
return 0;
}
}
}
printf("NO\n");
return 0;
}
|
4d595239da8333c5fd07bd4245974b5ca4e48c3f | d446ed18144ac191377c2a5e0585fb61317b96c2 | /src/eepp/ui/uieventdispatcher.cpp | 1c8bc71fee0dfa2ed36b953cb76fdd4a85d4f63c | [
"MIT"
] | permissive | thyrdmc/eepp | 6f8ee84f048efaf1b3aca931ea612e61136e15c4 | 93b72b1bcab794a43706658e7978c5e852c3b65a | refs/heads/master | 2023-06-25T11:18:16.371330 | 2019-05-22T04:26:41 | 2019-05-22T04:26:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 899 | cpp | uieventdispatcher.cpp | #include <eepp/ui/uieventdispatcher.hpp>
#include <eepp/ui/uiscenenode.hpp>
#include <eepp/ui/uinode.hpp>
#include <eepp/window/inputevent.hpp>
namespace EE { namespace UI {
UIEventDispatcher * UIEventDispatcher::New( SceneNode * sceneNode ) {
return eeNew( UIEventDispatcher, ( sceneNode ) );
}
UIEventDispatcher::UIEventDispatcher( SceneNode * sceneNode ) :
EventDispatcher( sceneNode )
{}
void UIEventDispatcher::inputCallback(InputEvent * Event) {
EventDispatcher::inputCallback( Event );
switch( Event->Type ) {
case InputEvent::KeyDown:
checkTabPress( Event->key.keysym.sym );
break;
}
}
void UIEventDispatcher::checkTabPress( const Uint32& KeyCode ) {
eeASSERT( NULL != mFocusControl );
if ( KeyCode == KEY_TAB && mFocusControl->isUINode() ) {
Node * Ctrl = static_cast<UINode*>( mFocusControl )->getNextWidget();
if ( NULL != Ctrl )
Ctrl->setFocus();
}
}
}}
|
0ff869f8d01a93ac8444a6b5105489e29091b3a5 | bee8e205a3ff0a4d0013fe5370b1c48f0f104d97 | /Prime Number 3.0/Prime Number 3.0/prime number 3.0.cpp | 71f9da3e0af0980a9f1e4b3f75a52da0687737a1 | [] | no_license | ahamza488/Prime-Number | 270a0466be6f40b5e0317fd203502df5417c96b5 | 256d246e89aecc7416edbc302221f15a364d4cfc | refs/heads/main | 2023-07-14T18:07:43.713944 | 2021-08-23T18:39:51 | 2021-08-23T18:39:51 | 399,211,975 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,179 | cpp | prime number 3.0.cpp | //This program is to write prime numbers between 1 and 1000........
#include <iostream>
using namespace std;
int main()
{
int n = 2, j = 2;
cout << "The Prime numbers between 1 and 1000 are :" << endl;
//This outer loop is to run the loop for first thousand (1000) numbers/integers......
for ( n = 2; n <= 1000; n++)
{
bool prime = true;
//This inner loop will check whether the number is divisible by the numbers between 2 and n-1
//Let suppose we have number 6....
//This inner loop will divide 6 by 2,3,4,5 one by one and check if remainder is zero or not.
//If the remainder comes out to be zero means the number is divisible by numbers other than
// 1 and 6. So the number is not a prime number.
for ( j = 2; j <= n-1; j++)
{
if (n%j == 0)
{
prime = false;
break;
}
}
if (prime == true)
{
cout << n << endl;
}
}
/*
while (n <= 100)
{
bool prime = true;
while (j <= n-1)
{
if (n%j == 0)
{
prime = false;
break;
}
j++;
}
if (prime == true)
{
cout << n << endl;
}
n++;
}
*/
return 0;
} |
a11c5b361d481535cef82cd3eea4822568718397 | 1b007890c7de12b57f9667bacc6d4f6b5cd7083c | /src/main/impl/static_measure_temp_window.hpp | 5f195420075b48837d3449ea92e7ef64a2df16d9 | [] | no_license | Akirathan/STM32-smart-heating | 93d80f4f02e2178ca2ba7ac0c49d28459d3c3e83 | 29d54827906ed5cd9f4f1f7539af35e7a052b71c | refs/heads/master | 2021-01-02T08:58:23.717616 | 2018-02-26T12:18:20 | 2018-02-26T12:18:20 | 85,754,402 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 938 | hpp | static_measure_temp_window.hpp | /**
* @file static_measure_temp_window.hpp
* @author Pavel Marek
* @date 9.8.2017
*/
#ifndef STATIC_MEASURE_TEMP_WINDOW_HPP_
#define STATIC_MEASURE_TEMP_WINDOW_HPP_
#include "static_temp_window.hpp"
#include "callbacks.hpp"
#include "rtc_controller.hpp"
#include "temp_sensor.hpp"
/**
* @brief Static window for displaying actual temperature.
*
* After @ref measure method is called, temperature is measured in every minute
* callback (@ref minCallback) and the current temperature is then displayed.
*
* @note Note that this window can run on background.
*/
class StaticMeasureTempWindow : public StaticTempWindow, public IMinCallback
{
public:
StaticMeasureTempWindow(const Coord& c = Coord(0,0));
~StaticMeasureTempWindow();
virtual void minCallback() override;
virtual void registerMinCallback() override;
void measure();
private:
bool registeredCallback = false;
};
#endif /* STATIC_MEASURE_TEMP_WINDOW_HPP_ */
|
0c981c9424151ad9a46302990abcfc41117120cf | 0aafc561a03e3682a3bc6f418981af28ab381e49 | /ann/src/NeuralNetwork.cpp | 11ee5872a51d562e202eeef8c103078496db735d | [] | no_license | andregri/Feed-Forward-Neural-Network | 87287ebe0933b73a0aca1ac5ee298b3c2d81715b | 119b582a26ba49f888b65a62238d303dadffe7ec | refs/heads/master | 2022-11-17T03:22:06.135182 | 2020-07-21T13:53:30 | 2020-07-21T13:53:30 | 277,548,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,169 | cpp | NeuralNetwork.cpp | #include "../include/NeuralNetwork.hpp"
#include <stdexcept>
/**
* Constructor: define input layer.
*/
NeuralNetwork::NeuralNetwork(int input_size)
{
this->input_size = input_size;
}
/**
* Add a layer to the topology specifying number of neurons and activation
* function.
*/
void NeuralNetwork::add_layer(int num_neurons, ActivationFunction fcn)
{
// Add the layer.
layers.emplace_back(num_neurons, fcn);
// Add the weight matrix randomly initialized.
add_weight_matrix();
// Add the bias column vector.
add_bias_matrix();
}
/**
* Add a layer to the architecture, but initialize the weight matrix.
*/
void NeuralNetwork::add_layer(int num_neurons, ActivationFunction fcn, Matrix weight, Matrix bias)
{
// Add the layer.
layers.emplace_back(num_neurons, fcn);
// Add the weight matrix randomly initialized.
add_weight_matrix(weight);
// Add the bias column vector.
add_bias_matrix(bias);
}
/**
* Feed-forward propagation function: take an input, propagates it in the
* network and returns the output.
*/
Matrix NeuralNetwork::fprop(std::vector<double> input)
{
if(input.size() != input_size)
throw std::invalid_argument("Input size must be equal to the input layer size!");
// Propagate the input to the first layer.
// Make a column vector from the input:
Matrix h0(input_size, 1, false, 0);
for(int i = 0; i < input_size; ++i) {
h0(i, 0) = input[i];
}
// Multiply the first weight matrix to obtain the first input
Matrix a = weight_matrixes[0] * h0 + bias[0];
for(int i = 0; i < layers.size() - 1; ++i) {
layers[i].set_neurons(a);
Matrix h = layers[i].get_acitvated_neurons();
a = weight_matrixes[i+1] * h + bias[i+1];
}
// Get output of the last layer
int last_layer_index = layers.size() - 1;
layers[last_layer_index].set_neurons(a);
Matrix output = layers[last_layer_index].get_acitvated_neurons();
return output;
}
/**
* Add a random weight matrix that fits between the last 2 layers.
* If the network has no layer because it is adding the first layer, then add
* a matrix that fits the input and the first hidden layer.
*/
void NeuralNetwork::add_weight_matrix()
{
if(layers.empty())
throw std::logic_error("First add a layer to the private member layers!");
int num_cols; // number of neurons in the second last layer.
if(layers.size() == 1) {
// adding the first hidden layer.
num_cols = input_size;
} else {
int second_last_layer = layers.size() - 2;
num_cols = layers[second_last_layer].size();
}
int num_rows = layers.back().size(); // number of neurons in the last layer.
weight_matrixes.emplace_back(num_rows, num_cols, true, 0);
}
/**
* Add the input matrix to the weight matrixes vector.
* Check that the matrix fits the network.
*/
void NeuralNetwork::add_weight_matrix(Matrix w)
{
int num_cols; // number of neurons in the second last layer.
if(layers.size() == 1) {
// adding the first hidden layer.
num_cols = input_size;
} else {
int second_last_layer = layers.size() - 2;
num_cols = layers[second_last_layer].size();
}
int num_rows = layers.back().size(); // number of neurons in the last layer.
// check if the matrix fits in the network.
if(w.shape()[0] != num_rows || w.shape()[1] != num_cols) {
throw std::invalid_argument("The weight matrix doesn't fit the last layers.");
}
weight_matrixes.push_back(w);
}
/**
* Add a random bias vector to the network.
*/
void NeuralNetwork::add_bias_matrix()
{
int num_neurons = layers.back().size();
bias.emplace_back(num_neurons, 1, true, 0);
}
/**
* Add the input bias vector to the network.
* Check if the size is correct.
*/
void NeuralNetwork::add_bias_matrix(Matrix b)
{
int num_neurons = layers.back().size();
// check if bias has the correct size
if(b.shape()[0] != num_neurons || b.shape()[1] != 1)
throw std::invalid_argument("Bias matrix must be as long as the number of neurons.");
bias.push_back(b);
} |
ddcdc54fcf45a77d3cfd86b431e01f7b72b4fa39 | 6ffd23679939f59f0a09c9507a126ba056b239d7 | /dnn/src/arm_common/conv_bias/int8x8x16/direct_8x8x16_nchw44_kern.h | c137e4c2a4b38327a8645eee0c050f912cb34688 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | MegEngine/MegEngine | 74c1c9b6022c858962caf7f27e6f65220739999f | 66b79160d35b2710c00befede0c3fd729109e474 | refs/heads/master | 2023-08-23T20:01:32.476848 | 2023-08-01T07:12:01 | 2023-08-11T06:04:12 | 248,175,118 | 5,697 | 585 | Apache-2.0 | 2023-07-19T05:11:07 | 2020-03-18T08:21:58 | C++ | UTF-8 | C++ | false | false | 1,478 | h | direct_8x8x16_nchw44_kern.h | #pragma once
#include "src/arm_common/simd_macro/marm_neon.h"
#include "src/common/utils.h"
#include "src/fallback/conv_bias/common.h"
namespace megdnn {
namespace arm_common {
namespace int8x8x16_direct_nchw44 {
/**
origin src shape <n, ic/4, h, w, 4>
packed src shape <n, ic/4, h, w, 16>
example: (format like <ic>)
origin
<0> <1> <2> <3>
packed
low 64 bit <0> <0> <0> <0> | <1> <1> <1> <1>
---------------------------------------------------------------------
high 64 bit <2> <2> <2> <2> | <3> <3> <3> <3>
**/
static inline void nchw44_pack_src(const int8_t* src, int8_t* dst, int length) {
static const uint8_t src_idx_buffer[16] = {0, 0, 0, 0, 1, 1, 1, 1,
2, 2, 2, 2, 3, 3, 3, 3};
constexpr int pack_ic = 4;
constexpr int simd_len = 16;
uint8x16_t src_idx = vld1q_u8(src_idx_buffer);
for (int i = 0; i < length; i++) {
int8x16_t result = vld_dup_tbl_s32(src + i * pack_ic, src_idx);
vst1q_s8(dst + i * simd_len, result);
}
}
template <BiasMode bias_mode, int filter_size, int stride>
struct ConvDirectInt8Nchw44Choose {
static void impl(
const int8_t* src, const int8_t* filter, const int16_t* bias, int16_t* dst,
const size_t oc, const size_t ic, const size_t ih, const size_t iw,
const size_t oh, const size_t ow);
};
} // namespace int8x8x16_direct_nchw44
} // namespace arm_common
} // namespace megdnn
// vim: syntax=cpp.doxygen
|
6eade33741a845dec6e1e551f83f608f582642bb | 3cac45c6403af935467e9127130a696b0a30fe2e | /HackerRank Problems/HackerRank Easy Problems CPP/Projects/Save The Prisoners/Save The Prisoners.cpp | 23f856453e0db6c0131e8432df26ce5b1feaac1d | [] | no_license | Ansible2/Programming-Practice-Problems | 7186a3f5fa34e4565e96357b8605f715becb96c2 | d9da0cc8532955b97236e146bc185140166421f0 | refs/heads/main | 2023-08-15T13:45:02.358457 | 2021-09-13T20:28:32 | 2021-09-13T20:28:32 | 389,763,739 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,800 | cpp | Save The Prisoners.cpp | //#include <bits/stdc++.h>
#include <vector>
#include <string>
#include <unordered_map>
#include <iostream>
using namespace std;
string ltrim(const string&);
string rtrim(const string&);
vector<string> split(const string&);
/*
* Complete the 'saveThePrisoner' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. INTEGER m
* 3. INTEGER s
*/
int saveThePrisoner(int numberOfPrisoners, int numberOfSweets, int startingChairNumber) {
return ((numberOfSweets - 1) + (startingChairNumber - 1)) % numberOfPrisoners + 1;
}
// slow loop approach
/*
int saveThePrisoner(int numberOfPrisoners, int numberOfSweets, int startingChairNumber) {
int currentChairNumber = startingChairNumber;
for (int candiesPassedOut = 1; candiesPassedOut < numberOfSweets; candiesPassedOut++) {
if (currentChairNumber > numberOfPrisoners) {
currentChairNumber = 1;
}
currentChairNumber++;
}
return currentChairNumber;
}
*/
// oop slow approach
/*
class prisoner
{
private:
int chairNumber;
prisoner* nextChair;
public:
void setChairNumber(int chairNumber_) {
chairNumber = chairNumber_;
}
int getChairNumber() {
return chairNumber;
}
void setNextChair(prisoner* nextChair_) {
nextChair = nextChair_;
}
prisoner* getNextChair() {
return nextChair;
}
prisoner()
: chairNumber(-1), nextChair(nullptr){
}
prisoner(int chairNumber_)
: chairNumber(chairNumber_), nextChair(nullptr){
}
prisoner(int chairNumber_, prisoner &nextChair_)
: chairNumber(chairNumber_), nextChair(&nextChair_){
}
~prisoner() {
//cout << "deconstructor called" << endl;
}
};
int saveThePrisoner(int numberOfPrisoners, int numberOfSweets, int startingChairNumber) {
prisoner* previousPrisoner{ nullptr };
prisoner* startingPrisoner{ nullptr };
prisoner* firstPrisoner{ nullptr };
for (int i = 1; i <= numberOfPrisoners; i++) {
prisoner* currentPrisoner = new prisoner(i);
if (i == startingChairNumber) {
startingPrisoner = currentPrisoner;
}
if (i == 1) {
firstPrisoner = currentPrisoner;
}
else {
previousPrisoner->setNextChair(currentPrisoner);
}
if (i == numberOfPrisoners) {
currentPrisoner->setNextChair(firstPrisoner);
}
previousPrisoner = currentPrisoner;
}
int prisonerToSave = -1;
prisoner* currentPrisonerAdd{ startingPrisoner };
for (int i = 1; i <= numberOfSweets; i++) {
if (i == numberOfSweets) {
prisonerToSave = currentPrisonerAdd->getChairNumber();
cout << "found prisoner to save" << endl;
}
else {
currentPrisonerAdd = currentPrisonerAdd->getNextChair();
}
}
prisoner* currentAddress{ nullptr };
prisoner* nextAddress{ firstPrisoner };
for (int i = 1; i <= numberOfPrisoners; i++) {
currentAddress = nextAddress;
nextAddress = currentAddress->getNextChair();
delete currentAddress;
}
return prisonerToSave;
}
*/
int main()
{
cout << saveThePrisoner(5,2,2) << endl;
cout << saveThePrisoner(7,19,2) << endl;
cout << saveThePrisoner(3,7,3) << endl;
/*
ofstream fout(getenv("OUTPUT_PATH"));
string t_temp;
getline(cin, t_temp);
int t = stoi(ltrim(rtrim(t_temp)));
for (int t_itr = 0; t_itr < t; t_itr++) {
string first_multiple_input_temp;
getline(cin, first_multiple_input_temp);
vector<string> first_multiple_input = split(rtrim(first_multiple_input_temp));
int n = stoi(first_multiple_input[0]);
int m = stoi(first_multiple_input[1]);
int s = stoi(first_multiple_input[2]);
int result = saveThePrisoner(n, m, s);
fout << result << "\n";
}
fout.close();
*/
return 0;
}
/*
string ltrim(const string& str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}
string rtrim(const string& str) {
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);
return s;
}
vector<string> split(const string& str) {
vector<string> tokens;
string::size_type start = 0;
string::size_type end = 0;
while ((end = str.find(" ", start)) != string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end + 1;
}
tokens.push_back(str.substr(start));
return tokens;
}
*/ |
6b33a50afb914dd720353e150b8a72d419412c17 | f6182b68e967e5c3bd3732e5c747ec4807e3c2d9 | /StackMisc.cpp | d5a1fee770d5f70a50c85dfd4b26de43f6715a67 | [] | no_license | abhishekbhunia/codingplayground | 506897f5972c7dfc567925ebb40d71b82b91c58a | 57826539e6194d945c16ffafef0cb0ae48b39e91 | refs/heads/master | 2021-03-24T12:31:32.452888 | 2016-02-24T05:56:07 | 2016-02-24T05:56:07 | 39,354,153 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 531 | cpp | StackMisc.cpp | //1. Greater element in an array: O(n) time O(n) space
void nextGreater(vector<int> v){
stack<int> s;
s.push(v[0]);
for (int i = 1; i < v.size(); i++){
if (s.empty())
s.push(v[i]);
else{
while (!s.empty()&&v[i] > s.top()){
cout << v[i] << ">" << s.top() << endl;
s.pop();
}
s.push(v[i]);
}
}
while (!s.empty()){
cout << s.top() << ">" << numeric_limits<int>::min() << endl;
s.pop();
}
}
void test_nextGreaterStack(){
vector<int> v{ 11, 13, 21, 3 };
nextGreater(v);
}
|
c4d0e18192deb9e4d6dcd7e2444b0d41688e60f0 | 1dd8db8d1fe5a8a3ad37c98e6ed11d39566ab257 | /Platform/inc/Complex.h | 27d845e572d14e7931d16103038e54b3e71459d6 | [] | no_license | rfc3344/cosmo_sys | d4eaa07fc75676362f1ca7b6669e33155a44d788 | 2ad7f102ebd4d604726f3b2948bc8db300cf6c4f | refs/heads/master | 2021-01-12T09:22:12.110823 | 2016-12-14T14:09:27 | 2016-12-14T14:09:27 | 76,040,859 | 0 | 0 | null | 2016-12-10T14:34:54 | 2016-12-09T14:10:26 | null | UTF-8 | C++ | false | false | 1,532 | h | Complex.h | #ifndef _COMPLEX_H_
#define _COMPLEX_H_
#define PI 3.141592653589793
class Complex
{
public:
Complex();
Complex(double _Re);
Complex(double _Re, double _Im);
Complex(const Complex &rhs);
double Real() const { return _real; }
double Imag() const { return _imag; }
Complex& operator+=(const double& d);
Complex& operator+=(const Complex& c);
Complex& operator-=(const double& d);
Complex& operator-=(const Complex& c);
Complex& operator*=(const double& d);
Complex& operator*=(const Complex& c);
Complex& operator/=(const double& d);
Complex& operator/=(const Complex& c);
Complex& operator=(const Complex& C);
void Set(const double& re, const double& im);
~Complex(void);
private:
double _real;
double _imag;
};
Complex operator+(const Complex& c1, const Complex& c2);
Complex operator-(const Complex& c1, const Complex& c2);
Complex operator*(const Complex& c1, const Complex& c2);
Complex operator*(const Complex& c1, const double d2);
Complex operator*(const double d1, const Complex& c2);
Complex operator/(const Complex& c1, const Complex& c2);
Complex operator/(const Complex& c1, const double d2);
Complex operator/(const double d1, const Complex& c2);
Complex operator+(const Complex& c);
Complex operator-(const Complex& c);
Complex Conj(const Complex& c);
double Mod(const Complex& c);
double ModSquare(const Complex& c);
#define ABSComplex(c) Mod(c)
#define ABSInt(c) (((c) > 0) ? (c) : -1 * (c))
#endif
|
41d1fe1c96ff0eba7807cf7609a35e8bc757ef23 | 8d942edd547f1c7f53b0e022417fd6dfe6708e27 | /電腦圖學導論/正課/Project4_Skeleton_glad/Skeleton/Skeleton/Codes/TrainView.cpp | 9129304c7900ccad8f0f6ebdc003c91a22d5d924 | [] | no_license | ChengHung-Wang/NTUST_COMPUTER_GRAPHICS | 7b23a62c441eae807050eb9221335b1dc8cf6f4f | d8c31e84f9dd8c83644feeeaacdb0f72f61e3a82 | refs/heads/master | 2023-09-04T03:51:32.586409 | 2021-11-01T13:42:03 | 2021-11-01T13:42:03 | null | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 38,815 | cpp | TrainView.cpp | /************************************************************************
File: TrainView.cpp
Author:
Michael Gleicher, gleicher@cs.wisc.edu
Modifier
Yu-Chi Lai, yu-chi@cs.wisc.edu
Comment:
The TrainView is the window that actually shows the
train. Its a
GL display canvas (Fl_Gl_Window). It is held within
a TrainWindow
that is the outer window with all the widgets.
The TrainView needs
to be aware of the window - since it might need to
check the widgets to see how to draw
Note: we need to have pointers to this, but maybe not know
about it (beware circular references)
Platform: Visio Studio.Net 2003/2005
*************************************************************************/
#include <iostream>
#include <FileSystem>
#include <fstream>
#include <Fl/fl.h>
// we will need OpenGL, and OpenGL needs windows.h
#include <windows.h>
//#include "GL/gl.h"
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <GL/glu.h>
#include <filesystem>
#include "TrainView.H"
#include "TrainWindow.H"
#include "Utilities/3DUtils.H"
#define STB_IMAGE_STATIC
#define STB_IMAGE_IMPLEMENTATION
#include "model.h"
#ifdef EXAMPLE_SOLUTION
# include "TrainExample/TrainExample.H"
#endif
//************************************************************************
//
// * Constructor to set up the GL window
//========================================================================
TrainView::
TrainView(int x, int y, int w, int h, const char* l)
: Fl_Gl_Window(x,y,w,h,l)
//========================================================================
{
mode( FL_RGB|FL_ALPHA|FL_DOUBLE | FL_STENCIL );
resetArcball();
//stbi_set_flip_vertically_on_load(true);設這個skybox會上下顛倒,top bottom交換
}
//************************************************************************
//
// * Reset the camera to look at the world
//========================================================================
void TrainView::
resetArcball()
//========================================================================
{
// Set up the camera to look at the world
// these parameters might seem magical, and they kindof are
// a little trial and error goes a long way
arcball.setup(this, 40, 250, .2f, .4f, 0);
}
//************************************************************************
//
// * FlTk Event handler for the window
//########################################################################
// TODO:
// if you want to make the train respond to other events
// (like key presses), you might want to hack this.
//########################################################################
//========================================================================
int TrainView::handle(int event)
{
// see if the ArcBall will handle the event - if it does,
// then we're done
// note: the arcball only gets the event if we're in world view
if (tw->worldCam->value())
if (arcball.handle(event))
return 1;
// remember what button was used
static int last_push;
switch(event) {
// Mouse button being pushed event
case FL_PUSH:
last_push = Fl::event_button();
// if the left button be pushed is left mouse button
if (last_push == FL_LEFT_MOUSE ) {
doPick();
add_drop(8.0f,1.0f);
damage(1);
return 1;
};
break;
// Mouse button release event
case FL_RELEASE: // button release
damage(1);
last_push = 0;
return 1;
// Mouse button drag event
case FL_DRAG:
// Compute the new control point position
if ((last_push == FL_LEFT_MOUSE) && (selectedCube >= 0)) {
ControlPoint* cp = &m_pTrack->points[selectedCube];
double r1x, r1y, r1z, r2x, r2y, r2z;
getMouseLine(r1x, r1y, r1z, r2x, r2y, r2z);
double rx, ry, rz;
mousePoleGo(r1x, r1y, r1z, r2x, r2y, r2z,
static_cast<double>(cp->pos.x),
static_cast<double>(cp->pos.y),
static_cast<double>(cp->pos.z),
rx, ry, rz,
(Fl::event_state() & FL_CTRL) != 0);
cp->pos.x = (float) rx;
cp->pos.y = (float) ry;
cp->pos.z = (float) rz;
damage(1);
}
//if (last_push == FL_LEFT_MOUSE) {
// add_drop(0.5f, 1.0f);
// damage(1);
// Sleep(5);
// return 1;
//}
break;
// in order to get keyboard events, we need to accept focus
case FL_FOCUS:
return 1;
// every time the mouse enters this window, aggressively take focus
case FL_ENTER:
focus(this);
break;
case FL_KEYBOARD:
int k = Fl::event_key();
int ks = Fl::event_state();
if (k == 'p') {
// Print out the selected control point information
if (selectedCube >= 0)
printf("Selected(%d) (%g %g %g) (%g %g %g)\n",
selectedCube,
m_pTrack->points[selectedCube].pos.x,
m_pTrack->points[selectedCube].pos.y,
m_pTrack->points[selectedCube].pos.z,
m_pTrack->points[selectedCube].orient.x,
m_pTrack->points[selectedCube].orient.y,
m_pTrack->points[selectedCube].orient.z);
else
printf("Nothing Selected\n");
return 1;
};
break;
}
return Fl_Gl_Window::handle(event);
}
//************************************************************************
//
// * this is the code that actually draws the window
// it puts a lot of the work into other routines to simplify things
//========================================================================
void TrainView::draw()
{
//*********************************************************************
//
// * Set up basic opengl informaiton
//
//**********************************************************************
//initialized glad
if (gladLoadGL())
{
if (!this->sinwave) {
this->sinwave = new
Shader(
"./Codes/shaders/sinwave.vert",
nullptr, nullptr, nullptr,
"./Codes/shaders/sinwave.frag");
}
if (!this->height_map) {
this->height_map = new
Shader(
"./Codes/shaders/height_map.vert",
nullptr, nullptr, nullptr,
"./Codes/shaders/height_map.frag");
}
if (!this->skybox) {
this->skybox = new
Shader(
"./Codes/shaders/skybox.vert",
nullptr, nullptr, nullptr,
"./Codes/shaders/skybox.frag");
float skyboxVertices[] = {
// positions
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f
};
// skybox VAO
glGenVertexArrays(1, &skyboxVAO);
glGenBuffers(1, &skyboxVBO);
glBindVertexArray(skyboxVAO);
glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
vector<const GLchar*> faces = {
"Images/skybox/right.jpg",
"Images/skybox/left.jpg",
"Images/skybox/top.jpg",
"Images/skybox/bottom.jpg",
"Images/skybox/front.jpg",
"Images/skybox/back.jpg",
};
cubemapTexture = loadCubemap(faces);
}
if (!this->tiles) {
this->tiles = new
Shader(
"./Codes/shaders/tiles.vert",
nullptr, nullptr, nullptr,
"./Codes/shaders/tiles.frag");
float tilesVertices[] = {
// positions
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
//-1.0f, 1.0f, -1.0f,不要畫水池屋頂
// 1.0f, 1.0f, -1.0f,
// 1.0f, 1.0f, 1.0f,
// 1.0f, 1.0f, 1.0f,
//-1.0f, 1.0f, 1.0f,
//-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f
};
// skybox VAO
glGenVertexArrays(1, &tilesVAO);
glGenBuffers(1, &tilesVBO);
glBindVertexArray(tilesVAO);
glBindBuffer(GL_ARRAY_BUFFER, tilesVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(tilesVertices), &tilesVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
vector<const GLchar*> faces = {
"Images/tiles.jpg",
"Images/tiles.jpg",
"Images/tiles.jpg",
"Images/tiles.jpg",
"Images/tiles.jpg",
"Images/tiles.jpg",
};
tiles_cubemapTexture = loadCubemap(faces);
}
if (!this->commom_matrices)
this->commom_matrices = new UBO();
//this->commom_matrices->size = 2 * sizeof(glm::mat4);
//glGenBuffers(1, &this->commom_matrices->ubo);
//glBindBuffer(GL_UNIFORM_BUFFER, this->commom_matrices->ubo);
//glBufferData(GL_UNIFORM_BUFFER, this->commom_matrices->size, NULL, GL_STATIC_DRAW);
//glBindBuffer(GL_UNIFORM_BUFFER, 0);
if (!wave) {
//wave = new Model("backpack/backpack.obj");
//wave = new Model("water/cube.obj");
//wave = new Model("water/water.obj");
wave = new Model("water/water_bunny.obj");
//wave = new Model("water/plane.obj");
for (int i = 0;i < 200;i++) {
string num = to_string(i);
if (num.size() == 1) {
num = "00" + num;
}
else if (num.size() == 2) {
num = "0" + num;
}
wave->add_height_map_texture((num + ".png").c_str(), "Images/height map");
//wave->add_height_map_texture((num + ".png").c_str(), "Images/height map2");
}
}
if (!this->screen) {
this->screen = new
Shader(
"./Codes/shaders/screen.vert",
nullptr, nullptr, nullptr,
"./Codes/shaders/screen.frag");
float quadVertices[] = { // vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates.
// positions // texCoords
-1.0f, 1.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f,
1.0f, -1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f
};
// screen quad VAO
glGenVertexArrays(1, &screen_quadVAO);
glGenBuffers(1, &screen_quadVBO);
glBindVertexArray(screen_quadVAO);
glBindBuffer(GL_ARRAY_BUFFER, screen_quadVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
screen->Use();
glUniform1i(glGetUniformLocation(screen->Program, "screenTexture"),0);
glGenFramebuffers(1, &screen_framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, screen_framebuffer);
glGenTextures(1, &screen_textureColorbuffer);
glBindTexture(GL_TEXTURE_2D, screen_textureColorbuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w(), h(), 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, screen_textureColorbuffer, 0);
glGenRenderbuffers(1, &screen_rbo);
glBindRenderbuffer(GL_RENDERBUFFER, screen_rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, w(), h()); // use a single renderbuffer object for both a depth AND stencil buffer.
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, screen_rbo); // now actually attach it
// now that we actually created the framebuffer and added all attachments we want to check if it is actually complete now
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << endl;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
if (!interactive_frame) {
this->interactive_frame = new
Shader(
"./Codes/shaders/interactive_frame.vert",
nullptr, nullptr, nullptr,
"./Codes/shaders/interactive_frame.frag");
float quadVertices[] = { // vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates.
// positions // texCoords
-1.0f, 1.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, 1.0f,
1.0f, -1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f
};
// screen quad VAO
glGenVertexArrays(1, &interactive_quadVAO);
glGenBuffers(1, &interactive_quadVBO);
glBindVertexArray(interactive_quadVAO);
glBindBuffer(GL_ARRAY_BUFFER, interactive_quadVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
// framebuffer configuration
glGenFramebuffers(1, &interactive_framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, interactive_framebuffer);
glGenTextures(1, &interactive_textureColorbuffer);
glBindTexture(GL_TEXTURE_2D, interactive_textureColorbuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w(), h(), 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, interactive_textureColorbuffer, 0);
glGenRenderbuffers(1, &interactive_rbo);
glBindRenderbuffer(GL_RENDERBUFFER, interactive_rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, w(), h()); // use a single renderbuffer object for both a depth AND stencil buffer.
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, interactive_rbo); // now actually attach it
// now that we actually created the framebuffer and added all attachments we want to check if it is actually complete now
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << endl;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
if (tiles_tex == -1) {
tiles_tex = TextureFromFile("Images/tiles.jpg", ".");
//tiles_tex = TextureFromFile("Images/church.png",".");
}
}
else
throw std::runtime_error("Could not initialize GLAD!");
static int pre_w = w(), pre_h = h();
// Set up the view port
glViewport(0, 0, w(), h());
if (pre_w != w() || pre_h != h()) {
glBindFramebuffer(GL_FRAMEBUFFER, screen_framebuffer);
glBindTexture(GL_TEXTURE_2D, screen_textureColorbuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w(), h(), 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, screen_textureColorbuffer, 0);
glBindRenderbuffer(GL_RENDERBUFFER, screen_rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, w(), h()); // use a single renderbuffer object for both a depth AND stencil buffer.
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, screen_rbo); // now actually attach it
// now that we actually created the framebuffer and added all attachments we want to check if it is actually complete now
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << endl;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
////=======================================================
// framebuffer configuration
glBindFramebuffer(GL_FRAMEBUFFER, interactive_framebuffer);
glBindTexture(GL_TEXTURE_2D, interactive_textureColorbuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w(), h(), 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, interactive_textureColorbuffer, 0);
glBindRenderbuffer(GL_RENDERBUFFER, interactive_rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, w(), h()); // use a single renderbuffer object for both a depth AND stencil buffer.
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, interactive_rbo); // now actually attach it
// now that we actually created the framebuffer and added all attachments we want to check if it is actually complete now
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << endl;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
pre_w = w();
pre_h = h();
// clear the window, be sure to clear the Z-Buffer too
glClearColor(0, 0, .3f, 0); // background should be blue
// we need to clear out the stencil buffer since we'll use
// it for shadows
glClearStencil(0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glEnable(GL_DEPTH);
// Blayne prefers GL_DIFFUSE
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
// prepare for projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
setProjection(); // put the code to set up matrices here
//######################################################################
// TODO:
// you might want to set the lighting up differently. if you do,
// we need to set up the lights AFTER setting up the projection
//######################################################################
// enable the lighting
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
// top view only needs one light
if (tw->topCam->value()) {
glDisable(GL_LIGHT1);
glDisable(GL_LIGHT2);
}
else {
glEnable(GL_LIGHT1);
glEnable(GL_LIGHT2);
}
//*********************************************************************
//
// * set the light parameters
//
//**********************************************************************
GLfloat lightPosition1[] = { 0,1,1,0 }; // {50, 200.0, 50, 1.0};
GLfloat lightPosition2[] = { 1, 0, 0, 0 };
GLfloat lightPosition3[] = { 0, -1, 0, 0 };
GLfloat yellowLight[] = { 0.5f, 0.5f, .1f, 1.0 };
GLfloat whiteLight[] = { 1.0f, 1.0f, 1.0f, 1.0 };
GLfloat blueLight[] = { .1f,.1f,.3f,1.0 };
GLfloat grayLight[] = { .3f, .3f, .3f, 1.0 };
//initDirLight();
//initPosLight();
/*glLightfv(GL_LIGHT0, GL_POSITION, lightPosition1);
glLightfv(GL_LIGHT0, GL_DIFFUSE, whiteLight);
glLightfv(GL_LIGHT0, GL_AMBIENT, grayLight);
glLightfv(GL_LIGHT1, GL_POSITION, lightPosition2);
glLightfv(GL_LIGHT1, GL_DIFFUSE, yellowLight);
glLightfv(GL_LIGHT2, GL_POSITION, lightPosition3);
glLightfv(GL_LIGHT2, GL_DIFFUSE, blueLight);*/
//*********************************************************************
// now draw the ground plane
//*********************************************************************
// set to opengl fixed pipeline(use opengl 1.x draw function)
glUseProgram(0);
glBindFramebuffer(GL_FRAMEBUFFER, screen_framebuffer);
glEnable(GL_DEPTH_TEST); // enable depth testing (is disabled for rendering screen-space quad)
// make sure we clear the framebuffer's content
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
setupFloor();
glDisable(GL_LIGHTING);
//drawFloor(200, 10);
//*********************************************************************
// now draw the object and we need to do it twice
// once for real, and then once for shadows
//*********************************************************************
glEnable(GL_LIGHTING);
setupObjects();
drawStuff();
// this time drawing is for shadows (except for top view)
if (!tw->topCam->value()) {
setupShadows();
drawStuff(true);
unsetupShadows();
}
Shader* choose_wave;
if (tw->waveBrowser->value() == 1) {
choose_wave = sinwave;
}
else if (tw->waveBrowser->value() == 2) {
choose_wave = height_map;
}
else {
choose_wave = height_map;
}
choose_wave->Use();
glUniform1i(glGetUniformLocation(choose_wave->Program, "toon_open"), tw->toon->value());
//setUBO();
//glBindBufferRange(
//GL_UNIFORM_BUFFER, /*binding point*/0, this->commom_matrices->ubo, 0, this->commom_matrices->size);
wave->height_map_index = tw->height_map_index;//int <- float
GLfloat projection[16];
GLfloat view[16];
glGetFloatv(GL_PROJECTION_MATRIX, projection);
glGetFloatv(GL_MODELVIEW_MATRIX, view);
glm::mat4 view_without_translate = glm::mat4(glm::mat3(glm::make_mat4(view)));
glm::mat4 view_inv = glm::inverse(glm::make_mat4(view));
glm::vec3 my_pos(view_inv[3][0], view_inv[3][1], view_inv[3][2]);
//cout << my_pos[0] << ' ' << my_pos[1] << ' ' << my_pos[2] << endl;
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(0, tw->y_axis->value(), 0));
model = glm::scale(model, glm::vec3(tw->scale->value(), tw->scale->value(), tw->scale->value()));
glUniform1f(glGetUniformLocation(choose_wave->Program, "amplitude"), tw->amplitude->value());
glUniform1f(glGetUniformLocation(choose_wave->Program, "interactive_amplitude"), tw->interactive_amplitude->value());
glUniform1f(glGetUniformLocation(choose_wave->Program, "wavelength"), tw->wavelength->value());
glUniform1f(glGetUniformLocation(choose_wave->Program, "interactive_wavelength"), tw->interactive_wavelength->value());
glUniform1f(glGetUniformLocation(choose_wave->Program, "time"), tw->time);
glUniform1f(glGetUniformLocation(choose_wave->Program, "speed"), tw->wavespeed->value());
glUniform1f(glGetUniformLocation(choose_wave->Program, "interactive_speed"), tw->interactive_wavespeed->value());
glUniform1f(glGetUniformLocation(choose_wave->Program, "Eta"), tw->Eta->value());
glUniform1f(glGetUniformLocation(choose_wave->Program, "ratio_of_reflect_refract"), tw->ratio_of_reflect_refract->value());
GLfloat translation_and_scale[16];
glGetFloatv(GL_MODELVIEW_MATRIX, translation_and_scale);
glUniform3f(glGetUniformLocation(choose_wave->Program, "viewPos"), my_pos[0], my_pos[1], my_pos[2]);
glUniformMatrix4fv(glGetUniformLocation(choose_wave->Program, "projection"), 1, GL_FALSE, projection);
glUniformMatrix4fv(glGetUniformLocation(choose_wave->Program, "view"), 1, GL_FALSE, view);
glUniformMatrix4fv(glGetUniformLocation(choose_wave->Program, "model"), 1, GL_FALSE, &model[0][0]);
glUniform1f(glGetUniformLocation(choose_wave->Program, "material.diffuse"), 0.0f);
glUniform1f(glGetUniformLocation(choose_wave->Program, "material.specular"), 1.0f);
glUniform1f(glGetUniformLocation(choose_wave->Program, "material.shininess"), 16.0f);
glUniform1f(glGetUniformLocation(choose_wave->Program, "dir_open"), tw->dir_L->value());
glUniform1f(glGetUniformLocation(choose_wave->Program, "point_open"), tw->point_L->value());
glUniform1f(glGetUniformLocation(choose_wave->Program, "spot_open"), tw->spot_L->value());
//glUniform1f(glGetUniformLocation(choose_wave->Program, "reflect_open"), tw->reflect->value());
//glUniform1f(glGetUniformLocation(choose_wave->Program, "refract_open"), tw->refract->value());
glUniform1f(glGetUniformLocation(choose_wave->Program, "flat_shading"), tw->height_map_flat->value());
glUniform1f(glGetUniformLocation(choose_wave->Program, "skybox"), cubemapTexture);
dir_light(choose_wave);
point_light(choose_wave);
spot_light(choose_wave,glm::normalize(glm::vec3(0,0,0) - my_pos));
glUniform2f(glGetUniformLocation(choose_wave->Program, "drop_point"), -1,-1);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, tiles_tex);
glUniform1i(glGetUniformLocation(choose_wave->Program, "tiles"), 2);
wave->Draw(*choose_wave, tw->waveBrowser->value());
for (int i = 0;i < all_drop.size();i++) {
if (tw->time - all_drop[i].time > all_drop[i].keep_time) {
all_drop.erase(all_drop.begin() + i);
i--;
continue;
}
glUniform2f(glGetUniformLocation(choose_wave->Program, "drop_point"), all_drop[i].point.x, all_drop[i].point.y);
glUniform1f(glGetUniformLocation(choose_wave->Program, "drop_time"), all_drop[i].time);
glUniform1f(glGetUniformLocation(choose_wave->Program, "interactive_radius"), all_drop[i].radius);
wave->Draw(*choose_wave, tw->waveBrowser->value());
}
glEnable(GL_CULL_FACE);
glm::mat4 tiles_model = glm::scale(glm::mat4(1.0f), glm::vec3(tw->scale->value(), tw->scale->value(), tw->scale->value()));
tiles->Use();
glUniform1f(glGetUniformLocation(tiles->Program, "tiles"), tiles_cubemapTexture);
glUniformMatrix4fv(glGetUniformLocation(tiles->Program, "projection"), 1, GL_FALSE, projection);
glUniformMatrix4fv(glGetUniformLocation(tiles->Program, "view"), 1, GL_FALSE, view);
glUniformMatrix4fv(glGetUniformLocation(tiles->Program, "model"), 1, GL_FALSE, &tiles_model[0][0]);
// skybox cube
glBindVertexArray(tilesVAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, tiles_cubemapTexture);
if(tw->tiles->value())glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glDepthFunc(GL_LESS); // set depth function back to default
glDisable(GL_CULL_FACE);
glDepthFunc(GL_LEQUAL);
skybox->Use();
glUniform1f(glGetUniformLocation(skybox->Program, "skybox"), cubemapTexture);
glUniformMatrix4fv(glGetUniformLocation(skybox->Program, "projection"), 1, GL_FALSE, projection);
glUniformMatrix4fv(glGetUniformLocation(skybox->Program, "model_view"), 1, GL_FALSE, &view_without_translate[0][0]);
// skybox cube
glBindVertexArray(skyboxVAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glDepthFunc(GL_LESS); // set depth function back to default
// now bind back to default framebuffer and draw a quad plane with the attached framebuffer color texture
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDisable(GL_DEPTH_TEST); // disable depth test so screen-space quad isn't discarded due to depth test.
// clear all relevant buffers
glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // set clear color to white (not really necessary actually, since we won't be able to see behind the quad anyways)
glClear(GL_COLOR_BUFFER_BIT);
this->screen->Use();
glUniform1i(glGetUniformLocation(screen->Program, "frame_buffer_type"),tw->frame_buffer_type->value());
glUniform1f(glGetUniformLocation(screen->Program, "screen_w"), w());
glUniform1f(glGetUniformLocation(screen->Program, "screen_h"), h());
glUniform1f(glGetUniformLocation(screen->Program, "t"), tw->time * 20);
glBindVertexArray(screen_quadVAO);
glBindTexture(GL_TEXTURE_2D, screen_textureColorbuffer); // use the color attachment texture as the texture of the quad plane
glDrawArrays(GL_TRIANGLES, 0, 6);
//unbind shader(switch to fixed pipeline)
glUseProgram(0);
}
void TrainView::add_drop(float radius,float keep_time) {
glBindFramebuffer(GL_FRAMEBUFFER, interactive_framebuffer);
glEnable(GL_DEPTH_TEST); // enable depth testing (is disabled for rendering screen-space quad)
// make sure we clear the framebuffer's content
glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
interactive_frame->Use();
GLfloat View[16];
GLfloat Projection[16];
glGetFloatv(GL_PROJECTION_MATRIX, Projection);
glGetFloatv(GL_MODELVIEW_MATRIX, View);
//transformation matrix
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(0, tw->y_axis->value(), 0));
model = glm::scale(model, glm::vec3(tw->scale->value(), tw->scale->value(), tw->scale->value()));
glUniformMatrix4fv(glGetUniformLocation(interactive_frame->Program, "projection"), 1, GL_FALSE, Projection);
glUniformMatrix4fv(glGetUniformLocation(interactive_frame->Program, "view"), 1, GL_FALSE, View);
glUniformMatrix4fv(glGetUniformLocation(interactive_frame->Program, "model"), 1, GL_FALSE, &model[0][0]);
wave->Draw(*interactive_frame, tw->waveBrowser->value());
glReadBuffer(GL_COLOR_ATTACHMENT0);
glm::vec3 uv;
glReadPixels(Fl::event_x(), h() - Fl::event_y(), 1, 1, GL_RGB, GL_FLOAT, &uv[0]);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
if (uv.b != 1.0) {
cout << "drop : "<< uv.x << ' ' << uv.y << endl;
all_drop.push_back(Drop(glm::vec2(uv.x, uv.y), tw->time, radius, keep_time));
}
else {
//drop_point.x = -1.0f;
}
}
unsigned int loadCubemap(vector<const GLchar*> faces)
{
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
int width, height, nrChannels;
for (unsigned int i = 0; i < faces.size(); i++)
{
unsigned char* data = stbi_load(faces[i], &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
stbi_image_free(data);
}
else
{
std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl;
stbi_image_free(data);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return textureID;
}
void TrainView::dir_light(Shader* choose_wave) {
glUniform3f(glGetUniformLocation(choose_wave->Program, "dirLight.direction"), 0.0f, 1.5f, 0.0f);
glUniform3f(glGetUniformLocation(choose_wave->Program, "dirLight.ambient"), 1.0f, 1.0f, 0.00f);
glUniform3f(glGetUniformLocation(choose_wave->Program, "dirLight.diffuse"), 0.4f, 0.4f, 0.4f);
glUniform3f(glGetUniformLocation(choose_wave->Program, "dirLight.specular"), 0.5f, 0.5f, 0.5f);
}
void TrainView::point_light(Shader* choose_wave) {
glUniform3f(glGetUniformLocation(choose_wave->Program, "pointLights.position"), 0, 10, 0);
glUniform3f(glGetUniformLocation(choose_wave->Program, "pointLights.direction"), 0.0f, -1.5f, 0.0f);
glUniform3f(glGetUniformLocation(choose_wave->Program, "pointLights.ambient"), 1.0f, 0.1f, 0.1f);
glUniform3f(glGetUniformLocation(choose_wave->Program, "pointLights.diffuse"), 0.8f, 0.8f, 0.8f);
glUniform3f(glGetUniformLocation(choose_wave->Program, "pointLights.specular"), 1.0f, 0.0f, 1.0f);
glUniform1f(glGetUniformLocation(choose_wave->Program, "pointLights.constant"), 1.0f);
glUniform1f(glGetUniformLocation(choose_wave->Program, "pointLights.linear"), 0.09f);
glUniform1f(glGetUniformLocation(choose_wave->Program, "pointLights.quadratic"), 0.032f);
}
void TrainView::spot_light(Shader* choose_wave, glm::vec3 front) {
glUniform3f(glGetUniformLocation(choose_wave->Program, "spotLight.position"), 0, 5, 0);
glUniform3f(glGetUniformLocation(choose_wave->Program, "spotLight.direction"), front[0], front[1], front[2]);
glUniform3f(glGetUniformLocation(choose_wave->Program, "spotLight.ambient"), 0.1f, 0.1f, 0.1f);
glUniform3f(glGetUniformLocation(choose_wave->Program, "spotLight.diffuse"), 1.0f, 0.0f, 0.0f);
glUniform3f(glGetUniformLocation(choose_wave->Program, "spotLight.specular"), 1.0f, 1.0f, 1.0f);
glUniform1f(glGetUniformLocation(choose_wave->Program, "spotLight.constant"), 1.0f);
glUniform1f(glGetUniformLocation(choose_wave->Program, "spotLight.linear"), 0.09f);
glUniform1f(glGetUniformLocation(choose_wave->Program, "spotLight.cutOff"), 0.032f);
glUniform1f(glGetUniformLocation(choose_wave->Program, "spotLight.quadratic"), glm::cos(glm::radians(12.5f)));
glUniform1f(glGetUniformLocation(choose_wave->Program, "spotLight.outerCutOff"), glm::cos(glm::radians(15.0f)));
}
//************************************************************************
//
// * This sets up both the Projection and the ModelView matrices
// HOWEVER: it doesn't clear the projection first (the caller handles
// that) - its important for picking
//========================================================================
void TrainView::
setProjection()
//========================================================================
{
// Compute the aspect ratio (we'll need it)
float aspect = static_cast<float>(w()) / static_cast<float>(h());
// Check whether we use the world camp
if (tw->worldCam->value())
arcball.setProjection(false);
// Or we use the top cam
else if (tw->topCam->value()) {
float wi, he;
if (aspect >= 1) {
wi = 110;
he = wi / aspect;
}
else {
he = 110;
wi = he * aspect;
}
// Set up the top camera drop mode to be orthogonal and set
// up proper projection matrix
glMatrixMode(GL_PROJECTION);
glOrtho(-wi, wi, -he, he, 200, -200);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(-90,1,0,0);
}
// Or do the train view or other view here
//####################################################################
// TODO:
// put code for train view projection here!
//####################################################################
else {
#ifdef EXAMPLE_SOLUTION
trainCamView(this,aspect);
#endif
}
}
//************************************************************************
//
// * this draws all of the stuff in the world
//
// NOTE: if you're drawing shadows, DO NOT set colors (otherwise, you get
// colored shadows). this gets called twice per draw
// -- once for the objects, once for the shadows
//########################################################################
// TODO:
// if you have other objects in the world, make sure to draw them
//########################################################################
//========================================================================
void TrainView::drawStuff(bool doingShadows)
{
// Draw the control points
// don't draw the control points if you're driving
// (otherwise you get sea-sick as you drive through them)
for (size_t i = 0; i < m_pTrack->points.size(); ++i) {
if (!doingShadows) {
if (((int)i) != selectedCube)
glColor3ub(240, 60, 60);
else
glColor3ub(240, 240, 30);
}
m_pTrack->points[i].draw();
}
// draw the track
//####################################################################
// TODO:
// call your own track drawing code
//####################################################################
#ifdef EXAMPLE_SOLUTION
drawTrack(this, doingShadows);
#endif
// draw the train
//####################################################################
// TODO:
// call your own train drawing code
//####################################################################
#ifdef EXAMPLE_SOLUTION
// don't draw the train if you're looking out the front window
if (!tw->trainCam->value())
drawTrain(this, doingShadows);
#endif
}
//
//************************************************************************
//
// * this tries to see which control point is under the mouse
// (for when the mouse is clicked)
// it uses OpenGL picking - which is always a trick
//########################################################################
// TODO:
// if you want to pick things other than control points, or you
// changed how control points are drawn, you might need to change this
//########################################################################
//========================================================================
void TrainView::
doPick()
//========================================================================
{
// since we'll need to do some GL stuff so we make this window as
// active window
make_current();
// where is the mouse?
int mx = Fl::event_x();
int my = Fl::event_y();
// get the viewport - most reliable way to turn mouse coords into GL coords
int viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
// Set up the pick matrix on the stack - remember, FlTk is
// upside down!
glMatrixMode(GL_PROJECTION);
glLoadIdentity ();
gluPickMatrix((double)mx, (double)(viewport[3]-my),
5, 5, viewport);
// now set up the projection
setProjection();
// now draw the objects - but really only see what we hit
GLuint buf[100];
glSelectBuffer(100,buf);
glRenderMode(GL_SELECT);
glInitNames();
glPushName(0);
// draw the cubes, loading the names as we go
for(size_t i=0; i<m_pTrack->points.size(); ++i) {
glLoadName((GLuint) (i+1));
m_pTrack->points[i].draw();
}
// go back to drawing mode, and see how picking did
int hits = glRenderMode(GL_RENDER);
if (hits) {
// warning; this just grabs the first object hit - if there
// are multiple objects, you really want to pick the closest
// one - see the OpenGL manual
// remember: we load names that are one more than the index
selectedCube = buf[3]-1;
printf("Selected Control Point %d\n", selectedCube);
} else // nothing hit, nothing selected
selectedCube = -1;
}
void TrainView::setUBO()
{
float wdt = this->pixel_w();
float hgt = this->pixel_h();
glm::mat4 view_matrix;
glGetFloatv(GL_MODELVIEW_MATRIX, &view_matrix[0][0]);
//HMatrix view_matrix;
//this->arcball.getMatrix(view_matrix);
glm::mat4 projection_matrix;
glGetFloatv(GL_PROJECTION_MATRIX, &projection_matrix[0][0]);
//projection_matrix = glm::perspective(glm::radians(this->arcball.getFoV()), (GLfloat)wdt / (GLfloat)hgt, 0.01f, 1000.0f);
glBindBuffer(GL_UNIFORM_BUFFER, this->commom_matrices->ubo);
glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(glm::mat4), &projection_matrix[0][0]);
glBufferSubData(GL_UNIFORM_BUFFER, sizeof(glm::mat4), sizeof(glm::mat4), &view_matrix[0][0]);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
} |
2f9fbee5890f457a45b30f73936ff1904522f6d7 | 2e6cb6bc783323b6ed9422f9a7c96e69718a2f3c | /Greedy/HDU1053.cpp | 4278a2cc1731a46e74a8eab0a964613c9953dccf | [] | no_license | derekzhang79/ACM | c58df5aabd48b6ba204b541f1f15adea878b31d5 | ac823592cc8a9ab09b42f49d2b86835e2255e096 | refs/heads/master | 2020-04-29T14:54:20.820467 | 2013-03-19T12:26:26 | 2013-03-19T12:26:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,143 | cpp | HDU1053.cpp | /*
Author: ShadowGeeker
GitHub: https://github.com/ShadowGeeker/
Blog: http://liuke.org/
*/
#include <iostream>
#include <cstdio>
#include <queue>
#include <string>
using namespace std;
class Node
{
public:
int id;
int parent;
int val;
bool operator<(const Node& rhs) const
{
// priority_queue是从大到小排序的
// 这样重载<可以使得实际上按照val从小到大排序
return val > rhs.val;
}
};
int GetIdx(char ch)
{
if (ch == '_') return 26;
return ch - 'A';
}
int main(int argc, char **argv)
{
string str;
string strEnd("END");
int i, j, idx, len, res;
while (cin >> str)
{
if (str == strEnd) break;
Node n[100] = {0};
len = str.size();
for (i = 0; i < len; ++i)
{
idx = GetIdx(str[i]);
n[idx].val++;
n[idx].id = n[idx].parent = idx;
}
j = 27;
// 入队
priority_queue<Node> q;
for (i = 0; i < j; ++i)
{
if (n[i].val) q.push(n[i]);
}
if (q.size() == 1)
{
printf("%d %d %.1f\n", len*8, len, 8.0);
continue;
}
// 建树过程
while (q.size() > 1)
{
// pop
Node a = q.top();
q.pop();
Node b = q.top();
q.pop();
// combine
n[j].val = a.val + b.val;
n[j].id = n[j].parent = j;
q.push(n[j]);
// set parent
n[a.id].parent = n[b.id].parent = j;
++j;
}
// calc depth
res = 0;
for (i = 0; i < 27; ++i)
{
if (n[i].val)
{
int height = 0;
Node tmp = n[i];
while (tmp.parent != tmp.id)
{
tmp = n[tmp.parent];
++height;
}
res += n[i].val * height;
}
}
printf("%d %d %.1f\n", len*8, res, len*8.0 / res);
}
return 0;
}
/*
哈弗曼编码问题
*/ |
f87bd2f80989c49733dfd338f5f56e02a43ac134 | 8192ce002c3f351351d13316b53563b2db1d0c96 | /Project_1/calc3.cpp | 1f605784f821fcee7c043b074debdf93d6411db9 | [] | no_license | Leman-Y/spring-2018-cs-135-projects | b31d651637515fdada4ec695479600c0974980da | cb18ce88e4e8ed348e2d0e2f9fcad8dfeba79a08 | refs/heads/master | 2020-04-01T21:30:24.890512 | 2019-02-16T21:42:20 | 2019-02-16T21:42:20 | 153,659,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,472 | cpp | calc3.cpp | /*
Author: Leman Yan
Course: CSCI-135
Instructor: Genady Maryash
Assignment: Project 1 Task D
Program: A calculator program that can understand squared numbers
*/
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int sum=0; //Initial sum
char math='+'; //Set math expression to +. Assume the first integer is positive.
char math1; //Another math expression
int number=0; //The numbers being inputed
int number1=0; //Another number
cin>>number; // We know the first thing in the expression is a number
while(cin>>math1){ //We know after a number there is an operation after.
if(math1=='^'){ //If the symbol is ^ then times the number by itself
number=number*number;
cin>>math1; //Get the next operatorion because we know after number^ is another operation.
}
if(math=='+'){ //If there is math1 doesnt equal to ^ then just add the number.
sum+=number;
}
if(math=='-'){
sum-=number;
}
math=math1; //Math is equal to math1.
cin>>number; //We get the next number.
//In the case of 10-10. Number=10. Default math is + so we add 10 to the sum. The next number is 10, but math is -, so 10-10=0. Then math gets changed to semi colon, so the sum is sent out.
if(math==';'){ //If the the math symbol is a semicolon
cout<<sum<<endl; //Send out the sum
sum=0; //The sum is zero now
math='+'; //Math is back to +
}
}
return 0;
}
|
fc32ca73988bea01c06bcf7d6edf657e46d1ab23 | f0b181538de900df297ea710aa8f8158ace17cf2 | /MarbleGame Source/Classes/platform.cpp | c41571190263c7687baba41b0168441767cde46b | [] | no_license | ChuckNice/SBU_Sources | fbc79cc8734e9f842a01233e61ef06cf6c5d6c24 | b802fa80b5d21e5cd99d0ce1921e7b1e30559834 | refs/heads/master | 2021-01-02T22:18:48.459277 | 2013-07-11T05:44:25 | 2013-07-11T05:44:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,193 | cpp | platform.cpp | #include "platform.h"
Platform::Platform(Scene *scene, Vector3 size) :
Cube(scene, size)
{
}
void Platform::onCreateRigidBody(btCollisionShape *sharedShape)
{
// create shape
const float width = m_size.x / 2.0f;
const float height = m_size.y / 2.0f;
const float depth = m_size.z / 2.0f;
btCollisionShape* shape;
if (sharedShape == NULL)
shape = new btBoxShape(btVector3(btScalar(width),btScalar(height),btScalar(depth)));
else
shape = sharedShape;
// set initial transform
btTransform startTransform;
startTransform.setFromOpenGLMatrix(getModelviewMatrix().mat);
// mass and local inertia are 0 (platforms are static)
btScalar mass(0.f);
btVector3 localInertia(0,0,0);
//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, shape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
// platform should have some friction
body->setFriction(1.0f);
body->setRollingFriction(1.0f);
// set this collidable entities rigid body
m_rigidBody = body;
}
|
65aef935111083e02409f12ef30d6129b89b5018 | a585a35f5a6c6468324ec60e0b14aa55d06a12ae | /src/collision_handler.cpp | c33f2d08d9ab07c81d270977cab85a07bd1b11dc | [] | no_license | vrndr/gamedev | dacc00617e4f5329dfa69ea29276ddea80b5604c | 7c30677b9738fd049fee227039ec5b4060d78d1d | refs/heads/master | 2021-01-23T19:38:25.884842 | 2014-03-08T06:55:31 | 2014-03-08T06:55:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,142 | cpp | collision_handler.cpp |
#include <algorithm>
#include "actor.h"
#include "collision_handler.h"
#include "stage.h"
void CollisionHandler::init() {
}
bool isActiveMovingActor(Actor *actor) {
return actor->isActorActive() && actor->isActorMoving();
}
Rectangle *getOverlaps(Actor *mainActor, Actor *otherActor) {
if (mainActor == otherActor) {
return NULL;
}
if (!otherActor->isActorCollidable()) {
return NULL;
}
Rectangle mainActorRect = mainActor->getPosition();
Rectangle otherActorRect = otherActor->getPosition();
float mx1 = mainActorRect.getX();
float my1 = mainActorRect.getY();
float mx2 = mainActorRect.getX() + mainActorRect.getWidth();
float my2 = mainActorRect.getY() + mainActorRect.getHeight();
float ox1 = otherActorRect.getX();
float oy1 = otherActorRect.getY();
float ox2 = otherActorRect.getX() + otherActorRect.getWidth();
float oy2 = otherActorRect.getY() + otherActorRect.getHeight();
float xLeft = std::max(mx1, ox1);
float xRight = std::min(mx2, ox2);
if (xLeft > xRight) {
return NULL;
}
float yTop = std::max(my1, oy1);
float yBottom = std::min(my2, oy2);
if (yTop > yBottom) {
return NULL;
}
Rectangle *overlap = new Rectangle(xLeft, yTop, xRight - xLeft, yBottom - yTop);
return overlap;
}
void notifyActors(Actor *mainActor, Actor *otherActor, Rectangle *overlap) {
mainActor->onCollision(otherActor, overlap);
otherActor->onCollision(mainActor, overlap);
}
void handleCollisionsWithOtherActors(Actor *mainActor, std::list<Actor *> allActors) {
for (std::list<Actor *>::iterator actor = allActors.begin();
actor != allActors.end(); actor++) {
Rectangle *overlap = getOverlaps(mainActor, *actor);
if (overlap) {
notifyActors(mainActor, *actor, overlap);
delete overlap;
}
}
}
void CollisionHandler::checkCollisions(const Stage &stage) {
std::list<Actor *> actors = stage.getAllActors();
for (std::list<Actor *>::iterator actor = actors.begin();
actor != actors.end(); actor++) {
if (!isActiveMovingActor(*actor)) {
continue;
}
handleCollisionsWithOtherActors(*actor, actors);
}
}
|
b74f9ff35a91cb6530d6873d53c30e20cae3bee5 | 0d466c823015789e2df1c792af23b41b4f569f6a | /src/cerata/vhdl/architecture.cc | 3f4201506e0917d900431946001e6b29c5f342e7 | [
"Apache-2.0"
] | permissive | abs-tudelft/cerata | 44a760b32e99c4d97c83fff51f8d9666b170839d | 2ae66df995910429f51fed68c95f4823bba5dae8 | refs/heads/develop | 2020-12-20T07:07:13.229223 | 2020-11-24T13:16:37 | 2020-11-24T13:16:37 | 235,993,608 | 3 | 2 | Apache-2.0 | 2023-02-27T15:40:28 | 2020-01-24T11:50:47 | C++ | UTF-8 | C++ | false | false | 9,867 | cc | architecture.cc | // Copyright 2018-2019 Delft University of Technology
//
// 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 "cerata/vhdl/architecture.h"
#include <vector>
#include <string>
#include <algorithm>
#include <memory>
#include "cerata/node.h"
#include "cerata/edge.h"
#include "cerata/expression.h"
#include "cerata/graph.h"
#include "cerata/vhdl/block.h"
#include "cerata/vhdl/declaration.h"
#include "cerata/vhdl/instantiation.h"
#include "cerata/vhdl/vhdl.h"
namespace cerata::vhdl {
MultiBlock Arch::GenerateCompDeclarations(const Component &comp, int indent) {
MultiBlock result(indent);
// Component declarations
auto inst_comps = comp.GetAllInstanceComponents();
for (const auto &ic : inst_comps) {
// Check for metadata that this component is not marked primitive
// In this case, a library package has been added at the top of the design file.
if ((ic->meta().count(meta::PRIMITIVE) == 0) || (ic->meta().at(meta::PRIMITIVE) != "true")) {
// TODO(johanpel): generate packages with component declarations
auto decl = Decl::Generate(*ic);
result << decl;
result << Line();
}
}
return result;
}
MultiBlock Arch::GenerateCompInstantiations(const Component &comp, int indent) {
MultiBlock result(indent);
auto instances = comp.children();
for (const auto &i : instances) {
auto inst_decl = Inst::Generate(*i);
result << inst_decl;
result << Line();
}
return result;
}
MultiBlock Arch::Generate(const Component &comp) {
MultiBlock result;
result << Line("architecture Implementation of " + comp.name() + " is");
result << GenerateCompDeclarations(comp, 1);
result << GenerateNodeDeclarations<Signal>(comp, 1);
result << GenerateNodeDeclarations<SignalArray>(comp, 1);
result << Line("begin");
result << GenerateCompInstantiations(comp, 1);
result << GenerateAssignments<Port>(comp, 1);
result << GenerateAssignments<Signal>(comp, 1);
result << GenerateAssignments<SignalArray>(comp, 1);
result << Line("end architecture;");
return result;
}
// TODO(johanpel): make this something less arcane
static Block GenerateMappingPair(const MappingPair &p,
size_t ia,
const std::shared_ptr<Node> &offset_a,
size_t ib,
const std::shared_ptr<Node> &offset_b,
const std::string &lh_prefix,
const std::string &rh_prefix,
bool a_is_array,
bool b_is_array) {
Block ret;
std::shared_ptr<Node> next_offset_a;
std::shared_ptr<Node> next_offset_b;
auto a_width = p.flat_type_a(ia).type_->width();
auto b_width = p.flat_type_b(ib).type_->width();
next_offset_a = (offset_a + (b_width ? b_width.value() : rintl(0)));
next_offset_b = (offset_b + (a_width ? a_width.value() : rintl(0)));
if (p.flat_type_a(0).type_->Is(Type::RECORD)) {
// Don't output anything for the nested record type.
} else {
auto a_ft = p.flat_type_a(ia);
auto b_ft = p.flat_type_b(ib);
if (a_ft.type_->Is(Type::BIT) && b_ft.type_->Is(Type::VECTOR)) {
b_is_array = true;
}
if (b_ft.type_->Is(Type::BIT) && a_ft.type_->Is(Type::VECTOR)) {
a_is_array = true;
}
std::string a;
std::string b;
a = a_ft.name(NamePart(lh_prefix, true));
// if right side is concatenated onto the left side
// or the left side is an array (right is also concatenated onto the left side)
if ((p.num_b() > 1) || a_is_array) {
if (a_ft.type_->Is(Type::BIT) || (b_ft.type_->Is(Type::BIT) && a_ft.type_->Is(Type::VECTOR))) {
a += "(" + offset_a->ToString() + ")";
} else {
a += "(" + (next_offset_a - 1ul)->ToString();
a += " downto " + offset_a->ToString() + ")";
}
}
b = b_ft.name(NamePart(rh_prefix, true));
if ((p.num_a() > 1) || b_is_array) {
if (b_ft.type_->Is(Type::BIT) || (a_ft.type_->Is(Type::BIT) && b_ft.type_->Is(Type::VECTOR))) {
b += "(" + offset_b->ToString() + ")";
} else {
b += "(" + (next_offset_b - 1ul)->ToString();
b += " downto " + offset_b->ToString() + ")";
}
}
Line l;
if (p.flat_type_a(ia).reverse_) {
l << b << " <= " << a;
} else {
l << a << " <= " << b;
}
ret << l;
}
return ret;
}
static Block GenerateAssignmentPair(std::vector<MappingPair> pairs, const Node &a, const Node &b) {
Block ret;
// Sort the pair in order of appearance on the flatmap
std::sort(pairs.begin(), pairs.end(), [](const MappingPair &x, const MappingPair &y) -> bool {
return x.index_a(0) < y.index_a(0);
});
bool a_array = false;
bool b_array = false;
size_t a_idx = 0;
size_t b_idx = 0;
// Figure out if these nodes are on NodeArrays and what their index is
if (a.array()) {
a_array = true;
a_idx = a.array().value()->IndexOf(a);
}
if (b.array()) {
b_array = true;
b_idx = b.array().value()->IndexOf(b);
}
// Loop over all pairs
for (const auto &pair : pairs) {
// Offset on the right side
std::shared_ptr<Node> b_offset = pair.width_a(intl(1)) * b_idx;
// Loop over everything on the left side
for (int64_t ia = 0; ia < pair.num_a(); ia++) {
// Get the width of the left side.
auto a_width = pair.flat_type_a(ia).type_->width();
// Offset on the left side.
std::shared_ptr<Node> a_offset = pair.width_b(intl(1)) * a_idx;
for (int64_t ib = 0; ib < pair.num_b(); ib++) {
// Get the width of the right side.
auto b_width = pair.flat_type_b(ib).type_->width();
// Generate the mapping pair with given offsets
auto mpblock = GenerateMappingPair(pair, ia, a_offset, ib, b_offset, a.name(), b.name(), a_array, b_array);
ret << mpblock;
// Increase the offset on the left side.
a_offset = a_offset + (b_width ? b_width.value() : rintl(1));
}
// Increase the offset on the right side.
b_offset = b_offset + (a_width ? a_width.value() : rintl(1));
}
}
return ret;
}
static Block GenerateNodeAssignment(const Node &dst, const Node &src) {
Block result;
// Check if a type mapping exists
auto optional_type_mapper = dst.type()->GetMapper(src.type());
if (optional_type_mapper) {
auto type_mapper = optional_type_mapper.value();
// Obtain the unique mapping pairs for this mapping
auto pairs = type_mapper->GetUniqueMappingPairs();
// Generate the mapping for this port-node pair.
result << GenerateAssignmentPair(pairs, dst, src);
result << ";";
} else {
CERATA_LOG(FATAL, "No type mapping available for: Node[" + dst.name() + ": " + dst.type()->name()
+ "] from Other[" + src.name() + " : " + src.type()->name() + "]");
}
return result;
}
Block Arch::Generate(const Port &port, int indent) {
Block ret(indent);
// We need to assign this port. If we properly resolved VHDL issues, and didn't do weird stuff like loop a
// port back up, the only thing that could drive this port is a signal. We're going to sanity check this anyway.
// Check if the port node is sourced at all. If it isn't, we don't have to assign it.
if (!port.input()) {
return ret;
}
// Generate the assignment.
auto edge = port.input().value();
if (!edge->src()->IsSignal()) {
CERATA_LOG(FATAL, "Component port is not sourced by signal.");
}
ret << GenerateNodeAssignment(*edge->dst(), *edge->src());
return ret;
}
Block Arch::Generate(const Signal &sig, int indent) {
Block ret(indent);
// We need to assign this signal when it is sourced by a node that is not an instance port.
// If the source is, then this is done in the associativity list of the port map of the component instantiation.
// Check if the signal node is sourced at all.
if (!sig.input()) {
return ret;
}
auto edge = sig.input().value();
Block b;
Node *src = edge->src();
Node *dst = edge->dst();
// Check if the source is a port, has a parent and if its parent is an instance.
// In that case, the source is coming from an instance, and we don't have to make the assignment since that is done
// at the instance port map.
if (src->IsPort() && src->parent() && src->parent().value()->IsInstance()) {
return ret;
}
// Check if a type mapping exists
auto type_mapper = dst->type()->GetMapper(src->type());
if (type_mapper) {
// Obtain the unique mapping pairs for this mapping
auto pairs = type_mapper.value()->GetUniqueMappingPairs();
// Generate the mapping for this port-node pair.
b << GenerateAssignmentPair(pairs, *dst, *src);
b << ";";
ret << b;
} else {
CERATA_LOG(FATAL, "Assignment of signal " + src->ToString()
+ " from " + dst->ToString()
+ " failed. No type mapper available.");
}
return ret;
}
Block Arch::Generate(const SignalArray &sig_array, int indent) {
Block ret(indent);
// Go over each node in the array
for (const auto &node : sig_array.nodes()) {
if (node->IsSignal()) {
const auto &sig = dynamic_cast<const Signal &>(*node);
ret << Generate(sig, indent);
} else {
CERATA_LOG(FATAL, "Signal Array contains non-signal node.");
}
}
return ret.Sort('(');
}
} // namespace cerata::vhdl
|
434b63d7c0fea910ef7ecc2a133c944508d99983 | 9d164088aa2d5a65215b77186c45da093ad68cb1 | /src/CGnuPlotEveryData.cpp | edf9aef549c5ddf139ceea7ec5a3a50775b5c4bd | [
"MIT"
] | permissive | colinw7/CQGnuPlot | 9c247a7ff8afd0060fd99d7f4c12d4f105dfc9d9 | c12ad292932a2116ab7fbb33be158adcf6c32674 | refs/heads/master | 2023-04-14T07:29:43.807602 | 2023-04-03T15:59:36 | 2023-04-03T15:59:36 | 26,377,931 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,268 | cpp | CGnuPlotEveryData.cpp | #include <CGnuPlotEveryData.h>
#include <CExpr.h>
#include <CStrUtil.h>
namespace {
bool evaluateExpression(CExpr *expr, const std::string &exprStr, CExprValuePtr &value) {
bool oldQuiet = expr->getQuiet();
expr->setQuiet(true);
if (! expr->evaluateExpression(exprStr, value))
value = CExprValuePtr();
expr->setQuiet(oldQuiet);
return true;
}
}
//---
CGnuPlotEveryData::
CGnuPlotEveryData(CExpr *expr, const std::string &str)
{
if (str != "")
(void) parse(expr, str);
}
bool
CGnuPlotEveryData::
parse(CExpr *expr, const std::string &str)
{
assert(expr);
std::vector<std::string> inds;
CStrUtil::addFields(str, inds, ":");
//---
auto parseInd = [&](int i, int &var, int def) {
var = def;
if (int(inds.size()) > i) {
CExprValuePtr value;
var = def;
if (inds[i] != "" && evaluateExpression(expr, inds[i], value)) {
long l;
if (value.isValid() && value->getIntegerValue(l))
var = int(l);
}
}
};
parseInd(0, pointStep_ , 1);
parseInd(1, blockStep_ , 1);
parseInd(2, pointStart_, 0);
parseInd(3, blockStart_, 0);
parseInd(4, pointEnd_ , std::numeric_limits<int>::max());
parseInd(5, blockEnd_ , std::numeric_limits<int>::max());
return true;
}
|
03004392e8a97d965aa78e5aa39c3fd748e6d216 | a90d9373304c4ec4b3ea8ec46314bf02e9b2e864 | /apps/elements/elements_view_data_source.h | 48ef0a0d330d892150a1de27a4c4d0a8048d02bb | [] | no_license | charlie-x/epsilon | 084668654b1de8cce292ad9ede63fd02e10d5419 | e4c3a98b24c2c407dac3b03332da4fb2c625b1e5 | refs/heads/master | 2023-06-08T19:59:28.898004 | 2023-01-30T10:11:19 | 2023-01-31T14:17:54 | 256,359,479 | 0 | 0 | null | 2020-04-17T00:16:41 | 2020-04-17T00:16:41 | null | UTF-8 | C++ | false | false | 1,363 | h | elements_view_data_source.h | #ifndef ELEMENTS_ELEMENTS_VIEW_DATA_SOURCE_H
#define ELEMENTS_ELEMENTS_VIEW_DATA_SOURCE_H
#include "elements_data_base.h"
#include "elements_view_delegate.h"
#include "palette.h"
namespace Elements {
class ElementsViewDataSource {
public:
ElementsViewDataSource(ElementsViewDelegate * delegate);
AtomicNumber selectedElement() const;
AtomicNumber previousElement() const;
void setSelectedElement(AtomicNumber z);
const DataField * field() const;
void setField(const DataField * dataField);
void setTextFilter(const char * filter) { m_textFilter = filter; }
/* Returns colors given by the data field, or default colors if the element
* does not match the filter. */
DataField::ColorPair filteredColors(AtomicNumber z) const;
AtomicNumber elementSearchResult() const;
const char * suggestedElementName();
const char * cycleSuggestion(bool goingDown);
private:
typedef bool (ElementsViewDataSource::*ElementTest)(AtomicNumber) const;
bool elementMatchesFilter(AtomicNumber z) const;
bool elementNameMatchesFilter(AtomicNumber z) const;
bool elementSymbolMatchesFilter(AtomicNumber z) const;
bool elementNumberMatchesFilter(AtomicNumber z) const;
AtomicNumber privateElementSearch(ElementTest test) const;
ElementsViewDelegate * m_delegate;
const char * m_textFilter;
AtomicNumber m_suggestedElement;
};
}
#endif
|
34a26dbe652de542a616ae30b98a0fd2b8d8789a | 8018f269727b5d698afe0b9dc5eb1680b2eaf1e4 | /Codeforces/GYM/2020_Shenyeng/D_Simul.cpp | c9fffef5d8f4f5ff6a918ad4d3d81b0af195d5cf | [
"MIT"
] | permissive | Mindjolt2406/Competitive-Programming | 1c68a911669f4abb7ca124f84b2b75355795651a | 54e8efafe426585ef0937637da18b7aaf0fef5e5 | refs/heads/master | 2022-03-20T14:43:37.791926 | 2022-01-29T11:34:45 | 2022-01-29T11:34:45 | 157,658,857 | 2 | 0 | null | 2019-02-10T08:48:25 | 2018-11-15T05:50:05 | C++ | UTF-8 | C++ | false | false | 5,297 | cpp | D_Simul.cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
template <typename T>
std::ostream & operator << (std::ostream & os, const std::vector<T> & vec);
template <typename T>
std::ostream & operator << (std::ostream & os, const std::set<T> & vec);
template <typename T>
std::ostream & operator << (std::ostream & os, const std::unordered_set<T> & vec);
template <typename T>
std::ostream & operator << (std::ostream & os, const std::multiset<T> & vec);
template <typename T>
std::ostream & operator << (std::ostream & os, const std::unordered_multiset<T> & vec);
template<typename T1, typename T2>
std::ostream & operator << (std::ostream & os, const std::pair<T1,T2> & p);
template<typename T1, typename T2>
std::ostream & operator << (std::ostream & os, const std::map<T1,T2> & p);
template<typename T1, typename T2>
std::ostream & operator << (std::ostream & os, const std::unordered_map<T1,T2> & p);
template <typename T>
std::ostream & operator << (std::ostream & os, const std::vector<T> & vec){
os<<"{";
for(auto elem : vec)
os<<elem<<",";
os<<"}";
return os;
}
template <typename T>
std::ostream & operator << (std::ostream & os, const std::set<T> & vec){
os<<"{";
for(auto elem : vec)
os<<elem<<",";
os<<"}";
return os;
}
template <typename T>
std::ostream & operator << (std::ostream & os, const std::unordered_set<T> & vec){
os<<"{";
for(auto elem : vec)
os<<elem<<",";
os<<"}";
return os;
}
template <typename T>
std::ostream & operator << (std::ostream & os, const std::multiset<T> & vec){
os<<"{";
for(auto elem : vec)
os<<elem<<",";
os<<"}";
return os;
}
template <typename T>
std::ostream & operator << (std::ostream & os, const std::unordered_multiset<T> & vec){
os<<"{";
for(auto elem : vec)
os<<elem<<",";
os<<"}";
return os;
}
template<typename T1, typename T2>
std::ostream & operator << (std::ostream & os, const std::pair<T1,T2> & p){
os<<"{"<<p.first<<","<<p.second<<"}";
return os;
}
template<typename T1, typename T2>
std::ostream & operator << (std::ostream & os, const std::map<T1,T2> & p){
os<<"{";
for(auto x: p)
os<<x.first<<"->"<<x.second<<", ";
os<<"}";
return os;
}
template<typename T1, typename T2>
std::ostream & operator << (std::ostream & os, const std::unordered_map<T1,T2> & p){
os<<"{";
for(auto x: p)
os<<x.first<<"->"<<x.second<<", ";
os<<"}";
return os;
}
/*-------------------------------------------------------------------------------------------------------------------------------------*/
#define t1(x) cerr<<#x<<"="<<x<<endl
#define t2(x, y) cerr<<#x<<"="<<x<<" "<<#y<<"="<<y<<endl
#define t3(x, y, z) cerr<<#x<<"=" <<x<<" "<<#y<<"="<<y<<" "<<#z<<"="<<z<<endl
#define t4(a,b,c,d) cerr<<#a<<"="<<a<<" "<<#b<<"="<<b<<" "<<#c<<"="<<c<<" "<<#d<<"="<<d<<endl
#define t5(a,b,c,d,e) cerr<<#a<<"="<<a<<" "<<#b<<"="<<b<<" "<<#c<<"="<<c<<" "<<#d<<"="<<d<<" "<<#e<<"="<<e<<endl
#define t6(a,b,c,d,e,f) cerr<<#a<<"="<<a<<" "<<#b<<"="<<b<<" "<<#c<<"="<<c<<" "<<#d<<"="<<d<<" "<<#e<<"="<<e<<" "<<#f<<"="<<f<<endl
#define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME
#ifndef ONLINE_JUDGE
#define tr(...) GET_MACRO(__VA_ARGS__,t6,t5, t4, t3, t2, t1)(__VA_ARGS__)
#else
#define tr(...)
#endif
/*-------------------------------------------------------------------------------------------------------------------------------------*/
#define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
#define fastio() ios::sync_with_stdio(0);cin.tie(0)
#define MEMS(x,t) memset(x,t,sizeof(x));
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
/*-------------------------------------------------------------------------------------------------------------------------------------*/
// #define MOD 1000000007
// #define MOD 998244353
#define endl "\n"
#define int long long
#define inf 1e18
#define ld long double
/*-------------------------------------------------------------------------------------------------------------------------------------*/
int fun(string s)
{
int n = s.length();
int ans = 0;
for(int i=0;i<n;i++)
{
int cnt = 0;
for(int j=i;j<n;j++)
{
cnt += (s[j] == '1');
if(cnt%2 == 1)
ans ++;
}
}
return ans;
}
bool comp(pair<int, string> a, pair<int, string> b) {
if (__builtin_popcount(a.first) == __builtin_popcount(b.first))
return a.first < b.first;
return __builtin_popcount(a.first) < __builtin_popcount(b.first);
}
signed main()
{
fastio();
int n;
cin>>n;
string ss(n,'1');
// int mask = 0;
vector<pair<int, string>> v;
int cnt = 0;
for(int mask=0;mask<(1 << n) && cnt < 200;mask++)
{
string s = "";
for(int i=n-1;i>=0;i--)
{
if(mask&(1LL<<i))
s+='1';
else
s+='0';
}
if(fun(s) == fun(ss)) {
cnt++;
tr(s, fun(s));
// tr(v.size());
// v.push_back({mask, s});
}
}
// sort(v.begin(), v.end());
// for (auto it : v) {
// tr(it.second, fun(it.second));
// }
} |
e06ed8a560675f0656b0a3860cda9364e8704fdf | 419bbcbcc74c5e18318372f5bc3eff24e97fcde9 | /source/Curve.hpp | b2a497fe9dfae72d2e7dad5e5e41800a4a64a773 | [] | no_license | ltjax/Rescue | 502f17b04d32284f43b487aad5a29457ccc15b17 | 6a8d0a36ae5bc390d161a9eec9d35459a64dd61c | refs/heads/master | 2021-01-20T18:15:39.069121 | 2020-03-22T17:12:16 | 2020-03-22T17:12:16 | 90,912,304 | 4 | 0 | null | 2019-03-15T15:53:10 | 2017-05-10T22:06:15 | C++ | UTF-8 | C++ | false | false | 1,495 | hpp | Curve.hpp | #pragma once
#include <string>
namespace Rescue
{
class Curve
{
public:
enum class FunctionType
{
Linear,
Polynomial,
Logistic
};
explicit Curve(FunctionType Type = FunctionType::Linear, float m = 1.f, float k = 1.f, float c = 0.f, float b = 0.f);
float evaluateFor(float x) const;
Curve withType(FunctionType type) const
{
return Curve{ type, mM, mK, mC, mB };
}
Curve withM(float m) const
{
return Curve{ mType, m, mK, mC, mB };
}
Curve withK(float k) const
{
return Curve{ mType, mM, k, mC, mB };
}
Curve withC(float c) const
{
return Curve{ mType, mM, mK, c, mB };
}
Curve withB(float b) const
{
return Curve{ mType, mM, mK, mC, b };
}
FunctionType type() const
{
return mType;
}
float m() const
{
return mM;
}
float k() const
{
return mK;
}
float c() const
{
return mC;
}
float b() const
{
return mB;
}
private:
FunctionType mType;
float mM;
float mK;
float mC;
float mB;
};
class RangedCurve
{
public:
explicit RangedCurve(Curve curve = Curve{}, float min = 0.f, float max = 1.f);
~RangedCurve();
float evaluateFor(float Rhs) const;
Curve normalized() const;
void setMin(float x);
float min() const;
void setMax(float x);
float max() const;
private:
Curve mCurve;
float mMin;
float mMax;
};
} |
87e4006ce08b8ef7ec9f13aac9d1fb004d7733a8 | bc33abf80f11c4df023d6b1f0882bff1e30617cf | /CPP/ic/综合3/排队游戏.cpp | 15f5864bed15039daee5ca6d99666adfcf06c808 | [] | no_license | pkuzhd/ALL | 0fad250c710b4804dfd6f701d8f45381ee1a5d11 | c18525decdfa70346ec32ca2f47683951f4c39e0 | refs/heads/master | 2022-07-11T18:20:26.435897 | 2019-11-20T13:25:24 | 2019-11-20T13:25:24 | 119,031,607 | 0 | 0 | null | 2022-06-21T21:10:42 | 2018-01-26T09:19:23 | C++ | GB18030 | C++ | false | false | 378 | cpp | 排队游戏.cpp | #include <iostream>
#include <string>
#include <stack>
using namespace std;
int main(int argc, char *argv[])
{
string str;
cin >> str;
stack<int> s;
for (int i = 0; i < str.size(); ++i)
{
if (str[i] == '(') // 遇到小男孩就入栈
{
s.push(i);
}
else // 遇到小女孩就出栈
{
cout << s.top() << " " << i << endl;
s.pop();
}
}
return 0;
} |
46efc515210d28faf594d991ad19612306fa612a | 26f32e286e96cf744ab623b0cdc4b755f566b5af | /chapter3/dp/uva/11259-tle.cpp | 310118af932022020bf57f31123a28ea61261e92 | [] | no_license | crbonilha/cp4-book | 0fd8916a93f226a22bc90142ea8341d2b39fdf40 | b23fc68f6bcbae4ad5bf4a4b2559461d64938996 | refs/heads/main | 2023-07-31T08:00:30.876074 | 2021-09-28T21:33:06 | 2021-09-28T21:33:06 | 306,436,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | cpp | 11259-tle.cpp | #include <bits/stdc++.h>
using namespace std;
const int COINS = 4;
const int MAX_V = 100000;
int coins[COINS];
int coinsAvlb[COINS];
int dp[COINS][MAX_V+1];
int solve(int coin, int val) {
if(coin == COINS) {
return val == 0;
}
int& ans = dp[coin][val];
if(ans != -1) {
return ans;
}
ans = 0;
for(int i=0; i <= coinsAvlb[coin] and val-i*coins[coin] >= 0; i++) {
ans += solve(coin+1, val-i*coins[coin]);
}
return ans;
}
int main() {
int t;
scanf("%d", &t);
while(t--) {
for(int i=0; i<COINS; i++) {
scanf("%d", &coins[i]);
}
int q;
scanf("%d", &q);
while(q--) {
for(int i=0; i<COINS; i++) {
scanf("%d", &coinsAvlb[i]);
}
int v;
scanf("%d", &v);
memset(dp, -1, sizeof(dp));
printf("%d\n", solve(0, v));
}
}
}
|
b46133d72fdf11e973ccdbaf055fc4acbf807081 | 04f2676422bed24a3fb91a762b77b6f91d64eace | /ch02/testdebug/widget.cpp | 541b33140632c42114420f799e76d6b428df44f6 | [] | no_license | rockerV/qtwork | fa6e50f206ab17670ff530aff0e3d4b617dab9ac | ca7f608f3ad02c45dfb950b5438692e92d59b95f | refs/heads/master | 2020-06-24T16:22:49.633452 | 2019-07-29T13:03:24 | 2019-07-29T13:03:24 | 199,014,176 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 550 | cpp | widget.cpp | #include "widget.h"
#include "ui_widget.h"
#include <QtTest/QTest> //added new line
#include <QDebug> //added
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
qDebug()<<(void *)(ui->label); //show the "wild" pointer
ui->setupUi(this);
ui->label->setText(tr("Test Bug")); //change text
QTest::qSleep(1000); //added new line
qDebug()<<(void *)(ui->label); //show normal pointer
qDebug()<<ui->label; //show label object
}
Widget::~Widget()
{
delete ui;
}
|
26658a1cb3fd44f76d581c1c8a78031c5c915196 | 695403943ccaef93fba271cb80f16dd84e368527 | /inc/TRestAxionSolarQCDFlux.h | 373eab336c42a6b887b5a77aba0568df35f3206e | [] | no_license | rest-for-physics/axionlib | b06af49fe4dfdce54e2eb7637263de328f210590 | d36acca177d665e2425c3c3afc8412bd06cc343d | refs/heads/master | 2023-08-31T09:23:49.016557 | 2023-07-03T20:08:30 | 2023-07-03T20:08:30 | 344,754,016 | 5 | 2 | null | 2023-09-11T10:47:06 | 2021-03-05T09:08:07 | C++ | UTF-8 | C++ | false | false | 5,718 | h | TRestAxionSolarQCDFlux.h | /*************************************************************************
* This file is part of the REST software framework. *
* *
* Copyright (C) 2016 GIFNA/TREX (University of Zaragoza) *
* For more information see http://gifna.unizar.es/trex *
* *
* REST is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* REST 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 a copy of the GNU General Public License along with *
* REST in $REST_PATH/LICENSE. *
* If not, see http://www.gnu.org/licenses/. *
* For the list of contributors see $REST_PATH/CREDITS. *
*************************************************************************/
#ifndef _TRestAxionSolarQCDFlux
#define _TRestAxionSolarQCDFlux
#include <TRestAxionSolarFlux.h>
#include <TRestAxionSolarModel.h>
//! A metadata class to load tabulated solar axion fluxes. Mass independent.
class TRestAxionSolarQCDFlux : public TRestAxionSolarFlux {
private:
/// The filename containning the solar flux table with continuum spectrum
std::string fFluxDataFile = ""; //<
/// The filename containning the solar flux spectra for monochromatic spectrum
std::string fFluxSptFile = ""; //<
/// It will be used when loading `.flux` files to define the input file energy binsize in eV.
Double_t fBinSize = 0; //<
/// It will be used when loading `.flux` files to define the threshold for peak identification
Double_t fPeakSigma = 0; //<
/// The tabulated solar flux continuum spectra TH1F(200,0,20)keV in cm-2 s-1 keV-1 versus solar radius
std::vector<TH1F*> fFluxTable; //!
/// The tabulated solar flux in cm-2 s-1 for a number of monochromatic energies versus solar radius
std::map<Double_t, TH1F*> fFluxLines; //!
/// Accumulative integrated solar flux for each solar ring for continuum spectrum (renormalized to unity)
std::vector<Double_t> fFluxTableIntegrals; //!
/// Accumulative integrated solar flux for each monochromatic energy (renormalized to unity)
std::vector<Double_t> fFluxLineIntegrals; //!
/// Total solar flux for monochromatic contributions
Double_t fTotalMonochromaticFlux = 0; //!
/// Total solar flux for monochromatic contributions
Double_t fTotalContinuumFlux = 0; //!
/// The ratio between monochromatic and total flux
Double_t fFluxRatio = 0; //!
/// A pointer to the continuum spectrum histogram
TH1F* fContinuumHist = nullptr; //!
/// A pointer to the monochromatic spectrum histogram
TH1F* fMonoHist = nullptr; //!
/// A pointer to the superposed monochromatic and continuum spectrum histogram
TH1F* fTotalHist = nullptr; //!
void ReadFluxFile();
void LoadContinuumFluxTable();
void LoadMonoChromaticFluxTable();
void IntegrateSolarFluxes();
public:
/// It returns true if continuum flux spectra was loaded
Bool_t isSolarTableLoaded() { return fFluxTable.size() > 0; }
/// It returns true if monochromatic flux spectra was loaded
Bool_t isSolarSpectrumLoaded() { return fFluxLines.size() > 0; }
/// It returns the integrated flux at earth in cm-2 s-1 for the given energy range
Double_t IntegrateFluxInRange(TVector2 eRange = TVector2(-1, -1), Double_t mass = 0) override;
/// It defines how to generate Monte Carlo energy and radius values to reproduce the flux
std::pair<Double_t, Double_t> GetRandomEnergyAndRadius(TVector2 eRange = TVector2(-1, -1),
Double_t mass = 0) override;
/// It defines how to read the solar tables at the inhereted class
Bool_t LoadTables() override;
/// It returns the total integrated flux at earth in cm-2 s-1
Double_t GetTotalFlux(Double_t mass = 0) override {
return fTotalContinuumFlux + fTotalMonochromaticFlux;
}
/// It returns an energy integrated spectrum in cm-2 s-1 keV-1
TH1F* GetEnergySpectrum(Double_t m = 0) override { return GetTotalSpectrum(); }
TH1F* GetContinuumSpectrum();
TH1F* GetMonochromaticSpectrum();
TH1F* GetTotalSpectrum();
virtual TCanvas* DrawSolarFlux() override;
/// Tables might be loaded using a solar model description by TRestAxionSolarModel
void InitializeSolarTable(TRestAxionSolarModel* model) {
// TOBE implemented
// This method should initialize the tables fFluxTable and fFluxLines
}
void ExportTables(Bool_t ascii = false) override;
void PrintMetadata() override;
void PrintContinuumSolarTable();
void PrintIntegratedRingFlux();
void PrintMonoChromaticFlux();
TRestAxionSolarQCDFlux();
TRestAxionSolarQCDFlux(const char* cfgFileName, std::string name = "");
~TRestAxionSolarQCDFlux();
ClassDefOverride(TRestAxionSolarQCDFlux, 1);
};
#endif
|
944afcde5eb02cbd92eed08c7fa1c319a3815d20 | 64f1b82d1451e83aa434ca339fa085c3e8cbbff6 | /.svn/pristine/94/944afcde5eb02cbd92eed08c7fa1c319a3815d20.svn-base | 6ddec9a018e9167639071178a98df6716cc0e535 | [] | no_license | wujw20/OpenCube | ce0a75a3388edcf00797458ca9e6f6988f4f52e2 | 752fecff4293e0e7110da0d5222e7909e23c16fc | refs/heads/master | 2023-04-13T01:21:53.182868 | 2017-08-25T05:21:59 | 2017-08-25T05:21:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 593 | 944afcde5eb02cbd92eed08c7fa1c319a3815d20.svn-base |
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include "../../../time_class.h"
extern int test_return;
void * test1(void *args) {
sem_t sem;
sem_init(&sem, 0, 0);
struct timespec old_time;
clock_gettime(CLOCK_REALTIME, &old_time);
struct timespec wait_time;
wait_time.tv_sec = 0;
wait_time.tv_nsec = 500000000;
if (sem_timedwait(&sem, &wait_time) != -1) {
return NULL;
}
struct timespec current_time;
clock_gettime(CLOCK_REALTIME, ¤t_time);
if (current_time - old_time > wait_time) {
return NULL;
}
test_return = 0;
return NULL;
}
| |
f02180f865e04d0a78a20eb282a60f1d9e3b58cc | 92b71ee8ebf3977e525e5375e9d41b8ead495937 | /3-28 RFID-RC522 ESP8266 D1 MINI/mfrc522/mfrc522.ino | fdfc7386b20c134b198a849a888d1a64110723c9 | [] | no_license | kdi6033/sensor | 9fc523eb6d419896478a7917d4b4f7bba23908bc | 0ed225a1a0aedc817e54099ad8e4a99018ba65ae | refs/heads/master | 2022-06-01T17:19:09.250405 | 2022-05-29T04:29:23 | 2022-05-29T04:29:23 | 137,852,420 | 7 | 11 | null | null | null | null | UTF-8 | C++ | false | false | 1,717 | ino | mfrc522.ino | /**
d1 mini rc52 wiring
RST - D3
MISO - D6
MOSI - D7
SCK - D5
SDA - D8
*/
#include "ESP8266WiFi.h"
#include <SPI.h>
#include <MFRC522.h>
constexpr uint8_t RST_PIN = 0; // Configurable, see typical pin layout above 18
constexpr uint8_t SS_PIN = 15; // Configurable, see typical pin layout above 16
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
delay(1000);
Serial.println("Setup");
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
Serial.println("Setup done");
}
void loop() {
// Serial.println("Loop...");
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent()) {
//delay(50);
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
//delay(50);
return;
}
// Show some details of the PICC (that is: the tag/card)
Serial.print(F("Card UID:"));
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println();
// Dump debug info about the card; PICC_HaltA() is automatically called
//mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
delay(1000);
}
// Helper routine to dump a byte array as hex values to Serial
void dump_byte_array(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);
}
}
|
00dd241cf419669ab2675480299674eb588eda9c | be5cef1ac1bfd1b93b97405175dd727ba4e1f4fe | /Source/Assignment2/SpeedPickup.cpp | 99fd279404e612edd9a04d2555d988fe47258b90 | [] | no_license | ArshhV/Multiplayer-Network-Game-Prototype | b774e5161a8f24dacf44c0f803d128a4633d6fcd | 32d51997c115dd0041f06325e21806e7e76aae41 | refs/heads/master | 2020-12-26T07:56:29.228670 | 2020-01-31T17:07:23 | 2020-01-31T17:07:23 | 237,439,525 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 918 | cpp | SpeedPickup.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "SpeedPickup.h"
#include "Assignment2.h"
#include "Components/StaticMeshComponent.h"
#include "Net/UnrealNetwork.h"
ASpeedPickup::ASpeedPickup()
{
//Keep movement synced from server to client
bReplicateMovement = true;
//This pickup is physics enabled and should move
GetStaticMeshComponent()->SetSimulatePhysics(true);
GetStaticMeshComponent()->SetMobility(EComponentMobility::Movable);
// set a base value
SpeedPower = 1000.0f;
}
void ASpeedPickup::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(ASpeedPickup, SpeedPower);
}
void ASpeedPickup::PickedUpBy(APawn * Pawn)
{
Super::PickedUpBy(Pawn);
if (Role == ROLE_Authority)
{
SetLifeSpan(0.1f);
}
}
float ASpeedPickup::GetPower()
{
return SpeedPower;
}
|
0b3f11357e16d470e94b0035e62094201c2b3f35 | 7350555cca78e8597999fc44dc4a0cd3ef7fa749 | /qtWb26_ValidatingUserInput/dialog.cpp | b942c4af07544e57fa62d7c92a91c44db9f46de3 | [] | no_license | CodePractice01/QT-Widgets-for-Beginners | 91e306cb2813da121463a03615ff686c569be02a | d460255100b8b320c9ce3bb76737220cb218551f | refs/heads/master | 2022-11-05T04:40:11.545731 | 2020-06-17T13:20:45 | 2020-06-17T13:20:45 | 269,102,153 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,048 | cpp | dialog.cpp | #include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
QRegularExpression rx("\\b[A-Z0-9._%+-]+@[A-Z]{2,4}\\b", QRegularExpression::CaseInsensitiveOption);
ui->txtEmail->setValidator(new QRegularExpressionValidator(rx, this));// (rx, this) -- expresion (rx) and the parent
connect(ui->txtEmail, &QLineEdit::textChanged, this, &Dialog::checkInput);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_buttonBox_accepted()
{
if(ui->txtEmail->hasAcceptableInput())
{
QMessageBox::information(this, "Email", ui->txtEmail->text());
accept();
}
else{
QMessageBox::critical(this, "Email","Not Valid");
}
}
void Dialog::on_buttonBox_rejected()
{
reject();
}
void Dialog::checkInput()
{
if(ui->txtEmail->hasAcceptableInput())
{
ui->txtEmail->setStyleSheet("QLineEdit{color : black;}");
}
else{
ui->txtEmail->setStyleSheet("QLineEdit{color : red;}");
}
}
|
86b6438aa83b96211de9de962756cb1729526c0a | 1eceddac0e9f42995f8f738de49042751e389790 | /source/DMEngine/AnimationDataEnable.cpp | c792d5f0c9df9b409b02f243f70a1543c1400f20 | [] | no_license | kerrot/DxlibMario | 16d21eb1915872ec1d7bd01ba776f8279b23946a | ef76c561d3dc6ac97f75ea872aa7f76da7d3b764 | refs/heads/master | 2021-06-16T18:06:12.308096 | 2017-06-02T07:35:07 | 2017-06-02T07:35:07 | 65,349,208 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 737 | cpp | AnimationDataEnable.cpp | #include "AnimationDataEnable.h"
#include "ObjectBase.h"
AnimationDataEnable::AnimationDataEnable(__int64 time)
: AnimationData(time) {
}
AnimationDataEnable::~AnimationDataEnable() {
}
void AnimationDataEnable::Apply(__int64 time, GameObjectPtr ptr, AnimationDataPtr next) {
if (!ptr) {
return;
}
AnimationDataEnablePtr data = std::dynamic_pointer_cast<AnimationDataEnable>(next);
if (!data) {
return;
}
if (time > next->GetTime()) {
data->Apply();
}
else {
Apply();
}
}
void AnimationDataEnable::Apply() {
if (_obj.expired()) {
return;
}
ObjectBasePtr ptr = _obj.lock();
ptr->SetEnable(_enable);
}
void AnimationDataEnable::SetEnable(ObjectBaseWPtr obj, bool enable) {
_obj = obj;
_enable = enable;
}
|
9bd0dd2cf18deec4e6ad70665c38d1406337b150 | 4536c89828880388a65f811a9e871a6ca26ad58b | /game/graphics/play/Chat.cpp | 5603a003707b1b6b98a2e0d732f74d87d060e6c0 | [] | no_license | CyberFlameGO/AwdClient | 2dbf24f17034abe166b5cc2403c700135e9cd6f4 | 2cc76980d0dbbbe80dff3deb539e3ba8c053d93c | refs/heads/main | 2023-05-31T07:41:56.228127 | 2021-06-20T22:03:09 | 2021-06-20T22:03:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,718 | cpp | Chat.cpp | // Фон
#define RECT_ALPHA 150
#define RECT_WIDTH 350.0f
#define RECT_HEIGHT 225.0f
#define CHAT_TOP_MARGIN 600.0f
// Текст
#define TEXT_FONT_SIZE 27
#define TEXT_LEFT_MARGIN 10.0f
#define TEXT_TOP_MARGIN 10.0f
#define MAX_LINE_LENGTH 28
#define MAX_LINES 10
#include "Chat.hpp"
#include "../../util/StringUtils.hpp"
#include "../../Game.hpp"
#include "../../util/RenderUtils.hpp"
namespace awd::game {
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* PUBLIC
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
Chat::Chat() : Drawable(ID_SCREEN_PLAY_CHAT) {
// Фон
width = RECT_WIDTH * renderScale;
height = RECT_HEIGHT * renderScale;
rect = std::make_unique<sf::RectangleShape>(sf::Vector2f(width, height));
rect->setFillColor(sf::Color(0, 0, 0, RECT_ALPHA));
// Текст
uint32_t textFontSize = TEXT_FONT_SIZE * renderScale;
text = std::make_unique<sfe::RichText>(*Game::instance().getFonts()->regularFont);
text->setCharacterSize(textFontSize);
}
void Chat::update() {
Drawable::update();
sf::Vector2f viewCenter = window->getView().getCenter();
sf::Vector2f viewSize = window->getView().getSize();
float viewX = viewCenter.x - viewSize.x / 2.0f;
float viewY = viewCenter.y - viewSize.y / 2.0f;
// Фон
float chatTopMargin = CHAT_TOP_MARGIN * renderScale;
rect->setPosition(viewX, viewY + chatTopMargin);
// Текст
float textLeftMargin = TEXT_LEFT_MARGIN * renderScale;
float textTopMargin = TEXT_TOP_MARGIN * renderScale;
text->setPosition(viewX + textLeftMargin, viewY + chatTopMargin + textTopMargin);
}
void Chat::draw() {
Drawable::draw();
// FIXME: см. коммент в StringUtils#getUtf8WideString
// window->draw(*rect);
// window->draw(*text);
}
void Chat::addChatMessage(const std::wstring& message) {
// Сначала просто строим новый текст, содержащий все сообщения
// в чате, без учёта ограничения на количество отображаемых строк.
std::wstring tempWholeChat = wholeChat + L'\n' +
StringUtils::wrapByLineLength(
StringUtils::encodeFormatting(message),
MAX_LINE_LENGTH, 9999);
// Затем отбрасываем наиболее старые сообщения.
tempWholeChat += L'\n'; // добавляем в конец '\n', чтобы нормально выделились все строки (в т.ч. последняя)
std::vector<std::wstring> lines;
std::wstring currentLine;
for (const wchar_t ch : tempWholeChat) {
if (ch == L'\n') {
if (!currentLine.empty()) { // может быть, если в сообщении несколько '\n' идут подряд
lines.push_back(currentLine);
currentLine = L"";
}
} else
currentLine += ch;
}
wholeChat = L""; // сброс
uint32_t linesNum = lines.size();
uint32_t begin = linesNum <= MAX_LINES ? linesNum : linesNum - MAX_LINES;
for (uint32_t i = begin; i < MAX_LINES; i++)
wholeChat += lines[i] + L'\n';
// Наконец, обновляем то, что видит игрок на экране
RenderUtils::enrichText(*text, wholeChat);
}
}
|
688bdec0900eb3d79acd284b426bd25d92932f09 | dcc3479089444309a1c16a22d700354fbe64a1f8 | /src/tensor/nn/tensor_pool.cpp | c9f17e7e2e4645695dbb1b448409f80656e6e82f | [
"MIT"
] | permissive | ilveroluca/eddl | 0916b7c7389f5e57d5256f455ae3a0ff3155bd96 | 02e37c0dfb674468495f4d0ae3c159de3b2d3cc0 | refs/heads/master | 2022-07-26T06:19:27.743600 | 2020-05-17T14:31:09 | 2020-05-17T14:31:09 | 264,906,140 | 0 | 0 | MIT | 2020-05-18T10:31:03 | 2020-05-18T10:31:03 | null | UTF-8 | C++ | false | false | 3,138 | cpp | tensor_pool.cpp | /*
* EDDL Library - European Distributed Deep Learning Library.
* Version: 0.6
* copyright (c) 2020, Universidad Politécnica de Valencia (UPV), PRHLT Research Centre
* Date: April 2020
* Author: PRHLT Research Centre, UPV, (rparedes@prhlt.upv.es), (jon@prhlt.upv.es)
* All rights reserved
*/
#include "eddl/tensor/nn/tensor_nn.h"
#include "eddl/hardware/cpu/nn/cpu_nn.h"
#ifdef cGPU
#include "eddl/hardware/gpu/gpu_tensor.h"
#include "eddl/hardware/gpu/gpu_hw.h"
#include "eddl/hardware/gpu/nn/gpu_nn.h"
#endif
void MPool2D(PoolDescriptor *D) {
/////////////////////////////////////////////////////////////////////
//// MPool2D
//// Dimensions must be compatible
//// A is input 4D Tensor, Batch x Channels x Rows x Cols
//// D is a PoolDescriptor
/////////////////////////////////////////////////////////////////////
if ((D->I->ndim != 4)) msg("Tensors are not 4D", "Tensor::MPool2D");
D->O->tsem->lock();
if (D->I->isCPU()) {
cpu_mpool2D(D);
}
#ifdef cGPU
else if (D->I->isGPU())
{
gpu_mpool2D(D);
}
#endif
#ifdef cFPGA
else {
}
#endif
D->O->tsem->unlock();
}
void MPool2D_back(PoolDescriptor *D) {
/////////////////////////////////////////////////////////////////////
//// MPool2D
//// Dimensions must be compatible
//// A is input 4D Tensor, Batch x Channels x Rows x Cols
//// D is a PoolDescriptor
/////////////////////////////////////////////////////////////////////
if ((D->I->ndim != 4)) msg("Tensors are not 4D", "Tensor::MPool2D_back");
D->ID->tsem->lock();
if (D->I->isCPU()) {
cpu_mpool2D_back(D);
}
#ifdef cGPU
else if (D->I->isGPU())
{
gpu_mpool2D_back(D);
}
#endif
#ifdef cFPGA
else {
}
#endif
D->ID->tsem->unlock();
}
void AvgPool2D(PoolDescriptor *D) {
/////////////////////////////////////////////////////////////////////
//// AvgPool2D
//// Dimensions must be compatible
//// A is input 4D Tensor, Batch x Channels x Rows x Cols
//// D is a PoolDescriptor
/////////////////////////////////////////////////////////////////////
if ((D->I->ndim != 4)) msg("Tensors are not 4D", "Tensor::AvgPool2D");
D->O->tsem->lock();
if (D->I->isCPU()) {
cpu_avgpool2D(D);
}
#ifdef cGPU
else if (D->I->isGPU())
{
gpu_avgpool2D(D);
}
#endif
#ifdef cFPGA
else {
}
#endif
D->O->tsem->unlock();
}
void AvgPool2D_back(PoolDescriptor *D) {
/////////////////////////////////////////////////////////////////////
//// AvgPool2D_back
//// Dimensions must be compatible
//// A is input 4D Tensor, Batch x Channels x Rows x Cols
//// D is a PoolDescriptor
/////////////////////////////////////////////////////////////////////
if ((D->I->ndim != 4)) msg("Tensors are not 4D", "Tensor::AvgPool2D_back");
D->ID->tsem->lock();
if (D->I->isCPU()) {
cpu_avgpool2D_back(D);
}
#ifdef cGPU
else if (D->I->isGPU())
{
gpu_avgpool2D_back(D);
}
#endif
#ifdef cFPGA
else {
}
#endif
D->ID->tsem->unlock();
}
|
7f5b8aab78ad346e25bb52f997102626050861ad | 4a1ef66e84febdd996ccccb1d7cdf0002ba9e411 | /projects/Sample2/Headers/SimpleSampleBaseClass.h | 7c2cfb7c764aaba906849b761802697cabb17609 | [
"MIT"
] | permissive | grtwall/kigs | dc782b517626ab792048a3f74e670ba39ae17aaa | 2ada0068c8618935ed029db442ecf58f6bf96126 | refs/heads/master | 2023-06-06T12:11:44.054106 | 2021-06-28T11:31:43 | 2021-06-28T11:35:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 598 | h | SimpleSampleBaseClass.h | #pragma once
#include "CoreModifiable.h"
#include <iostream>
class SimpleSampleBaseClass : public CoreModifiable
{
public:
DECLARE_ABSTRACT_CLASS_INFO(SimpleSampleBaseClass, CoreModifiable, Application);
DECLARE_INLINE_CONSTRUCTOR(SimpleSampleBaseClass) { std::cout << "SimpleSampleBaseClass constructor" << std::endl; }
protected:
void InitModifiable() override;
virtual void Update(const Timer& timer, void* addParam) override;
// method that add 1 to the given parameter
DECLARE_METHOD(incrementParam);
// list all CoreModifiable methods
COREMODIFIABLE_METHODS(incrementParam);
};
|
feca09de2efa00ccdaae89eaacb9c13196917642 | f936231c0b4344c07cb918498bb46b5373996ab8 | /E42Algorithm/ALGORITHM/bst.cpp | 0c867d9d96038a5a5fcae3d39bdf0940e71a6108 | [
"MIT"
] | permissive | aditta97/Algorithm | 6acd975ec30eceabc7cf040610dd873506c2c1a4 | f078a99261c2c2f00ffd8707a83c2c253e27f231 | refs/heads/master | 2020-06-24T15:46:50.609850 | 2019-07-26T11:47:24 | 2019-07-26T11:47:24 | 199,005,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,331 | cpp | bst.cpp | #include<stdio.h>
#include<stdlib.h>
typedef struct BST
{
int data;
struct BST *left;
struct BST *right;
}node;
node *create();
void insert(node *,node *);
void preorder(node *);
int main()
{
char ch;
node *root=NULL,*temp;
do
{
temp=create();
if(root==NULL)
root=temp;
else
insert(root,temp);
printf("nDo you want to enter more(y/n)?");
getchar();
scanf("%c",&ch);
}while(ch=='y'|ch=='Y');
printf("nPreorder Traversal: ");
preorder(root);
return 0;
}
node *create()
{
node *temp;
printf("nEnter data:");
temp=(node*)malloc(sizeof(node));
scanf("%d",&temp->data);
temp->left=temp->right=NULL;
return temp;
}
void insert(node *root,node *temp)
{
if(temp->data<root->data)
{
if(root->left!=NULL)
insert(root->left,temp);
else
root->left=temp;
}
if(temp->data>root->data)
{
if(root->right!=NULL)
insert(root->right,temp);
else
root->right=temp;
}
}
void preorder(node *root)
{
if(root!=NULL)
{
printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}
}
|
78da4ad65b6392f4c8f6d99c8d1d465eaa8887ec | 653e5cd3724231bef882b419b1dc8fdc3502d807 | /Misc/Matrix/SVD/3x3/xswap_3x3.cpp | d79aafc30b9257436ef10bf067c046ac6a0bc403 | [
"MIT"
] | permissive | Hyeong-Yong/STM32-libraries | 95299a3082fb5af6e286243b8762df39928a5b90 | f0d05495acee83be8fbefe0bbbb0ec7fd236cef5 | refs/heads/master | 2023-06-21T18:37:57.950435 | 2020-12-06T07:43:09 | 2020-12-06T07:43:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 831 | cpp | xswap_3x3.cpp | //
// Academic License - for use in teaching, academic research, and meeting
// course requirements at degree granting institutions only. Not for
// government, commercial, or other organizational use.
// File: xswap.cpp
//
// MATLAB Coder version : 4.0
// C/C++ source code generated on : 12-Feb-2019 21:10:49
//
// Include Files
#include "rt_nonfinite.h"
#include "svd_3x3.h"
#include "xswap_3x3.h"
// Function Definitions
//
// Arguments : float x[9]
// int ix0
// int iy0
// Return Type : void
//
void xswap_3x3(float x[9], int ix0, int iy0)
{
int ix;
int iy;
int k;
float temp;
ix = ix0 - 1;
iy = iy0 - 1;
for (k = 0; k < 3; k++) {
temp = x[ix];
x[ix] = x[iy];
x[iy] = temp;
ix++;
iy++;
}
}
//
// File trailer for xswap.cpp
//
// [EOF]
//
|
7b6fb5cf55a8cdbfe18a40664c9dac67e4af9d51 | 86b211d5e7a8e7db729a193f61e0e2bc3dcc2bec | /1015/a.cpp | 753f2e5d7a9622aa65db060f63d01153d7a3cc3a | [] | no_license | Hsueh-Xue/PAT-Top-Practice | 0022ea23b44ba67f1bbaa0956f0cb5c5ea1be4ea | 73f4ac9b0fdd9ad38af1440dbde277b1b822cd66 | refs/heads/master | 2020-12-22T05:05:10.656126 | 2020-02-03T04:58:55 | 2020-02-03T04:58:55 | 236,677,349 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 471 | cpp | a.cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
char s1[N], s2[N];
int main() {
#ifdef XHT
freopen("1.in", "r", stdin);
#endif
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
scanf("%s %s", s1 + 1, s2 + 1);
n = strlen(s1 + 1);
int Max = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 1, k = i; j <= n; ++j) {
if (k <= n && s1[j] == s2[k]) ++k;
Max = max(Max, k - i);
}
}
printf("%d\n", n - Max);
return 0;
}
|
f6d68e361ef7d2439980c4e3a1694b682485c9e3 | a97cb7fb087ac7b545146e0fbdb0e272db337aab | /Game/ai_summon_player.cpp | dfb1cdd69ab9edf2bd79b219489a3af8516a3cf5 | [] | no_license | djnandinho26/Legend_Server_S16 | e331a15613f2099d4c37945d8b041a3be58e1420 | b1111b2fd1db85d6aa25f850be446903ec7928ba | refs/heads/main | 2023-04-25T03:10:52.968102 | 2022-08-16T12:50:04 | 2022-08-16T12:50:04 | 373,501,276 | 0 | 0 | null | 2021-06-03T12:35:46 | 2021-06-03T12:35:45 | null | UTF-8 | C++ | false | false | 1,306 | cpp | ai_summon_player.cpp | bool SummonPlayerAI::ViewportListAddConditions(Unit* pAdd)
{
if ( pAdd->IsPlayer() )
return true;
if ( pAdd->IsCreature() && (pAdd->ToCreature()->IsMonster() || pAdd->ToCreature()->IsNeutral()) )
{
return true;
}
return false;
}
bool SummonPlayerAI::MoveAttempt()
{
me()->FollowOwner();
return true;
}
bool SummonPlayerAI::MoveAllowed(int16 x, int16 y)
{
return me()->GetWorld()->GetGrid(x, y).IsSummonedMoveAllowed();
}
bool SummonPlayerAI::SearchEnemy()
{
if ( me()->GetSummoner()->IsInSafeZone() )
{
me()->SetTarget(nullptr);
return true;
}
Object * pObject = nullptr;
int32 min_distance = 999;
VIEWPORT_LOOP_OBJECT(me(), pObject)
if ( !pObject->IsCreature() || !pObject->ToCreature()->IsLive() )
continue;
if ( !pObject->ToCreature()->IsMonster() )
continue;
if ( pObject->ToCreature()->IsSummoned() && pObject->ToCreature()->GetSummoner()->IsPlayer() )
continue;
int32 dis = DISTANCE(me()->GetSummoner(), pObject);
if ( dis < min_distance )
{
me()->SetTarget(pObject->ToUnit());
min_distance = dis;
}
VIEWPORT_CLOSE
return true;
}
void SummonPlayerAI::OnDie()
{
if ( me()->GetSummoner() && me()->GetSummoner()->GetSummoned() == me() )
{
me()->GetSummoner()->SendSummonedHP(0, 60);
me()->GetSummoner()->KillSummoned(false);
}
} |
30065f7ae7c25f22c59c592ac5f8c89266cb65e5 | 7cad0d9e242c458a3ccb05726f4f8bc2cf71c95f | /html/submissions/990/submission.cpp | f8ae7f1385f6a39eb276f13c325a960e5e3be8bd | [] | no_license | nguyenvu9405/online-judge | 20a8f616bec5e49eef744033c63915f73e1d4878 | 2972e5bd6520f84712ece1c47451b71b077f0792 | refs/heads/master | 2020-03-31T02:11:39.949251 | 2018-11-04T16:49:10 | 2018-11-04T16:49:10 | 151,812,521 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 591 | cpp | submission.cpp | #include <iostream>
using namespace std;
long long s,n;
long long a[100];
void input()
{
cin >> n;
}
void check()
{
long long t = 0;
for (long long i = 1; i <= n; i++)
{
if (a[i] == 0) t++; else t--;
if (t < 0) return;
}
if (t == 0) s++;
}
void bk(long long j)
{
for (long long i = 0; i <= 1; i++)
{
if(a[0]>=a[1]&&a[0]<=n/2)
{ a[j] = i;
if (j == n) check();
else bk(j + 1);
}
}
}
int main()
{
input();
bk(1);
cout << s;
return 0;
}
|
06e1c1b129103c1ea31119e3c7f8adbf4304122b | 66d83375fb1122e397fa52cc26acc4405e48976e | /build/main.cpp | 829e52a45c3d1cdb3f872c29fa20a005b604ffa5 | [] | no_license | lemourin/ponywars3 | e8816d3163f56b215adbf172b5d8e4ad3164e84b | 336604917ecb58a3ebec873a1737139d126fb7ac | refs/heads/master | 2021-07-13T22:12:00.981721 | 2021-07-11T09:45:29 | 2021-07-11T09:45:29 | 51,439,299 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 273 | cpp | main.cpp | #include "Utility/Window.hpp"
#include <QGuiApplication>
int main(int argc, char **argv) {
QGuiApplication app(argc, argv);
// app.setOverrideCursor(Qt::BlankCursor);
qputenv("QSG_RENDER_LOOP", "threaded");
Window window;
window.show();
return app.exec();
}
|
0f7368df778ced6c8176d20b3636f7b3cfa91091 | 5433e8b48fbd027cae3a99496e68eeb56a5940b3 | /external/MoreStructures/CompressedOctree/CompressedONode.h | bea0a7af51162a469d8a4fff5cce6afc01e4007c | [] | no_license | choyfung/RegistrationPipeline | 55e3b79ded25c608bf6b25273f2888c5c807ab86 | aa8ee3e976e75d60d944cb77a3f4fe5e93ed08e5 | refs/heads/master | 2021-05-20T15:10:19.859253 | 2017-01-21T19:09:21 | 2017-01-21T19:09:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,472 | h | CompressedONode.h | #ifndef _COMPRESSED_ONODE_
#define _COMPRESSED_ONODE_
#include <vector>
#include <list>
#include <iostream>
#include "../AuxiliaryClasses/Element.h"
#include "./CompressedInformacioGeometrica.h"
//#include "./CompressedCandidateZone.h"
#define INSIDE 1
#define OUTSIDE 0
#define INTERSECT 2
#define CONTAINS 3
class CompressedCandidateZone;
class CompressedONode
{
private:
point3D ancoratge; //Punt d'ancoratge del cub al que es refereix el node
long double mida; //Mida del costat del cub al que es refereix el node
int nivell; //Nivell que es troba el node
vector<Element *> llistaElements; //Llista d'esferes que conte el node (tant si es fulla com si no)
CompressedInformacioGeometrica *infGeo; //Informacio geometrica del node
CompressedONode *f1,*f2,*f3,*f4,*f5,*f6,*f7,*f8; //Els 8 fills
vector<CompressedCandidateZone *> nodeZones; //List of candidate zones rooted at this CompressedONode
int afegirElementFillCorresponent(Element *,int); //Metode que calcula el fill que s'ha de posar l'esfera i crida el metode "afegirElement" amb el fill calculat. L'enter es el nivell maxim que pot tenir un node. Retorna el nivell que insereix l'esfera
public:
CompressedONode(); //Constructor per defecte
CompressedONode(point3D,double,int); //Constructor per un node "fulla blanca" (ancoratge,mida,nivell)
CompressedONode(const CompressedONode &n); //Constructor copia
~CompressedONode(); //Destructor
CompressedONode& operator=(const CompressedONode &n);
point3D getAncoratge();
double getMida();
int getNivell();
CompressedONode* getFill1();
CompressedONode* getFill2();
CompressedONode* getFill3();
CompressedONode* getFill4();
CompressedONode* getFill5();
CompressedONode* getFill6();
CompressedONode* getFill7();
CompressedONode* getFill8();
vector<Element *> getLlistaElements();
CompressedInformacioGeometrica* getInfGeo();
void setInfGeo(CompressedInformacioGeometrica*);
void setAncoratge(point3D);
void setMida(double);
void setNivell(int);
void setLlistaElements(vector<Element *>);
void setFill1(CompressedONode *);
void setFill2(CompressedONode *);
void setFill3(CompressedONode *);
void setFill4(CompressedONode *);
void setFill5(CompressedONode *);
void setFill6(CompressedONode *);
void setFill7(CompressedONode *);
void setFill8(CompressedONode *);
void setNodeZones(CompressedCandidateZone * cand); //Enllaça el CompressedONode que toca amb la zona que toca
vector<CompressedCandidateZone *> getNodeZones(){return nodeZones;}
void copiarAtributs(CompressedONode *);
int afegirElement(Element *,int, CompressedONode *); //Metode per afegir una esfera al node passant com a parametre l'esfera, el nivell maxim que pot tenir un node i el pare. Retorna el nivell que ha posat l'esfera
void esborrarElement(Element *,int,CompressedONode *); //Metode per esborrar un element del compressed octree
int tipus(); //Retorna quin es el seu tipus de node (fulla blanca, negre o node parcial).
bool esFulla(); //Retorna cert si el node no te fills
bool nodeBuit(); //Retorna cert si es fulla blanca
int crearFills(int); //Metode que crea els fills d'un node a partir dels 2 elements que hi ha.
bool pertany(Element *e);
vector<bool> aQuinsFills(Element *e);
int aQuinFill(Element *e); //Retorna el numero de fill que pertany l'element e.
int aQuinFill(CompressedONode *n); //Retorna el numero de fill que pertany el node n.
int fillNoFullaBlanca(); //Retorna el numero de fill que no es fulla blanca (en cas que nomes n'hi hagi un)
bool formaPart(point3D p); //Retorna cert si el punt forma part del node, fals altrament.
void marcarElement(Element *e); //Metode que busca un element i li canvia l'atribut "marcat"
void actualitzarInfGeo(); //Metode per actualitzar la informacio geometrica
list<Element*> * weightedNeighbors(Element *e,double epsilon); //Retorna la llista d'elements que formen part de la circumferencia "e-epsilon"
bool contained(Element *e,double r); //Retorna cert si el node forma part de la circumferencia zona "e-r", altrament fals
bool stabbingSimple(Element *e, double r);
bool stabbing(Element *e,double r); //Retorna cert si alguna part del node forma part de la circumferencia "e-r", altrament fals
int checkIntersection(double p_xmin, double p_xmax, double p_ymin, double p_ymax, double p_zmin, double p_zmax);
list<Element*> * report(Element *e); //Report all Elements in the node matching the parameters radius
list<Element*> * reportIf(Element *e,double r); //Report all Elements in the node matching the parameters radius and distance requirement
static bool compatible(CompressedInformacioGeometrica,CompressedInformacioGeometrica*,bool bNum,bool bHisto,bool bDist,double eps); //Operation for atribute compatibility
static bool compatible_num_elements(CompressedInformacioGeometrica,CompressedInformacioGeometrica*); //First attribute: number of elements
static bool compatible_weights(CompressedInformacioGeometrica,CompressedInformacioGeometrica*); //Second attribute: weights
static bool compatible_distances(CompressedInformacioGeometrica,CompressedInformacioGeometrica*,double eps); //Third attribute: distances
void pintar(); //Metode per pintar 2 plans al node (si te fills)
void write(); //Metode que escriu per la terminal l'octree en POSTORDRE (arrel,f1,f2,f3,...)
void write2(ostream& os); //Metode per write a traves d'un ostream
};
#endif
|
e1127bb87c4a624c9c0cbba226c528fabe54f01f | 8e8c45fd0ba1cfe97c7939019b2ee7f392038504 | /GoBeaverGo/RunController.h | d6142b53e31f62296501522df00e786dfc956c3f | [
"MIT"
] | permissive | erwinbonsma/BusyBeaverGB | 33ffded684b0b6918ea0f5e40f841064b6c1a4e7 | fc65397b446e7c688b6762a90aa2fe7abd4b4772 | refs/heads/master | 2022-05-10T00:35:47.833429 | 2022-04-10T20:07:49 | 2022-04-10T20:07:49 | 163,868,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,145 | h | RunController.h | /*
* Go Beaver Go, a puzzle game based on a variant of the 2L programming language
*
* Copyright 2019, Erwin Bonsma
*/
#ifndef __RUN_CONTROLLER_INCLUDED
#define __RUN_CONTROLLER_INCLUDED
#include <Gamebuino-Meta.h>
#include "Controller.h"
constexpr uint8_t unitRunSpeed = 6;
constexpr uint8_t maxRunSpeed = 20;
enum class RunAction : int {
Play = 0,
Pause = 1,
Step = 2,
Rewind = 3,
None = 8
};
struct LedActivation {
uint8_t inc;
uint8_t dec;
uint8_t shr;
uint8_t shl;
};
class RunController : public Controller {
LedActivation _ledActivation;
int16_t _tapeShift;
uint16_t _stepsPerTick;
uint8_t _runSpeed = 0;
uint8_t _stepPeriod;
uint8_t _ticksSinceLastStep = 0;
bool _paused;
bool _challengeCompleted;
void runMenu();
RunAction activeActionButtonA();
void changeRunSpeed(int delta);
void tryChangeTapeShift(int delta);
void handleProgramTermination();
void reset();
void decayLedActivation(uint8_t amount);
void updateLedActivation();
void drawLeds();
public:
RunController();
void setRunSpeed(int speed);
void activate();
void update();
void draw();
};
#endif
|
fbf8263afe5e68064d8a024474048f1979fb7253 | 11e9fdc832e174c35ee9f678890b319526e506c6 | /PowerPaint/StrField.h | 3a8ba4eef403c5b44b10c8a2ebd69fba6811bef0 | [] | no_license | wangdi190/ChengGong | 96a5c9073f8b269cebbdf02e09df2687a40d5cce | ae03dc97c98f5dc7fbdd75a8ba5869f423b83a48 | refs/heads/master | 2020-05-29T09:16:20.922613 | 2016-09-28T08:13:13 | 2016-09-28T08:13:13 | 69,441,767 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 542 | h | StrField.h | // StrField.h: interface for the StrField class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_STRFIELD_H__0013C460_34FD_4B67_BF6C_5EA63AE5A716__INCLUDED_)
#define AFX_STRFIELD_H__0013C460_34FD_4B67_BF6C_5EA63AE5A716__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class StrField
{
public:
int SetNewStr(char *str);
StrField();
virtual ~StrField();
char *lpt[256];
int fldsum;
};
#endif // !defined(AFX_STRFIELD_H__0013C460_34FD_4B67_BF6C_5EA63AE5A716__INCLUDED_)
|
687a0a92484281c1b4538e1f5728e58201a54141 | a7df14cd7914602e3e98b93f445eb98848e6419b | /unitTests/src/common/factory_test.cpp | 351cac0451a8db068cb1e146bf9a6bb9c8a2417e | [] | no_license | HerbikJedrzej/mappingPlatform | d02ae5ae5ea3d7af73d0c547eaec5370413cbb99 | feb10a9316f401d386352e51d6fd15dc9cf0b595 | refs/heads/main | 2023-03-16T07:39:30.202984 | 2021-03-13T14:50:46 | 2021-03-13T14:50:46 | 344,261,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,155 | cpp | factory_test.cpp | #include <gtest/gtest.h>
#include <SPI_driver_Mock.hh>
#include <I2C_driver_Mock.hh>
#include <GPIO_driver_Mock.hh>
#include <factory.hh>
TEST(factory, cycle){TEST_LOG_HEADER
auto gpio = Drivers::createDriverGPIO({0, 1, 4, 7, 12, 17, 18, 22});
auto i2c = Drivers::createDriver();
auto spi = Drivers::createDriverSPI();
gpio.at(22)->setPinReading({true, true});
spi->setReciveBuffor({{0x5a, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}});
i2c->setReadingBuffor({
Drivers::I2Cdata{0x0000, {21, 38, 55, 72, 89, 106, 123, 140, 157, 174}},
Drivers::I2Cdata{0x000a, {150}},
Drivers::I2Cdata{0x000b, {90}},
Drivers::I2Cdata{0x000c, {0}},
Drivers::I2Cdata{0x0100, {154, 153, 153, 153, 153, 153, 241, 63}},
Drivers::I2Cdata{0x0108, {205, 204, 204, 204, 204, 204, 0, 64}},
Drivers::I2Cdata{0x0110, {205, 204, 204, 204, 204, 204, 8, 64}},
Drivers::I2Cdata{0x0118, {102, 102, 102, 102, 102, 102, 16, 64}},
Drivers::I2Cdata{0x0120, { 51, 51, 51, 51, 51, 51, 243, 63}},
Drivers::I2Cdata{0x0128, {154, 153, 153, 153, 153, 153, 1, 64}},
Drivers::I2Cdata{0x0130, {154, 153, 153, 153, 153, 153, 9, 64}},
Drivers::I2Cdata{0x0138, {205, 204, 204, 204, 204, 204, 16, 64}},
Drivers::I2Cdata{0x0203, {2}},
Drivers::I2Cdata{0x0204, {0, 0, 0, 0, 0, 0, 22, 64}},
Drivers::I2Cdata{0x020c, {0xff, 0xf, 0, 0}},
Drivers::I2Cdata{0x0210, {103, 43, 0, 0}},
Drivers::I2Cdata{0x0214, {206, 86, 0, 0}},
Drivers::I2Cdata{0x0218, { 53, 130, 0, 0}},
Drivers::I2Cdata{0x021c, {156, 173, 0, 0}},
// Drivers::I2Cdata{0x0220, {0, 0, 0, 0}},
// Drivers::I2Cdata{0x0224, {0, 0, 0, 0}},
});
Factory factory("./configs/raspberryPlatform_factory_test.bin", "./configs/stmPlatform_factory_test.bin");
EXPECT_NO_THROW(
auto platform = factory.clearAndCreate();
EXPECT_DOUBLE_EQ(platform->currentPosition.x, platform->expectedPosition.x);
EXPECT_DOUBLE_EQ(platform->currentPosition.y, platform->expectedPosition.y);
EXPECT_DOUBLE_EQ(platform->currentPosition.angle, platform->expectedPosition.angle);
platform->expectedPosition.x = 25.63;
platform->expectedPosition.y = -2125.63;
platform->expectedPosition.angle = 95.4931640625;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
EXPECT_NE(platform->currentPosition.x, platform->expectedPosition.x);
EXPECT_NE(platform->currentPosition.y, platform->expectedPosition.y);
EXPECT_NE(platform->currentPosition.angle, platform->expectedPosition.angle);
auto sentSpiData = spi->getSendLine();
sentSpiData[0] = 0x5a;
ASSERT_EQ(sentSpiData.size(), 19);
spi->setReciveBuffor({sentSpiData});
std::this_thread::sleep_for(std::chrono::milliseconds(50));
EXPECT_DOUBLE_EQ(platform->currentPosition.x, platform->expectedPosition.x);
EXPECT_DOUBLE_EQ(platform->currentPosition.y, platform->expectedPosition.y);
EXPECT_DOUBLE_EQ(platform->currentPosition.angle, platform->expectedPosition.angle);
EXPECT_DOUBLE_EQ(platform->currentPosition.x, 25.63);
EXPECT_DOUBLE_EQ(platform->currentPosition.y, -2125.63);
EXPECT_DOUBLE_EQ(platform->currentPosition.angle, 95.4931640625);
);
auto sentSpiData = spi->getSendLine();
ASSERT_EQ(sentSpiData.size(), 19);
EXPECT_TRUE(i2c->clearBuffor());
EXPECT_TRUE(spi->clearBuffor());
auto states = gpio.at(17)->getPinSetting();
EXPECT_EQ(states.size(), 2);
states = gpio.at(0)->getPinSetting();
EXPECT_EQ(states.size(), 2);
states = gpio.at(4)->getPinSetting();
EXPECT_EQ(states.size(), 2);
EXPECT_TRUE(gpio.at(0)->clearBuffor());
EXPECT_TRUE(gpio.at(1)->clearBuffor());
EXPECT_TRUE(gpio.at(4)->clearBuffor());
EXPECT_TRUE(gpio.at(7)->clearBuffor());
EXPECT_TRUE(gpio.at(12)->clearBuffor());
EXPECT_TRUE(gpio.at(17)->clearBuffor());
EXPECT_TRUE(gpio.at(18)->clearBuffor());
EXPECT_TRUE(gpio.at(22)->clearBuffor());
}
|
dfaeb385d1d6c82e2e2bff651b8936d529358ea6 | 7cf6aec7dcd826f0bf5f7ba00ad0d390a7610c0e | /Codewars/properfractions.cpp | 1191071aaab058d5e3ffa56e614f2ad7114865bf | [] | no_license | AddaCR/home | f19488af837b7b3695066904188a20c62df0038f | 3599e67cb9b0be8352457a580bdbfeda73bacbc6 | refs/heads/main | 2023-01-30T03:40:06.156140 | 2020-12-14T12:11:07 | 2020-12-14T12:11:07 | 321,323,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 500 | cpp | properfractions.cpp | //number of proper fractions
long properFractions(long n) {
if(n == 1)
return 0;
long result = n;
long m = n, c = 2;
while(m > 1 && c * c <= m) {
if(m % c == 0) {
result = (result / c) * (c - 1);
while(m % c == 0) {
m = m / c;
}}
if(c == 2)
c = 3;
else if(c == 3)
c = 5;
else if (c % 6 == 5)
c += 2;
else
c += 4;
}
if(m != 1) {
result = (result / m) * (m - 1);
}
return result;
} |
ab277a4f5806b166cebb590f921be1c2b2f58f1f | 7febf8327ca68131b52de39ad2b5106bec470aa2 | /ordenacao/mergesort.cpp | b7a503751b98da4663d1c939aab9e18981af74ac | [
"MIT"
] | permissive | danielsaad/AA-IFB-CC | 5265509ace8d1fb34e5d67185c1007cf761b1d77 | f3a9ff076419f7a560dc83e9fef1fb3b1f01994c | refs/heads/master | 2023-07-21T18:33:20.000302 | 2023-07-11T21:01:41 | 2023-07-11T21:01:41 | 52,815,934 | 4 | 5 | MIT | 2023-07-11T21:01:43 | 2016-02-29T19:06:51 | C++ | UTF-8 | C++ | false | false | 1,627 | cpp | mergesort.cpp | #include <iostream>
#include <random>
#include <vector>
#include <algorithm>
using namespace std;
void merge(vector<int>& v,vector<int>& v1,vector<int>& v2){
unsigned int i,j,k;
i = j = k = 0;
while(i<v1.size() && j<v2.size()){
if(v1[i]<=v2[j]){
v[k++] = v1[i++];
}
else{
v[k++] = v2[j++];
}
}
while(i<v1.size()){
v[k++] = v1[i++];
}
while(j<v2.size()){
v[k++] = v2[j++];
}
}
vector<int> mergesort(vector<int>& v){
if(v.size()<=1){
return v;
}
std::vector<int>::iterator middle = v.begin() + (v.size() / 2);
vector<int> v1(v.begin(), middle);
vector<int> v2(middle, v.end());
v1 = mergesort(v1);
v2 = mergesort(v2);
merge(v,v1,v2);
return v;
}
int main(){
const int min = 0;
const int max = 1000;
const int n = 1000;
std::ios::sync_with_stdio(false);
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased
vector<int> v(1000);
for(int i=0;i<n;i++){
v[i] = uni(rng);
}
cout << "Imprimindo vetor antes da ordenação.\n";
for(int i=0;i<n;i++){
cout << "v[" << i << "] = " << v[i] << "\n";
}
cout << "\nMergesort!\n";
vector<int> vs = mergesort(v);
v.clear();
cout << "Imprimindo vetor depois da ordenação.\n";
for(int i=0;i<n;i++){
cout << "v[" << i << "] = " << vs[i] << "\n";
}
return 0;
}
|
5ee8f67a524536d94ab01b48379a28fb2b028e8f | d94aeeb531ca5866f91ef4ee7bd696e2b09be061 | /contests/hashcode-2019/include/HashCode.hpp | d672c0d785fc8490139535b9cbf13058c6476741 | [] | no_license | alexvelea/competitive | ffbe56d05a41941f39d8fa8e3fc366e97c73c2e0 | f1582ba49174ca956359de6f68e26f6b30306a4d | refs/heads/master | 2022-10-20T17:04:25.483158 | 2020-06-18T23:33:25 | 2020-06-18T23:33:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 976 | hpp | HashCode.hpp | #ifndef HASHCODE_HASHCODE_HPP
#define HASHCODE_HASHCODE_HPP
#include <string>
#include <fstream>
#include <cassert>
#include "Debug.hpp"
#include "Logger.hpp"
#include "Macros.hpp"
#include "Output.hpp"
int test_number;
std::string InputFile() {
return "tests/test-" + std::to_string(test_number) + ".in";
}
std::string AnsFile() {
return "answers/test-" + std::to_string(test_number) + ".ans";
}
std::string BestCostFile() {
return "answers/test-" + std::to_string(test_number) + ".best_cost";
}
std::string LockFile() {
return "locks/test-" + std::to_string(test_number) + ".lock";
}
std::ifstream GetInputStream() {
std::ifstream in(InputFile().c_str());
if (!in) {
Die("Error while reading file %s\n", InputFile().c_str());
}
return in;
}
void InitHashCode(int argc, char** argv) {
if (argc == 1) {
Die("Run with ./exec 1 for test 1");
}
test_number = atoi(argv[1]);
}
#endif // HASHCODE_HASHCODE_HPP
|
f2e682720f09cf125ab4698c85945d45de6ce850 | 9223091bf8ccd7d8fed246ac61c41f07920079e7 | /GAM450BuildSystem/src/Base/modules/functionbinding/Function.h | 85ed5b8a08d12d162aab749e970a9e445dabebd2 | [] | no_license | JiyoonKang/GAM450 | 37ae8a40a08d9c86064550ff2ee04ab164d6b243 | 2532ea01dd8f623d881dbd5eaa657eaa73853c0b | refs/heads/master | 2021-01-12T14:24:29.521646 | 2016-10-04T04:14:44 | 2016-10-04T04:14:44 | 69,933,800 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 23,540 | h | Function.h | /*******************************************************************************
* All content © 2015 DigiPen (USA) Corporation, all rights reserved.
* Reproduction or disclosure of this file or its contents without the prior
* written consent of DigiPen Institute of Technology is prohibited.
*
* File: Function.h
* Author: Judy Cheng, (Credit Zachary Nawar)
* Class: GAM300/GAM302/GAM350/GAM352/GAM375/GAM400
******************************************************************************/
#pragma once
#include "FuncSignature.h"
#include "Base/util/Utilities.h"
#include "Base\modules\introspection\variable\Variable.h"
#include "Base\util\Macros.h"
namespace Base
{
//////////////////////////////////////////////////////////////////////////
// STATIC FUNCTION WITH A RETURN VALUE
class Variable;
template <typename FuncType, FuncType FuncPtr, typename R>
void Call(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 0, "FunctionBinding", "Wrong overload!");
ret->GetValue<R>() = (*FuncPtr)();
}
template <typename FuncType, FuncType FuncPtr, typename R, typename A1>
void Call(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 1, "FunctionBinding", "Wrong overload!");
ret->GetValue<R>() = (*FuncPtr)(args[0].GetValue<A1>());
}
template <typename FuncType, FuncType FuncPtr, typename R, typename A1, typename A2>
void Call(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 2, "FunctionBinding", "Wrong overload!");
ret->GetValue<R>() = (*FuncPtr)(args[0].GetValue<A1>(), args[1].GetValue<A2>());
}
template <typename FuncType, FuncType FuncPtr, typename R, typename A1, typename A2, typename A3>
void Call(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 3, "FunctionBinding", "Wrong overload!");
ret->GetValue<R>() = (*FuncPtr)(args[0].GetValue<A1>(), args[1].GetValue<A2>(),
args[2].GetValue<A3>());
}
//////////////////////////////////////////////////////////////////////////
// CALL STATIC FUNCTION WITHOUT A RETURN VALUE
template <typename FuncType, FuncType FuncPtr>
void CallVoid(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 0, "FunctionBinding", "Wrong overload!");
(*FuncPtr)();
}
template <typename FuncType, FuncType FuncPtr, typename A1>
void CallVoid(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 1, "FunctionBinding", "Wrong overload!");
(*FuncPtr)(args[0].GetValue<A1>());
}
template <typename FuncType, FuncType FuncPtr, typename A1, typename A2>
void CallVoid(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 2, "FunctionBinding", "Wrong overload!");
(*FuncPtr)(args[0].GetValue<A1>(), args[1].GetValue<A2>());
}
template <typename FuncType, FuncType FuncPtr, typename A1, typename A2, typename A3>
void CallVoid(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 3, "FunctionBinding", "Wrong overload!");
(*FuncPtr)(args[0].GetValue<A1>(), args[1].GetValue<A2>(), args[2].GetValue<A3>());
}
template <typename FuncType, FuncType FuncPtr, typename A1, typename A2, typename A3, typename A4>
void CallVoid(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 4, "FunctionBinding", "Wrong overload!");
(*FuncPtr)(args[0].GetValue<A1>(), args[1].GetValue<A2>(), args[2].GetValue<A3>(), args[3].GetValue<A4>());
}
template <typename FuncType, FuncType FuncPtr, typename A1, typename A2, typename A3, typename A4, typename A5>
void CallVoid(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 5, "FunctionBinding", "Wrong overload!");
(*FuncPtr)(args[0].GetValue<A1>(), args[1].GetValue<A2>(), args[2].GetValue<A3>(), args[3].GetValue<A4>(), args[4].GetValue<A5>());
}
//////////////////////////////////////////////////////////////////////////
// FUNCTION WITH A RETURN VALUE
template <typename FuncType, FuncType FuncPtr, typename R, typename C>
void CallMethod(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 0, "FunctionBinding", "Wrong overload!");
ret->GetValue<R>() = (((C*)context)->*FuncPtr)();
}
template <typename FuncType, FuncType FuncPtr, typename R, typename C, typename A1>
void CallMethod(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 1, "FunctionBinding", "Wrong overload!");
ret->GetValue<R>() = (((C*)context)->*FuncPtr)(args[0].GetValue<A1>());
}
//////////////////////////////////////////////////////////////////////////
// FUNCTION WITH NO RETURN VALUE
template <typename FuncType, FuncType FuncPtr, typename C>
void CallMethodVoid(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 0, "FunctionBinding", "Wrong overload!");
(((C*)context)->*FuncPtr)();
}
template <typename FuncType, FuncType FuncPtr, typename C, typename A1>
void CallMethodVoid(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 1, "FunctionBinding", "Wrong overload!");
(((C*)context)->*FuncPtr)(args[0].GetValue<A1>());
}
template <typename FuncType, FuncType FuncPtr, typename C, typename A1, typename A2>
void CallMethodVoid(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 2, "FunctionBinding", "Wrong overload!");
(((C*)context)->*FuncPtr)(args[0].GetValue<A1>(), args[1].GetValue<A2>());
}
template <typename FuncType, FuncType FuncPtr, typename C, typename A1, typename A2, typename A3>
void CallMethodVoid(Variable* ret, void* context, Variable* args, size_t argCount)
{
ErrorIf2(argCount != 3, "FunctionBinding", "Wrong overload!");
(((C*)context)->*FuncPtr)(args[0].GetValue<A1>(), args[1].GetValue<A2>(), args[2].GetValue<A3>());
}
//////////////////////////////////////////////////////////////////////////
class Function
{
public:
Function();
Function(const Function& rhs);
Function& operator=(const Function& rhs);
const FunctionSignature* Signature() const { return &m_sig; }
// Binding
template<typename C>
void Bind(C& c)
{
m_context = &c;
}
template<typename C>
void Bind(C* c)
{
m_context = c;
}
void ExplicitBind(const TypeInfo* type, void* data)
{
m_context = Variable(type, data);
}
void ForceBind(void* data)
{
if (m_sig.GetContext())
m_context = Variable(m_sig.GetContext(), data);
}
operator bool()
{
return m_callHelper != nullptr;
}
void Clear(void);
// Get the context (owner) of the function
inline Variable& Context() { return m_context; }
const Variable& Context() const { return m_context; }
// If it is a class function (has an owner) then it is a method
bool IsMethod() const { return m_sig.GetContext() ? true : false; }
//////////////////////////////////////////////////////////////////////////
// STATIC FUNCTION WITH A RETURN VALUE
template<typename R>
Function(R(*fn)(void), void(*helper)(Variable*, void*, Variable*, size_t));
template<typename R, typename A1>
Function(R(*fn)(A1), void(*helper)(Variable*, void*, Variable*, size_t));
template<typename R, typename A1, typename A2>
Function(R(*fn)(A1, A2), void(*helper)(Variable*, void*, Variable*, size_t));
template<typename R, typename A1, typename A2, typename A3>
Function(R(*fn)(A1, A2, A3), void(*helper)(Variable*, void*, Variable*, size_t));
//////////////////////////////////////////////////////////////////////////
// STATIC FUNCTION WITH NO RETURN VALUE
Function(void(*fn)(void), void(*helper)(Variable*, void*, Variable*, size_t));
template<typename A1>
Function(void(*fn)(A1), void(*helper)(Variable*, void*, Variable*, size_t));
template<typename A1, typename A2>
Function(void(*fn)(A1, A2), void(*helper)(Variable*, void*, Variable*, size_t));
template<typename A1, typename A2, typename A3>
Function(void(*fn)(A1, A2, A3), void(*helper)(Variable*, void*, Variable*, size_t));
template<typename A1, typename A2, typename A3, typename A4>
Function(void(*fn)(A1, A2, A3, A4), void(*helper)(Variable*, void*, Variable*, size_t));
template<typename A1, typename A2, typename A3, typename A4, typename A5>
Function(void(*fn)(A1, A2, A3, A4, A5), void(*helper)(Variable*, void*, Variable*, size_t));
//////////////////////////////////////////////////////////////////////////
// CLASS METHODS WITH A RETURN VALUE, NON-CONST
template<typename R, typename C>
Function(R(C::*fn)(void), void(*helper)(Variable*, void*, Variable*, size_t));
template<typename R, typename C, typename A1>
Function(R(C::*fn)(A1), void(*helper)(Variable*, void*, Variable*, size_t));
//////////////////////////////////////////////////////////////////////////
// CLASS METHODS WITH NO RETURN VALUE, NON-CONST
template<typename C>
Function(void (C::*fn)(void), void(*helper)(Variable*, void*, Variable*, size_t));
template<typename C, typename A1>
Function(void (C::*fn)(A1), void(*helper)(Variable*, void*, Variable*, size_t));
template<typename C, typename A1, typename A2>
Function(void (C::*fn)(A1, A2), void(*helper)(Variable*, void*, Variable*, size_t));
template<typename C, typename A1, typename A2, typename A3>
Function(void (C::*fn)(A1, A2, A3), void(*helper)(Variable*, void*, Variable*, size_t));
//////////////////////////////////////////////////////////////////////////
// CLASS METHOD WITH A RETURN VALUE, CONST
template<typename R, typename C>
Function(R(C::*fn)(void) const, void(*helper)(Variable*, void*, Variable*, size_t));
template<typename R, typename C, typename A1>
Function(R(C::*fn)(A1) const, void(*helper)(Variable*, void*, Variable*, size_t));
//////////////////////////////////////////////////////////////////////////
// CLASS METHOD WITH NO RETURN VALUE, CONST
template<typename C>
Function(void (C::*fn)(void) const, void(*helper)(Variable*, void*, Variable*, size_t));
template<typename C, typename A1>
Function(void (C::*fn)(A1) const, void(*helper)(Variable*, void*, Variable*, size_t));
template<typename C, typename A1, typename A2>
Function(void (C::*fn)(A1, A2) const, void(*helper)(Variable*, void*, Variable*, size_t));
//////////////////////////////////////////////////////////////////////////
// OPERATORS
void operator()(Variable& ret, Variable* args, size_t argCount) const;
void operator()(Variable& ret, Variable* args, size_t argCount);
void operator()(Variable& ret) const;
template <typename A1>
void operator()(Variable& ret, A1 arg1) const;
template <typename A1, typename A2>
void operator()(Variable& ret, A1 arg1, A2 arg2) const;
template <typename A1, typename A2, typename A3>
void operator()(Variable& ret, A1 arg1, A2 arg2, A3 arg3) const;
template <typename A1, typename A2, typename A3, typename A4>
void operator()(Variable& ret, A1 arg1, A2 arg2, A3 arg3, A4 arg4) const;
template <typename A1, typename A2, typename A3, typename A4, typename A5>
void operator()(Variable& ret, A1 arg1, A2 arg2, A3 arg3, A4 arg4, A5 arg5) const;
void operator()(void) const;
template <typename A1>
void operator()(A1 arg1) const;
template <typename A1, typename A2>
void operator()(A1 arg1, A2 arg2) const;
template <typename A1, typename A2, typename A3>
void operator()(A1 arg1, A2 arg2, A3 arg3) const;
template <typename A1, typename A2, typename A3, typename A4>
void operator()(A1 arg1, A2 arg2, A3 arg3, A4 arg4) const;
template <typename A1, typename A2, typename A3, typename A4, typename A5>
void operator()(A1 arg1, A2 arg2, A3 arg3, A4 arg4, A5 arg5) const;
private:
Variable m_context;
FunctionSignature m_sig;
void(*m_callHelper)(Variable*, void*, Variable*, size_t);
};
#define HP void (*helper)(Variable*, void*, Variable*, size_t)
#define PE :m_sig(fn), m_callHelper(helper) {}
//////////////////////////////////////////////////////////////////////////
// STATIC FUNCTIONS WITH A RETURN VALUE
template<typename R>
Function::Function(R(*fn)(void), HP) PE;
template<typename R, typename A1>
Function::Function(R(*fn)(A1), HP) PE;
template<typename R, typename A1, typename A2>
Function::Function(R(*fn)(A1, A2), HP) PE;
template<typename R, typename A1, typename A2, typename A3>
Function::Function(R(*fn)(A1, A2, A3), HP) PE;
//////////////////////////////////////////////////////////////////////////
// STATIC FUNCTIONS WITH NO RETURN VALUE
template<typename A1>
Function::Function(void(*fn)(A1), HP) PE;
template<typename A1, typename A2>
Function::Function(void(*fn)(A1, A2), HP) PE;
template<typename A1, typename A2, typename A3>
Function::Function(void(*fn)(A1, A2, A3), HP) PE;
template<typename A1, typename A2, typename A3, typename A4>
Function::Function(void(*fn)(A1, A2, A3, A4), HP) PE;
template<typename A1, typename A2, typename A3, typename A4, typename A5>
Function::Function(void(*fn)(A1, A2, A3, A4, A5), HP) PE;
//////////////////////////////////////////////////////////////////////////
// CLASS METHODS WITH RETURN VALUE, NON CONST
template<typename R, typename C>
Function::Function(R(C::*fn)(void), HP) PE;
template<typename R, typename C, typename A1>
Function::Function(R(C::*fn)(A1), HP) PE;
//////////////////////////////////////////////////////////////////////////
// CLASS METHODS WITHOUT RETURN VALUE, NON CONST
template<typename C>
Function::Function(void (C::*fn)(void), HP) PE;
template<typename C, typename A1>
Function::Function(void (C::*fn)(A1), HP) PE;
template<typename C, typename A1, typename A2>
Function::Function(void (C::*fn)(A1, A2), HP) PE;
template<typename C, typename A1, typename A2, typename A3>
Function::Function(void (C::*fn)(A1, A2, A3), HP) PE;
//////////////////////////////////////////////////////////////////////////
// CLASS METHODS WITH RETURN VALUE, CONST
template<typename R, typename C>
Function::Function(R(C::*fn)(void) const, HP) PE;
template<typename R, typename C, typename A1>
Function::Function(R(C::*fn)(A1) const, HP) PE;
//////////////////////////////////////////////////////////////////////////
// CLASS METHODS WITHOUT RETURN VALUE, CONST
template<typename C>
Function::Function(void (C::*fn)(void) const, HP) PE;
template<typename C, typename A1>
Function::Function(void (C::*fn)(A1) const, HP) PE;
template<typename C, typename A1, typename A2>
Function::Function(void (C::*fn)(A1, A2) const, HP) PE;
#undef HP
#undef PE
// FUNCTION BUILDERS
//////////////////////////////////////////////////////////////////////////
// STATIC FUNCTION WITH A RETURN VALUE
#define TS(...) template<typename FuncType, FuncType FuncPtr, ##__VA_ARGS__>
#define RV(...) Function(fn, &Call<FuncType, FuncPtr, ##__VA_ARGS__> )
TS(typename R)
Function BuildFunction(R(*fn)(void))
{
return RV(R);
}
TS(typename R, typename A1)
Function BuildFunction(R(*fn)(A1))
{
return RV(R, A1);
}
TS(typename R, typename A1, typename A2)
Function BuildFunction(R(*fn)(A1, A2))
{
return RV(R, A1, A2);
}
template<typename FuncType, FuncType FuncPtr, typename R, typename A1, typename A2, typename A3>
Function BuildFunction(R(*fn)(A1, A2, A3))
{
return Function(fn, &Call<FuncType, FuncPtr, R, A1, A2, A3>);
}
//////////////////////////////////////////////////////////////////////////
// STATIC FUNCTION WITH NO RETURN VALUE
#undef RV
#define RV(...) Function(fn, &CallVoid<FuncType, FuncPtr, ##__VA_ARGS__> )
template<typename FuncType, FuncType FuncPtr>
Function BuildFunction(void(*fn)(void))
{
return Function(fn, &CallVoid<FuncType, FuncPtr>);
}
TS(typename A1)
Function BuildFunction(void(*fn)(A1))
{
return RV(A1);
}
TS(typename A1, typename A2)
Function BuildFunction(void(*fn)(A1, A2))
{
return RV(A1, A2);
}
TS(typename A1, typename A2, typename A3)
Function BuildFunction(void(*fn)(A1, A2, A3))
{
return RV(A1, A2, A3);
}
TS(typename A1, typename A2, typename A3, typename A4)
Function BuildFunction(void(*fn)(A1, A2, A3, A4))
{
return RV(A1, A2, A3, A4);
}
TS(typename A1, typename A2, typename A3, typename A4, typename A5)
Function BuildFunction(void(*fn)(A1, A2, A3, A4, A5))
{
return RV(A1, A2, A3, A4, A5);
}
//////////////////////////////////////////////////////////////////////////
// CLASS METHODS WITH A RETURN VALUE, NON-CONST
#undef RV
#define RV(...) Function(fn, &CallMethod<FuncType, FuncPtr, ##__VA_ARGS__> )
TS(typename R, typename C)
Function BuildFunction(R(C::*fn)(void))
{
return RV(R, C);
}
TS(typename R, typename C, typename A1)
Function BuildFunction(R(C::*fn)(A1))
{
return RV(R, C, A1);
}
//////////////////////////////////////////////////////////////////////////
// CLASS METHODS WITH RETURN VALUE, CONST
TS(typename R, typename C)
Function BuildFunction(R(C::*fn)(void) const)
{
return RV(R, C);
}
TS(typename R, typename C, typename A1)
Function BuildFunction(R(C::*fn)(A1) const)
{
return RV(R, C, A1);
}
//////////////////////////////////////////////////////////////////////////
// CLASS METHODS WITH NO RETURN VALUE, NON-CONST
#undef RV
#define RV(...) Function(fn, &CallMethodVoid<FuncType, FuncPtr, ##__VA_ARGS__> )
TS(typename C)
Function BuildFunction(void (C::*fn)(void))
{
return RV(C);
}
template<typename FuncType, FuncType FuncPtr, typename C, typename A1>
Function BuildFunction(void (C::*fn)(A1))
{
return Function(fn, &CallMethodVoid<FuncType, FuncPtr, C, A1>);
}
template<typename FuncType, FuncType FuncPtr, typename C, typename A1, typename A2>
Function BuildFunction(void (C::*fn)(A1, A2))
{
return Function(fn, &CallMethodVoid<FuncType, FuncPtr, C, A1, A2>);
}
template<typename FuncType, FuncType FuncPtr, typename C, typename A1, typename A2, typename A3>
Function BuildFunction(void (C::*fn)(A1, A2, A3))
{
return Function(fn, &CallMethodVoid<FuncType, FuncPtr, C, A1, A2, A3>);
}
//////////////////////////////////////////////////////////////////////////
// CLASS METHODS WITH NO RETURN VALUE, CONST
#undef RV
#define RV(...) Function(fn, &CallMethodVoid<FuncType, FuncPtr, ##__VA_ARGS__> )
TS(typename C)
Function BuildFunction(void (C::*fn)(void) const)
{
return RV(C);
}
TS(typename C, typename A1)
Function BuildFunction(void (C::*fn)(A1) const)
{
return RV(C, A1);
}
TS(typename C, typename A1, typename A2)
Function BuildFunction(void (C::*fn)(A1, A2) const)
{
return RV(C, A1, A2);
}
#undef TS
#undef RV
// CALLING FUNCTIONS
//////////////////////////////////////////////////////////////////////////
// FUNCTIONS WITH A RETURN VALUE
template<typename A1>
void Function::operator()(Variable& ret, A1 arg1) const
{
ErrorIf2(m_sig.ArgCount() != 1, "Bound Function calling", "Wrong Overload!");
ErrorIf2(m_sig.GetArg(0) != GET_TYPE(A1), "Bound Function calling", "Argument type error!");
Variable argStack[1];
new (argStack)Variable(arg1);
m_callHelper(&ret, m_context.GetData(), argStack, m_sig.ArgCount());
}
template<typename A1, typename A2>
void Function::operator()(Variable& ret, A1 arg1, A2 arg2) const
{
ErrorIf2(m_sig.ArgCount() != 1, "Bound Function calling", "Wrong Overload!");
ErrorIf2(m_sig.GetArg(0) != GET_TYPE(A1), "Bound Function calling", "Argument type error!");
Variable argStack[2];
new (argStack)Variable(arg1);
new (argStack + 1) Variable(arg2);
m_callHelper(&ret, m_context.GetData(), argStack, m_sig.ArgCount());
}
template<typename A1, typename A2, typename A3>
void Function::operator()(Variable& ret, A1 arg1, A2 arg2, A3 arg3) const
{
ErrorIf2(m_sig.ArgCount() != 1, "Bound Function calling", "Wrong Overload!");
ErrorIf2(m_sig.GetArg(0) != GET_TYPE(A1), "Bound Function calling", "Argument type error!");
Variable argStack[3];
new (argStack)Variable(arg1);
new (argStack + 1) Variable(arg2);
new (argStack + 2) Variable(arg3);
m_callHelper(&ret, m_context.GetData(), argStack, m_sig.ArgCount());
}
//////////////////////////////////////////////////////////////////////////
// FUNCTION WITH NO RETURN VALUE
template<typename A1>
void Function::operator()(A1 arg1) const
{
ErrorIf2(m_sig.ArgCount() != 1, "Bound Function calling", "Wrong Overload!");
ErrorIf2(m_sig.GetArg(0) != GET_TYPE(A1), "Bound Function calling", "Argument type error!");
Variable argStack[1];
new (argStack)Variable(arg1);
m_callHelper(NULL, m_context.GetData(), argStack, m_sig.ArgCount());
}
template<typename A1, typename A2>
void Function::operator()(A1 arg1, A2 arg2) const
{
ErrorIf2(m_sig.ArgCount() != 2, "Bound Function calling", "Wrong Overload!");
ErrorIf2(m_sig.GetArg(0) != GET_TYPE(A1), "Bound Function calling", "Argument type error!");
ErrorIf2(m_sig.GetArg(1) != GET_TYPE(A2), "Bound Function calling", "Argument type error!");
Variable argStack[2];
new (argStack)Variable(arg1);
new (argStack + 1) Variable(arg2);
m_callHelper(NULL, m_context.GetData(), argStack, m_sig.ArgCount());
}
template<typename A1, typename A2, typename A3>
void Function::operator()(A1 arg1, A2 arg2, A3 arg3) const
{
ErrorIf2(m_sig.ArgCount() != 3, "Bound Function calling", "Wrong Overload!");
ErrorIf2(m_sig.GetArg(0) != GET_TYPE(A1), "Bound Function calling", "Argument type error!");
Variable argStack[3];
new (argStack)Variable(arg1);
new (argStack + 1) Variable(arg2);
new (argStack + 2) Variable(arg3);
m_callHelper(NULL, m_context.GetData(), argStack, m_sig.ArgCount());
}
template<typename A1, typename A2, typename A3, typename A4>
void Function::operator()(A1 arg1, A2 arg2, A3 arg3, A4 arg4) const
{
ErrorIf2(m_sig.ArgCount() != 4, "Bound Function calling", "Wrong Overload!");
ErrorIf2(m_sig.GetArg(0) != GET_TYPE(A1), "Bound Function calling", "Argument type error!");
Variable argStack[4];
new (argStack)Variable(arg1);
new (argStack + 1) Variable(arg2);
new (argStack + 2) Variable(arg3);
new (argStack + 3) Variable(arg4);
m_callHelper(NULL, m_context.GetData(), argStack, m_sig.ArgCount());
}
template<typename A1, typename A2, typename A3, typename A4, typename A5>
void Function::operator()(A1 arg1, A2 arg2, A3 arg3, A4 arg4, A5 arg5) const
{
ErrorIf2(m_sig.ArgCount() != 5, "Bound Function calling", "Wrong Overload!");
ErrorIf2(m_sig.GetArg(0) != GET_TYPE(A1), "Bound Function calling", "Argument type error!");
Variable argStack[5];
new (argStack)Variable(arg1);
new (argStack + 1) Variable(arg2);
new (argStack + 2) Variable(arg3);
new (argStack + 3) Variable(arg4);
new (argStack + 4) Variable(arg5);
m_callHelper(NULL, m_context.GetData(), argStack, m_sig.ArgCount());
}
} |
254b3300e3e80a0400ffc079fe9197b16b2c9bb3 | 2fdcf56c5e791dd9a4605a41ef7bc601e2fc9135 | /Info/aprindere/main.cpp | 63fc22fdaf9c9cea314acd2be773f22a1bc6ce37 | [] | no_license | DinuCr/CS | 42cc4a7920fb5a2ac5e1179930169e4d8d71592e | 8d381a622e70dd234d7a978501dcb7cf67e83adc | refs/heads/master | 2020-06-02T14:11:49.223214 | 2020-05-24T01:27:46 | 2020-05-24T01:27:46 | 191,174,654 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | cpp | main.cpp | #include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("aprindere.in");
ofstream fout("aprindere.out");
vector <int> v[1010];
int t[1010];
int w[1010];
int n,m,i,j,ans,x,nr,z;
int main()
{
fin>>n>>m;
for(i=0; i<n; ++i)
fin>>w[i];
for(i=1; i<=m; ++i)
{
fin>>x;
fin>>t[x]>>nr;
for(j=1; j<=nr; ++j)
{
fin>>z;
v[x].push_back(z);
}
}
for(i=0; i<n; ++i)
if(!w[i])
{
ans+=t[i];
for(j=0; j<v[i].size(); ++j)
w[v[i][j]]=!w[v[i][j]];
}
fout<<ans;
}
|
ab8e144d16abf1da8c7cbdb06e6c77cbcc46b9c9 | 15acc94f5b592e5a4c5f9b7633e7005d1af2d9cf | /ClassMemberInit2.cpp | d9b4fd926687c5afa48f2d9552de23b64c246569 | [] | no_license | AshwiniChilukuri/learning-cpp | cd7d25fddc5b0a60d2a3b2e23a890a6683199590 | 10cc20c64f76ae9ada37837f4bfd29dd7d618f4c | refs/heads/master | 2021-01-21T10:38:44.517118 | 2017-06-23T04:28:31 | 2017-06-23T04:28:31 | 91,702,101 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 691 | cpp | ClassMemberInit2.cpp | //initializing member variables that are classes
#include <iostream>
using namespace std;
class Date1
{
private:
int m_year;
int m_month;
int m_day;
public:
Date1(int year,int month,int day) : m_year{year},m_month{month},m_day{day}//uniform initialization
{
cout<<"yesterday= "<<m_year<<" "<<m_month<<" "<<m_day;
}
};
class Date2
{
private:
Date1 date;
int m_year;
int m_month;
int m_day;
public:
Date2(int year=2017,int month=06,int day=01) : date{year,month,day-1},m_year{year},m_month{month},m_day{day}
{
cout<<endl<<"today= "<<m_year<<" "<<m_month<<" "<<m_day;
}
};
int main()
{
Date2 date2(2016,06,03);
return 0;
} |
7daf8d35a68aca0863c2da0f76603b41591ab971 | 32ea98f33cb9550ee81f7a498e8b8238a04800c0 | /arguments3.cpp | 1d87b0738991e24a585f9a418f316e887663a000 | [] | no_license | pkroy0185/C-plus-plus-programs2 | 2e6a841f27571934a793fa5b2b49c7ba7c728766 | 70a4f1dc0b65bd1a28ced94a139f18b66c5813cc | refs/heads/main | 2023-04-01T10:20:59.402411 | 2021-03-22T17:24:21 | 2021-03-22T17:24:21 | 350,429,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,048 | cpp | arguments3.cpp | #include<iostream>
#include<cstring>
using namespace std;
class book
{ private:
int pages;
float price;
string name,author;
public:
void GetData(string ,string ,int ,float );
void DisplayData();
};
void book::GetData(string n, string a,int p,float amount)
{
name=n;
author=a;
pages=p;
price=amount;
}
void book::DisplayData()
{
cout<<"\nDisplaying Details of book :\n"<<endl;
cout<<" NAME : "<<name<<endl;
cout<<" AUTHOR : "<<author<<endl;
cout<<" PAGES : "<<pages<<endl;
cout<<" PRICE : "<<price<<endl;
}
int main()
{
book b1;
string n,a;
int p;
float amount;
cout<<"This program takes input about details of a book and displays it.....\n";
cout<<"Enter Details of book :\n"<<endl;
cout<<"NAME : ";
getline(cin,n);
cout<<"AUTHOR : ";
getline(cin,a);
cout<<"PAGES : ";
cin>>p;
cout<<"PRICE : ";
cin>>amount;
b1.GetData(n,a,p,amount);
b1.DisplayData();
return 0;
} |
c5496d6430a1548f3bf2967a2b4f3b282f6ec56c | fe9d477d1215cc83fa7f3d1ae666e37b7904e6fb | /ChessGame/ChessGame/Rook.h | d8a24acddc84cc5fa36f0e4b492ac316e979c5ba | [] | no_license | ambtid/ChessGame | 252a0e4dc4f5ae27b97393f4a5c39d99cdf48b8c | 7fff89617a230814174cd974e0aedfea7b83dfd1 | refs/heads/main | 2023-03-16T09:16:36.062355 | 2021-03-10T21:24:12 | 2021-03-10T21:24:12 | 346,495,425 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | h | Rook.h | #pragma once
#include "BasicTool.h"
class Rook : public BasicTool
{
public:
Rook(int LocX, int LocY, int color) :BasicTool(LocX, LocY, color) {};
bool MoveTo(int LocX, int LocY)
{
if (!(LocX == this->LocX && LocY != this->LocY) || (LocX != this->LocX && LocY == this->LocY)) {
return false;
}
}
void Print();
};
|
0945a36d5921ceb6ff46ffa81bbd8d716bdd4800 | 9f9660f318732124b8a5154e6670e1cfc372acc4 | /Case_save/Case20/Case/case1/100/k | bb6037f2505f58a70fdc466a7cbbcbd5275810e3 | [] | no_license | mamitsu2/aircond5 | 9a6857f4190caec15823cb3f975cdddb7cfec80b | 20a6408fb10c3ba7081923b61e44454a8f09e2be | refs/heads/master | 2020-04-10T22:41:47.782141 | 2019-09-02T03:42:37 | 2019-09-02T03:42:37 | 161,329,638 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,798 | k | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "100";
object k;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -2 0 0 0 0];
internalField nonuniform List<scalar>
459
(
0.00104076
0.00110629
0.00102585
0.00110024
0.00117198
0.00123787
0.00129898
0.00135727
0.00141541
0.00147667
0.00152986
0.00157177
0.00160154
0.00162256
0.00163168
0.000688987
0.000876869
0.000890143
0.000905087
0.000901468
0.000852666
0.000743157
0.000641337
0.000558136
0.00048867
0.000430646
0.000382277
0.000342042
0.0003086
0.00028062
0.000256718
0.000236671
0.000249625
0.000226073
0.0027209
0.00520386
0.00147453
0.00145218
0.00150772
0.00158282
0.00166977
0.00177112
0.00188772
0.00201617
0.00214225
0.00224424
0.00229062
0.00223663
0.00205299
0.00186927
0.00119501
0.00130347
0.00200545
0.00189925
0.00186978
0.00175559
0.00156873
0.00126977
0.00103035
0.000847586
0.000706453
0.000596701
0.00051146
0.000445022
0.000392727
0.000351712
0.000323886
0.000324097
0.000851091
0.000465023
0.00496434
0.0121148
0.00212001
0.00177625
0.0017981
0.00187611
0.00197142
0.00208504
0.00221654
0.00235971
0.00249799
0.00260258
0.00265063
0.00263123
0.00256099
0.00250121
0.00249584
0.00198245
0.00301825
0.00276044
0.00241235
0.00209332
0.00178964
0.001217
0.000847286
0.000643889
0.000521819
0.000441756
0.000385148
0.000342861
0.000310398
0.000286985
0.00028815
0.000342169
0.00150404
0.000710059
0.00788156
0.0229196
0.00329286
0.00204927
0.00202211
0.00211884
0.00223491
0.0023682
0.00251951
0.00268533
0.00284757
0.00296501
0.0030202
0.0030193
0.0029866
0.00296761
0.00304697
0.00332491
0.00417863
0.0033241
0.00292822
0.00249774
0.00212835
0.00181594
0.00123022
0.00112338
0.00109525
0.0010861
0.00107101
0.00103172
0.000955626
0.000869692
0.000777039
0.000628532
0.000593847
0.00268369
0.000858049
0.0113775
0.0369646
0.00573153
0.00231257
0.00216689
0.00228592
0.00244385
0.00263018
0.00284562
0.00308435
0.00331231
0.00346934
0.00354523
0.00355509
0.00351441
0.00344191
0.00336733
0.0032254
0.00295977
0.00279617
0.00271107
0.00254094
0.00226891
0.00207393
0.00196276
0.00193905
0.00195521
0.00197468
0.00196453
0.00189468
0.00174698
0.00152945
0.00130632
0.00107735
0.000902936
0.0018188
0.00135049
0.00116109
0.00157267
0.00201173
0.0154067
0.0506406
0.0111386
0.00296643
0.00235362
0.00243038
0.00261951
0.00286762
0.00317165
0.00353675
0.00384286
0.00401253
0.00407298
0.00405945
0.0039743
0.0037774
0.003415
0.0029369
0.00256309
0.00245664
0.00260175
0.00274254
0.00252678
0.00235396
0.00227649
0.00228654
0.00234564
0.00241509
0.0024584
0.00244067
0.00232312
0.00205402
0.00174856
0.00144942
0.00123154
0.00143851
0.00144261
0.00134895
0.00289158
0.00230701
0.0199743
0.0591057
0.022731
0.00689081
0.00357352
0.0030232
0.00310243
0.00337869
0.00376229
0.00427725
0.00455097
0.00461886
0.00457844
0.0044919
0.00436916
0.00415935
0.00377281
0.00321185
0.00267488
0.00239435
0.00257641
0.00308817
0.00290347
0.00271373
0.00262218
0.00262342
0.00268786
0.00278497
0.00288384
0.00296652
0.00299888
0.00289085
0.00254162
0.00217385
0.00193401
0.00195871
0.00219554
0.00286563
0.00431477
0.00344126
0.0212589
0.0673171
0.0404306
0.0245829
0.0138361
0.00815315
0.0060275
0.00552241
0.00564004
0.00571921
0.0055445
0.00529505
0.00504454
0.00481775
0.00461391
0.00440747
0.00413659
0.00371077
0.00313334
0.00254941
0.00256084
0.00355558
0.00343588
0.00323556
0.00313112
0.00310614
0.00313419
0.00320263
0.00331793
0.00350386
0.0037776
0.00412361
0.00434996
0.00437275
0.00476316
0.00614839
0.00929762
0.0140834
0.0251093
0.00657898
0.0203707
0.0299501
0.0280291
0.0242334
0.0195253
0.0149694
0.0115419
0.00932025
0.00799993
0.00702225
0.00630078
0.00575927
0.00534117
0.00500601
0.00472944
0.00450288
0.00433187
0.00420565
0.00384427
0.00292651
0.00255279
0.00412512
0.00417557
0.00400771
0.00391332
0.00385248
0.00379591
0.00374969
0.0037502
0.00385896
0.004132
0.00458644
0.00520147
0.0059414
0.00690692
0.00801065
0.00889362
0.0091934
0.00918478
0.00547724
0.0133503
0.0185857
0.0172718
0.0146426
0.0121327
0.0101316
0.00864281
0.00752649
0.00669093
0.00605522
0.00555505
0.00515057
0.00482696
0.00459698
0.00451778
0.00466151
0.0045912
0.00344341
0.00260593
0.00471736
0.00517028
0.00514119
0.00517422
0.00517185
0.00509027
0.00493824
0.00474405
0.00458128
0.00456706
0.00481476
0.00529971
0.00596183
0.00670858
0.00733708
0.00751929
0.00698282
0.00566857
0.00377437
0.0117194
0.0189417
0.0173254
0.0145651
0.0123241
0.0104527
0.00892847
0.00770328
0.00669261
0.00583539
0.00512943
0.00457214
0.00416679
0.00393037
0.00390919
0.00413034
0.0042573
0.00353313
0.00261059
0.00511548
0.00594199
0.00609805
0.00632148
0.00642855
0.00640259
0.00627582
0.0060819
0.00587299
0.00571457
0.00576924
0.00607922
0.00661887
0.00728552
0.00799663
0.00846058
0.00849399
0.0060705
0.00392797
0.00915739
0.0100182
0.0108189
0.012088
0.0108546
0.00883044
0.0076496
0.00666109
0.00582583
0.00511842
0.00452786
0.00404585
0.00363435
0.00327544
0.00296185
0.00269317
0.00247526
0.00231816
0.00220611
0.00206682
0.00198921
0.00242028
0.00252986
0.00256945
0.0026123
0.0026345
0.00264211
0.00265124
0.00268114
0.00275726
0.00291675
0.00314493
0.00346048
0.00385993
0.00433623
0.00495911
0.00511542
0.00484667
0.0042012
0.00356642
)
;
boundaryField
{
floor
{
type kqRWallFunction;
value nonuniform List<scalar>
29
(
0.00163168
0.000688987
0.000876869
0.000890143
0.000905087
0.000901468
0.000852666
0.000743157
0.000641337
0.000558136
0.00048867
0.000430646
0.000382277
0.000342042
0.0003086
0.00028062
0.000256718
0.000236671
0.000249625
0.000226073
0.000226073
0.000465023
0.000710059
0.000858049
0.00163168
0.000688987
0.00130347
0.00198245
0.00332491
)
;
}
ceiling
{
type kqRWallFunction;
value nonuniform List<scalar>
43
(
0.00915739
0.0100182
0.0108189
0.012088
0.0108546
0.00883044
0.0076496
0.00666109
0.00582583
0.00511842
0.00452786
0.00404585
0.00363435
0.00327544
0.00296185
0.00269317
0.00247526
0.00231816
0.00220611
0.00206682
0.00198921
0.00242028
0.00252986
0.00256945
0.0026123
0.0026345
0.00264211
0.00265124
0.00268114
0.00275726
0.00291675
0.00314493
0.00346048
0.00385993
0.00433623
0.00495911
0.00511542
0.00484667
0.0042012
0.00356642
0.0203707
0.0299501
0.0117194
)
;
}
sWall
{
type kqRWallFunction;
value uniform 0.00915739;
}
nWall
{
type kqRWallFunction;
value nonuniform List<scalar> 6(0.00201173 0.00230701 0.00344126 0.00377437 0.00392797 0.00356642);
}
sideWalls
{
type empty;
}
glass1
{
type kqRWallFunction;
value nonuniform List<scalar> 9(0.00104076 0.0027209 0.00496434 0.00788156 0.0113775 0.0154067 0.0199743 0.0212589 0.0203707);
}
glass2
{
type kqRWallFunction;
value nonuniform List<scalar> 2(0.00657898 0.00547724);
}
sun
{
type kqRWallFunction;
value nonuniform List<scalar>
14
(
0.00104076
0.00110629
0.00102585
0.00110024
0.00117198
0.00123787
0.00129898
0.00135727
0.00141541
0.00147667
0.00152986
0.00157177
0.00160154
0.00162256
)
;
}
heatsource1
{
type kqRWallFunction;
value nonuniform List<scalar> 3(0.00116109 0.00157267 0.00201173);
}
heatsource2
{
type kqRWallFunction;
value nonuniform List<scalar> 4(0.00186927 0.00119501 0.00119501 0.00249584);
}
Table_master
{
type kqRWallFunction;
value nonuniform List<scalar> 9(0.001217 0.000847286 0.000643889 0.000521819 0.000441756 0.000385148 0.000342861 0.000310398 0.000286985);
}
Table_slave
{
type kqRWallFunction;
value nonuniform List<scalar> 9(0.00123022 0.00112338 0.00109525 0.0010861 0.00107101 0.00103172 0.000955626 0.000869692 0.000777039);
}
inlet
{
type turbulentIntensityKineticEnergyInlet;
intensity 0.05;
value uniform 0.0003375;
}
outlet
{
type zeroGradient;
}
}
// ************************************************************************* //
| |
74b16cac13ed58cfa41594dfc5143c580c306a74 | 4a862886091da0eebb2f063adef91febb1196a35 | /mp4/create2.cc | 69d46cb9a64ec169c40eb15bde4cd35cf7991291 | [] | no_license | edpier/dash | 0977d936d1d7fe13f8f1e95a10ac9b2ccbfcdb66 | c167d1ad1314cc4e6fd441c9857e483a4f6fd543 | refs/heads/master | 2020-04-08T14:42:55.134281 | 2019-11-13T04:02:32 | 2019-11-13T04:02:32 | 159,448,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,817 | cc | create2.cc | #include <fstream>
#include "Box.h"
#include "ChunkOffset.h"
#include "Container.h"
#include "DataEntryURL.h"
#include "DataReference.h"
#include "FileType.h"
#include "HandlerReference.h"
#include "MediaHeader.h"
#include "MovieFragmentHeader.h"
#include "MovieHeader.h"
#include "SampleDescription.h"
#include "SampleSize.h"
#include "SampleToChunk.h"
#include "SegmentType.h"
#include "StreamByteSink.h"
#include "SyncSample.h"
#include "TimeToSample.h"
#include "TrackExtends.h"
#include "TrackFragmentDecodeTime.h"
#include "TrackFragmentHeader.h"
#include "TrackFragmentRun.h"
#include "TrackHeader.h"
#include "VideoMediaHeader.h"
int main(int argc, char** argv) {
StreamByteSink sink(new std::ofstream("out2.mp4"));
Box box;
SegmentType* styp = new SegmentType();
styp->set("dash", 0);
styp->add("iso6");
styp->add("avc1");
styp->add("mp41");
box.setContents(styp);
box.write(sink);
Container* moof = new Container("moof");
MovieFragmentHeader* mfhd = new MovieFragmentHeader();
mfhd->setSequenceNumber(1);
moof->add(mfhd);
Container* traf = new Container("traf");
moof->add(traf);
TrackFragmentHeader* tfhd = new TrackFragmentHeader();
tfhd->setSampleDescriptionIndex(0);
tfhd->setDefaultSampleDuration(0);
traf->add(tfhd);
// tfdt Track Fragment Decode Time
TrackFragmentDecodeTime* tfdt = new TrackFragmentDecodeTime();
tfdt->setBaseMediaDecodeTime(0);
traf->add(tfdt);
TrackFragmentRun* trun = new TrackFragmentRun();
traf->add(trun);
// need to set things
// set nalu size and flags to indicate I frame or not.
// sample size includes the four byte size field
box.setContents(moof);
box.write(sink);
} //end of main
|
e4b738e8479a6bb09eff88e8b0467130bbb6ec80 | f938c747585c90a369bee744cdfa31e4a7771a05 | /Session_1/Session_1.cpp | c18332b90f64c13842efc24abef616a312be403d | [] | no_license | javad123javad/TeamTraining | e3fe6c98e62131a7218e09accfae2845ecd49a1e | f639f6c0eaca539acdf2363065b81a74b1b2e680 | refs/heads/master | 2020-12-15T00:18:51.628199 | 2020-01-25T02:44:17 | 2020-01-25T02:44:17 | 234,925,522 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,266 | cpp | Session_1.cpp | // Session_1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include "Personnel.h"
#include "Staff.h"
int main()
{
Staff S1("Javad", "Rahimi"), S2("Hamed","Rahimi");
std::cout << "S1: " << S1.returnInfo() << std::endl;
std::cout << "S2: " << S2.returnInfo() << std::endl;
//S2 = S1;
std::swap(S2, S1);
std::cout << "S2: " << S2.returnInfo() << std::endl;
Staff S3(std::move(S2));
std::cout << "S2: " << S2.returnInfo() << std::endl;
/*****************/
Personnel P1;
P1.addStaff(&S1);
Personnel P2(std::move(P1));
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
|
9eb55a84524ec8e25d3586cf4377921c85619c10 | 512ed181d5ed9d71c2ea999d97859f8966207243 | /platform/android/src/style/layers/fill_extrusion_layer.hpp | 11a74bc8ef931a7263f1e3dc37446bb2510c9050 | [
"NCSA",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"Libpng",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"JSON",
"IJG",
"Zlib",
"ISC",
"BSL-1.0",
"Apache-2.0",
"OpenSSL",
"BSD-2-Clause",
"MIT",
... | permissive | tonylikestoburns/mapbox-gl-native | 3e05d7823646a9768631c9188cabea0f5c282a92 | 0eaac988f1b1bf0463bb512f10d346a0a1b0e266 | refs/heads/master | 2023-08-09T03:56:13.183033 | 2020-02-18T08:08:04 | 2020-02-18T08:08:04 | 131,966,036 | 1 | 0 | NOASSERTION | 2023-09-09T04:15:28 | 2018-05-03T08:37:38 | C++ | UTF-8 | C++ | false | false | 2,479 | hpp | fill_extrusion_layer.hpp | // This file is generated. Edit android/platform/scripts/generate-style-code.js, then run `make android-style-code`.
#pragma once
#include "layer.hpp"
#include "../transition_options.hpp"
#include <mbgl/style/layers/fill_extrusion_layer.hpp>
#include <jni/jni.hpp>
namespace mbgl {
namespace android {
class FillExtrusionLayer : public Layer {
public:
static constexpr auto Name() { return "com/mapbox/mapboxsdk/style/layers/FillExtrusionLayer"; };
static jni::Class<FillExtrusionLayer> javaClass;
static void registerNative(jni::JNIEnv&);
FillExtrusionLayer(jni::JNIEnv&, jni::String, jni::String);
FillExtrusionLayer(mbgl::Map&, mbgl::style::FillExtrusionLayer&);
FillExtrusionLayer(mbgl::Map&, std::unique_ptr<mbgl::style::FillExtrusionLayer>);
~FillExtrusionLayer();
// Properties
jni::Object<jni::ObjectTag> getFillExtrusionOpacity(jni::JNIEnv&);
void setFillExtrusionOpacityTransition(jni::JNIEnv&, jlong duration, jlong delay);
jni::Object<TransitionOptions> getFillExtrusionOpacityTransition(jni::JNIEnv&);
jni::Object<jni::ObjectTag> getFillExtrusionColor(jni::JNIEnv&);
void setFillExtrusionColorTransition(jni::JNIEnv&, jlong duration, jlong delay);
jni::Object<TransitionOptions> getFillExtrusionColorTransition(jni::JNIEnv&);
jni::Object<jni::ObjectTag> getFillExtrusionTranslate(jni::JNIEnv&);
void setFillExtrusionTranslateTransition(jni::JNIEnv&, jlong duration, jlong delay);
jni::Object<TransitionOptions> getFillExtrusionTranslateTransition(jni::JNIEnv&);
jni::Object<jni::ObjectTag> getFillExtrusionTranslateAnchor(jni::JNIEnv&);
jni::Object<jni::ObjectTag> getFillExtrusionPattern(jni::JNIEnv&);
void setFillExtrusionPatternTransition(jni::JNIEnv&, jlong duration, jlong delay);
jni::Object<TransitionOptions> getFillExtrusionPatternTransition(jni::JNIEnv&);
jni::Object<jni::ObjectTag> getFillExtrusionHeight(jni::JNIEnv&);
void setFillExtrusionHeightTransition(jni::JNIEnv&, jlong duration, jlong delay);
jni::Object<TransitionOptions> getFillExtrusionHeightTransition(jni::JNIEnv&);
jni::Object<jni::ObjectTag> getFillExtrusionBase(jni::JNIEnv&);
void setFillExtrusionBaseTransition(jni::JNIEnv&, jlong duration, jlong delay);
jni::Object<TransitionOptions> getFillExtrusionBaseTransition(jni::JNIEnv&);
jni::jobject* createJavaPeer(jni::JNIEnv&);
}; // class FillExtrusionLayer
} // namespace android
} // namespace mbgl
|
2f128dab3ce4d7980a753059b671976a6617b238 | b101a4659c4c62bb84735acb1881c19efddf6765 | /cpp_04/ex03/Cure.hpp | 7564bce3cb27da2aa4a5ceddb3bc5a3783c788f0 | [] | no_license | wphylici/cpp | f108c9550b2421d52d18ec696099b7d0be19fc14 | ad61bb346c6e7fa6031b35e83dfc1d1b3590a791 | refs/heads/master | 2023-04-01T06:13:53.740934 | 2021-04-14T14:56:48 | 2021-04-14T14:56:48 | 347,576,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,203 | hpp | Cure.hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Cure.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: wphylici <wphylici@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/27 07:34:27 by wphylici #+# #+# */
/* Updated: 2021/03/27 07:35:25 by wphylici ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CURE_HPP
# define CURE_HPP
#include "AMateria.hpp"
class Cure : public AMateria
{
public:
Cure();
Cure(std::string const &type);
Cure(Cure const &);
virtual ~Cure();
Cure &operator = (Cure const &cure);
virtual AMateria *clone() const;
virtual void use(ICharacter &target);
};
#endif
|
91c9423d704af357716fec23a19480b5281d4c40 | a44bbbbf6bd769403d624cbe2e244c33dbe2eddb | /User3.0/User/RightPaneView.h | 7dab83148c080722b129cf7ab38f35c46414d2cc | [] | no_license | shangdufeng/HealthCloud | 97dd4f333dcbb5af12c74b6be55d38ca36bc49c1 | a2a224d1fd4bad9e2835e3121eea5735d1bb9138 | refs/heads/master | 2020-06-04T12:50:05.212380 | 2015-07-10T01:37:39 | 2015-07-10T01:37:39 | 38,854,116 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,143 | h | RightPaneView.h | #pragma once
#include "RightLoginView.h"
#include "RightRegView.h"
#include "rightmessagereadview.h"
#include "rightcontactview.h"
#include "rightinputview.h"
#include "rightlatestinfoview.h"
#include "righthisqueview.h"
#include "righthealrepview.h"
#include "rightexcepinfoview.h"
/*#include "righthealtoolview.h"*/
#include "CalorieToolView.h"
#include "rightaddinfoview.h"
#include "rightchangeinfoview.h"
#include "rightmydocview.h"
#include "rightdoclistview.h"
#include "rightinvidocview.h"
#include "rightresetpassview.h"
#include "rightchgperinfoview.h"
#include "rightplatuseview.h"
#include "rightReg2View.h"
#include "RightWelcomeView.h"
// CRightPaneView 窗体视图
class CRightPaneView : public CFormView
{
DECLARE_DYNCREATE(CRightPaneView)
protected:
CRightPaneView(); // 动态创建所使用的受保护的构造函数
virtual ~CRightPaneView();
public:
CRightLoginView m_rightloginview;
CRightRegView m_rightregview;
public:
enum { IDD = IDD_RIGHT_PANE };
#ifdef _DEBUG
virtual void AssertValid() const;
#ifndef _WIN32_WCE
virtual void Dump(CDumpContext& dc) const;
#endif
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
virtual void OnInitialUpdate();
void ShowView(CDialog* pHideView, CDialog* pShowView);
CRightMessagereadView m_rightmessagereadview;
CRightContactView m_rightcontactview;
CRightInputView m_rightinputview;
CRightLatestinfoView m_rightlatestinfoview;
CRightHisqueView m_righthisqueview;
CRightHealrepView m_righthealrepview;
CRightExcepinfoView m_rightexcepinfoview;
CCalorieToolView m_CalorieToolView;
/* CRightHealtoolView m_righthealtoolview;*/
CRightAddinfoView m_rightaddinfoview;
CRightChangeinfoView m_rightchangeinfoview;
CRightMydocView m_rightmydocview;
CRightDoclistView m_rightdoclistview;
CRightInvidocView m_rightinvidocview;
CRightResetpassView m_rightresetpassview;
CRightChgperinfoView m_rightchgperinfoview;
CRightPlatuseView m_rightplatuseview;
CRightReg2View m_rightreg2view;
CRightWelcomeView m_rightwelcomeview;
virtual BOOL PreTranslateMessage(MSG* pMsg);
};
|
c77b97c5ab1ca8dca9f954f32813db64310dd739 | 1f29b384110b0c8930376c201593d8e6a256ecf7 | /Classes/layer/LoadingLayer.h | a90fdfa2f98ba00c8bce541240c4920a7d007d64 | [] | no_license | speak2u/runnning-panda | 8bf5f113c7b84f782a58ad001c6b51253e435d9b | 39f40e888170a983cbc1bbc14d7a17d6d864d63c | refs/heads/master | 2021-01-14T11:24:44.532568 | 2014-08-02T07:12:25 | 2014-08-02T07:12:25 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 587 | h | LoadingLayer.h | #ifndef _LOADING_LAYER_H_
#define _LOADING_LAYER_H_
#include "cocos2d.h"
class LoadingLayer : public cocos2d::Layer
{
public:
LoadingLayer(void);
~LoadingLayer(void);
virtual bool init();
CREATE_FUNC(LoadingLayer);
public:
static cocos2d::Scene* createScene();
private:
void assetsLoaded(float dt);
void armatureLoaded(float dt);
void textureLoaded(cocos2d::Texture2D* ttu2D);
private:
int totalResCount;
int curResLoaded;
float percentage;
char chPer[116];
cocos2d::LabelTTF * ttfPer;
//½ø¶ÈÌõ
cocos2d::ProgressTimer *mProgress;
};
#endif // !_LOADING_LAYER_H_
|
f19c4f26548729f8584adc69bc25dd2ad5822ae3 | 480e33f95eec2e471c563d4c0661784c92396368 | /CondCore/DBOutputService/test/stubs/IOVPayloadEndOfJob.h | e62f09cdea5f3b0c3a327865d6b574bbe3ea8e7b | [
"Apache-2.0"
] | permissive | cms-nanoAOD/cmssw | 4d836e5b76ae5075c232de5e062d286e2026e8bd | 4eccb8a758b605875003124dd55ea58552b86af1 | refs/heads/master-cmsswmaster | 2021-01-23T21:19:52.295420 | 2020-08-27T08:01:20 | 2020-08-27T08:01:20 | 102,867,729 | 7 | 14 | Apache-2.0 | 2022-05-23T07:58:09 | 2017-09-08T14:03:57 | C++ | UTF-8 | C++ | false | false | 632 | h | IOVPayloadEndOfJob.h | #ifndef CondCore_DBOutputService_test_IOVPayloadEndOfJob_h
#define CondCore_DBOutputService_test_IOVPayloadEndOfJob_h
#include "FWCore/Framework/interface/EDAnalyzer.h"
#include <string>
namespace edm {
class ParameterSet;
class Event;
class EventSetup;
} // namespace edm
//
// class decleration
//
class Pedestals;
class IOVPayloadEndOfJob : public edm::EDAnalyzer {
public:
explicit IOVPayloadEndOfJob(const edm::ParameterSet& iConfig);
virtual ~IOVPayloadEndOfJob();
virtual void analyze(const edm::Event& evt, const edm::EventSetup& evtSetup);
virtual void endJob();
private:
std::string m_record;
};
#endif
|
c98f79b43d6406a148237213ad25d9559a81910a | 1b6b5f630696eb5ca848399a7cf8910ebc5d3fc2 | /skinnyleetcode/arrayRankTransform.cpp | 0758eb24922b4f6af60fa8668765953058cf6c59 | [] | no_license | hmofrad/CodingPractice | bde55f7616d44f20aaaf544cf3c88b37f05651a0 | 7f642e4b9a2e3db0fe54ba66e8d3bf98b8407dce | refs/heads/master | 2022-12-10T03:49:06.226039 | 2020-09-02T02:48:29 | 2020-09-02T02:48:29 | 63,923,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 602 | cpp | arrayRankTransform.cpp | /*
* https://leetcode.com/problems/rank-transform-of-an-array/submissions/
* (c) Mohammad Hasanzadeh Mofrad, 2020
* (e) m.hasanzadeh.mofrad@gmail.com
*/
class Solution {
public:
vector<int> arrayRankTransform(vector<int>& arr) {
std::vector<int> arr1 = arr;
std::sort(arr1.begin(), arr1.end());
std::unordered_map<int, int> sorted;
int i = 1;
for(int a: arr1) {
if(not sorted.count(a)) {sorted[a]=i; i++;}
}
for(int& a: arr) {
a=sorted[a];
}
return arr;
}
}; |
4f84d66dae37b7e622ac697681ccdf8a924338f7 | 97790b82f556c639173a54ad6aab498f5db62017 | /small_shit_h.h | 4b96013049c701a69082e7c9a8f71200a91242bb | [] | no_license | Fedya1998/libs | 5274a2cdfa42de403e7fdc243e9ac99369c08ade | 55ee038eb09fe2a9a45bc5d2616a6fd2b55f2f53 | refs/heads/master | 2021-01-01T17:30:46.160651 | 2017-08-30T10:40:52 | 2017-08-30T10:40:52 | 98,092,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | h | small_shit_h.h | //
// Created by fedya on 29.06.17.
//
#ifndef GAME_SMALL_SHIT_H_H
#define GAME_SMALL_SHIT_H_H
#endif //GAME_SMALL_SHIT_H_H
enum errors{
ERR_BAD_INDEX,
ERROR_EMPTY_LINE = 1,
ERROR_WRONG_PARENTHESES,
ERROR_UNDEFINED_FUNCTION,
ERROR_BAD_TREE,
ERROR_WRONG_TYPE,
ERROR_UNDEFINED_VALUE,
ERROR_UNDEFINED_TYPE,
ERROR_UNDEFINED_OPERATION,
ERROR_LOST_LABEL
};
const int BAD_LABEL = 0;
class Label;
//template <typename T> int Compare_Label(List_Elem <T> * elem, Label * label);
template <typename T> class Buf; |
1bf641243abd3601238253d6f26e1eb9c3cd7dec | 66bfa5827cee4f00e3b17fb1b595382893fe8542 | /venus.cs.qc.cuny.edu/~alayev/cs211/code/lecture4/Date.cpp | 5e4f03e3a8067bc22ae12e6da84163d14786bf76 | [] | no_license | brushstrokes/cs211 | 4059f3bd743cf0368fa590fd0852c43201e81c75 | 560d489b994d8403ffa42dda1609580072fa8fae | refs/heads/master | 2020-06-29T02:30:42.932237 | 2019-08-04T01:31:05 | 2019-08-04T01:31:05 | 200,412,361 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,453 | cpp | Date.cpp | // Date.cpp
#include "Date.h"
// Initializes a date to the default value of January 1, 1970
Date::Date() {
month = 1;;
day = 1;
year = 1970;
}
// Initializes the class taking in a day number (over the whole year)
// and a year number.
Date::Date(int dayNum, int y) {
if (dayNum < 1)
dayNum = 1;
if ((y % 4 == 0) && (dayNum > 366))
dayNum = 366;
else if (dayNum > 365)
dayNum = 365;
year = y;
if (dayNum <= 31) {
month = 1;
day = dayNum;
} else {
dayNum -= 31;
if ((year % 4 == 0) && (dayNum <= 29)) {
day = dayNum;
month = 2;
return;
}
else if (year % 4 == 0)
dayNum -= 29;
else if (dayNum <= 28) {
day = dayNum;
month = 2;
return;
}
else
dayNum -= 28;
if (dayNum <= 31) {
month = 3;
day = dayNum;
}
else {
dayNum -= 31;
if (dayNum <= 30) {
month = 4;
day = dayNum;
}
else {
dayNum -= 30;
if (dayNum <= 31) {
month = 5;
day = dayNum;
}
else {
dayNum -= 31;
if (dayNum <= 30) {
month = 6;
day = dayNum;
}
else {
dayNum -= 30;
if (dayNum <= 31) {
month = 7;
day = dayNum;
}
else {
dayNum -= 31;
if (dayNum <= 31) {
month = 8;
day = dayNum;
}
else {
dayNum -= 31;
if (dayNum <= 30) {
month = 9;
day = dayNum;
}
else {
dayNum -= 30;
if (dayNum <= 31) {
month = 10;
day = dayNum;
}
else {
dayNum -= 31;
if (dayNum <= 30) {
month = 11;
day = dayNum;
}
else {
month = 12;
day = dayNum - 30;
}
}
}
}
}
}
}
}
}
}
}
// Initializes a date to the values in the parameters. If the
// date is not legal, sets the date to 1 of the illegal value.
// (Illegal years are set to 2000)
Date::Date(int m, int d, int y) {
month = m;
day = d;
year = y;
fixDate();
}
// Returns the month stored by the class
string Date::getMonth() const {
if (month == 1)
return "January";
if (month == 2)
return "February";
if (month == 3)
return "March";
if (month == 4)
return "April";
if (month == 5)
return "May";
if (month == 6)
return "June";
if (month == 7)
return "July";
if (month == 8)
return "August";
if (month == 9)
return "September";
if (month == 10)
return "October";
if (month == 11)
return "November";
return "December";
}
// Returns the day stored by the class
int Date::getDay() const { return day;}
// Retruns the year stored by the class
int Date::getYear() const { return year;}
// Returns a date that is the number of
// days forward from the parameter. Ie. if the date stored
// in the class were January 1, 2003, and 5 were passed to this
// function, it would return January 6, 2003. Negative numbers
// are also allowed as parameters
Date Date::addDays(int n) const {
int dayNum = dayOfYear();
dayNum += n;
int tempYear = year;
while (dayNum < 1) {
tempYear--;
if (tempYear % 4 == 0)
dayNum += 366;
else
dayNum += 365;
}
while (((tempYear % 4 == 0) && (dayNum > 366)) ||
((tempYear % 4 != 0) && (dayNum > 365))) {
if (tempYear % 4 == 0)
dayNum -= 366;
else
dayNum -= 365;
tempYear++;
}
return Date(dayNum, tempYear);
}
// Returns which day of the year this class is
int Date::dayOfYear() const {
if (month == 1)
return day;
int temp = day + 31;
if (month == 2)
return temp;
temp += 28;
if (year % 4 == 0)
temp++;
if (month == 3)
return temp;
temp += 31;
if (month == 4)
return temp;
temp += 30;
if (month == 5)
return temp;
temp += 31;
if (month == 6)
return temp;
temp += 30;
if (month == 7)
return temp;
temp += 31;
if (month == 8)
return temp;
temp += 31;
if (month == 9)
return temp;
temp += 30;
if (month == 10)
return temp;
temp += 31;
if (month == 11)
return temp;
temp += 30;
return temp;
}
// Fixes the date so that it is in legal range
void Date::fixDate() {
if (month < 1)
month = 1;
if (month > 12)
month = 12;
if (day < 1)
day = 1;
if (day > 31)
day = 31;
if (((month == 4) || (month == 6) || (month == 9) || (month == 11)) &&
(day > 30))
day = 30;
if ((month == 2) && (year % 4 != 0) && (day > 28))
day = 28;
if ((month == 2) && (year % 4 == 0) && (day > 29))
day = 29;
}
string Date::toString(int i) {
int k = i, numDigits = 0;
if (k < 0)
k = k*-1;
while (k > 0) {
numDigits++;
k = k / 10;
}
if (numDigits == 0)
numDigits++;
char d[numDigits+1];
d[numDigits] = '\0';
for (int j = numDigits-1, k = 1; j >= 0; j--, k *= 10)
d[j] = (char) ((i / k) % 10 + '0');
return string(d);
}
// Returns the Date passed to it as a string
string Date::toString(const Date d) {
string temp = d.getMonth();
temp = temp + " " + toString(d.getDay()) + ", " + toString(d.getYear());
return temp;
}
|
ab4cafcaa4c27fc90cbffb819abb828bbbd03e80 | ec48cd589ba42cb4a33730882e7713719de1864f | /temperature_and_humidity_sesor/temperature_and_humidity_sesor.ino | b7ddb01f9eb8e78135970c1ce39f626379aa4f64 | [] | no_license | abhirup-kabiraj/arduino-projects | 4321ac20397309ef8a6b10a5740c9906f264489e | f968b493a3c1c8fd428352bc86168ead271f96f5 | refs/heads/main | 2023-07-01T11:39:09.205089 | 2021-08-06T09:05:46 | 2021-08-06T09:05:46 | 393,320,177 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 621 | ino | temperature_and_humidity_sesor.ino | #include "DHT.h"
#define TYPE DHT11
int tempC;
int sensepin=2;
int tempF;
int humid;
DHT HT(sensepin,TYPE);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
HT.begin();
delay(500);
}
void loop() {
// put your main code here, to run repeatedly:
tempC=HT.readTemperature();
tempF=HT.readTemperature(true);
humid=HT.readHumidity();
Serial.print("TEMPERATURE=");
Serial.print(tempC);
Serial.print(" C ");
Serial.print(" or ");
Serial.print(tempF);
Serial.println(" F ");
Serial.print("Humidity= ");
Serial.println(humid);
Serial.print("\n\n");
delay(1000);
}
|
6623f68b3791f2405b93c211d0a9548a5973e6da | fec261e7717769078dd0044b3ac19e509ff65afa | /cpp/linked-list/list-cycle.cpp | 3da7c14d7ca92b007234f78eb634ebfa56649c45 | [] | no_license | ne7ermore/playground | af94854c6da01b43b1e10ea891129a749ea9d807 | 072406e562e0d33c650ba01bf9ebfbe593f55d5c | refs/heads/master | 2021-06-02T13:19:34.110406 | 2020-05-28T10:49:12 | 2020-05-28T10:49:12 | 108,945,081 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,267 | cpp | list-cycle.cpp | /**
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to.
If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
* **/
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(0) {}
};
class Solution
{
public:
bool hasCycle(ListNode *head)
{
if (!head || !head->next)
return false;
ListNode *snode = head;
int step = 1;
while (head)
{
step++;
head = head->next;
if (step % 2)
snode = snode->next;
if (snode == head)
return true;
}
return false;
}
}; |
37fdb93debe9d138f4428991a76b2c2e901870e3 | d7d368a67334cad351938edb9ba6871887ed086d | /src/apmmon/linux/InputDevice.cpp | 7f15e148969e02243e10189c67adb7f12d2421dc | [
"MIT"
] | permissive | Mokon/mnet | 7c2e3502d3a37571657025c5960479381f1fc73c | a127d810dc4aba76bf8136ffecc850c61eec1617 | refs/heads/master | 2020-03-29T21:10:25.167463 | 2019-02-04T02:25:48 | 2019-02-04T02:25:48 | 150,353,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,981 | cpp | InputDevice.cpp | /*
* Copyright (c) 2018 David 'Mokon' Bond <mokon@mokon.net>
* Author: David 'Mokon' Bond <mokon@mokon.net>
*
* 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 <fcntl.h>
#include <linux/InputDevice.hpp>
#include <unistd.h>
namespace apm {
InputDevice::InputDevice(const fs::path& _file)
: InputDevice(fs::directory_entry(_file))
{
}
InputDevice::InputDevice(const fs::directory_entry& _file)
: file(_file)
, fd(open(file.path().c_str(), O_RDONLY))
{
if (isValid())
{
setSupportedEvents();
if (supportsKeyboardEvents())
{
setSupportedKeys();
}
}
}
InputDevice::~InputDevice()
{
close();
}
bool
InputDevice::isValid() const
{
return isOpen() and file.is_character_file();
}
bool
InputDevice::isKeyboard() const
{
return supportsKeys(KEY_A | KEY_B | KEY_C | KEY_Z);
}
struct epoll_event
InputDevice::getEpollEvent()
{
struct epoll_event event;
event.events = EPOLLIN;
event.data.fd = fd;
fd = -1;
return event;
}
bool
InputDevice::isOpen() const
{
return fd != -1;
}
void
InputDevice::close()
{
if (isOpen())
{
if (::close(fd) < 0)
{
std::perror("input device close failed");
}
fd = -1;
}
}
void
InputDevice::setSupportedEvents()
{
if (ioctl(fd, EVIOCGBIT(0, sizeof(supportedEvents)), &supportedEvents) < 0)
{
if (errno != ENOTTY)
{
throw std::system_error(errno, std::generic_category());
}
}
}
bool
InputDevice::supportsKeyboardEvents() const
{
return (EV_KEY & supportedEvents) == EV_KEY;
}
void
InputDevice::setSupportedKeys()
{
if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(supportedKeys)), &supportedKeys) < 0)
{
throw std::system_error(errno, std::generic_category());
}
}
bool
InputDevice::supportsKeys(int32_t keys) const
{
return (keys & supportedKeys) == keys;
}
} // namespace apm
|
245c8f2864187221641aeffce0b488536da131d5 | ac9e998c4fc5ea2fc68b9f5265975d9af415a11b | /tflm-cmsisnn-mbed-image-recognition/image_recognition/stm32f746_discovery/image_provider.cc | 858fa87d660f78a92fd98fec93920f5e6b1db5dd | [
"Apache-2.0"
] | permissive | ARM-software/ML-examples | 384bd46a85eb6b12f3e444506114369153927da3 | 35d42e4122405a494bea2c0b549e782d201ee56a | refs/heads/main | 2023-08-25T07:20:27.632090 | 2023-08-09T13:16:25 | 2023-08-09T13:16:25 | 116,682,868 | 408 | 201 | Apache-2.0 | 2023-08-09T13:15:16 | 2018-01-08T13:53:15 | C++ | UTF-8 | C++ | false | false | 1,381 | cc | image_provider.cc | /*
* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
* Copyright (c) 2019-2021 Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*
* 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
*
* 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 "image_recognition/image_provider.h"
#include "BSP/Drivers/BSP/STM32746G-Discovery/stm32746g_discovery_camera.h"
TfLiteStatus InitCamera(tflite::ErrorReporter* error_reporter) {
if (BSP_CAMERA_Init(RESOLUTION_R160x120) != CAMERA_OK) {
TF_LITE_REPORT_ERROR(error_reporter, "Failed to init camera.\n");
return kTfLiteError;
}
return kTfLiteOk;
}
TfLiteStatus GetImage(tflite::ErrorReporter* error_reporter, int frame_width,
int frame_height, int channels, uint8_t* frame) {
(void)error_reporter;
(void)frame_width;
(void)frame_height;
(void)channels;
BSP_CAMERA_ContinuousStart(frame);
return kTfLiteOk;
}
|
ffb3324a4d0d4e4bf285a6be11c78947afa9f6f5 | 19457e122e66833518939ee477f5d46047b2021e | /deep_learning/src/Drones_Test_Multiboot/src/main_controller.cpp | ddf42b811f90d37dde11bab09d4a5818179329ed | [] | no_license | SISONGXU/ProjetS8_TargetDrone | b6d17b17e2deb99e6fe3cbb2befbf922e0c31663 | 43fd52f88869ec137a17266bd4858dbe74783811 | refs/heads/master | 2021-04-15T13:19:33.697577 | 2018-04-26T13:59:45 | 2018-04-26T13:59:45 | 126,826,676 | 0 | 0 | null | 2018-04-17T11:37:01 | 2018-03-26T12:39:18 | C++ | UTF-8 | C++ | false | false | 4,213 | cpp | main_controller.cpp | #include <drone_test/keyboard_controller.h>
#include <iostream>
#include <ncurses.h>
#include <unistd.h>
//position couleur
int couleur_x;
int couleur_y;
//distance entre couleur et drone
int distance_max=100;
int distance_x=400;
int distance_y=200;
//taille image
int taille_image=856;
//position centrale de l'ecran
//int x_min = taille_image*(5/11);
//int x_max = taille_image*(6/11);
int x_min = 375;
int x_max = 425;
//int pos y
int y_min = 150;
int y_max = 250;
//tracking actif a 1
int track=0;
//vitesse de deplacement
float vitesse_x = 0.0;
float vitesse_y = 0.0;
float taille_h;
float yaw;
//recuperation de la position couleur
void posCallback(const geometry_msgs::Point myPos)
{
couleur_x=myPos.x;
couleur_y = myPos.y;
taille_h = myPos.z;
}
int keypressed(void)
{
int ch = getch();
if (ch != ERR) {
ungetch(ch);
return 1;
} else {
return 0;
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "autocontroller");
ros::NodeHandle n;
ros::Rate loop_rate(30);
ros::Subscriber sub = n.subscribe("/cible", 1000, posCallback);
DroneController bebop;
float avancement = 0.00, translation = 0.00, hauteur = 0.00, rotation = 0.00;
initscr();
cbreak();
noecho();
nodelay(stdscr, TRUE);
while(ros::ok())
{
if (keypressed()) // a key is pressed
{
switch(getch()) // ASCII values
{
case 116: // t: decoller
bebop.sendTakeoff();
track=0;
break;
case 110: // n: atterrir
bebop.sendLand();
track=0;
break;
case 105: // i: avancer
avancement = 0.1;
break;
case 107: // k: reculer
avancement = -0.1;
break;
case 97: // a: rotation gauche
rotation = 0.1;
break;
case 100: // d:rotation doite
rotation = -0.1;
break;
case 106: // j:translation gauche
translation = 0.1;
break;
case 108: // l:translation droite
translation = -0.1;
break;
case 119: // w:monter en altitude
hauteur = 0.1;
break;
case 115: // s:descendre en altitude
hauteur = -0.5;
break;
case 118: // v: track or stop tracking
if(track!=1){
track=1;
}
else if(track!=0){
track=0;
}
break;
default:
break;
}
flushinp(); // on vide le buffer de getch
}
else // a key is not pressed
{
if(track!=0)
{
printf("couleur X %d\n\r",couleur_x);
printf("couleur y %d\n\r" ,couleur_y);
printf("taille %f\n\r",taille_h);
//calcul vitesse de deplacement en hauteur
if(couleur_y<y_min){
vitesse_y = 0.1;
printf("monter \n\r");
}else if(couleur_y>y_max){
vitesse_y = -0.1;
printf("descendre \n\r");
}else{
vitesse_y = 0;
printf("altitude OK \n\r");
}
printf("changement d'altitude %f\n\r",vitesse_y);
hauteur = vitesse_y;
//calcul vitesse de deplacement en rotation
if(couleur_x<x_min){
vitesse_x = 0.1*((x_min-couleur_x)/50);
printf("tourner gauche \n\r");
}else if(x_max<couleur_x){
vitesse_x = -0.1*((couleur_x-x_max)/50);
printf("tourner droite \n\r");
}else{
vitesse_x = 0;
printf("ne pas tourner \n\r");
}
printf("vitesse de rotation %f\n\r",vitesse_x);
rotation = vitesse_x;
//calcul vitesse de deplacement avant/arrière
if((taille_h>2500)&&(taille_h<10000)){
printf("rester\n\r");
avancement=0;
}
if(taille_h<2500){
printf("avancer\n\r");
avancement=0.1;
}
if(taille_h>10000){
printf("reculer\n\r");
avancement=-0.1;
}
if(taille_h<100){
// a key is pressed avancement=0;
printf("Cilbe perdu\n\r");
}
printf("vitesse avancement %f\n\r",avancement);
}
printf("\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r");
}
bebop.setCommand(avancement, translation, hauteur, rotation);
avancement = 0.00, translation = 0.00, hauteur = 0.00, rotation = 0.00;
ros::spinOnce();
loop_rate.sleep();
}
endwin();
}
|
80490495c4eb33360c7876ba263483c4c3721db0 | 9d164088aa2d5a65215b77186c45da093ad68cb1 | /src/CQGnuPlotMark.cpp | f8999ba33b29b17fb307c110c07663837cad8fee | [
"MIT"
] | permissive | colinw7/CQGnuPlot | 9c247a7ff8afd0060fd99d7f4c12d4f105dfc9d9 | c12ad292932a2116ab7fbb33be158adcf6c32674 | refs/heads/master | 2023-04-14T07:29:43.807602 | 2023-04-03T15:59:36 | 2023-04-03T15:59:36 | 26,377,931 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 822 | cpp | CQGnuPlotMark.cpp | #include <CQGnuPlotMark.h>
#include <CQGnuPlotPlot.h>
#include <CQGnuPlotRenderer.h>
CQGnuPlotMark::
CQGnuPlotMark(CQGnuPlotPlot *plot) :
CGnuPlotMark(plot)
{
}
CQGnuPlotMark *
CQGnuPlotMark::
dup() const
{
CQGnuPlotPlot *qplot = static_cast<CQGnuPlotPlot *>(plot_);
CQGnuPlotMark *stroke = new CQGnuPlotMark(qplot);
stroke->CGnuPlotMark::operator=(*this);
return stroke;
}
CQGnuPlotEnum::SymbolType
CQGnuPlotMark::
type() const
{
return CQGnuPlotEnum::symbolConv(CGnuPlotMark::type());
}
void
CQGnuPlotMark::
setType(const CQGnuPlotEnum::SymbolType &type)
{
CGnuPlotMark::setType(CQGnuPlotEnum::symbolConv(type));
}
QColor
CQGnuPlotMark::
color() const
{
return toQColor(CGnuPlotMark::color());
}
void
CQGnuPlotMark::
setColor(const QColor &color)
{
CGnuPlotMark::setColor(fromQColor(color));
}
|
e88188862a6a357dcae3d50f556bc2195528d90d | db7ee01b459bc69dda7f834d6da1b8122dd5c03f | /libfs/bench/ubench/main.h | eb05b4bd35db0fdd237f952b7974d50358f288af | [] | no_license | snalli/aerie | 71a5cf5ccc5451fc05f7a4882ea9ad132018956e | 529bea4230066e57132499e12a19a5aa10b4ae74 | refs/heads/master | 2021-01-18T11:47:18.910253 | 2016-08-30T22:48:51 | 2016-08-30T22:48:51 | 66,979,443 | 9 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 401 | h | main.h | #ifndef __STAMNOS_UBENCH_MAIN_H
#define __STAMNOS_UBENCH_MAIN_H
#include <vector>
#include <string>
struct UbenchDescriptor {
UbenchDescriptor(const char* name, int (*foo)(int, char* []))
: ubench_name(name),
ubench_function(foo)
{ }
std::string ubench_name;
int (*ubench_function)(int, char* []);
};
extern std::vector<UbenchDescriptor> ubench_table;
#endif // __STAMNOS_UBENCH_MAIN_H
|
fce77410124aea3e184052da4d076e48950f1f7d | 931ccb5e734ce1f836c9aaf014ab7894dcd9f16c | /src/CustomeHashTable.cpp | 46979d12a069ee8f585090b142a8b3dc361cc4f1 | [] | no_license | prateek13688/Algorithms | f5d0fbe62ec59d63dfccf9604488e48d5689ec92 | e30fbf958e223a05d7c668dc8947dda4813ef1e5 | refs/heads/master | 2021-01-10T05:18:25.509233 | 2016-03-27T19:35:10 | 2016-03-27T19:35:10 | 54,807,235 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31 | cpp | CustomeHashTable.cpp | #include "CustomeHashTable.h"
|
f1bf7a676c445d03a86f7081b3bca7bed8f486f4 | 6f9dee04b0cf108b8f5757f0cf39bc2623e1403d | /src/adv/p2.cc | 079d76b5131d8888c6e7dcc5e4557c42d00d9940 | [
"CC-BY-3.0"
] | permissive | mtsay-zz/cue | 3b50e3ca2ab100273d7fae2b5fbb5b360966d693 | 0a0200ec8ebcb827e25ba404a734e4ff9179f4bf | refs/heads/master | 2021-05-26T19:38:59.542106 | 2013-02-01T00:06:21 | 2013-02-01T00:06:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 581 | cc | p2.cc | #include<stdio.h>
char stack[256];
int stack_top;
char buf[256];
void push(char c) {
stack[stack_top++] = c;
}
char pop() {
return stack[--stack_top];
}
char map[256];
void init_map() {
map['}'] = '{';
map[']'] = '[';
map[')'] = '(';
}
int main() {
scanf("%s", buf);
init_map();
for (int i = 0; buf[i]; i++)
switch(buf[i]) {
case '{':
case '[':
case '(':
push(buf[i]);
break;
case '}':
case ']':
case ')':
if (pop() != map[buf[i]])
return printf("%d\n", i), 0;
break;
}
}
|
1eb3fbefe490b3de7c5571c42aca1da667b2feb4 | 0db77cc6e932facf49aa02dc166a3b4da70b0ecd | /Bermuda/Bermuda/StatusTracker.cpp | 1eece7515af5438c98a398ff568ebb52cdf7e7ab | [] | no_license | PimV/Bermuda-TheGame | fb871f736cc1b7501f0dfeb1dc89c2c31fce6bdf | 61be066db0b86b2f2af847d89d09dabb6895f917 | refs/heads/master | 2020-03-30T11:23:56.360284 | 2015-01-17T01:55:04 | 2015-01-17T01:55:04 | 24,408,829 | 0 | 0 | null | 2015-01-17T01:55:07 | 2014-09-24T09:26:04 | C | UTF-8 | C++ | false | false | 1,565 | cpp | StatusTracker.cpp | #include "StatusTracker.h"
StatusTracker::StatusTracker()
{
init();
}
void StatusTracker::init()
{
achievements.push_back(new Achievement("Apples picked"));
achievements.push_back(new Achievement("Carrots picked"));
achievements.push_back(new Achievement("Fish caught"));
achievements.push_back(new Achievement("Gold mined"));
achievements.push_back(new Achievement("Ice mined"));
achievements.push_back(new Achievement("Cacti chopped"));
achievements.push_back(new Achievement("Rocks mined"));
achievements.push_back(new Achievement("Trees chopped"));
achievements.push_back(new Achievement("Bats killed"));
achievements.push_back(new Achievement("Rabbits killed"));
achievements.push_back(new Achievement("Scorpions killed"));
achievements.push_back(new Achievement("Wasps killed"));
achievements.push_back(new Achievement("Wolves killed"));
}
std::vector<Achievement*> StatusTracker::getAllAchievements()
{
return this->achievements;
}
void StatusTracker::addAchievementCount(AchievementsEnum enumIn)
{
achievements[(int)enumIn]->addAmount();
}
void StatusTracker::setAllStats(std::vector<int> stats)
{
if (stats.size() <= this->achievements.size())
{
for (size_t i = 0; i < stats.size(); i++)
{
this->achievements[i]->setAmount(stats[i]);
}
}
}
void StatusTracker::cleanup()
{
for (size_t i = 0; i < achievements.size(); i++)
{
delete achievements[i];
achievements[i] = nullptr;
}
std::vector<Achievement*>().swap(this->achievements); //Clear and shrink vector
}
StatusTracker::~StatusTracker()
{
this->cleanup();
}
|
9106f49223be70e31fbf3ec2cbdb0b97dd14cdb0 | 39963008d220f9ac5d7fd9e03c844dba536ba15e | /dp_important_type/dptree2/bookofevil.cpp | aa81b5086544f30d2bb0ea23b6eba2dc1a9a4d0a | [] | no_license | nimishkapoor/cp_concept | b153891497493294039a44e86174264fed8daa9e | f081147fc3350bfbf4a360c6cc32391afed7eccc | refs/heads/master | 2020-05-30T16:11:44.899169 | 2020-01-24T03:18:20 | 2020-01-24T03:18:20 | 189,840,389 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,287 | cpp | bookofevil.cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define watch(x) cout << (#x) << " is " << (x) << endl
#define mod(x, m) ((((x) % (m)) + (m)) % (m))
#define max3(a, b, c) max(a, max(b, c))
#define min3(a, b, c) min(a, min(b, c))
#define gcd __gcd
#define nof1 __builtin_popcountll
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> ii;
typedef pair<int, ii> iii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef vector<iii> viii;
typedef vector<long long int> vl;
const double pi = 2 * acos(0.0);
const int inf = 0x3f3f3f3f;
const double infd = 1.0/0.0;
const int ninf = -2e5;
#define pb push_back
#define mp make_pair
#define fr first
#define sc second
#define clr(a) memset(a, -1, sizeof(a))
#define all(v) v.begin(), v.end()
#define alla(a,n) a, a+n
#define endl "\n"
long long power(long long x, long long y,long long MOD)
{
long long res = 1;
x = x % MOD;
while (y > 0)
{
if (y & 1)
res = (res*x) % MOD;
y = y>>1;
x = (x*x) % MOD;
}
return res;
}
long long mul(long long a,long long b,long long MOD)
{
if(b==1)
{
return a;
}
if(b%2==0)
{
return 2*(mul(a,b/2,MOD)%MOD);
}
else
{
return (a+(2*(mul(a,b/2,MOD))%MOD))%MOD;
}
}
/*ll ncr[6001][6001];
void nCr(long long MOD)
{
for(ll i=0;i<=6000;i++)
{
for(ll k=0;k<=6000;k++)
{
if(k<=i)
{
if((k==0)||(k==i))
ncr[i][k]=1;
else
ncr[i][k]=(ncr[i-1][k-1]+ncr[i-1][k])%MOD;
}
}
}
}
ll inv[100005];
void mulmodinv(long long MOD)
{
inv[1]=1;
inv[0]=1;
for(int i = 2; i <= 100005; i++)
inv[i] = inv[MOD % i]*(MOD-MOD / i) % MOD;
}*/
bool ispow2(ll n)
{
if(((n & (n-1)) == 0) && n!=0)
{
return true;
}
return false;
}
vi g[100007];
int in[100007];
int out[100007];
int mark[100007];
void dfs1(int parent)
{
if(mark[parent]!=1)
{
in[parent]=ninf;
}
else
{
in[parent]=0;
}
for(unsigned int i=0;i<g[parent].size();i++)
{
if(in[g[parent][i]]==-1)
{
dfs1(g[parent][i]);
in[parent]=max(in[parent],1+in[g[parent][i]]);
}
}
}
void dfs2(int parent)
{
int mx1=ninf,mx2=ninf;
for(unsigned int i=0;i<g[parent].size();i++)
{
if(out[g[parent][i]]==-1)
{
if(in[g[parent][i]]>mx1)
{
mx2=mx1;
mx1=in[g[parent][i]];
}
else if(in[g[parent][i]]>mx2)
{
mx2=in[g[parent][i]];
}
}
}
for(unsigned int i=0;i<g[parent].size();i++ )
{
if(out[g[parent][i]]==-1)
{
if(in[g[parent][i]]==mx1)
{
out[g[parent][i]]=1+max(out[parent],1+mx2);
}
else
{
out[g[parent][i]]=1+max(out[parent],1+mx1);
}
if(mark[g[parent][i]]==1 && out[g[parent][i]]<0)
{
out[g[parent][i]]=0;
}
dfs2(g[parent][i]);
}
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
clr(in);
clr(out);
clr(mark);
int n,m,d,u,v,ans=0,x;
cin>>n>>m>>d;
for(int i=0;i<m;i++)
{
cin>>x;
mark[x]=1;
}
for(int i=0;i<n-1;i++)
{
cin>>u>>v;
g[u].pb(v);
g[v].pb(u);
}
dfs1(1);
if(mark[1]==1)
{
out[1]=0;
}
else
{
out[1]=ninf;
}
dfs2(1);
for(int i=1;i<=n;i++)
{
if(in[i]<=d && out[i]<=d)
{
ans++;
}
}
cout<<ans<<endl;
/*for(int i=1;i<=n;i++)
{
cout<<in[i]<<" ";
}
cout<<endl;
for(int i=1;i<=n;i++)
{
cout<<out[i]<<" ";
}
cout<<endl;*/
return 0;
}
|
5eede7ecf547cb7aff6e0f439f4738a299a30b9a | bbcf9a3dbca573d4c123ddca5dc359aa39ebecc6 | /Advanced Classes Project/Project IV/Part I/main.cpp | 127b4ccdd8897b8a5768a7a1f895d8e5c461d2e8 | [] | no_license | Darosan404/CPP | 1d5c623d5735b19704f5d60cc57535554ff6cc23 | 5bc55c7cb126c1efee6cd589724f1a95fbd7c98d | refs/heads/main | 2023-04-22T23:14:59.862063 | 2021-05-05T02:15:16 | 2021-05-05T02:15:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 627 | cpp | main.cpp | # include "Theparkingmeter.h"
# include "Theparkedcar.h"
# include "Thepoliceofficer.h"
# include "Theparkingticket.h"
# include <iostream>
using namespace::std;
int main(){
TheParkedCar car;
cin >> car;
TheParkingMeter meter(60);
ThePoliceOfficer officer;
cin >> officer;
int illegalMinutes = officer.examine(car, meter);
if (illegalMinutes > 0){
cout << endl;
TheParkingTicket ticket(0.0, illegalMinutes);
cout << car << endl;
cout << officer << endl;
cout << ticket;
}
else{
cout << "No crimes committed!" << endl;
}
system("pause");
return 0;
}
|
3e1a4b5c6b282a42470c6c3d73e73c3dca2a472c | 76141fe310e7c443ae832bf14ee3ad9dcf25899a | /src/vfs/smbfs/helpers/lib/charset.cpp | d323cbb65773d04f4cc57a42df4498d371196c49 | [] | no_license | kybl/mc-cpp | 9b6e996b229632e409292dd460b4921bc13bee36 | ca9992a875d72b32026ca8163dabb63c496fcdda | refs/heads/master | 2022-11-25T05:53:48.552423 | 2020-08-06T17:19:08 | 2020-08-06T17:19:08 | 285,595,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,203 | cpp | charset.cpp | /*
Unix SMB/Netbios implementation.
Version 1.9.
Character set handling
Copyright (C) Andrew Tridgell 1992-1998
Copyright (C) 2011-2020
Free Software Foundation, Inc.
This file is part of the Midnight Commander.
The Midnight Commander is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of the License,
or (at your option) any later version.
The Midnight Commander 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/>.
*/
#define CHARSET_C
#include <cctype>
#include "includes.h"
#include "lib/strutil.h"
const char *unix_error_string (int error_num);
extern int DEBUGLEVEL;
/*
* Codepage definitions.
*/
#if !defined(KANJI)
/* lower->upper mapping for IBM Code Page 850 - MS-DOS Latin 1 */
unsigned char const cp_850[][4] = {
/* dec col/row oct hex description */
/* 133 08/05 205 85 a grave */
/* 183 11/07 267 B7 A grave */ {0x85, 0xB7, 1, 1},
/* 160 10/00 240 A0 a acute */
/* 181 11/05 265 B5 A acute */ {0xA0, 0xB5, 1, 1},
/* 131 08/03 203 83 a circumflex */
/* 182 11/06 266 B6 A circumflex */ {0x83, 0xB6, 1, 1},
/* 198 12/06 306 C6 a tilde */
/* 199 12/07 307 C7 A tilde */ {0xC6, 0xC7, 1, 1},
/* 132 08/04 204 84 a diaeresis */
/* 142 08/14 216 8E A diaeresis */ {0x84, 0x8E, 1, 1},
/* 134 08/06 206 86 a ring */
/* 143 08/15 217 8F A ring */ {0x86, 0x8F, 1, 1},
/* 145 09/01 221 91 ae diphthong */
/* 146 09/02 222 92 AE diphthong */ {0x91, 0x92, 1, 1},
/* 135 08/07 207 87 c cedilla */
/* 128 08/00 200 80 C cedilla */ {0x87, 0x80, 1, 1},
/* 138 08/10 212 8A e grave */
/* 212 13/04 324 D4 E grave */ {0x8A, 0xD4, 1, 1},
/* 130 08/02 202 82 e acute */
/* 144 09/00 220 90 E acute */ {0x82, 0x90, 1, 1},
/* 136 08/08 210 88 e circumflex */
/* 210 13/02 322 D2 E circumflex */ {0x88, 0xD2, 1, 1},
/* 137 08/09 211 89 e diaeresis */
/* 211 13/03 323 D3 E diaeresis */ {0x89, 0xD3, 1, 1},
/* 141 08/13 215 8D i grave */
/* 222 13/14 336 DE I grave */ {0x8D, 0xDE, 1, 1},
/* 161 10/01 241 A1 i acute */
/* 214 13/06 326 D6 I acute */ {0xA1, 0xD6, 1, 1},
/* 140 08/12 214 8C i circumflex */
/* 215 13/07 327 D7 I circumflex */ {0x8C, 0xD7, 1, 1},
/* 139 08/11 213 8B i diaeresis */
/* 216 13/08 330 D8 I diaeresis */ {0x8B, 0xD8, 1, 1},
/* 208 13/00 320 D0 Icelandic eth */
/* 209 13/01 321 D1 Icelandic Eth */ {0xD0, 0xD1, 1, 1},
/* 164 10/04 244 A4 n tilde */
/* 165 10/05 245 A5 N tilde */ {0xA4, 0xA5, 1, 1},
/* 149 09/05 225 95 o grave */
/* 227 14/03 343 E3 O grave */ {0x95, 0xE3, 1, 1},
/* 162 10/02 242 A2 o acute */
/* 224 14/00 340 E0 O acute */ {0xA2, 0xE0, 1, 1},
/* 147 09/03 223 93 o circumflex */
/* 226 14/02 342 E2 O circumflex */ {0x93, 0xE2, 1, 1},
/* 228 14/04 344 E4 o tilde */
/* 229 14/05 345 E5 O tilde */ {0xE4, 0xE5, 1, 1},
/* 148 09/04 224 94 o diaeresis */
/* 153 09/09 231 99 O diaeresis */ {0x94, 0x99, 1, 1},
/* 155 09/11 233 9B o slash */
/* 157 09/13 235 9D O slash */ {0x9B, 0x9D, 1, 1},
/* 151 09/07 227 97 u grave */
/* 235 14/11 353 EB U grave */ {0x97, 0xEB, 1, 1},
/* 163 10/03 243 A3 u acute */
/* 233 14/09 351 E9 U acute */ {0xA3, 0xE9, 1, 1},
/* 150 09/06 226 96 u circumflex */
/* 234 14/10 352 EA U circumflex */ {0x96, 0xEA, 1, 1},
/* 129 08/01 201 81 u diaeresis */
/* 154 09/10 232 9A U diaeresis */ {0x81, 0x9A, 1, 1},
/* 236 14/12 354 EC y acute */
/* 237 14/13 355 ED Y acute */ {0xEC, 0xED, 1, 1},
/* 231 14/07 347 E7 Icelandic thorn */
/* 232 14/08 350 E8 Icelandic Thorn */ {0xE7, 0xE8, 1, 1},
{0x9C, 0, 0, 0}, /* Pound */
{0, 0, 0, 0}
};
#else /* KANJI */
/* lower->upper mapping for IBM Code Page 932 - MS-DOS Japanese SJIS */
unsigned char const cp_932[][4] = {
{0, 0, 0, 0}
};
#endif /* KANJI */
char xx_dos_char_map[256];
char xx_upper_char_map[256];
char xx_lower_char_map[256];
char *dos_char_map = xx_dos_char_map;
char *upper_char_map = xx_upper_char_map;
char *lower_char_map = xx_lower_char_map;
/*
* This code has been extended to deal with ascynchronous mappings
* like MS-DOS Latin US (Code page 437) where things like :
* a acute are capitalized to 'A', but the reverse mapping
* must not hold true. This allows the filename case insensitive
* matching in do_match() to work, as the DOS/Win95/NT client
* uses 'A' as a mask to match against characters like a acute.
* This is the meaning behind the parameters that allow a
* mapping from lower to upper, but not upper to lower.
*/
static void
add_dos_char (int lower, BOOL map_lower_to_upper, int upper, BOOL map_upper_to_lower)
{
lower &= 0xff;
upper &= 0xff;
DEBUGADD (6, ("Adding chars 0x%x 0x%x (l->u = %s) (u->l = %s)\n",
lower, upper,
map_lower_to_upper ? "True" : "False", map_upper_to_lower ? "True" : "False"));
if (lower)
dos_char_map[lower] = 1;
if (upper)
dos_char_map[upper] = 1;
lower_char_map[lower] = (char) lower; /* Define tolower(lower) */
upper_char_map[upper] = (char) upper; /* Define toupper(upper) */
if (lower && upper)
{
if (map_upper_to_lower)
lower_char_map[upper] = (char) lower;
if (map_lower_to_upper)
upper_char_map[lower] = (char) upper;
}
}
/****************************************************************************
initialise the charset arrays
****************************************************************************/
void
charset_initialise (void)
{
int i;
#ifdef LC_ALL
/* include <locale.h> in includes.h if available for OS */
/* we take only standard 7-bit ASCII definitions from ctype */
setlocale (LC_ALL, "C");
#endif
for (i = 0; i <= 255; i++)
{
dos_char_map[i] = 0;
}
for (i = 0; i <= 127; i++)
{
if (isalnum (i) || strchr ("._^$~!#%&-{}()@'`", (char) i))
add_dos_char (i, False, 0, False);
}
for (i = 0; i <= 255; i++)
{
char c = (char) i;
upper_char_map[i] = lower_char_map[i] = c;
/* Some systems have buggy isupper/islower for characters
above 127. Best not to rely on them. */
if (i < 128)
{
if (isupper ((int) c))
lower_char_map[i] = tolower (c);
if (islower ((int) c))
upper_char_map[i] = toupper (c);
}
}
}
/****************************************************************************
load the client codepage.
****************************************************************************/
typedef const unsigned char (*codepage_p)[4];
static codepage_p
load_client_codepage (int client_codepage)
{
pstring codepage_file_name;
unsigned char buf[8];
FILE *fp = nullptr;
SMB_OFF_T size;
codepage_p cp_p = nullptr;
SMB_STRUCT_STAT st;
DEBUG (5, ("load_client_codepage: loading codepage %d.\n", client_codepage));
if (strlen (CODEPAGEDIR) + 14 > sizeof (codepage_file_name))
{
DEBUG (0, ("load_client_codepage: filename too long to load\n"));
return nullptr;
}
pstrcpy (codepage_file_name, CODEPAGEDIR);
pstrcat (codepage_file_name, "/");
pstrcat (codepage_file_name, "codepage.");
slprintf (&codepage_file_name[strlen (codepage_file_name)],
sizeof (pstring) - (strlen (codepage_file_name) + 1), "%03d", client_codepage);
if (sys_stat (codepage_file_name, &st) != 0)
{
DEBUG (0, ("load_client_codepage: filename %s does not exist.\n", codepage_file_name));
return nullptr;
}
/* Check if it is at least big enough to hold the required
data. Should be 2 byte version, 2 byte codepage, 4 byte length,
plus zero or more bytes of data. Note that the data cannot be more
than 4 * MAXCODEPAGELINES bytes.
*/
size = st.st_size;
if (size < CODEPAGE_HEADER_SIZE || size > (CODEPAGE_HEADER_SIZE + 4 * MAXCODEPAGELINES))
{
DEBUG (0, ("load_client_codepage: file %s is an incorrect size for a \
code page file (size=%d).\n", codepage_file_name, (int) size));
return nullptr;
}
/* Read the first 8 bytes of the codepage file - check
the version number and code page number. All the data
is held in little endian format.
*/
if ((fp = sys_fopen (codepage_file_name, "r")) == nullptr)
{
DEBUG (0, ("load_client_codepage: cannot open file %s. Error was %s\n",
codepage_file_name, unix_error_string (errno)));
return nullptr;
}
if (fread (buf, 1, CODEPAGE_HEADER_SIZE, fp) != CODEPAGE_HEADER_SIZE)
{
DEBUG (0, ("load_client_codepage: cannot read header from file %s. Error was %s\n",
codepage_file_name, unix_error_string (errno)));
goto clean_and_exit;
}
/* Check the version value */
if (SVAL (buf, CODEPAGE_VERSION_OFFSET) != CODEPAGE_FILE_VERSION_ID)
{
DEBUG (0, ("load_client_codepage: filename %s has incorrect version id. \
Needed %hu, got %hu.\n", codepage_file_name, (uint16) CODEPAGE_FILE_VERSION_ID, SVAL (buf, CODEPAGE_VERSION_OFFSET)));
goto clean_and_exit;
}
/* Check the codepage matches */
if (SVAL (buf, CODEPAGE_CLIENT_CODEPAGE_OFFSET) != (uint16) client_codepage)
{
DEBUG (0, ("load_client_codepage: filename %s has incorrect codepage. \
Needed %hu, got %hu.\n", codepage_file_name, (uint16) client_codepage, SVAL (buf, CODEPAGE_CLIENT_CODEPAGE_OFFSET)));
goto clean_and_exit;
}
/* Check the length is correct. */
if (IVAL (buf, CODEPAGE_LENGTH_OFFSET) != (size - CODEPAGE_HEADER_SIZE))
{
DEBUG (0, ("load_client_codepage: filename %s has incorrect size headers. \
Needed %u, got %u.\n", codepage_file_name, (uint32) (size - CODEPAGE_HEADER_SIZE), IVAL (buf, CODEPAGE_LENGTH_OFFSET)));
goto clean_and_exit;
}
size -= CODEPAGE_HEADER_SIZE; /* Remove header */
/* Make sure the size is a multiple of 4. */
if ((size % 4) != 0)
{
DEBUG (0, ("load_client_codepage: filename %s has a codepage size not a \
multiple of 4.\n", codepage_file_name));
goto clean_and_exit;
}
/* Allocate space for the code page file and read it all in. */
if ((cp_p = (codepage_p) malloc (size + 4)) == nullptr)
{
DEBUG (0, ("load_client_codepage: malloc fail.\n"));
goto clean_and_exit;
}
if (fread ((char *) cp_p, 1, size, fp) != size)
{
DEBUG (0, ("load_client_codepage: read fail on file %s. Error was %s.\n",
codepage_file_name, unix_error_string (errno)));
goto clean_and_exit;
}
/* Ensure array is correctly terminated. */
memset (((char *) cp_p) + size, '\0', 4);
fclose (fp);
return cp_p;
clean_and_exit:
/* pseudo destructor :-) */
if (fp != nullptr)
fclose (fp);
if (cp_p)
free ((char *) cp_p);
return nullptr;
}
/****************************************************************************
initialise the client codepage.
****************************************************************************/
void
codepage_initialise (int client_codepage)
{
int i;
static codepage_p cp = nullptr;
if (cp != nullptr)
{
DEBUG (6,
("codepage_initialise: called twice - ignoring second client code page = %d\n",
client_codepage));
return;
}
DEBUG (6, ("codepage_initialise: client code page = %d\n", client_codepage));
/*
* Known client codepages - these can be added to.
*/
cp = load_client_codepage (client_codepage);
if (cp == nullptr)
{
#ifdef KANJI
DEBUG (6, ("codepage_initialise: loading dynamic codepage file %s/codepage.%d \
for code page %d failed. Using default client codepage 932\n", CODEPAGEDIR, client_codepage, client_codepage));
cp = cp_932;
client_codepage = KANJI_CODEPAGE;
#else /* KANJI */
DEBUG (6, ("codepage_initialise: loading dynamic codepage file %s/codepage.%d \
for code page %d failed. Using default client codepage 850\n", CODEPAGEDIR, client_codepage, client_codepage));
cp = cp_850;
client_codepage = MSDOS_LATIN_1_CODEPAGE;
#endif /* KANJI */
}
/*
* Setup the function pointers for the loaded codepage.
*/
initialize_multibyte_vectors (client_codepage);
if (cp)
{
for (i = 0; !((cp[i][0] == '\0') && (cp[i][1] == '\0')); i++)
add_dos_char (cp[i][0], (BOOL) cp[i][2], cp[i][1], (BOOL) cp[i][3]);
}
}
/*******************************************************************
add characters depending on a string passed by the user
********************************************************************/
void
add_char_string (const char *s)
{
char *extra_chars = (char *) strdup (s);
char *t;
if (!extra_chars)
return;
for (t = strtok (extra_chars, " \t\r\n"); t; t = strtok (nullptr, " \t\r\n"))
{
char c1 = 0, c2 = 0;
int i1 = 0, i2 = 0;
if (isdigit ((unsigned char) *t) || (*t) == '-')
{
sscanf (t, "%i:%i", &i1, &i2);
add_dos_char (i1, True, i2, True);
}
else
{
sscanf (t, "%c:%c", &c1, &c2);
add_dos_char ((unsigned char) c1, True, (unsigned char) c2, True);
}
}
free (extra_chars);
}
|
0e5f4ce84b1bd7fb299ab2fa23102b09ae19c7b5 | 1f5ae06f97b69cbb30b97c71dfc4968212e79106 | /ex_1/U201612922_1.cpp | c95a4c8010142decf8ec05dbf1e887a159fd9c35 | [] | no_license | dmmlcloud/C-_ex | 17bca8fb29ce39ab53010a20f02d596abfad2d57 | de0ccc6ba4efe439775b1c02267d3494303e7256 | refs/heads/master | 2020-04-30T01:59:59.925430 | 2019-03-19T15:43:17 | 2019-03-19T15:43:17 | 176,545,971 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,826 | cpp | U201612922_1.cpp | #include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
struct STACK {
int *elems; //申请内存用于存放栈的元素
int max; //栈能存放的最大元素个数
int pos; //栈实际已有元素个数,栈空时pos=0;
};
void initSTACK(STACK *const p, int m); //初始化p指向的栈:最多m个元素
void initSTACK(STACK *const p, const STACK&s); //用栈s初始化p指向的栈
int size(const STACK *const p); //返回p指向的栈的最大元素个数max
int howMany(const STACK *const p); //返回p指向的栈的实际元素个数pos
int getelem(const STACK *const p, int x); //取下标x处的栈元素
STACK *const push(STACK *const p, int e); //将e入栈,并返回p
STACK *const pop(STACK *const p, int &e); //出栈到e,并返回p
STACK *const assign(STACK*const p, const STACK&s); //赋s给p指的栈,并返回p
void print(const STACK*const p); //打印p指向的栈
void destroySTACK(STACK*const p); //销毁p指向的栈
FILE *fp = NULL;
int main(int argc, char *argv[])
{
fp = fopen("U201612922_1", "w");
int flag = 0;
int iflag = 0;
STACK t, q;
STACK *s = &t;
STACK *p = &q;
int count = 1;
while (count < argc)
{
if (!strcmp(argv[count], "-S"))
{
printf("S");
fprintf(fp, "S");
if (iflag == 1)
flag = 1;
if (iflag == 0)
{
int max = atoi(argv[++count]);
initSTACK(s, max);
iflag = 1;
printf(" %d", max);
fprintf(fp, " %d", max);
count++;
}
}
else if (!strcmp(argv[count], "-I"))
{
printf(" I");
fprintf(fp, " I");
while (argv[++count][0] != '-')
{
int elem = atoi(argv[count]);
s = push(s, elem);
if (iflag == 0 || s == NULL)
{
flag = 1;
break;
}
if ((count + 1) == argc)
{
count++;
break;
}
}
if (flag == 0)
print(s);
}
else if (!strcmp(argv[count], "-O"))
{
printf(" O");
fprintf(fp, " O");
int i = atoi(argv[++count]);
if (iflag == 0 || i > s->pos)
flag = 1;
if (flag == 0)
{
while (i--)
{
int elem = 0;
s = pop(s, elem);
}
print(s);
count++;
}
}
else if (!strcmp(argv[count], "-A"))
{
printf(" A");
fprintf(fp, " A");
if (iflag == 0)
flag = 1;
if (flag == 0)
{
p = assign(p, *s);
print(p);
count = count + 2;
STACK *temp = p;
p = s;
s = temp;
}
}
else if (!strcmp(argv[count], "-C"))
{
printf(" C");
fprintf(fp, " C");
if (iflag == 0)
flag = 1;
if (flag == 0)
{
initSTACK(p, *s);
print(p);
count++;
STACK *temp = p;
p = s;
s = temp;
}
}
else if (!strcmp(argv[count], "-N"))
{
printf(" N");
fprintf(fp, " N");
if (iflag == 0)
flag = 1;
if (flag == 0)
{
printf(" %d", howMany(s));
fprintf(fp, " %d", howMany(s));
count++;
}
}
else if (!strcmp(argv[count], "-G"))
{
printf(" G");
fprintf(fp, " G");
if (iflag == 0)
flag = 1;
if (flag == 0)
{
int elem = getelem(s, atoi(argv[++count]));
if (elem == EOF)
flag = 1;
if (flag == 0)
{
printf(" %d", elem);
fprintf(fp, " %d", elem);
count++;
}
}
}
else
flag = 1;
if (flag == 1)
{
printf(" E");
fprintf(fp, " E");
break;
}
}
fclose(fp);
return 0;
}
void initSTACK(STACK *const p, int m)//初始化p指向的栈:最多m个元素
{
p->elems = new int[m];
p->max = m;
p->pos = 0;
}
void initSTACK(STACK *const p, const STACK&s)//用栈s初始化p指向的栈
{
p->elems = s.elems;
p->pos = s.pos;
p->max = s.max;
}
int size(const STACK *const p)//返回p指向的栈的最大元素个数max
{
return p->max;
}
int howMany(const STACK *const p)//返回p指向的栈的实际元素个数pos
{
return p->pos;
}
int getelem(const STACK *const p, int x)//取下标x处的栈元素
{
if (p->pos <= x || x < 0)
return EOF;
return p->elems[x];
}
STACK *const push(STACK *const p, int e)//将e入栈,并返回p
{
if (p->pos >= p->max)
return NULL;
p->elems[p->pos] = e;
p->pos++;
return p;
}
STACK *const pop(STACK *const p, int &e)//出栈到e,并返回p
{
e = p->elems[p->pos - 1];
p->pos--;
return p;
}
STACK *const assign(STACK*const p, const STACK&s)//赋s给p指的栈,并返回p
{
p->elems = new int[s.max];
for (int i = 0; i < s.pos; i++)
p->elems[i] = s.elems[i];
p->pos = s.pos;
p->max = s.max;
return p;
}
void print(const STACK*const p)//打印p指向的栈
{
for (int i = 0; i < p->pos; i++)
{
printf(" %d", p->elems[i]);
fprintf(fp, " %d", p->elems[i]);
}
}
void destroySTACK(STACK*const p)//销毁p指向的栈
{
free(p->elems);
p->elems = NULL;
}
|
73ff75c283df9d7bf671d7bbbd3c957acea34a3c | b966559c85422d89ddf77a91c6b96bf4080fabe0 | /Source/OrcVsHuman/GameManager.h | 1352df810c9ee4a332fd27a5181bb7d34022f140 | [] | no_license | FashGek/UnrealOrcPacman | ae7717b59cb3e61d1d1bea4c2766cf894688a11b | f5f350fed45b95766e9023e219fd26991fc97ee2 | refs/heads/master | 2020-04-05T23:30:02.510617 | 2015-07-06T03:59:19 | 2015-07-06T03:59:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,077 | h | GameManager.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include <vector>
#include "GameManager.generated.h"
class AOrcAIBase;
class APowerUp;
enum EGameState
{
GS_PlayerVulnerable,
GS_PlayerInvincible,
};
UCLASS()
class ORCVSHUMAN_API AGameManager : public AActor
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Game Manager")
AActor* MainPlayer;
std::vector<AOrcAIBase*> Orcs;
std::vector<AActor*> Coins;
std::vector<APowerUp*> PowerUps;
EGameState GameState;
public:
static AGameManager* Instance() { return instance; };
// Sets default values for this actor's properties
AGameManager(const FObjectInitializer& ObjectInitializer);
// Called when the game starts
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
private:
void checkOrcCollisions();
void checkCoinCollisions();
void checkPowerCoinCollisions();
private:
static AGameManager* instance;
float invincibleTimer;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.