text
stringlengths 8
6.88M
|
|---|
#include <Servo.h>
#include <math.h>
Servo servo, servo2, servo3, servo4;
const byte numLEDs = 3;
//byte ledPin[numLEDs] = {11, 12, 13};
const byte buffSize = 40;
char inputBuffer[buffSize];
const char startMarker = '<';
const char endMarker = '>';
byte bytesRecvd = 0;
boolean readInProgress = false;
boolean newDataFromPC = false;
char messageFromPC[buffSize] = {0};
double servoSpeed = 0.0;
double servoSpeed2 = 0.0;
double servoSpeed3 = 0.0;
double servoSpeed4 = 0.0;
int joystick = -1;
unsigned long curMillis;
unsigned long prevReplyToPCmillis = 0;
unsigned long replyToPCinterval = 1000;
//=============
void setup() {
Serial.begin(9600);
// initialize the servos
servo.attach(10);
//servo2.attach(11);
servo3.attach(11);
//servo4.attach(13);
// tell the PC we are ready
Serial.println("<Arduino is ready>");
}
//=============
void loop() {
curMillis = millis();
getDataFromPC();
updateServos();
replyToPC();
}
//=============
void getDataFromPC() {
// receive data from PC and save it into inputBuffer
if(Serial.available() > 0) {
char x = Serial.read();
// the order of these IF clauses is significant
if (x == endMarker) {
readInProgress = false;
newDataFromPC = true;
inputBuffer[bytesRecvd] = 0;
parseData();
}
if(readInProgress) {
inputBuffer[bytesRecvd] = x;
bytesRecvd ++;
if (bytesRecvd == buffSize) {
bytesRecvd = buffSize - 1;
}
}
if (x == startMarker) {
bytesRecvd = 0;
readInProgress = true;
}
}
}
//=============
void parseData() {
// split the data into its parts
char * strtokIndx; // this is used by strtok() as an index
/*strtokIndx = strtok(inputBuffer, ",");
joystick = atoi(strtokIndx); //gets which joystick it is */
strtokIndx = strtok(inputBuffer,","); // get the first part - the string CHANGED FROM: strtok(inputBuffer, ",")
servoSpeed = atof(strtokIndx);
servoSpeed *= 100.0;
if(servoSpeed >= 3)
servoSpeed = fscale(-2, 102, 90, 20, servoSpeed, -2);
else if(servoSpeed <= -3)
servoSpeed = fscale(-2, 102, 90, 160, abs(servoSpeed), -2);
else
servoSpeed = 90;
strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
servoSpeed2 = atof(strtokIndx); // convert this part to an integer
servoSpeed2 *= 100.0;
if(servoSpeed2 >= 3)
servoSpeed2 = fscale(-2, 102, 90, 20, servoSpeed2, -2);
//servoSpeed2 = map(servoSpeed2, 0, 100, 90, 70);
else if(servoSpeed2 <= -3)
servoSpeed2 = fscale(-2, 102, 90, 160, abs(servoSpeed2), -2);
//servoSpeed2 = map(servoSpeed2, 0, -100, 90, 110);
else
servoSpeed2 = 90;
strtokIndx = strtok(NULL, ",");
servoSpeed3 = atof(strtokIndx);
servoSpeed3 *= 100.0;
if(servoSpeed3 >= 3)
servoSpeed3 = fscale(-2, 102, 90, 20, servoSpeed3, -2);
else if(servoSpeed3 <= -3)
servoSpeed3 = fscale(-2, 102, 90, 160, abs(servoSpeed3), -2);
else
servoSpeed3 = 90;
strtokIndx = strtok(NULL, ",");
servoSpeed4 = atof(strtokIndx);
servoSpeed4 *= 100.0;
if(servoSpeed4 >= 3)
servoSpeed4 = fscale(-2, 102, 90, 20, servoSpeed4, -2);
else if(servoSpeed4 <= -3)
servoSpeed4 = fscale(-2, 102, 90, 160, abs(servoSpeed4), -2);
else
servoSpeed4 = 90;
}
//=============
void replyToPC() {
if (newDataFromPC) {
newDataFromPC = false;
Serial.print("<Msg ");
Serial.print(messageFromPC);
Serial.print(" Servo1 ");
Serial.print(servoSpeed);
Serial.print(" Servo2 ");
Serial.print(servoSpeed2);
Serial.print(" Servo3 ");
Serial.print(servoSpeed3);
Serial.print(" Time ");
Serial.print(curMillis >> 9); // divide by 512 is approx = half-seconds
Serial.println(">");
}
}
//============
void updateServos() {
updateServo();
updateServo2();
updateServo3();
updateServo4();
}
//=============
void updateServo() {
// if(joystick == 0) //change joystick num later
servo.write(servoSpeed);
}
//=============
void updateServo2() {
// if(joystick == 1) //change joystick num later
servo2.write(servoSpeed2);
}
//=============
void updateServo3() {
// if(joystick == 1) //change joystick num later
servo3.write(servoSpeed3);
}
//=============
void updateServo4() {
// if(joystick == 1) //change joystick num later
servo4.write(servoSpeed4);
}
//=============
float fscale( float originalMin, float originalMax, float newBegin, float newEnd, float inputValue, float curve){
float OriginalRange = 0;
float NewRange = 0;
float zeroRefCurVal = 0;
float normalizedCurVal = 0;
float rangedValue = 0;
boolean invFlag = 0;
// condition curve parameter
// limit range
if (curve > 10) curve = 10;
if (curve < -10) curve = -10;
curve = (curve * -.1) ; // - invert and scale - this seems more intuitive - postive numbers give more weight to high end on output
curve = pow(10, curve); // convert linear scale into lograthimic exponent for other pow function
/*
Serial.println(curve * 100, DEC); // multply by 100 to preserve resolution
Serial.println();
*/
// Check for out of range inputValues
if (inputValue < originalMin) {
inputValue = originalMin;
}
if (inputValue > originalMax) {
inputValue = originalMax;
}
// Zero Refference the values
OriginalRange = originalMax - originalMin;
if (newEnd > newBegin){
NewRange = newEnd - newBegin;
}
else
{
NewRange = newBegin - newEnd;
invFlag = 1;
}
zeroRefCurVal = inputValue - originalMin;
normalizedCurVal = zeroRefCurVal / OriginalRange; // normalize to 0 - 1 float
/*
Serial.print(OriginalRange, DEC);
Serial.print(" ");
Serial.print(NewRange, DEC);
Serial.print(" ");
Serial.println(zeroRefCurVal, DEC);
Serial.println();
*/
// Check for originalMin > originalMax - the math for all other cases i.e. negative numbers seems to work out fine
if (originalMin > originalMax ) {
return 0;
}
if (invFlag == 0){
rangedValue = (pow(normalizedCurVal, curve) * NewRange) + newBegin;
}
else // invert the ranges
{
rangedValue = newBegin - (pow(normalizedCurVal, curve) * NewRange);
}
return rangedValue;
}
|
// Alfred Shaker
// accumulating_observer.cpp
// cs33901
#include "accumulating_observer.h"
#include <iostream>
#include <string>
#include <vector>
void AccumulatingObserver::update(Observable* obs) {
// get state, save state
char state = obs->get_state();
upperCase.push_back(state);
}
void AccumulatingObserver::show_data() {
// get output
std::cout << "Uppers: ";
for (int index = 0; index < upperCase.size(); ++index)
std::cout << upperCase[index];
std::cout << "\n";
}
|
//O(n) using bucket of size t+1 and then slide window of k
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if(t < 0 || k < 0) return false;
unordered_map<long, long> mp;
long w = t+1;
for(int i = 0; i < nums.size(); ++i){
long bucket = ((long)nums[i] - INT_MIN)/w;
if(mp.count(bucket) ||
mp.count(bucket-1) && abs(nums[i] - mp[bucket-1]) < w ||
mp.count(bucket+1) && abs(nums[i] - mp[bucket+1]) < w ) return true;
//When there are duplicate keys, the function will return true immediately.
mp[bucket] = nums[i];
if(i >= k) mp.erase(((long)nums[i-k] - INT_MIN)/w);
}
return false;
}
};
//nlog(k). use BST.
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if(t < 0 || k < 0) return false;
set<long> se;
for(int i = 0; i < nums.size(); ++i){
set<long>::iterator it = se.lower_bound((long)nums[i]-t);
if(it != se.end() && abs((long)*it - nums[i]) <= t) {
return true;
}
se.insert(nums[i]);
if(i >= k) se.erase(nums[i-k]);
}
return false;
}
};
|
#ifndef UTILS_ERROR_HANDLING_STATUS_H_
#define UTILS_ERROR_HANDLING_STATUS_H_
namespace utils {
namespace error_handling {
enum class Status {
kOk,
kError
};
} // namespace utils
} // namespace error_handling
#endif
|
#include "githabic.h"
#include <iostream>
#include <cmath>
using namespace std;
int task4(){
int x;
cout << "Used task 30 (IF) from Abramyan book" << endl;
cout << "Enter your number:" << endl;
cin >> x;
x = abs(x);
if (x%2 == 0){
if (x < 100){
if (x < 10) cout << "Even one-digit numeric";
else cout << "Even two-digit numeric";
}
else cout << "Even three-digit numeric";
}
else {
if (x < 100){
if (x < 10) cout << "Odd one-digit numeric";
else cout << "Odd two-digit numeric";
}
else cout << "Odd three-digit numeric";
}
}
|
/*
* TestTime.cpp
*
* Created on: 02-Nov-2016
* Author: sirisha
*/
using namespace std;
#include "TestHeader.h"
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <ctime>
class TestTime;
class TestTime {
private:
time_t currentRawTimeInSeconds;
struct tm currentTime;
char buf[180];
static TestTime *testTime_t;
private:
TestTime() {
cout << "TestTime costructor..." << endl;
}
public:
~TestTime() {
cout << "TestTime Destructor..." << endl;
}
public:
static TestTime* getTimeInstance(void);
static void destructTimerInstance(void);
string getCurrentTime(void);
};
TestTime* TestTime::testTime_t = 0;
string TestTime::getCurrentTime(void) {
this->currentRawTimeInSeconds = time(0);
this->currentTime = *localtime(¤tRawTimeInSeconds);
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", ¤tTime);
cout << __func__ << "(" << __LINE__ << ") Current object address: " << this << endl;
return buf;
}
TestTime* TestTime::getTimeInstance() {
if(!testTime_t)
testTime_t = new TestTime();
return testTime_t;
//return 0;
}
void TestTime::destructTimerInstance(void) {
cout << __func__ <<"(" <<__LINE__ << ") Invoing destructor manually..." << endl;
//~TestTime();
}
#if 1
int main() {
TestTime *t1, *t2;
int a;
int &ra =a ;
int &rra = ra;
cout << "ref: " << ra << " , orig: " << a << "ref to ref: " << rra << endl;
cout << "\naddress of ref: " << &ra << " , and address of orig: " << &a << endl;
cout << "sizeof of ref: " << sizeof(ra) << " , and size of orig: " << sizeof(a) << endl;
cout << "After modifying ref and orig..." << endl;
ra=a+4;
cout << "ref: " << ra << " , orig: " << a << "ref to ref: " << rra << endl;
cout << "address of ref: " << &ra << " , and address of orig: " << &a << endl;
cout << "sizeof of ref: " << sizeof(ra) << " , and size of orig: " << sizeof(a) << endl;
cout << "Testing ref to an object..." <<endl;
t1 = TestTime::getTimeInstance();
TestTime &rt1 = *t1;
//cout << "ref-to-an-object: " << rt1 << " , orig: " << t1 << "ref to ref to object: tbd " << endl;
cout << "address of ref: " << &rt1 << " , and address of orig: " << t1 << endl;
cout << "sizeof of ref: " << sizeof(rt1) << " , and size of orig: " << sizeof(*t1) << endl;
cout << "Object t1: " << t1->getCurrentTime() << endl;
sleep(5);
cout << "Object t1 again: " << t1->getCurrentTime() << endl;
sleep(10);
t2 = TestTime::getTimeInstance();
cout << "Object t2: " << t2->getCurrentTime() << endl;
cout << "\n main leaving, destructor should get called..." << endl;
//TestTime::destructTimerInstance();
return 0;
}
#endif
|
//
// Created by 송지원 on 2019-10-23.
//
#include "iostream"
using namespace std;
int main() {
int n, i;
scanf("%d", &n);
for (i=1; i<10; i++){
printf("%d * %d = %d\n", n, i, n*i);
}
}
|
/*The function should return the modified array
as specified in the problem statement */
vector<int> threeWayPartition(vector<int> A, int a, int b)
{
// only gravity will pull me down
// Three way partitioning
int lo = 0, hi = A.size()-1, i = 0;
while(i <= hi) {
if (A[i] < a)
swap(A[i++], A[lo++]);
else if (A[i] > b)
swap(A[i], A[hi--]);
else
i++;
}
return A;
}
|
#include "GeneticOperator.h"
Crossover::Crossover()
{
}
chromosomePair Crossover::crossover(chromosomePair parents)
{
int tmp1, tmp2, tmp3;
tmp1 = (rand() % 1028) + 1;
Sleep(1);
tmp2 = (rand() % 100) * (rand() % 200);
Sleep(1);
tmp3 = (((rand() % 2048) * tmp2) + tmp1) % 4096;
int breakingPoint = (tmp3 % 69) + 1;
brokenChromosome parent1 = breakChromosome(breakingPoint, parents.first.getStrategy());
brokenChromosome parent2 = breakChromosome(breakingPoint, parents.second.getStrategy());
string strategyOff1 = parent1.first + parent2.second;
string strategyOff2 = parent2.first + parent1.second;
Chromosome child1(strategyOff1);
Chromosome child2(strategyOff2);
return make_pair(child1, child2);
}
brokenChromosome Crossover::breakChromosome(int breakingPoint, string parentsStrategy)
{
brokenChromosome result;
result.first = "";
result.second = "";
for (int i = 0; i < breakingPoint; i++)
result.first += parentsStrategy[i];
for (int i = breakingPoint; i < 70; i++)
result.second += parentsStrategy[i];
return result;
}
Mutation::Mutation()
{
}
Chromosome Mutation::mutation(Chromosome individual)
{
string newStrategy = individual.getStrategy();
bool different = true;
vector<int> mutatedLocuses;
int tmp1, tmp2, tmp3;
tmp1 = (rand() % 1028) + 1;
Sleep(1);
tmp2 = (rand() % 100) * (rand() % 200);
Sleep(1);
tmp3 = (((rand() % 2048) * tmp2) + tmp1) % 4096;
int numberOfLocuses = (tmp3 % 3) + 1;
int mutationLocus;
for (int i = 0; i < numberOfLocuses; i++)
{
do
{
mutationLocus = rand() % 70;
for (int tmp : mutatedLocuses)
{
if (tmp == mutationLocus)
{
different = false;
break;
}
else
different = true;
}
} while (different == false);
if (newStrategy[mutationLocus] == 'C')
newStrategy[mutationLocus] = 'D';
else
newStrategy[mutationLocus] = 'C';
mutatedLocuses.push_back(mutationLocus);
}
mutatedLocuses.empty();
Chromosome mutated(newStrategy);
return mutated;
}
|
/*
该函数只返回n的一个因数,可以通过和Miller Rabin配合来进行质因数分解。
*/
ll pollard_rho(ll n)
{
ll i, x, y, k, d,c;
while(true)
{
c=rand()%(n-1)+1; //f(x)=x^2-c
i = 1;
y=x = rand() % (n-1)+1;
k = 2;
while(true)
{
i++;
d = gcd(y-x+n, n);
if (d > 1 && d < n) return d;
if (i == k) y = x, k *= 2;
x = (mod(x, x, n) + n - c) % n;
if(x==y) break;
}
}
}
|
#pragma once
//////////////////////////////////////////////////////////////////////////
// ExpandCollapseControl.h - Provides expand and collapse functionality//
// to hide and unhide data on web browser //
// //
// Language: Visual C++ 2015 //
// Platform: MicroSoft Surface Pro, Windows 10 //
// Application: Code Publisher - CSE 687 Project 3 //
// Author: Manasa Malali Nagabhushana SUID:845368670 //
//////////////////////////////////////////////////////////////////////////
#include<string.h>
#include<unordered_map>
#include<iostream>
#include<vector>
#include<stack>
#include<unordered_set>
#include "../AbstractSyntaxTree/AbstrSynTree.h"
#include"../Parser/ActionsAndRules.h"
using namespace CodeAnalysis;
class ExpandCollapse {
public:
ExpandCollapse();
void TreeWalkDemo(ASTNode* root);
std::unordered_map<std::string, std::vector<std::pair<int, int>>> RetrieveFileLength();
void CheckType(ASTNode* root, std::pair<int, int> lcount);
private:
std::string newType;
AbstrSynTree &node;
std::unordered_map<std::string, std::vector<std::pair<int, int>>> FileLength;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "adjunct/desktop_pi/desktop_file_chooser.h"
#include "adjunct/desktop_util/file_chooser/file_chooser_fun.h"
#include "adjunct/desktop_util/sessions/opsessionmanager.h"
#include "adjunct/quick/ClassicApplication.h"
#include "adjunct/quick/application/SessionLoadContext.h"
#include "adjunct/quick/dialogs/SessionManagerDialog.h"
class CreateSessionSelectionListener : public DesktopFileChooserListener
{
public:
DesktopFileChooserRequest& GetRequest() { return request; }
CreateSessionSelectionListener(ClassicApplication& application, BOOL insert)
: m_application(&application), insert(insert) {}
void OnFileChoosingDone(DesktopFileChooser* chooser, const DesktopFileChooserResult& result)
{
if (result.files.GetCount())
{
OpFile file;
OP_STATUS err = file.Construct(result.files.Get(0)->CStr());
if (OpStatus::IsSuccess(err))
{
OpSharedPtr<OpSession> session(g_session_manager->CreateSessionFromFileL(&file));
OpStatus::Ignore(m_application->CreateSessionWindows(session, insert));
}
}
}
private:
DesktopFileChooserRequest request;
ClassicApplication* m_application;
BOOL insert;
};
SessionLoadContext::SessionLoadContext(ClassicApplication& application)
: m_application(&application)
, m_chooser(NULL)
, m_chooser_listener(NULL)
{}
SessionLoadContext::~SessionLoadContext()
{
OP_DELETE(m_chooser_listener);
m_chooser_listener = NULL;
OP_DELETE(m_chooser);
m_chooser = NULL;
}
BOOL SessionLoadContext::OnInputAction(OpInputAction* action)
{
switch (action->GetAction())
{
case OpInputAction::ACTION_GET_ACTION_STATE:
{
OpInputAction* child_action = action->GetChildAction();
switch (child_action->GetAction())
{
case OpInputAction::ACTION_REOPEN_WINDOW:
{
int index = child_action->GetActionData();
OpSession *session = m_closed_sessions.Get(index);
BOOL enabled = (session != NULL);
child_action->SetEnabled(enabled);
return TRUE;
}
}
break;
}
case OpInputAction::ACTION_INSERT_SESSION:
case OpInputAction::ACTION_OPEN_SESSION:
{
if (!m_chooser)
RETURN_VALUE_IF_ERROR(DesktopFileChooser::Create(&m_chooser), TRUE);
BOOL insert = (action->GetAction() == OpInputAction::ACTION_INSERT_SESSION);
CreateSessionSelectionListener *selection_listener = OP_NEW(CreateSessionSelectionListener, (*m_application, insert));
if (selection_listener)
{
m_chooser_listener = selection_listener;
DesktopFileChooserRequest& request = selection_listener->GetRequest();
request.action = DesktopFileChooserRequest::ACTION_FILE_OPEN;
OpString tmp_storage;
request.initial_path.Set(g_folder_manager->GetFolderPathIgnoreErrors(OPFILE_SESSION_FOLDER, tmp_storage));
g_languageManager->GetString(Str::S_SELECT_SESSION_FILE, request.caption);
OpString filter;
OP_STATUS rc = g_languageManager->GetString(Str::SI_WIN_SETUP_FILES, filter);
if (OpStatus::IsSuccess(rc) && filter.HasContent())
{
StringFilterToExtensionFilter(filter.CStr(), &request.extension_filters);
}
DesktopWindow* parent = m_application->GetActiveDesktopWindow(FALSE);
OpStatus::Ignore(m_chooser->Execute(parent ? parent->GetOpWindow() : NULL, selection_listener, request));
}
return TRUE;
}
case OpInputAction::ACTION_REOPEN_WINDOW:
{
int index = action->GetActionData();
OpSharedPtr<OpSession> session(m_closed_sessions.Get(index));
if (OpStatus::IsSuccess(m_application->CreateSessionWindows(session)))
m_closed_sessions.Remove(index);
break;
}
case OpInputAction::ACTION_SELECT_SESSION:
{
INT32 session_no = action->GetActionData();
if (session_no + 1 == 0)
{
SessionManagerDialog* dialog = OP_NEW(SessionManagerDialog, (*m_application));
if (dialog)
dialog->Init(m_application->GetActiveDesktopWindow(TRUE));
return TRUE;
}
OpSharedPtr<OpSession> session(g_session_manager->ReadSession(session_no));
OpStatus::Ignore(m_application->CreateSessionWindows(session));
return TRUE;
}
}
return FALSE;
}
|
#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <set>
#include <stack>
#include <cstdio>
#include <cstring>
#include <climits>
#include <cstdlib>
using namespace std;
int main() {
int n;
scanf("%d", &n);
int high = 0, low = 0;
bool same = true;
int a[4];
memset(a, 0, 4 * sizeof(int));
int tmp = n, cnt = 0;
while (tmp != 0) {
a[cnt++] = tmp % 10;
tmp /= 10;
}
for (int i = 0; i < 3; i++) {
if (a[i] != a[i + 1]) {
same = false;
break;
}
}
if (same) {
printf("%04d - %04d = 0000\n", n, n);
}
else {
const int target = 6174;
int diff = 0;
while (diff != target) {
sort(a, a + 4);
high = 0; low = 0;
for (int i = 0; i < 4; i++) {
high += a[i] * pow(10, i);
low += a[i] * pow(10, 3 - i);
}
diff = high - low;
printf("%04d - %04d = %04d\n", high, low, diff);
cnt = 0;
tmp = diff;
memset(a, 0, 4 * sizeof(int));
while (tmp != 0) {
a[cnt++] = tmp % 10;
tmp /= 10;
}
}
}
return 0;
}
|
#include "GnMeshPCH.h"
#include "GnGamePCH.h"
#include "GLayer.h"
GnInterfacePtr GLayer::smpModalInterface = NULL;
void GLayer::SetModalState(GnInterface* pModalInterface)
{
smpModalInterface = pModalInterface;
}
GnInterface* GLayer::GetModalState()
{
return smpModalInterface;
}
void GLayer::AddChild(GnInterface* pObject)
{
AddChild(pObject, 0 );
}
void GLayer::AddChild(GnInterface* pObject, int iZOrder)
{
// if( pObject->GetChildrenSize() == 0 )
// {
addChild( pObject->GetParentUseNode(), iZOrder );
// }
// else
// {
//
// for ( gtuint i = 0 ; i < pObject->GetChildrenSize(); i++ )
// {
// GnInterface* child = pObject->GetChild( i );
// addChild( child->GetParentUseNode(), iZOrder++ );
// }
// }
mInterfaceChildren.Add( pObject );
}
void GLayer::RemoveChild(GnInterface* pObject)
{
mInterfaceChildren.RemoveAndFill( pObject );
}
void GLayer::ccTouchesBegan(CCSet* pTouches, CCEvent* event)
{
if( smpModalInterface )
{
GnInterfacePtr ptr = smpModalInterface;
for( CCSetIterator it = pTouches->begin(); it != pTouches->end(); ++it )
{
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->locationInView( touch->view() );
ptr->Push( touchPoint.x, touchPoint.y );
}
return;
}
for( CCSetIterator it = pTouches->begin(); it != pTouches->end(); ++it )
{
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->locationInView( touch->view() );
for ( gtuint i = 0 ; i < mInterfaceChildren.GetSize(); i++ )
{
GnInterface* child = mInterfaceChildren.GetAt( i );
if( child->Push( touchPoint.x, touchPoint.y ) )
{
child->SetCurrentTouch( touch );
break;
}
}
}
}
void GLayer::ccTouchesMoved(CCSet* pTouches, CCEvent* event)
{
if( smpModalInterface )
{
GnInterfacePtr ptr = smpModalInterface;
for( CCSetIterator it = pTouches->begin(); it != pTouches->end(); ++it )
{
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->locationInView( touch->view() );
ptr->PushMove( touchPoint.x, touchPoint.y );
}
return;
}
for( CCSetIterator it = pTouches->begin(); it != pTouches->end(); ++it )
{
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->locationInView( touch->view() );
for ( gtuint i = 0 ; i < mInterfaceChildren.GetSize(); i++ )
{
GnInterface* child = mInterfaceChildren.GetAt( i );
if( touch == child->GetCurrentTouch() )
child->PushMove( touchPoint.x, touchPoint.y );
}
}
}
void GLayer::ccTouchesEnded(CCSet* pTouches, CCEvent* event)
{
if( smpModalInterface )
{
GnInterfacePtr ptr = smpModalInterface;
for( CCSetIterator it = pTouches->begin(); it != pTouches->end(); ++it )
{
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->locationInView( touch->view() );
ptr->PushUp( touchPoint.x, touchPoint.y );
}
return;
}
for( CCSetIterator it = pTouches->begin(); it != pTouches->end(); ++it )
{
CCTouch* touch = (CCTouch*)(*it);
CCPoint touchPoint = touch->locationInView( touch->view() );
for ( gtuint i = 0 ; i < mInterfaceChildren.GetSize(); i++ )
{
GnInterface* child = mInterfaceChildren.GetAt( i );
if( touch == child->GetCurrentTouch() )
{
if( child->PushUp( touchPoint.x, touchPoint.y ) )
break;
}
else
{
child->PushUpPersonalChildren( touchPoint.x, touchPoint.y );
}
}
}
}
void GDrawActorController::Draw()
{
Gn2DAVData* avData = mpController->GetMesh()->GetAVData();
if( avData == NULL )
return;
GnColorA tempColor = mColor;
for( gtuint i = 0 ; i < avData->GetCollisionCount() ; i++ )
{
GnColorA color[Gg2DCollision::COLLISION_MAX] =
{
GnColorA( 255, 255, 0, 1 ),
GnColorA( 155, 155, 0, 1 )
};
Gn2DAVData::CollisionRect drawRect = avData->GetCollisionRect( i );
mColor = color[drawRect.mType];
DrawRect( drawRect.mRect );
}
Gn2DSequence* attackSequence = NULL;
if( mpController->GetActor()->GetSequence( 3, attackSequence ) == false )
{
GnLogA( "Failed Load AttackSquence");
return;
}
Gn2DAVData* avDataAttack = attackSequence->GetAVData();
if( avDataAttack->GetCollisionCount() > 1 )
{
avDataAttack->Move( mpController->GetMesh()->GetOriginalPosition() );
if( mpController->GetMesh()->GetFlipX() )
{
avDataAttack->FlipX( true, mpController->GetMesh()->GetOriginalPosition().x );
}
mColor = GnColorA( 0, 0, 255, 1 );
Gn2DAVData::CollisionRect attackRect = avDataAttack->GetCollisionRect( 1 );
//float scale = attackRect.mRect.GetWidth() * GetGameState()->GetGameScale();
//attackRect.mRect.SetWidth( scale );
//scale = attackRect.mRect.GetHeight() * GetGameState()->GetGameScale();
//attackRect.mRect.SetHeight( scale );
DrawRect( attackRect.mRect );
}
float temp = mThickness;
mThickness = 5;
mColor = GnColorA( 0, 255, 255, 1 );
GnVector2 point = avData->GetImageCenter();
point += mpController->GetMesh()->GetPosition();
DrawPoint( point );
mColor = GnColorA( 0, 0, 255, 1 );
mThickness = temp;
mColor = tempColor;
}
void GDrawFarAttack::Draw()
{
mColor = GnColorA( 255, 0, 0, 1 );
DrawRect( mpFarAttack->GetAttackRect() );
}
void GnExtraDataPrimitivesLayer::Draw()
{
if( mpMeshObject == NULL )
return;
for( gtuint i = 0; i < mpMeshObject->GetExtraDataSize(); i++ )
{
GnVector2ExtraData* vec2Data = GnDynamicCast(GnVector2ExtraData, mpMeshObject->GetExtraData( i ));
if( vec2Data )
{
GnVector2 point = vec2Data->GetValueVector2();
point += mpMeshObject->GetPosition();
DrawPoint( point );
}
}
}
|
//
// Created by HHPP on 2020/4/30.
//
#include "Polygon.h"
#include "Point.h"
#include "Line.h"
Polygon::Polygon(int n, double ** p) {
num=n;
poly=new Point[n];
for(int i=0;i<n;i++){
poly[i].x=p[i][0];
poly[i].y=p[i][1];
}
}
double Polygon::largestX() {
double largestX=poly[0].x;
double largest=poly[0].y;
for(int i=1;i<num;i++){
if(poly[i].y>largest){
largest=poly[i].y;
largestX=poly[i].x;
}
}
return largestX;
}
double Polygon::largestY() {
double largest=poly[0].y;
for(int i=1;i<num;i++){
if(poly[i].y>largest){
largest=poly[i].y;
}
}
return largest;
}
double Polygon::lowestY() {
double lowest=poly[0].y;
for(int i=1;i<num;i++){
if(poly[i].y<lowest){
lowest=poly[i].y;
}
}
return lowest;
}
double Polygon::leftMostX() {
double result=poly[0].x;
for(int i=1;i<num;i++){
if(poly[i].x<result){
result=poly[i].x;
}
}
return result;
}
double Polygon::leftMostY() {
double result=poly[0].x;
double resultY=poly[0].y;
for(int i=1;i<num;i++){
if(poly[i].x<result){
result=poly[i].x;
resultY=poly[i].y;
}
}
return resultY;
}
double Polygon::rightMostX() {
double result=poly[0].x;
for(int i=1;i<num;i++){
if(poly[i].x>result){
result=poly[i].x;
}
}
return result;
}
double Polygon::rightMostY() {
double result=poly[0].x;
double resultY=poly[0].y;
for(int i=1;i<num;i++){
if(poly[i].x>result){
result=poly[i].x;
resultY=poly[i].y;
}
}
return resultY;
}
bool Polygon::Outside(Point random) {
int count=0;
for(int i=0;i<num-1;i++){
Line l(poly[i],poly[i+1]);
double intersect=l.fromXtoY(random.getX());
if(intersect>random.getY()){
count++;
}
}
Line final(poly[num-1],poly[0]);
if(final.fromXtoY(random.getX())>random.getY()){
count++;
}
if(count%2==0){
return true;
}
else{
return false;
}
}
|
#pragma GCC optimize("Ofast")
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <iterator>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
struct BstNode
{
int data;
BstNode* left;
BstNode* right;
};
BstNode* rootptr = NULL;
BstNode* GetNewNode(int data) {
BstNode* newNode = new BstNode(); // returns back the address the new node
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode; // address of newNode
}
void insert(BstNode* &rootptr, int data) {
if(rootptr == NULL) {
rootptr = GetNewNode(data);
return;
}
else if(data < rootptr->data) {
insert(rootptr->left,data);
}
else {
insert(rootptr->right, data);
}
// (data > rootptr->data)? insert(rootptr->right,data) : insert(rootptr->left, data);
}
void min(BstNode* &rootptr) {
while(rootptr->left != NULL) {
rootptr = rootptr->left;
}
// rootptr = rootptr->right;
}
bool search(BstNode* rootptr, int data) {
// cout << data << endl;
if(rootptr == NULL) return false;
if(rootptr->data == data) return true;
else if(data <= rootptr->data) return search(rootptr->left,data);
else return search(rootptr->right, data);
}
void Delete(BstNode* &rootptr, int data) {
if(rootptr == NULL ) return;
else if(data < rootptr->data) Delete(rootptr->left, data);
else if(data > rootptr->data) Delete(rootptr->right, data);
else { // Wohoo, we finally found the node, now we can delete it 😈
// Case 1: No Child
if(rootptr->left == NULL && rootptr->right == NULL) {
delete rootptr;
rootptr = NULL;
}
// Case 2: One Child
else if(rootptr->left == NULL) {
BstNode* temp = rootptr;
// delete rootptr;
rootptr = rootptr->left;
delete temp;
}
else if(rootptr->right == NULL) {
BstNode* temp = rootptr;
rootptr = rootptr->right;
delete temp;
}
// Case 3: Two Children
else {
BstNode* temp = min(rootptr->right);
rootptr->data = temp->data;
Delete(rootptr->right, temp->data);
}
}
}
int main(int argc, char* argv[]) {
abhisheknaiidu();
insert(rootptr, 5);
insert(rootptr, 3);
insert(rootptr, 1);
insert(rootptr,10);
insert(rootptr,4);
insert(rootptr,11);
int n;
cin >> n;
if(search(rootptr, n) == true) cout << "Found" << endl;
else cout << "Not Found";
Delete(rootptr, n)
// search(rootptr, 20);
// Iterative Version:
// Node *newNode(int key)
// {
// Node *node = new Node;
// node->data = key;
// node->left = node->right = nullptr;
// return node;
// }
// void insert(Node **headref, int data)
// {
// if (*headref == NULL)
// {
// *headref = newNode(data);
// return;
// }
// Node *travptr = *headref;
// Node *parentNode = NULL;
// while (travptr != NULL)
// {
// parentNode = travptr;
// travptr = (data > travptr->data) ? travptr->right : travptr->left;
// }
// if (data > parentNode->data)
// parentNode->right = newNode(data);
// else
// parentNode->left = newNode(data);
// }
// bool find(Node **headref, int data)
// {
// Node *travptr = *headref;
// if (data == (*headref)->data)
// return true;
// while (travptr != NULL && travptr->data != data)
// travptr = (data > travptr->data) ? travptr->right : travptr->left;
// if (travptr == NULL)
// {
// return false;
// }
// return true;
// }
return 0;
}
|
#include "ros/ros.h"
#include <ros/package.h> //not sure if needed
// #include "std_msgs/String.h"
#include <std_msgs/Int32MultiArray.h>
#include <std_msgs/Float32MultiArray.h>
#include<geometry_msgs/PoseStamped.h>
#include "mission/maintomission.h"
#include <std_msgs/Int32.h>
#include <sstream>
#include <stdio.h>
#include <iostream>
#include <string>
#include<queue>
#include<vector>
#include<math.h>
using namespace std;
#include "mission/mission_action.h"
ros::Publisher tomain;
ros::Publisher forST2_little;
ros::Publisher forplaner;
std_msgs::Int32MultiArray for_ST2_little;
ros::Publisher forST2_littlecom;
ros::Subscriber sub;
ros::Subscriber subplaner;
ros::Subscriber subST2_little;
std_msgs::Int32 to_main;
std_msgs::Float32MultiArray for_planer;
float planer_rx = 9;
std::vector<int> ST2_little_rx{0,0,0,0,0,0,0,0,0};
int initialize = 1;
// int planer_tx = 88;
std::vector<int> hand{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
std::vector<float> planer_tx{0,0,0};
std::vector<int> ST2_little_tx{0,0,0};
std::vector<int> claw{0,0,0,0,0};
std::vector<int> claw_color{0,0,0,0,0};
std::vector<int> reefl_color{2, 3, 2, 3, 2};
std::vector<int> reefr_color{3, 2, 3, 2, 3};
std::vector<int> reefp_color{2, 3, 2, 3, 2};
std::vector<int> reef_null{0, 0, 0, 0, 0};
int state_planer = 0;
int state_ST2_little = 0;
int state_mission = 2;
int success = 1, fail = 0, ing = 2, stop = 3;
int tx = 101;
int team;
int data_len = 9;
bool publish_planer;
class mission_setting{
public:
int mission_no;
string mission_name;
int count;
int count_planer = 0;
int count_ST2_little = 0;
int action[10];
int prepare;
mission_setting(int num, string name, int no, int pre){//int array[],
mission_no = num;
mission_name = name;
count = no;
// for( int i = 0; i < 10; i++){
// action[ i ] = array[ i ];
// }
prepare = pre;
// setting_( num, name, count );
}
}; mission_setting emergency(0, "emergency", 0, 0);//[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
mission_setting windsock( 1, "windsock", 0, 1);
mission_setting lhouse(2, "lhouse", 0, 2);
mission_setting flag( 3, "flag", 0, 0);
mission_setting anchorN(4, "anchorN", 0, 0);
mission_setting anchorS(5, "anchorS", 0, 0);
mission_setting reef_l( 6, "reef_l", 0, 0);
mission_setting reef_r( 7, "reef_r", 0, 0);
mission_setting reef_p( 8, "reef_p", 0, 0);
mission_setting placecup_h( 9, "placecup_h", 0, 0);
mission_setting placecup_p( 10, "placecup_p", 0, 0);
mission_setting placecup_r( 11, "placecup_r", 0, 0);
mission_setting getcup(12, "getcup", 0, 0);
mission_setting getcup_12( 13, "getcup_12", 0, 0);
mission_setting getcup_34( 14, "getcup_34", 0, 0);
void publish_ST2_little(int platform, int servo, int claw ){//
ST2_little_tx[0] = platform;// up down of platform
ST2_little_tx[1] = servo;//windsock servo and tightness servo
ST2_little_tx[2] = claw;// determine servos open or close
// for ( int i = 0; i < 9; i++){
// for_ST2_little.data.push_back(ST2_little_tx[i]);
// // ROS_INFO("publish in for %d ", ST2_little_tx[i]);
// }
// ROS_INFO("publish ST2_little %d %d %d", ST2_little_tx[0], ST2_little_tx[1], ST2_little_tx[2]);
// forST2_little.publish(for_ST2_little);
// // ST2_little_tx.clear();
// for_ST2_little.data.clear();
}
bool checkST2_state(std::vector<int> &tx){
// if st2 tx == rx
int state = 1;
for ( int i = 0; i < data_len; i++){
if ( tx[i] != ST2_little_rx[i]){
state = 0;
break;
}
}
return state;
}
void publish_planner(){
for_planer.data.push_back(planer_tx[0]);
for_planer.data.push_back(planer_tx[1]);
for_planer.data.push_back(planer_tx[2]);
forplaner.publish(for_planer);
for_planer.data.clear();
}
int claw_trans( std::vector<int> &vector ){
int temp = 0;
for ( int i = 0; i < vector.size(); i++){
if ( vector[i] == 1){
temp += pow( 2, i );
}
}
ROS_INFO(" check %d", temp);
return temp;
}
void claw_action(int color, int state, std::vector<int> &reef_color){
switch (state)
{
case 0:{ // placecup depending on color determine which claw to open
for ( int i = 0; i < claw_color.size(); i++){
if ( claw_color[i] == color){
claw[i] = 1;
claw_color[i] = reef_color[i];
ROS_INFO("claw action servo :%d action : %d", i, claw[i] );
}
ROS_INFO("claw color %d", reef_color[i] );
}
break;
}
case 1:{ // getcup
for ( int i = 0; i < claw.size(); i++){
claw[i] = 0; // 0 for close 1 for open
claw_color[i] = reef_color[i];
ROS_INFO("claw color %d", reef_color[i] );
}
break;
}
default:
break;
}
if ( state_planer == 1){
int hd = claw_trans(claw);
publish_ST2_little( 3, 2, hd);
}
if ( state_ST2_little == 1){
state_mission = success;
// for ( int i = 0; i < reef_color.size(); i++){
// claw_color[i] = reef_color[i];
// ROS_INFO("claw color %d", reef_color[i] );
// }
}
else{
state_mission = ing;
}
}
int degree_transform( int d ){
int theta;
theta = d;
return theta;
}
void init(){
ROS_INFO("initialize");
}
void chatterCallback_planer(const std_msgs::Int32MultiArray::ConstPtr& msg)
{
// ROS_INFO("I heard action: [%d]", msg->data[0]);
state_planer = msg -> data[0] ;
}
void chatterCallback_ST2_little(const std_msgs::Int32MultiArray::ConstPtr& msg)
{
// ROS_INFO("I heard ST2_little: [%d]", msg->data[0]);
for ( int i = 0; i < data_len; i++){
ST2_little_rx[i] = msg -> data[i];
}
}
void chatterCallback(const mission::maintomission::ConstPtr& msg)
{
ROS_INFO("I heard action: [%d]", msg->action);
tx++;
state_planer = msg->planer_state;
team = msg->team;
// initialize here st2 will give number 5 initially
// if ( initialize == 1 && ST2_little_rx[0] == 5){
// init();
// initialize = 0;
// }
switch (msg->action)
{
case 0: //emergency
state_mission = stop;
break;
case 3: // flag
state_mission = success;
break;
case 4: // anchorN
state_mission = success;
break;
case 5: // anchorS
state_mission = success;
break;
case 6: // reef_l
if ( state_planer == 1){
if ( reef_l.count == 0){ // open claw
state_mission = ing;
ST2_little_tx[0] = 0;
for ( int i = 1; i < 9; i++){
ST2_little_tx[i] = 1;
}
}
else if ( checkST2_state(ST2_little_tx) == 1 && reef_l.count == 1){ // lower platform
ST2_little_tx[0] = 0;
for ( int i = 1; i < 8; i++){
ST2_little_tx[i] = 1;
}
ST2_little_tx[8] = 2;
}
else if ( checkST2_state(ST2_little_tx) == 1 && reef_l.count == 2){ // raise platform
ST2_little_tx[0] = 0;
for ( int i = 1; i < 8; i++){
ST2_little_tx[i] = 1;
}
ST2_little_tx[8] = 1;
}
else if ( checkST2_state(ST2_little_tx) == 1 && reef_l.count == 3){
state_mission = success;
reef_l.count = 0;
}
}
claw_action(0,1, reefl_color);
break;
case 7: // reef_r
claw_action(0,1, reefr_color);
break;
case 8: // reef_p
claw_action(0,1, reefp_color);
break;
case 11: // placecup_r
for ( int color = 2; color <= 3; color ++){
claw_action(color, 0, reef_null);
}
// state_mission = success;
break;
// case 12:{
// ST2_little_tx[0] = 8787;
// for_ST2_little.data[0] = ST2_little_tx[0];
// forST2_little.publish(for_ST2_little);
// break;
// }
default:
break;
}
// ROS_INFO("hand vector: ");
// for( int i = 0; i < 13; i ++){
// ROS_INFO("%d, ", hand[i]);
// }
// ROS_INFO("\n");
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "mission");
ros::NodeHandle n;
forplaner = n.advertise<std_msgs::Float32MultiArray>("MissionToplaner", 1);
forST2_little = n.advertise<std_msgs::Int32MultiArray>("MissionToST2_little", 1);
forST2_littlecom = n.advertise<std_msgs::Int32MultiArray>("txST1", 1);
// ros::Publisher forNavigation = n.advertise<geometry_msgs::PoseStamped>("move_base_simple/goal", 1);
// ros::Publisher forplaner = n.advertise<std_msgs::String>("forplaner", 1);
// ros::Publisher forST2_little = n.advertise<std_msgs::String>("forST2_little", 1);
tomain = n.advertise<std_msgs::Int32>("MissionToMain", 100);
sub = n.subscribe("MainToMission", 1000, chatterCallback);
subplaner = n.subscribe("planerToMission", 1000, chatterCallback_planer);
subST2_little = n.subscribe("ST2_littleToMission", 1000, chatterCallback_ST2_little);
// ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
ros::Rate loop_rate(10);
int count = 0;
while (ros::ok())
{
for ( int i = 0; i < data_len; i++){
for_ST2_little.data.push_back(ST2_little_tx[i]);
// ROS_INFO("publish in for %d ", ST2_little_tx[i]);
}
forST2_little.publish(for_ST2_little);
for_ST2_little.data.clear();
// to_main.state = state_mission;
to_main.data = state_mission;
tomain.publish(to_main);
ros::spinOnce();
loop_rate.sleep();
++count;
}
return 0;
}
|
#pragma once
namespace Move
{
class Kalman
{
float q; //process noise covariance
float r; //measurement noise covariance
float x; //value
float p; //estimation error covariance
float k; //kalman gain
bool firstValue;
public:
Kalman()
{
p=0.47f;
q=0.0625f;
r=4.0f;
firstValue=true;
}
void init(float p, float q, float r)
{
this->p=p;
this->q=q;
this->r=r;
}
float update(float measurement)
{
if (measurement!=measurement)
return x;
if (firstValue)
{
firstValue=false;
x=measurement;
return x;
}
//prediction update
//omit x = x
p = p + q;
//measurement update
k = p / (p + r);
x = x + k * (measurement - x);
p = (1 - k) * p;
return x;
}
};
}
|
/**
* @file
* @brief Implementation of user class MyHit.
*/
#include "MyHit.hh"
#include "G4SystemOfUnits.hh"
//using namespace CLHEP;
// -- one more nasty trick for new and delete operator overloading:
G4Allocator<MyHit> MyHitAllocator;
MyHit::MyHit(const G4int Detector_ID, const G4bool isPrimary, const G4String name)
: DetectorID(Detector_ID), DetectorName(name), isPrimary(isPrimary)// <<-- note BTW this is the only way to initialize a "const" member
{
eDep = 0.0;
}
MyHit::~MyHit()
{
}
void MyHit::Print()
{
G4cout<<"Hit: DetectorID= "<<DetectorID<<"\t eDep= "<<eDep/keV<<" keV, isPrimary="<<(isPrimary?"true":"false")<<G4endl;
G4cout<<"\tGlobal Time = "<<globalTime/ns<<"\tLocal Time = "<<localTime/ns<<G4endl<<G4endl;
}
|
#include <iostream>
#include <gl/glut.h>
#include<windows.h>
#include <math.h>
#include "object.h"
using namespace std;
Object object = Object();
void chessboard()
{
glClearColor(0, 1, 1, 0);// For displaying the window color
glMatrixMode(GL_PROJECTION);// Choosing the type of projection
glLoadIdentity();
gluOrtho2D(0, 800, 0,800);// for setting the transformation which here is 2D
int c = 0;
glClear(GL_COLOR_BUFFER_BIT);
GLint x, y;
//Chessboard
for (x = 0; x <= 800; x += 100)
{
for (y = 0; y <= 800; y += 100)
{
// if color is 0 then draw white box and change value of color = 1
if (c == 0)
{
glColor3f(0.945f, 0.980f, 0.933f); //white color
c = 1;
}
// if color is 1 then draw black box and change value of color = 0
else
{
glColor3f(0.478f, 0.231f, 0.043f); // brown color
c = 0;
}
object.drawSquare(x, y + 100, x + 100, y + 100, x + 100, y, x, y);
}
}
//Chess Pieces
glColor3f(0.105, 0.094, 0.066); // Black Chess Pieces
glScalef(1.0,1.0,1.0);
object.drawRook(50,50);
object.drawKnight(150,50);
object.drawKnight(550,250);
object.drawBishop(250,50);
object.drawBishop(550,50);
object.drawQueen(350,50);
object.drawKing(450,50);
glPushMatrix();
for(int i = 0; i < 5 ; i++)
{
object.drawPawn(450,150);
glTranslatef(100,0,0);
}
glPopMatrix();
object.drawPawn(50,150);
object.drawPawn(150,150);
object.drawPawn(250,350);
object.drawPawn(350,350);
object.drawRook(750,50);
glColor3f(0.701, 0.521, 0.384); // Brown Chess Pieces
glScalef(1.0,1.0,1.0);
object.drawRook(750,750);
object.drawKnight(650,750);
object.drawKnight(250,550);
object.drawBishop(250,750);
object.drawBishop(550,750);
object.drawQueen(350,750);
object.drawKing(450,750);
glPushMatrix();
for(int i = 0; i < 5 ; i++)
{
object.drawPawn(450,650);
glTranslatef(100,0,0);
}
glPopMatrix();
object.drawPawn(50,650);
object.drawPawn(150,650);
object.drawPawn(250,450);
object.drawPawn(350,450);
object.drawRook(50,750);
glFlush();
glFinish();
}
int main(int agrc, char ** argv)
{
glutInit(&agrc, argv);// Initialize GLUT
// Set display mode
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);// Set top - left display window position.
glutInitWindowPosition(100, 100);
glutInitWindowSize(800, 800);// Set display window width and height
glutCreateWindow("Chess");// Create display window with the given title
glutDisplayFunc(chessboard);
glutMainLoop();
}
|
#include <iostream>
using namespace std;
template <typename T, typename U>
U sum(T a, U b){
return(a+b);
}
int main(){
int x = 7;
double y = 7.12;
cout << sum(x,y) << endl;
}
|
// octree_test.cpp
#include "../library/leap.h"
using namespace leap::system;
using namespace leap::rendering;
using namespace leap::world;
using namespace leap;
int main(int argc, char* argv[]) {
std::vector<vec3> loaded_chunks;
constexpr float CHUNK_REAL_EDGE = CHUNK_EDGE * BLOCK_EDGE;
constexpr float WORLD_REAL_HALF_WIDTH = WORLD_WIDTH_CHUNKS * CHUNK_REAL_EDGE / 2;
constexpr float WORLD_REAL_HALF_HEIGHT = WORLD_HEIGHT_CHUNKS * CHUNK_REAL_EDGE / 2;
for (int y_chunk = 0; y_chunk < WORLD_HEIGHT_CHUNKS; ++y_chunk) {
for (int z_chunk = 0; z_chunk < WORLD_WIDTH_CHUNKS; ++z_chunk) {
for (int x_chunk = 0; x_chunk < WORLD_WIDTH_CHUNKS; ++x_chunk) {
const math::vec3 loc{
static_cast<float>(x_chunk * CHUNK_REAL_EDGE - WORLD_REAL_HALF_WIDTH + CHUNK_REAL_EDGE / 2),
static_cast<float>(y_chunk * CHUNK_REAL_EDGE - WORLD_REAL_HALF_HEIGHT + CHUNK_REAL_EDGE / 2),
static_cast<float>(z_chunk * CHUNK_REAL_EDGE - WORLD_REAL_HALF_WIDTH + CHUNK_REAL_EDGE / 2)};
loaded_chunks.push_back(loc);
}
}
}
octree::Node<std::vector<std::size_t>>* root
= new octree::Node<std::vector<std::size_t>>({0, 0, 0}, WORLD_WIDTH_CHUNKS * CHUNK_EDGE * BLOCK_EDGE, 4);
for (std::size_t i = 0; i < loaded_chunks.size(); ++i) {
octree::v3i32 pos{
int32_t(math::floor(loaded_chunks[i].x())),
int32_t(math::floor(loaded_chunks[i].y())),
int32_t(math::floor(loaded_chunks[i].z())),
};
root->put(pos)->data().push_back(i);
}
for (auto& p : loaded_chunks) {
octree::v3i32 t{
int32_t(math::floor(p.x())),
int32_t(math::floor(p.y())),
int32_t(math::floor(p.z())),
};
const auto node = root->find(t);
LEAP_ASSERT(node != nullptr);
const auto data = node->data();
LEAP_ASSERT(data.size() == 1);
const auto& r = loaded_chunks[data[0]];
system::log_info(std::format("{}, {}, {}\t\t{}, {}, {}",
p.x(), p.y(), p.z(), r.x(), r.y(), r.z()));
LEAP_ASSERT(
p.x() == r.x() &&
p.y() == r.y() &&
p.z() == r.z());
}
delete root;
return 0;
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
map<LL,LL> val;
set<LL> S;
LL fa(LL u,LL v) {
S.clear();
while (u) {
S.insert(u);
u >>= 1;
}
while (v) {
if (S.count(v)) return v;
v >>= 1;
}
return 1;
}
void add(LL u,LL s,LL w) {
while (u > s) {
if (!val.count(u)) val[u] = w;
else val[u] += w;
//cout << u << " " << w <<endl;
u >>= 1;
}
}
LL query(LL u,LL s) {
LL ans = 0;
while (u > s) {
if (val.count(u)) ans += val[u];
//cout << u << " " << val[u] << endl;
u >>= 1;
}
return ans;
}
int main() {
int q;
scanf("%d",&q);
int op;LL u,v,w;
while (q--) {
scanf("%d%I64d%I64d",&op,&u,&v);
if (op == 1) {
scanf("%I64d",&w);
LL s = fa(u,v);
add(u,s,w);
add(v,s,w);
} else {
LL s = fa(u,v);
printf("%I64d\n",query(u,s)+query(v,s));
}
}
return 0;
}
|
#include <cstdio>
using namespace std;
/*
//3
int numMayor( int n1, int n2, int n3);
int main(){
int n1 = 4;
int n2 = 7;
int n3 = 3;
int mayor;
mayor = numMayor(n1,n2,n3);
printf("El mayor es %d", mayor);
}
int numMayor( int n1, int n2, int n3){
int mayor;
if ((n1>n2) && (n1>n3)){
mayor = n1;
}else{
if ((n2>n1) && (n2>n3)){
mayor = n2;
}else{
mayor = n3;
}
}
return mayor;
}
int cuentaCaracter(char car, int &cont){
cont = 0;
char c;
do{
printf("Introduzca un caracter(+,-,*,/): ");
scanf("%c", &c);
if (c == car){
cont = cont + 1;
}
}while (c != '.');
}
int cuentaCaracter(char c);
int main(){
char caracter;
int cont;
printf("que caracter desea contar: ");
scanf("%c", &caracter);
cuentaCaracter(caracter, cont);
printf("El numero de veces que aparece el caracter %c es: %d", caracter, cont);
}
//8
int factorial(int num){
int fact = 1;
for(int i=0 ;i < num; i++){
fact = fact * (i+1);
}
return fact;
}
int combinatorio(int m, int n){
int a = factorial(m);
int b = factorial(n);
int comb = 0.00;
int c = m - n;
comb = a/(b*factorial(c));
return comb;
}
int main(){
int a = 1;
int b = 3;
int c;
c = combinatorio(b,a);
printf("\n%d" , c);
}
//9
bool esPerfecto(int num){
int suma=0;
bool perfecto;
for(int i=1; i <= num/2; i++){
if(num % i == 0){
suma = suma +i;
}
}
perfecto= (suma == num);
return perfecto;
}
int main(){
int a = 6;
int m = 0;
int n = 3000;
for(int i=m; i<n; i++){
if(esPerfecto(i)){
printf("\n%d", i);
}
}
}*/
//10
|
#pragma once
#include <windows.h>
#include <iostream>
#include <TlHelp32.h>
#include "defines.h"
namespace driver
{
class kernel_interface
{
public:
HANDLE driver_handle;
kernel_interface(LPCSTR registry_path)
{
driver_handle = CreateFile(registry_path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
}
bool restore_original_drivercontrol()
{
if (driver_handle == INVALID_HANDLE_VALUE)
return false;
DWORD bytes;
bool returned = false;
if (DeviceIoControl(driver_handle, IO_RESTORE_ORIGINAL_DRIVERCONTROL, &returned, sizeof(returned), &returned, sizeof(returned), &bytes, NULL))
return returned;
}
template <typename T>
T read_virtual_memory(ULONG pid, ULONG source)
{
if (driver_handle == INVALID_HANDLE_VALUE)
{
return 0;
}
T buff;
KERNEL_MEMORY_REQUEST kernel_memory_request;
kernel_memory_request.pid = pid;
kernel_memory_request.source = reinterpret_cast<void*>(source);
kernel_memory_request.buffer = &buff;
kernel_memory_request.size = sizeof(T);
if (DeviceIoControl(driver_handle, IO_READ_VIRTUAL_MEMORY, &kernel_memory_request, sizeof(kernel_memory_request), &kernel_memory_request, sizeof(kernel_memory_request), 0, 0))
{
return buff;
}
return buff;
}
template <typename T>
bool write_virtual_memory(ULONG pid, ULONG source, T buffer)
{
if (driver_handle == INVALID_HANDLE_VALUE)
{
return false;
}
DWORD bytes;
KERNEL_MEMORY_REQUEST kernel_memory_request;
kernel_memory_request.pid = pid;
kernel_memory_request.source = reinterpret_cast<void*>(source);
kernel_memory_request.buffer = &buffer;
kernel_memory_request.size = sizeof(T);
if (DeviceIoControl(driver_handle, IO_WRITE_VIRTUAL_MEMORY, &kernel_memory_request, sizeof(kernel_memory_request), 0, 0, &bytes, NULL))
{
return true;
}
return false;
}
ULONG get_process_id(std::string process_name)
{
PROCESSENTRY32 processentry;
HANDLE snapshot_handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (snapshot_handle == INVALID_HANDLE_VALUE)
return NULL;
processentry.dwSize = sizeof(MODULEENTRY32);
while (Process32Next(snapshot_handle, &processentry))
{
if (process_name.compare(processentry.szExeFile) == NULL)
{
CloseHandle(snapshot_handle);
return processentry.th32ProcessID;
}
}
CloseHandle(snapshot_handle);
return NULL;
}
};
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2006-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Peter Krefting
*/
#include "core/pch.h"
#include "modules/prefs/prefsmanager/prefsnotifier.h"
#ifdef PREFS_NOTIFIER
#include "modules/prefs/prefsmanager/collections/pc_fontcolor.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/prefs/prefsmanager/prefsmanager.h"
#ifdef DYNAMIC_PROXY_UPDATE
void PrefsNotifier::OnProxyChangedL()
{
# ifdef PREFS_READ
// Load the preference file, since we need to check with it to see
// if the user has overridden the default settings.
PrefsFile *reader = const_cast<PrefsFile *>(g_prefsManager->GetReader());
reader->LoadAllL();
# endif
// Read proxy changes. Will broadcast changes if needed.
g_pcnet->ProxyChangedL();
# ifdef PREFS_READ
// Unload when we are done.
reader->Flush();
# endif
}
#endif
#ifdef PREFS_HAVE_REREAD_FONTS
void PrefsNotifier::OnFontChangedL()
{
# ifdef PREFS_READ
// Load the preference file, since we need to check with it to see
// if the user has overridden the default settings.
PrefsFile *reader = const_cast<PrefsFile *>(g_prefsManager->GetReader());
reader->LoadAllL();
# endif
// Read proxy changes. Will broadcast changes if needed.
g_pcfontscolors->FontChangedL();
# ifdef PREFS_READ
// Unload when we are done.
reader->Flush();
# endif
}
#endif
#ifdef PREFS_HAVE_NOTIFIER_ON_COLOR_CHANGED
void PrefsNotifier::OnColorChangedL()
{
# ifdef PREFS_READ
// Load the preference file, since we need to check with it to see
// if the user has overridden the default settings.
PrefsFile *reader = const_cast<PrefsFile *>(g_prefsManager->GetReader());
reader->LoadAllL();
# endif
// Read color changes. Will broadcast changes if needed.
g_pcfontscolors->ColorChangedL();
# ifdef PREFS_READ
// Unload when we are done.
reader->Flush();
# endif
}
#endif
#endif // PREFS_NOTIFIER
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2006 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef SVG_DOM_RECT_IMPL_H
#define SVG_DOM_RECT_IMPL_H
#include "modules/svg/svg_dominterfaces.h"
#include "modules/svg/src/SVGRect.h"
class SVGDOMRectImpl : public SVGDOMRect
{
public:
SVGDOMRectImpl(SVGRectObject* rect);
virtual ~SVGDOMRectImpl();
virtual const char* GetDOMName();
virtual SVGObject* GetSVGObject() { return m_rect; }
virtual OP_BOOLEAN SetX(double x);
virtual double GetX();
virtual OP_BOOLEAN SetY(double y);
virtual double GetY();
virtual OP_BOOLEAN SetWidth(double width);
virtual double GetWidth();
virtual OP_BOOLEAN SetHeight(double height);
virtual double GetHeight();
SVGRectObject* GetRect() { return m_rect; }
private:
SVGRectObject* m_rect;
};
#endif // !SVG_DOM_RECT_IMPL_H
|
#ifndef GLOBAL_H
#define GLOBAL_H
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
extern int modPart;
extern int display;
extern int showNormals;
extern int REAL;
extern int WIDTH;
extern int HEIGHT;
extern std::vector<int> NORMAL;
/*extern int LX;
extern int LY;
extern int LZ;*/
#endif // GLOBAL_H
|
// Copyright (c) 2007-2021 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/config.hpp>
#include <pika/assert.hpp>
#include <pika/coroutines/coroutine.hpp>
#include <pika/functional/bind.hpp>
#include <pika/modules/errors.hpp>
#include <pika/modules/logging.hpp>
#include <pika/threading_base/create_work.hpp>
#include <pika/threading_base/register_thread.hpp>
#include <pika/threading_base/set_thread_state.hpp>
#include <pika/threading_base/thread_data.hpp>
#include <pika/threading_base/threading_base_fwd.hpp>
#include <fmt/format.h>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <string>
#include <utility>
namespace pika::threads::detail {
thread_result_type set_active_state(thread_id_ref_type thrd, thread_schedule_state newstate,
thread_restart_state newstate_ex, execution::thread_priority priority,
thread_state previous_state)
{
if (PIKA_UNLIKELY(!thrd))
{
PIKA_THROW_EXCEPTION(pika::error::null_thread_id, "threads::detail::set_active_state",
"null thread id encountered");
return thread_result_type(thread_schedule_state::terminated, invalid_thread_id);
}
// make sure that the thread has not been suspended and set active again
// in the meantime
thread_state current_state = get_thread_id_data(thrd)->get_state();
if (current_state.state() == previous_state.state() && current_state != previous_state)
{
// NOLINTNEXTLINE(bugprone-branch-clone)
LTM_(warning).format(
"set_active_state: thread is still active, however it was non-active since the "
"original set_state request was issued, aborting state change, thread({}), "
"description({}), new state({})",
thrd, get_thread_id_data(thrd)->get_description(), get_thread_state_name(newstate));
return thread_result_type(thread_schedule_state::terminated, invalid_thread_id);
}
execution::thread_schedule_hint schedulehint{
static_cast<std::int16_t>(get_thread_id_data(thrd)->get_last_worker_thread_num())};
// just retry, set_state will create new thread if target is still active
error_code ec(throwmode::lightweight); // do not throw
set_thread_state(thrd.noref(), newstate, newstate_ex, priority, schedulehint, true, ec);
return thread_result_type(thread_schedule_state::terminated, invalid_thread_id);
}
///////////////////////////////////////////////////////////////////////////
thread_state set_thread_state(thread_id_type const& thrd, thread_schedule_state new_state,
thread_restart_state new_state_ex, execution::thread_priority priority,
execution::thread_schedule_hint schedulehint, bool retry_on_active, error_code& ec)
{
if (PIKA_UNLIKELY(!thrd))
{
PIKA_THROWS_IF(ec, pika::error::null_thread_id, "threads::detail::set_thread_state",
"null thread id encountered");
return thread_state(thread_schedule_state::unknown, thread_restart_state::unknown);
}
// set_state can't be used to force a thread into active state
if (new_state == thread_schedule_state::active)
{
PIKA_THROWS_IF(ec, pika::error::bad_parameter, "threads::detail::set_thread_state",
"invalid new state: {}", new_state);
return thread_state(thread_schedule_state::unknown, thread_restart_state::unknown);
}
thread_state previous_state;
std::size_t k = 0;
do {
// action depends on the current state
previous_state = get_thread_id_data(thrd)->get_state();
thread_schedule_state previous_state_val = previous_state.state();
// nothing to do here if the state doesn't change
if (new_state == previous_state_val)
{
// NOLINTNEXTLINE(bugprone-branch-clone)
LTM_(warning).format(
"set_thread_state: old thread state is the same as new thread state, aborting "
"state change, thread({}), description({}), new state({})",
thrd, get_thread_id_data(thrd)->get_description(),
get_thread_state_name(new_state));
if (&ec != &throws) ec = make_success_code();
return thread_state(new_state, previous_state.state_ex());
}
// the thread to set the state for is currently running, so we
// schedule another thread to execute the pending set_state
switch (previous_state_val)
{
case thread_schedule_state::active:
{
if (retry_on_active)
{
// schedule a new thread to set the state
// NOLINTNEXTLINE(bugprone-branch-clone)
LTM_(warning).format("set_thread_state: thread is currently active, scheduling "
"new thread, thread({}), description({}), new state({})",
thrd, get_thread_id_data(thrd)->get_description(),
get_thread_state_name(new_state));
thread_init_data data(
util::detail::bind(&set_active_state, thread_id_ref_type(thrd), new_state,
new_state_ex, priority, previous_state),
"set state for active thread", priority);
create_work(get_thread_id_data(thrd)->get_scheduler_base(), data, ec);
if (&ec != &throws) ec = make_success_code();
}
else
{
pika::execution::this_thread::detail::yield_k(
k, "pika::threads::detail::set_thread_state");
++k;
// NOLINTNEXTLINE(bugprone-branch-clone)
LTM_(warning).format("set_thread_state: thread is currently active, but not "
"scheduling new thread because retry_on_active = false, "
"thread({}), description({}), new state({})",
thrd, get_thread_id_data(thrd)->get_description(),
get_thread_state_name(new_state));
continue;
}
if (&ec != &throws) ec = make_success_code();
return previous_state; // done
}
case thread_schedule_state::terminated:
{
// NOLINTNEXTLINE(bugprone-branch-clone)
LTM_(warning).format("set_thread_state: thread is terminated, aborting state "
"change, thread({}), description({}), new state({})",
thrd, get_thread_id_data(thrd)->get_description(),
get_thread_state_name(new_state));
if (&ec != &throws) ec = make_success_code();
// If the thread has been terminated while this set_state was
// pending nothing has to be done anymore.
return previous_state;
}
case thread_schedule_state::pending: [[fallthrough]];
case thread_schedule_state::pending_boost:
if (thread_schedule_state::suspended == new_state)
{
// we do not allow explicit resetting of a state to suspended
// without the thread being executed.
std::string str =
fmt::format("set_thread_state: invalid new state, can't demote a pending "
"thread, thread({}), description({}), new state({})",
thrd, get_thread_id_data(thrd)->get_description(), new_state);
// NOLINTNEXTLINE(bugprone-branch-clone)
LTM_(fatal) << str;
PIKA_THROWS_IF(ec, pika::error::bad_parameter,
"threads::detail::set_thread_state", "{}", str);
return thread_state(
thread_schedule_state::unknown, thread_restart_state::unknown);
}
break;
case thread_schedule_state::suspended: break; // fine, just set the new state
case thread_schedule_state::pending_do_not_schedule: [[fallthrough]];
default:
{
PIKA_ASSERT_MSG(false,
fmt::format("set_thread_state: previous state was {}",
previous_state_val)); // should not happen
break;
}
}
// If the previous state was pending we are supposed to remove the
// thread from the queue. But in order to avoid linearly looking
// through the queue we defer this to the thread function, which
// at some point will ignore this thread by simply skipping it
// (if it's not pending anymore).
// NOLINTNEXTLINE(bugprone-branch-clone)
LTM_(info).format(
"set_thread_state: thread({}), description({}), new state({}), old state({})", thrd,
get_thread_id_data(thrd)->get_description(), get_thread_state_name(new_state),
get_thread_state_name(previous_state_val));
// So all what we do here is to set the new state.
if (get_thread_id_data(thrd)->restore_state(new_state, new_state_ex, previous_state))
{
break;
}
// state has changed since we fetched it from the thread, retry
// NOLINTNEXTLINE(bugprone-branch-clone)
LTM_(warning).format(
"set_thread_state: state has been changed since it was fetched, retrying, "
"thread({}), description({}), new state({}), old state({})",
thrd, get_thread_id_data(thrd)->get_description(), get_thread_state_name(new_state),
get_thread_state_name(previous_state_val));
} while (true);
thread_schedule_state previous_state_val = previous_state.state();
if (!(previous_state_val == thread_schedule_state::pending ||
previous_state_val == thread_schedule_state::pending_boost) &&
(new_state == thread_schedule_state::pending ||
new_state == thread_schedule_state::pending_boost))
{
// REVIEW: Passing a specific target thread may interfere with the
// round robin queuing.
auto* thrd_data = get_thread_id_data(thrd);
auto* scheduler = thrd_data->get_scheduler_base();
scheduler->schedule_thread(thrd, schedulehint, false, thrd_data->get_priority());
// NOTE: Don't care if the hint is a NUMA hint, just want to wake up
// a thread.
scheduler->do_some_work(schedulehint.hint);
}
if (&ec != &throws) ec = make_success_code();
return previous_state;
}
} // namespace pika::threads::detail
|
#include <QSplitter>
#include <QLayout>
#include <QTableView>
#include <QStandardItemModel>
#include <QHeaderView>
#include <QToolBar>
#include <QToolButton>
#include <QTextEdit>
#include <QPushButton>
#include <QFileSystemWatcher>
#include "hostsmanager.h"
#include "hostmanagerwidget.h"
/**
* @brief HostManagerWidget::HostManagerWidget
* @param parent
* This widget is supplied for manager the Windows hosts filr or Mac OSX host file
* You can add or delete the ip-host map
* You can modif y the ip-host-host map
*
*/
HostManagerDialog::HostManagerDialog( QWidget *parent)
: QDialog(parent)
, m_fileView(new QTextEdit())
, m_manager(new HostManager )
{
initializeTableView();
createToolButtons();
setup();
loadHostFile();
}
HostManagerDialog::~HostManagerDialog()
{
if (m_manager) {
delete m_manager ;
m_manager = 0 ;
}
}
void HostManagerDialog::createToolButtons()
{
QToolButton * m_reloadButton = new QToolButton();
m_reloadButton->setText(tr("&Reload"));
m_reloadButton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
QToolButton * m_addButton = new QToolButton(this);
m_addButton->setText(tr("&Add"));
m_addButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
m_addButton->setIcon(QIcon(":/images/add_item.png"));
connect(m_addButton,SIGNAL(clicked(bool)),this,SLOT(addItem()));
QToolButton * m_removeButton = new QToolButton(this);
m_removeButton->setText("&Remove");
m_removeButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
m_removeButton->setIcon(QIcon(":/images/minus_item.png"));
connect(m_removeButton,SIGNAL(clicked(bool)),this,SLOT(removeItem()));
m_toolBar = new QToolBar(this);
m_toolBar->setProperty("border",true);
m_toolBar->addWidget(m_reloadButton);
m_toolBar->addWidget(m_addButton);
m_toolBar->addWidget(m_removeButton);
}
void HostManagerDialog::loadHostFile( )
{
m_fileView->clear();
QHash<QString,HostManager::IP > iphosts = m_manager->ipHosts();
m_fileView->setDocument(new QTextDocument(m_manager->readAllConf()));
//m_fileView->setReadOnly(true);
}
void HostManagerDialog::setup()
{
setMinimumSize(600,500);
setWindowTitle(tr("Host file manager"));
QVBoxLayout * tableLayout = new QVBoxLayout ;
tableLayout->addWidget(m_tableview);
tableLayout->addWidget(m_toolBar);
tableLayout->setMargin(0);
tableLayout->setSpacing(0);
QHBoxLayout * hLayout = new QHBoxLayout ;
hLayout->addLayout(tableLayout);
hLayout->addWidget(m_fileView);
QPushButton * saveButton = new QPushButton(tr("&Save"));
QPushButton * closeButton = new QPushButton(tr("&Close"));
connect(saveButton,SIGNAL(clicked(bool)),this,SLOT(accept()));
connect(closeButton,SIGNAL(clicked(bool)),this,SLOT(close()));
QHBoxLayout * buttonLayout = new QHBoxLayout ;
buttonLayout->addWidget(saveButton );
buttonLayout->addWidget(closeButton);
buttonLayout->addStretch();
QVBoxLayout *mainLayout = new QVBoxLayout ;
QFrame * frame = new QFrame(this);
frame->setFrameShape(QFrame::HLine);
frame->setFrameStyle(QFrame::Sunken);
mainLayout->addLayout(hLayout);
mainLayout->addWidget(frame);
mainLayout->addLayout(buttonLayout);
setLayout(mainLayout);
}
void HostManagerDialog::addItem()
{
QModelIndex index = m_tableview->currentIndex();
if (!index.isValid()) {
return ;
}
QStandardItem * item1 = new QStandardItem ;
QStandardItem * item2 = new QStandardItem ;
QList<QStandardItem*> itemlist ;
itemlist << item1 << item2 ;
m_model->insertRow(index.row(),itemlist);
}
void HostManagerDialog::removeItem()
{
QModelIndex index = m_tableview->currentIndex();
if (!index.isValid()) {
return ;
}
m_model->removeRow(index.row());
}
void HostManagerDialog::accept()
{
QString text = m_fileView->document()->toPlainText();
m_manager->saveDataToDisk(text);
return QDialog::accept();
}
void HostManagerDialog::reload()
{
m_model->clear();
loadDataFromFile();
}
void HostManagerDialog::initializeTableView()
{
m_tableview = new QTableView ;
QStringList headerlist ;
headerlist << tr("Host") << tr("Ip");
m_tableview->horizontalHeader()->setStretchLastSection(true);
m_tableview->verticalHeader()->setHidden(true);
m_model = new QStandardItemModel();
m_model->setHorizontalHeaderLabels(headerlist);
m_tableview->setModel(m_model);
loadDataFromFile();
}
void HostManagerDialog::loadDataFromFile()
{
m_model->clear();
QHash<QString, HostManager::IP > iphosts = m_manager->ipHosts();
QHashIterator<QString,HostManager::IP > iter(iphosts);
while (iter.hasNext()) {
iter.next();
QString host = iter.key();
HostManager::IP ip = iter.value();
QStandardItem * item_host = new QStandardItem ;
item_host->setText(host);
QStandardItem * item_ip = new QStandardItem ;
item_ip->setText(ip.ip);
item_ip->setData(true,Qt::UserRole + 1);
QList<QStandardItem* > itemlist ;
itemlist << item_host << item_ip ;
m_model->appendRow(itemlist);
}
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <queue>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
#define INT_MIN (1<<31)
#define INT_MAX (~INT_MIN)
#define UNREACHABLE (INT_MAX>>2)
#define INF (1e300)
#define eps (1e-9)
#define MODULO 1000000007
ifstream fin("10541_input.txt");
#define cin fin
#define NLEN 10
#define CARRY_LEN 8
#define CARRY 100000000
struct Number {
Number() {
num.resize(NLEN);
for (int i = 0; i < NLEN; i++)
num[i] = 0;
}
Number(const Number & a) {
num = vector<long long>(NLEN, 0);
for (int i = 0; i < NLEN; i++)
this->num[i] = a.num[i];
}
string toString() {
int i = NLEN - 1;
while (i > 0 && num[i] == 0) i--;
string s = to_string(num[i--]);
while (i >= 0) {
string ts = to_string(num[i]);
int tlen = ts.length();
for (int j = 0; j < CARRY_LEN - tlen; j++) {
s = s + '0';
}
s = s + ts;
i--;
}
return s;
}
Number & operator+(Number a) {
long long carry = 0;
for (int i = 0; i < NLEN; i++) {
num[i] += a.num[i] + carry;
carry = num[i] / CARRY;
num[i] %= CARRY;
}
return *this;
}
Number & operator=(Number a) {
num.swap(a.num);
return *this;
}
Number & operator=(long long a) {
for (int i = 1; i < NLEN; i++)
num[i] = 0;
num[0] = a;
return *this;
}
vector<long long> num;
};
Number f[202][102];
int main()
{
int tttt;
cin >> tttt;
while (tttt--) {
// cout << "==================" << endl;
int n, k;
cin >> n >> k;
n++;
vector<long long> a(k, 0);
for (int i = 0 ; i < k; i++) {
cin >> a[i];
// cout << a[i] << ' ';
}
// cout << endl;
for (int i = 0; i <= n; i++)
for (int j = 0; j <= k; j++)
f[i][j] = Number();
for (int i = 0; i <= n; i++) {
f[i][0] = 1;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= k; j++) {
for (int l = 0; l <= i - a[j - 1] - 1; l++) {
f[i][j] = f[i][j] + f[l][j - 1];
}
}
}
// for (int i = 0; i <= n; i++, cout << endl)
// for (int j = 0; j <= k; j++)
// cout << f[i][j].toString() << ' ';
cout << f[n][k].toString() << endl;
}
}
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 100
struct Point{
double x,y;
};
struct Line {
double ax,ay,bx,by;
void init(Point A, Point B){
ax = A.x,ay = A.y;
bx = B.x,by = B.y;
}
};
double cross(Line K, double a, double b) {
double cross1 = (a - K.ax)*(K.by - K.ay);
double cross2 = (b - K.ay)*(K.bx - K.ax);
return (cross1 - cross2);
}
bool intersection(Line A, Line B){
//快速排斥實驗
if ( max(A.ax,A.bx) < min(B.ax,B.bx) ||
max(A.ay,A.by) < min(B.ay,B.by) ||
max(B.ax,B.bx) < min(A.ax,A.bx) ||
max(B.ay,B.by) < min(A.ay,A.by) ){
return false;
}
//跨立實驗
if ( cross(B,A.ax,A.ay)*cross(B,A.bx,A.by) > 0 ||
cross(A,B.ax,B.ay)*cross(A,B.bx,B.by) > 0 ){
return false;
}
return true;
}
bool in(Point k, Point a, Point b){
Point lt,rd;
lt.x = min(a.x,b.x), lt.y = max(a.y,b.y);
rd.x = max(a.x,b.x), rd.y = min(a.y,b.y);
return (lt.x <= k.x)&&(lt.y >= k.y)&&(rd.x >= k.x)&&(rd.y <= k.y);
}
int main(int argc, char const *argv[])
{
int kase;
scanf("%d",&kase);
Line slash;
Line L,R,T,D;
Point LT,LD,RT,RD;
Point SS,SE;
while( kase-- ){
scanf("%lf %lf %lf %lf",&SS.x, &SS.y, &SE.x, &SE.y);
slash.init(SS,SE);
scanf("%lf %lf %lf %lf",<.x, <.y, &RD.x, &RD.y);
LD.x = LT.x, LD.y = RD.y;
RT.x = RD.x, RT.y = LT.y;
L.init(LD,LT);
R.init(RT,RD);
T.init(LT,RT);
D.init(LD,RD);
if( in(SS,LT,RD) || in(SE,LT,RD) )
printf("T\n");
else if( intersection(slash,L) ||
intersection(slash,R) ||
intersection(slash,T) ||
intersection(slash,D) ) printf("T\n");
else
printf("F\n");
}
return 0;
}
|
//带有额外整型参数的operator new重载
#include<new>
using namespace std;
class MemoryDemo
{
public:
MemoryDemo();
~MemoryDemo();
void* operator new(size_t size) throw(bad_alloc);
void operator delete(void* ptr) throw();
void* operator new[](size_t size) throw(bad_alloc);
void operator delete[](void* ptr)throw();
void* operator new(size_t size,const nothrow_t&) throw();
void operator delete(void* ptr,const nothrow_t&) throw();
void* operator new[](size_t size,const nothrow_t&) throw();
void operator delete[](void* ptr,const nothrow_t&) throw();
void* operator new(size_t size,int extra) throw(bad_alloc);
};
void* MemoryDemo::operator new(size_t size,int extra) throw(bad_allcoc)
{
cout<<"operator new with extra int arg\n";
return (::operator new(size));
}
|
//
// Peer.cpp
// superasteroids
//
// Created by Cristian Marastoni on 21/05/14.
//
//
#include "EndPoint.h"
#include "Internal.h"
#include "NetTime.h"
#include "Connection.h"
#include "Channel.h"
#include <algorithm>
#include "../Debug.h"
namespace {
struct IfDisconnected {
bool operator()(Connection const *connection) {
return connection->GetState() == Connection::STATE_DISCONNECTED;
}
};
}
EndPoint::EndPoint():
mPeerListener(NULL),
mLocalPeer(0),
mMaxConnections(0),
mPacketID(0),
mAcceptConnections(false),
mIsServer(false)
{
}
EndPoint::~EndPoint() {
Close();
for(uint32 i=0;i<mMaxConnections;++i) {
delete mConnectionsPool[i];
}
}
bool EndPoint::IsNetworkAvailable() const {
//TODO: Should find an interface and check if connected
return true;
};
void EndPoint::Init(Settings const &settings, EndPointListener *listener) {
mMaxConnections = settings.maxNumConnections;
mPacketID = (settings.packetId[1] << 8) | settings.packetId[0];
mConnections.reserve(mMaxConnections);
mConnectionsPool = new Connection*[mMaxConnections];
mPeerListener = listener;
mLocalPeer = 0;
mPort = settings.port;
for(uint32 peer=0;peer<mMaxConnections;++peer) {
Connection *connection = new Connection();
connection->Init(this);
connection->SetID(peer);
connection->SetPeerListener(mPeerListener);
mConnectionsPool[peer] = connection;
}
}
bool EndPoint::Listen() {
if(SocketOpen(true)) {
mIsServer = true;
mAcceptConnections = true;
mLocalPeer = NetSettings::SERVER_PEER_ID;
return true;
}else {
mIsServer = false;
mAcceptConnections = false;
mLocalPeer = 0;
return false;
}
}
bool EndPoint::Connect(IpAddress const &address) {
if(SocketOpen(true)) {
mIsServer = false;
mAcceptConnections = false;
Connection *connection = CreateConnection();
connection->SetID(NetSettings::SERVER_PEER_ID);
connection->StartConnection(address);
return true;
}else {
return false;
}
}
void EndPoint::Close() {
CloseAllConnections();
mSocket.close();
for(auto it = mConnections.begin(); it != mConnections.end();++it) {
ReleaseConnection(*it);
}
mConnections.clear();
mAcceptConnections = false;
mIsServer = false;
Debug::Log("NET", "NetPort closed");
}
void EndPoint::Disconnect(NetID peer) {
Connection *connection = FindConnectionById(peer);
if(connection == NULL) {
return;
}
connection->Disconnect();
ReleaseConnection(connection);
mConnections.erase(std::remove(mConnections.begin(), mConnections.end(), connection));
}
void EndPoint::AcceptIncomingConnection(bool accept) {
mAcceptConnections = accept;
}
void EndPoint::Update(float dt) {
if(!IsOpened()) {
return;
}
SocketReceive();
for(auto it=mConnections.begin(); it!=mConnections.end();++it) {
if((*it)->Update(dt) == Connection::STATE_DISCONNECTED) {
ReleaseConnection((*it));
}
}
mConnections.erase(std::remove_if(mConnections.begin(), mConnections.end(), IfDisconnected()), mConnections.end());
}
bool EndPoint::IsOpened() const {
return mSocket.isOpen();
}
bool EndPoint::IsServer() const {
return mIsServer;
}
void EndPoint::SendMessageTo(NetID peer, uint8 messageID, uint8 channelId, BitStream &data) {
Connection *remote = FindConnectionById(peer);
if(remote != NULL) {
remote->ProduceMessage(data, messageID, channelId);
}
}
void EndPoint::BroadcastMessage(uint8 messageID, uint8 channelId, BitStream &data) {
for(auto it = mConnections.begin();it!=mConnections.end();++it) {
(*it)->ProduceMessage(data, messageID, channelId);
}
}
NetID EndPoint::GetLocalPeer() const {
return mLocalPeer;
}
void EndPoint::CloseAllConnections() {
for(unsigned i=0;i<mConnections.size();++i) {
mConnections[i]->Disconnect();
}
}
void EndPoint::SendPacket(IpAddress const &address, NetMessageHeader const &header, uint8 const *data)
{
uint8 outgoingPacket[NetSettings::MTU_MAX_SIZE];
BitStream packet(outgoingPacket, NetSettings::MTU_MAX_SIZE);
NetPacketHeader packetHeader;
packetHeader.mProtocolID = mPacketID;
packetHeader.mPeerID = mLocalPeer;
packetHeader.mNumMessages = 1;
packet << packetHeader;
packet << header;
if(header.mSize > 0) {
packet.append(data, header.mSize);
}
packet.flush();
net::Status status = mSocket.send(packet.buffer(), packet.size(), address);
if(status != net::Ok) {
OnSocketError(status);
}
}
void EndPoint::HandleReceivedPacket(const uint8 *buffer, size_t bufferSize, IpAddress const &remoteAddress) {
Debug::Log("NET", "Received message size %d from %s", bufferSize, remoteAddress.toString());
BitStream bs(buffer, bufferSize);
if(!ParseHeader(bs)) {
return;
}
Connection *remote = FindConnectionByAddress(remoteAddress);
NetMessageHeader msgHeader;
while(ParseNextMessage(bs, msgHeader)) {
if(msgHeader.mMessageId < NetSettings::NET_MESSAGE_NUM_RESERVED_ID) {
HandleSystemMessage(remoteAddress, remote, msgHeader, bs);
}else if(remote != NULL) {
remote->OnMessageReceived(msgHeader, bs);
}else {
Debug::Error("Received CUSTOM message from unknown sender %s. Discarding packet", remoteAddress.toString());
break;
}
}
}
bool EndPoint::ParseHeader(BitStream const &bs) {
const uint8 MAX_MESSAGE_PER_PACKET = static_cast<uint8 >((NetSettings::MTU_MAX_SIZE - sizeof(NetPacketHeader)) / 4);
if(bs.size() < sizeof(NetPacketHeader)) {
Debug::Error("NET", "Invalid Packet (size %d)", bs.size());
return false;
}
NetPacketHeader packetHeader;
bs >> packetHeader;
if(packetHeader.mProtocolID != mPacketID) {
Debug::Error("NET","Received message with ID: %d", packetHeader,mPacketID);
return false;
}
if(packetHeader.mNumMessages > MAX_MESSAGE_PER_PACKET) {
Debug::Error("NET","Invalid packet num messages");
return false;
}
return true;
}
bool EndPoint::ParseNextMessage(BitStream const &bs, NetMessageHeader &msgHeader) {
if(bs.remaining_bytes() < sizeof(msgHeader)) {
return false;
}
bs >> msgHeader;
if(msgHeader.mChannelId > NetChannels::NUM_CHANNELS) {
Debug::Error("NET","ChannelNo > MAX_NUM_CHANNELS");
return false;
}
uint32 remainingBytes = bs.remaining_bytes();
if(msgHeader.mSize > bs.remaining_bytes()) {
Debug::Error("NET","Invalid message size. (MessageSize >= Buffer Size)");
return false;
}
return true;
}
void EndPoint::HandleSystemMessage(IpAddress const &remoteAddress, Connection *remote, NetMessageHeader const &msgHeader, BitStream const &bs)
{
if(msgHeader.mMessageId == NET_MESSAGE_CONNECT) {
if(remote == NULL && (mConnections.size() == mMaxConnections)) {
DenyConnection(remoteAddress, NetStatusCode::DISCONNECTED_USER_LIMIT);
}else {
if(remote == NULL) {
remote = CreateConnection();
}
remote->OnConnectionAttempt(remoteAddress,mSessionID);
}
}
else if(remote != NULL) {
if(msgHeader.mMessageId == NET_MESSAGE_ACCEPTED) {
uint8 peerID;
bs.unpack16(mSessionID);
bs.unpack8(peerID);
mLocalPeer = peerID;
remote->OnConnectionAccepted(mSessionID);
}else if(msgHeader.mMessageId == NET_MESSAGE_CONNECT_ACK) {
remote->OnConnectionAcknowledged();
}else if(msgHeader.mMessageId == NET_MESSAGE_DENIED) {
Debug::Log("NET", "CONNECTION DENIED BY %s", remote->GetAddress().toString());
if(remote->GetState() == Connection::STATE_CONNECTING) {
uint32 denialReason;
bs.unpack32(denialReason);
remote->OnConnectionDenied(denialReason);
}else {
Debug::Log("MESSAGE_DENIED from %s RECEIVED IN STATE %d", remoteAddress.toString(), remote->GetState());
}
}else if(msgHeader.mMessageId == NET_MESSAGE_DISCONNECT) {
remote->Disconnect();
}else if(msgHeader.mMessageId == NET_MESSAGE_PING) {
remote->OnPing(bs);
}else if(msgHeader.mMessageId == NET_MESSAGE_PONG) {
remote->OnPong(bs);
}else if(msgHeader.mMessageId == NET_MESSAGE_ACK){
remote->OnAck(msgHeader.mChannelId, msgHeader.mSequenceNum);
}else {
Debug::Error("NET", "Unknown SYSTEM MESSAGE %d received from %s",
msgHeader.mMessageId, remoteAddress.toString());
}
}else {
Debug::Log("Message %d received from %s but no connection found", remoteAddress.toString());
}
}
Connection *EndPoint::CreateConnection() {
Debug::Log("NET", "Creating new connection");
Connection *remote = NULL;
for(int i=0;i<mMaxConnections && remote==NULL;++i) {
if(mConnectionsPool[i] != NULL) {
remote = mConnectionsPool[i];
mConnectionsPool[i] = NULL;
mConnections.push_back(remote);
}
}
return remote;
}
void EndPoint::ReleaseConnection(Connection *remote) {
if(remote != NULL) {
Debug::Log("NET", "Releasing connection %s", remote->GetAddress().toString());
mConnectionsPool[remote->GetID()] = remote;
}
}
void EndPoint::DenyConnection(IpAddress const &address, uint32 reason) {
NetStackData<32> data;
data.pack32(reason);
data.flush();
NetMessageHeader header;
header.mSequenceNum = 0;
header.mChannelId = NetChannels::UNRELIABLE;
header.mMessageId = NET_MESSAGE_DENIED;
header.mSize = data.size();
Debug::Log("NET", "Deny connection to %s reason %d",
address.toString(), reason);
SendPacket(address, header, data.buffer());
}
Connection *EndPoint::FindConnectionById(uint8 peerID) const{
std::vector<Connection*>::const_iterator it = std::find_if(mConnections.begin(), mConnections.end(), Connection::FindById(peerID));
if(it != mConnections.end()) {
return *it;
}else {
Debug::Log("NET", "Cannot find connection with id %d", peerID);
return NULL;
}
}
Connection *EndPoint::FindConnectionByAddress(IpAddress const &address) const{
std::vector<Connection*>::const_iterator it = std::find_if(mConnections.begin(), mConnections.end(), Connection::FindByAddress(address));
if(it != mConnections.end()) {
return *it;
}else {
Debug::Log("NET", "Cannot find connection with address %s", address.toString());
return NULL;
}
}
bool EndPoint::SocketOpen(bool blocking) {
if(mSocket.open() != net::Ok) {
return false;
}
mSocket.setBlocking(blocking);
if(mSocket.bind(mPort) != net::Ok) {
mSocket.close();
return false;
}
Debug::Log("NET", "Socket opened");
return true;
}
void EndPoint::SocketReceive() {
uint8 buffer[NetSettings::MTU_MAX_SIZE];
IpAddress remoteAddress;
size_t byteReceived;
size_t numPacketRead = 0;
net::Status status;
do {
status = mSocket.recv(buffer, NetSettings::MTU_MAX_SIZE, byteReceived, remoteAddress);
if(status == net::Ok) {
if(byteReceived > 0) {
++numPacketRead;
HandleReceivedPacket(buffer, byteReceived, remoteAddress);
}
}else if(status != net::WouldBlock) {
OnSocketError(status);
}
}while(status == net::Ok && numPacketRead >= NetSettings::MAX_PACKET_READ_PER_FRAME);
}
void EndPoint::OnSocketError(net::Status status) {
Close();
if(mPeerListener != NULL) {
if(status == net::Disconnected) {
mPeerListener->OnNetworkError(NetStatusCode::DISCONNECTED);
}else {
mPeerListener->OnNetworkError(NetStatusCode::NETWORK_ERROR);
}
}
}
|
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepExtrema_ExtFF_HeaderFile
#define _BRepExtrema_ExtFF_HeaderFile
#include <Extrema_ExtSS.hxx>
#include <TColStd_SequenceOfReal.hxx>
#include <Extrema_SequenceOfPOnSurf.hxx>
#include <BRepAdaptor_Surface.hxx>
#include <Extrema_POnSurf.hxx>
#include <Standard_DefineAlloc.hxx>
class TopoDS_Face;
class BRepExtrema_ExtFF
{
public:
DEFINE_STANDARD_ALLOC
BRepExtrema_ExtFF()
{
}
//! It calculates all the distances. <br>
Standard_EXPORT BRepExtrema_ExtFF(const TopoDS_Face& F1,const TopoDS_Face& F2);
Standard_EXPORT void Initialize(const TopoDS_Face& F2) ;
//! An exception is raised if the fields have not been initialized. <br>
//! Be careful: this method uses the Face F2 only for classify, not for the fields. <br>
Standard_EXPORT void Perform(const TopoDS_Face& F1,const TopoDS_Face& F2);
//! True if the distances are found. <br>
Standard_Boolean IsDone() const
{
return myExtSS.IsDone();
}
//! Returns True if the surfaces are parallel. <br>
Standard_Boolean IsParallel() const
{
return myExtSS.IsParallel();
}
//! Returns the number of extremum distances. <br>
Standard_Integer NbExt() const
{
return mySqDist.Length();
}
//! Returns the value of the <N>th extremum square distance. <br>
Standard_Real SquareDistance(const Standard_Integer N) const
{
return mySqDist.Value(N);
}
//! Returns the parameters on the Face F1 of the <N>th extremum distance. <br>
void ParameterOnFace1(const Standard_Integer N,Standard_Real& U,Standard_Real& V) const
{
myPointsOnS1.Value(N).Parameter(U, V);
}
//! Returns the parameters on the Face F2 of the <N>th extremum distance. <br>
void ParameterOnFace2(const Standard_Integer N,Standard_Real& U,Standard_Real& V) const
{
myPointsOnS2.Value(N).Parameter(U, V);
}
//! Returns the Point of the <N>th extremum distance. <br>
gp_Pnt PointOnFace1(const Standard_Integer N) const
{
return myPointsOnS1.Value(N).Value();
}
//! Returns the Point of the <N>th extremum distance. <br>
gp_Pnt PointOnFace2(const Standard_Integer N) const
{
return myPointsOnS2.Value(N).Value();
}
private:
Extrema_ExtSS myExtSS;
TColStd_SequenceOfReal mySqDist;
Extrema_SequenceOfPOnSurf myPointsOnS1;
Extrema_SequenceOfPOnSurf myPointsOnS2;
Handle(BRepAdaptor_Surface) myHS;
};
#endif
|
#ifndef CORE_NET_EVENT_LOOP_H
#define CORE_NET_EVENT_LOOP_H
#include "lock.hpp"
#include "TcpSock.h"
#include <pthread.h>
#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/function.hpp>
#include <vector>
namespace core { namespace net {
class SockWaiterBase;
class EventLoop : private boost::noncopyable, public boost::enable_shared_from_this<EventLoop>
{
public:
typedef boost::function<void()> EvTask;
EventLoop();
~EventLoop();
bool AddTcpSockToLoop(TcpSockSmartPtr sp_tcp);
int GetActiveTcpNum();
void TerminateLoop();
void SetSockWaiter(boost::shared_ptr<SockWaiterBase> spwaiter);
bool StartLoop(pthread_t& tid);
boost::shared_ptr<SockWaiterBase> GetEventWaiter() { return m_event_waiter; }
//bool IsTcpExist(TcpSockSmartPtr sp_tcp);
bool QueueTaskToLoop(EvTask task);
bool QueueTaskToWriteLoop(EvTask task);
bool IsInLoopThread();
bool IsInWriteLoopThread();
bool UpdateTcpSock(TcpSockSmartPtr sp_tcp);
void RemoveTcpSock(TcpSockSmartPtr sp_tcp);
private:
static void WriteLoopStartedNotify();
void AddTcpSockToLoopInLoopThread(TcpSockSmartPtr sp_tcp);
static void* Loop(void*);
void CloseAllClient();
boost::shared_ptr<SockWaiterBase> m_event_waiter;
volatile bool m_terminal;
volatile bool m_islooprunning;
pthread_t m_cur_looptid;
std::vector<EvTask> m_pendings;
common::locker m_lock;
const SockEvent m_handle_type;
std::string m_write_thread_name;
pthread_t m_write_thread_pid;
};
} }
#endif // end of CORE_NET_EVENT_LOOP_H
|
// Created by: Kirill GAVRILOV
// Copyright (c) 2013-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _OpenGl_TextureBuffer_H__
#define _OpenGl_TextureBuffer_H__
#include <Graphic3d_TextureUnit.hxx>
#include <OpenGl_Buffer.hxx>
//! Texture Buffer Object.
//! This is a special 1D texture that VBO-style initialized.
//! The main differences from general 1D texture:
//! - no interpolation between field;
//! - greater sizes;
//! - special sampler object in GLSL shader to access data by index.
//!
//! Notice that though TBO is inherited from VBO this is to unify design
//! user shouldn't cast it to base class and all really useful methods
//! are declared in this class.
class OpenGl_TextureBuffer : public OpenGl_Buffer
{
DEFINE_STANDARD_RTTIEXT(OpenGl_TextureBuffer, OpenGl_Buffer)
public:
//! Helpful constants
static const unsigned int NO_TEXTURE = 0;
public:
//! Create uninitialized TBO.
Standard_EXPORT OpenGl_TextureBuffer();
//! Destroy object, will throw exception if GPU memory not released with Release() before.
Standard_EXPORT virtual ~OpenGl_TextureBuffer();
//! Override VBO target
Standard_EXPORT virtual unsigned int GetTarget() const Standard_OVERRIDE;
//! Returns true if TBO is valid.
//! Notice that no any real GL call is performed!
bool IsValid() const
{
return OpenGl_Buffer::IsValid()
&& myTextureId != NO_TEXTURE;
}
//! Destroy object - will release GPU memory if any.
Standard_EXPORT virtual void Release (OpenGl_Context* theGlCtx) Standard_OVERRIDE;
//! Creates VBO and Texture names (ids) if not yet generated.
//! Data should be initialized by another method.
Standard_EXPORT bool Create (const Handle(OpenGl_Context)& theGlCtx) Standard_OVERRIDE;
//! Perform TBO initialization with specified data.
//! Existing data will be deleted.
Standard_EXPORT bool Init (const Handle(OpenGl_Context)& theGlCtx,
const unsigned int theComponentsNb,
const Standard_Integer theElemsNb,
const float* theData);
//! Perform TBO initialization with specified data.
//! Existing data will be deleted.
Standard_EXPORT bool Init (const Handle(OpenGl_Context)& theGlCtx,
const unsigned int theComponentsNb,
const Standard_Integer theElemsNb,
const unsigned int* theData);
//! Perform TBO initialization with specified data.
//! Existing data will be deleted.
Standard_EXPORT bool Init (const Handle(OpenGl_Context)& theGlCtx,
const unsigned int theComponentsNb,
const Standard_Integer theElemsNb,
const unsigned short* theData);
//! Perform TBO initialization with specified data.
//! Existing data will be deleted.
Standard_EXPORT bool Init (const Handle(OpenGl_Context)& theGlCtx,
const unsigned int theComponentsNb,
const Standard_Integer theElemsNb,
const Standard_Byte* theData);
//! Bind TBO to specified Texture Unit.
Standard_EXPORT void BindTexture (const Handle(OpenGl_Context)& theGlCtx,
const Graphic3d_TextureUnit theTextureUnit) const;
//! Unbind TBO.
Standard_EXPORT void UnbindTexture (const Handle(OpenGl_Context)& theGlCtx,
const Graphic3d_TextureUnit theTextureUnit) const;
//! Returns name of TBO.
unsigned int TextureId() const { return myTextureId; }
//! Returns internal texture format.
unsigned int TextureFormat() const { return myTexFormat; }
protected:
unsigned int myTextureId; //!< texture id
unsigned int myTexFormat; //!< internal texture format
};
DEFINE_STANDARD_HANDLE(OpenGl_TextureBuffer, OpenGl_Buffer)
#endif // _OpenGl_TextureBuffer_H__
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <exception>
#include <limits>
#include <vector>
#include "IWallet.h"
#include "Serialization/ISerializer.h"
namespace payment_service
{
class RequestSerializationError : public std::exception
{
public:
const char *what() const throw() override { return "Request error"; }
};
struct Save
{
struct Request
{
void serialize(const cn::ISerializer &serializer) const;
};
struct Response
{
void serialize(const cn::ISerializer &serializer) const;
};
};
struct Reset {
struct Request {
std::string viewSecretKey;
uint32_t scanHeight = std::numeric_limits<uint32_t>::max();
void serialize(cn::ISerializer& serializer);
};
struct Response {
void serialize(const cn::ISerializer &serializer) const;
};
};
struct ExportWallet
{
struct Request
{
std::string exportFilename;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
void serialize(const cn::ISerializer &serializer) const;
};
};
struct ExportWalletKeys
{
struct Request
{
std::string exportFilename;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
void serialize(const cn::ISerializer &serializer) const;
};
};
struct GetViewKey
{
struct Request
{
void serialize(const cn::ISerializer &serializer) const;
};
struct Response
{
std::string viewSecretKey;
void serialize(cn::ISerializer &serializer);
};
};
struct GetStatus
{
struct Request
{
void serialize(const cn::ISerializer &serializer) const;
};
struct Response
{
uint32_t blockCount;
uint32_t knownBlockCount;
std::string lastBlockHash;
uint32_t peerCount;
uint32_t depositCount;
uint32_t transactionCount;
uint32_t addressCount;
void serialize(cn::ISerializer &serializer);
};
};
struct CreateDeposit
{
struct Request
{
uint64_t amount;
uint64_t term;
std::string sourceAddress;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::string transactionHash;
void serialize(cn::ISerializer &serializer);
};
};
struct WithdrawDeposit
{
struct Request
{
uint64_t depositId;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::string transactionHash;
void serialize(cn::ISerializer &serializer);
};
};
struct SendDeposit
{
struct Request
{
uint64_t amount;
uint64_t term;
std::string sourceAddress;
std::string destinationAddress;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::string transactionHash;
void serialize(cn::ISerializer &serializer);
};
};
struct GetDeposit
{
struct Request
{
size_t depositId;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
uint64_t amount;
uint64_t term;
uint64_t interest;
uint64_t height;
uint64_t unlockHeight;
std::string creatingTransactionHash;
std::string spendingTransactionHash;
bool locked;
std::string address;
void serialize(cn::ISerializer &serializer);
};
};
struct GetAddresses
{
struct Request
{
void serialize(const cn::ISerializer &serializer) const;
};
struct Response
{
std::vector<std::string> addresses;
void serialize(cn::ISerializer &serializer);
};
};
struct CreateAddress
{
struct Request
{
std::string spendSecretKey;
std::string spendPublicKey;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::string address;
void serialize(cn::ISerializer &serializer);
};
};
struct CreateAddressList
{
struct Request
{
std::vector<std::string> spendSecretKeys;
bool reset = false;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::vector<std::string> addresses;
void serialize(cn::ISerializer &serializer);
};
};
struct DeleteAddress
{
struct Request
{
std::string address;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
void serialize(const cn::ISerializer &serializer) const;
};
};
struct GetSpendKeys
{
struct Request
{
std::string address;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::string spendSecretKey;
std::string spendPublicKey;
void serialize(cn::ISerializer &serializer);
};
};
struct GetBalance
{
struct Request
{
std::string address;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
uint64_t availableBalance;
uint64_t lockedAmount;
uint64_t lockedDepositBalance;
uint64_t unlockedDepositBalance;
void serialize(cn::ISerializer &serializer);
};
};
struct GetBlockHashes
{
struct Request
{
uint32_t firstBlockIndex;
uint32_t blockCount;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::vector<std::string> blockHashes;
void serialize(cn::ISerializer &serializer);
};
};
struct TransactionHashesInBlockRpcInfo
{
std::string blockHash;
std::vector<std::string> transactionHashes;
void serialize(cn::ISerializer &serializer);
};
struct GetTransactionHashes
{
struct Request
{
std::vector<std::string> addresses;
std::string blockHash;
uint32_t firstBlockIndex = std::numeric_limits<uint32_t>::max();
uint32_t blockCount;
std::string paymentId;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::vector<TransactionHashesInBlockRpcInfo> items;
void serialize(cn::ISerializer &serializer);
};
};
struct CreateIntegrated
{
struct Request
{
std::string address;
std::string payment_id;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::string integrated_address;
void serialize(cn::ISerializer &serializer);
};
};
struct SplitIntegrated
{
struct Request
{
std::string integrated_address;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::string address;
std::string payment_id;
void serialize(cn::ISerializer &serializer);
};
};
struct TransferRpcInfo
{
uint8_t type;
std::string address;
int64_t amount;
std::string message;
void serialize(cn::ISerializer &serializer);
};
struct TransactionRpcInfo
{
uint8_t state;
std::string transactionHash;
uint32_t blockIndex;
uint64_t timestamp;
uint32_t confirmations = 0;
bool isBase;
uint64_t unlockTime;
int64_t amount;
uint64_t fee;
std::vector<TransferRpcInfo> transfers;
std::string extra;
std::string paymentId;
size_t firstDepositId = cn::WALLET_INVALID_DEPOSIT_ID;
size_t depositCount = 0;
void serialize(cn::ISerializer &serializer);
};
struct GetTransaction
{
struct Request
{
std::string transactionHash;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
TransactionRpcInfo transaction;
void serialize(cn::ISerializer &serializer);
};
};
struct TransactionsInBlockRpcInfo
{
std::string blockHash;
std::vector<TransactionRpcInfo> transactions;
void serialize(cn::ISerializer &serializer);
};
struct GetTransactions
{
struct Request
{
std::vector<std::string> addresses;
std::string blockHash;
uint32_t firstBlockIndex = std::numeric_limits<uint32_t>::max();
uint32_t blockCount;
std::string paymentId;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::vector<TransactionsInBlockRpcInfo> items;
void serialize(cn::ISerializer &serializer);
};
};
struct GetUnconfirmedTransactionHashes
{
struct Request
{
std::vector<std::string> addresses;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::vector<std::string> transactionHashes;
void serialize(cn::ISerializer &serializer);
};
};
struct WalletRpcOrder
{
std::string address;
uint64_t amount;
std::string message;
void serialize(cn::ISerializer &serializer);
};
struct WalletRpcMessage
{
std::string address;
std::string message;
void serialize(cn::ISerializer &serializer);
};
struct SendTransaction
{
struct Request
{
std::vector<std::string> sourceAddresses;
std::vector<WalletRpcOrder> transfers;
std::string changeAddress;
uint64_t fee = 1000;
uint32_t anonymity = cn::parameters::MINIMUM_MIXIN;
std::string extra;
std::string paymentId;
uint64_t unlockTime = 0;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::string transactionHash;
std::string transactionSecretKey;
void serialize(cn::ISerializer &serializer);
};
};
struct CreateDelayedTransaction
{
struct Request
{
std::vector<std::string> addresses;
std::vector<WalletRpcOrder> transfers;
std::string changeAddress;
uint64_t fee = 1000;
uint32_t anonymity = cn::parameters::MINIMUM_MIXIN;
std::string extra;
std::string paymentId;
uint64_t unlockTime = 0;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::string transactionHash;
void serialize(cn::ISerializer &serializer);
};
};
struct GetDelayedTransactionHashes
{
struct Request
{
void serialize(const cn::ISerializer &serializer) const;
};
struct Response
{
std::vector<std::string> transactionHashes;
void serialize(cn::ISerializer &serializer);
};
};
struct DeleteDelayedTransaction
{
struct Request
{
std::string transactionHash;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
void serialize(const cn::ISerializer &serializer) const;
};
};
struct SendDelayedTransaction
{
struct Request
{
std::string transactionHash;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
void serialize(const cn::ISerializer &serializer) const;
};
};
struct GetMessagesFromExtra
{
struct Request
{
std::string extra;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::vector<std::string> messages;
void serialize(cn::ISerializer &serializer);
};
};
struct EstimateFusion
{
struct Request
{
uint64_t threshold;
std::vector<std::string> addresses;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
uint32_t fusionReadyCount;
uint32_t totalOutputCount;
void serialize(cn::ISerializer &serializer);
};
};
struct SendFusionTransaction
{
struct Request
{
uint64_t threshold;
uint32_t anonymity = 0;
std::vector<std::string> addresses;
std::string destinationAddress;
void serialize(cn::ISerializer &serializer);
};
struct Response
{
std::string transactionHash;
void serialize(cn::ISerializer &serializer);
};
};
} //namespace payment_service
|
#pragma once
#include "LayerBuilder.hpp"
#include "Utils/ArrayView.hpp"
#include "Utils/NotNull.hpp"
#include "LayerBuilder.hpp"
#include "NodeBuilders/ConnectedLayerNodeBuilder.hpp"
#include <vector>
#include <memory>
struct UnaryNodeBuilder;
struct ConstSingleValueNodeBuilder;
struct MultipleInputLayerNodeBuilder;
struct MultipleInputNodeBuilder;
struct FullyConnectedLayerSpecs;
struct InputLayerSpecs;
struct FullyConnectedLayerBuilder : LayerBuilder
{
FullyConnectedLayerBuilder(NotNull<PassThroughLayerNodeBuilder> activationLayer, std::size_t numOutputs);
NotNull<FullyConnectedLayerBuilder> setInputLayer(FullyConnectedLayerSpecs specs);
void setInputLayer(InputLayerSpecs const& specs);
private:
ConnectedLayerNodeBuilder* m_fullyConnectedLayer;
std::unique_ptr<LayerBuilder> m_inputLayer;
};
|
#include "regulator.h"
#include <stdio.h>
Regulator::Regulator(QObject *parent) : QObject(parent)
{
openPort();
timeoutTimer = new QTimer(this);
endtimeTimer = new QTimer(this);
connect(timeoutTimer,&QTimer::timeout,this,&Regulator::handleTimeout);
QObject::connect(endtimeTimer,SIGNAL(timeout()),this,SLOT(handleEndTimeout()));
ReSendCount = 0;
type=IDLE;
endtype=IDLE;
r_state = RIDLE;
}
void Regulator::beginRegulate()
{
}
void Regulator::beginTest()
{
}
//具体的串口产生需要根据实际情况进行调整
void Regulator::openPort()
{
regulatorPort=new QSerialPort(this);
foreach (const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
{
QString portDescription=info.description();
if(portDescription.contains(QString("CH340")))
{
qDebug()<<"regulator found";
RegulatorFound = true;
regulatorPort->setPort(info);
regulatorPort->setBaudRate(QSerialPort::Baud9600);
regulatorPort->setDataBits(QSerialPort::Data8);
regulatorPort->setParity(QSerialPort::NoParity);
regulatorPort->setStopBits(QSerialPort::OneStop);
regulatorPort->setFlowControl(QSerialPort::NoFlowControl);
regulatorPort->open(QIODevice::ReadWrite);
connect(regulatorPort,&QSerialPort::readyRead,this,&Regulator::parseData);
return;
}
}
RegulatorFound = false;
emit regulatorPortNotFound();
return;
}
void Regulator::sendData(DataPoint voltage,DataPoint newData)
{
if(type != IDLE)return; //指令冲突处理
orderClear(DataOrder);
char checkcode;
DataOrder.head = QString("2aeb").toLocal8Bit();
DataOrder.head = QByteArray::fromHex(DataOrder.head);
DataOrder.address = QString("02").toLocal8Bit();
DataOrder.address = QByteArray::fromHex(DataOrder.address);
DataOrder.commandtype = QString("05").toLocal8Bit();
DataOrder.commandtype = QByteArray::fromHex(DataOrder.commandtype);
DataOrder.datalength = QString("18").toLocal8Bit();//
DataOrder.datalength = QByteArray::fromHex(DataOrder.datalength);
checkcode = dataIntoString(DataOrder.data,voltage,newData);
checkcode ^= 0x02^0x05^0x18;
DataOrder.checkcode.append(checkcode);
DataOrder.tail = QString("ad").toLocal8Bit();
DataOrder.tail = QByteArray::fromHex(DataOrder.tail);
//发送指令
sendInstruction(DataOrder);
//状态改变 发送消息
type = WaitForDataCheckBack;
}
//节能模拟指令
void Regulator::simulationSaving()
{
if(type != IDLE)return;
orderClear(SimulationOrder);
SimulationOrder.head = QString("2aeb").toLocal8Bit();
SimulationOrder.head = QByteArray::fromHex(SimulationOrder.head);
SimulationOrder.address = QString("02").toLocal8Bit();
SimulationOrder.address = QByteArray::fromHex(SimulationOrder.address);
SimulationOrder.commandtype = QString("02").toLocal8Bit();
SimulationOrder.commandtype = QByteArray::fromHex(SimulationOrder.commandtype);
SimulationOrder.datalength = QString("01").toLocal8Bit();
SimulationOrder.datalength = QByteArray::fromHex(SimulationOrder.datalength);
SimulationOrder.data = QString("00").toLocal8Bit();
SimulationOrder.data = QByteArray::fromHex(SimulationOrder.data);
SimulationOrder.checkcode = QString("01").toLocal8Bit();
SimulationOrder.checkcode = QByteArray::fromHex(SimulationOrder.checkcode);
SimulationOrder.tail = QString("ad").toLocal8Bit();
SimulationOrder.tail = QByteArray::fromHex(SimulationOrder.tail);
//发送指令
sendInstruction(SimulationOrder);
//状态改变 发送消息
type = WaitForSimulationBack;
}
//软关机指令
void Regulator::shutDownHardware()
{
if(type != IDLE)return;
orderClear(ShutDownOrder);
endtype = WaitForShutDownEnd;
ShutDownOrder.head = QString("2aeb").toLocal8Bit();
ShutDownOrder.head = QByteArray::fromHex(ShutDownOrder.head);
ShutDownOrder.address = QString("02").toLocal8Bit();
ShutDownOrder.address = QByteArray::fromHex(ShutDownOrder.address);
ShutDownOrder.commandtype = QString("03").toLocal8Bit();
ShutDownOrder.commandtype = QByteArray::fromHex(ShutDownOrder.commandtype);
ShutDownOrder.datalength = QString("01").toLocal8Bit();
ShutDownOrder.datalength = QByteArray::fromHex(ShutDownOrder.datalength);
ShutDownOrder.data = QString("00").toLocal8Bit();
ShutDownOrder.data = QByteArray::fromHex(ShutDownOrder.data);
ShutDownOrder.checkcode = QString("00").toLocal8Bit();
ShutDownOrder.checkcode = QByteArray::fromHex(ShutDownOrder.checkcode);
ShutDownOrder.tail = QString("ad").toLocal8Bit();
ShutDownOrder.tail = QByteArray::fromHex(ShutDownOrder.tail);
//发送指令
sendInstruction(ShutDownOrder);
//状态改变 发送消息
type = WaitForShutDownBack;
}
//发送阈值指令
void Regulator::sendThershold(int percentage, DataPoint voltage, DataPoint newData)
{
if(type != IDLE)return;
MinVoltageData = voltage;
NewVoltageData = newData;
orderClear(ThersholdOrder);
char checkcode;
ThersholdOrder.head = QString("2aeb").toLocal8Bit();
ThersholdOrder.head = QByteArray::fromHex(ThersholdOrder.head);
ThersholdOrder.address = QString("02").toLocal8Bit();
ThersholdOrder.address = QByteArray::fromHex(ThersholdOrder.address);
ThersholdOrder.commandtype = QString("06").toLocal8Bit();
ThersholdOrder.commandtype = QByteArray::fromHex(ThersholdOrder.commandtype);
ThersholdOrder.datalength = QString("01").toLocal8Bit();
ThersholdOrder.datalength = QByteArray::fromHex(ThersholdOrder.datalength);
ThersholdOrder.data.append(percentage);
checkcode=0x02^0x06^0x01^percentage;
ThersholdOrder.checkcode.append(checkcode);
ThersholdOrder.tail = QString("ad").toLocal8Bit();
ThersholdOrder.tail = QByteArray::fromHex(ThersholdOrder.tail);
//发送指令
sendInstruction(ThersholdOrder);
//状态改变 发送消息
type = WaitForThersholdBack;
}
bool Regulator::isRegulatorFound()
{
return RegulatorFound;
}
//软开机指令
void Regulator::startHardware()
{
if(type != IDLE)return;
orderClear(StartOrder);
endtype = WaitForStartEnd;
StartOrder.head = QString("2aeb").toLocal8Bit();
StartOrder.head = QByteArray::fromHex(StartOrder.head);
StartOrder.address = QString("02").toLocal8Bit();
StartOrder.address = QByteArray::fromHex(StartOrder.address);
StartOrder.commandtype = QString("04").toLocal8Bit();
StartOrder.commandtype = QByteArray::fromHex(StartOrder.commandtype);
StartOrder.datalength = QString("01").toLocal8Bit();
StartOrder.datalength = QByteArray::fromHex(StartOrder.datalength);
StartOrder.data = QString("00").toLocal8Bit();
StartOrder.data = QByteArray::fromHex(StartOrder.data);
StartOrder.checkcode = QString("07").toLocal8Bit();
StartOrder.checkcode = QByteArray::fromHex(StartOrder.checkcode);
StartOrder.tail = QString("ad").toLocal8Bit();
StartOrder.tail = QByteArray::fromHex(StartOrder.tail);
//发送指令
sendInstruction(StartOrder);
//状态改变 发送消息
type = WaitForStartBack;
}
/*
* 解析数据 主要是收到回复的 “OK" "ER"要重发
* 注意每次readytoread的时候已经接受了完整的数据
*/
void Regulator::parseData()
{
QByteArray tempbuffer=regulatorPort->readAll();
// qDebug()<<tempbuffer.length();
//qDebug()<<"before readall"<<regulatorPort->peek(4);
//tempbuffer.append(regulatorPort->readAll());
//printf("back data is %c\r\n",tempbuffer.at(0));
//printf("back data 2 is %c\r\n",tempbuffer.at(tempbuffer.size()-1));
qDebug()<<"after readall"<<tempbuffer.at(0)<<tempbuffer.at(1);
// switch (r_state)
// {
// case RIDEL:
// if(tempbuffer.contains("O"))
// {
// r_state = RM_O;
// }
// else if(tempbuffer.contains("E"))
// {
// r_state = RM_E;
// }
// break;
// case RM_O:
if(tempbuffer.contains("OK"))
{
ReSendCount = 0;
timeoutTimer->stop();
r_state = RIDLE;
switch (type)
{
case WaitForStartBack:
type = IDLE;
endtimeTimer->start(MAX_ENDTIMEOUT);
emit startBack();
break;
case WaitForShutDownBack:
type = IDLE;
endtimeTimer->start(MAX_ENDTIMEOUT);
emit shutDownBack();
break;
case WaitForSimulationBack:
type = IDLE;
emit simulationBack();
break;
case WaitForDataCheckBack:
type = IDLE;
emit dataSendBack();
break;
case WaitForThersholdBack:
emit thersholdBack();
qDebug()<<"2";
type = IDLE;
sendData(MinVoltageData,NewVoltageData);
break;
default:
break;
}
}
// break;
// case RM_E://回复ER 重发
if(tempbuffer.contains("ER"))
{
r_state = RIDLE;
timeoutTimer->stop();//停止延时计时
ReSendCount += 1;
if(ReSendCount > MAX_RESEND_COUNT)
{
//ReSendCount = 0;
emit regulatorError();
qDebug()<<"error emit";
return;
}
qDebug()<<"er coount"<<ReSendCount;
switch (type)
{
case WaitForSimulationBack:
sendInstruction(SimulationOrder);
break;
case WaitForStartBack:
sendInstruction(StartOrder);
break;
case WaitForShutDownBack:
sendInstruction(ShutDownOrder);
break;
case WaitForDataCheckBack:
sendInstruction(DataOrder);
case WaitForThersholdBack:
sendInstruction(ThersholdOrder);
break;
default:
break;
}
}
if(tempbuffer.contains("END"))
{
endtimeTimer->stop();
switch (endtype)
{
case WaitForStartEnd:
endtype = IDLE;
emit startOver();
break;
case WaitForShutDownEnd:
endtype = IDLE;
emit shutDownOver();
break;
default:
break;
}
}
}
void Regulator::handleTimeout()
{
timeoutTimer->stop();
emit regulatorError();
}
void Regulator::handleEndTimeout()
{
endtimeTimer->stop();
emit regulatorError();
}
void Regulator::orderClear(regulatorinstruction order)
{
order.head.clear();
order.address.clear();
order.commandtype.clear();
order.datalength.clear();
order.data.clear();
order.checkcode.clear();
order.tail.clear();
}
void Regulator::sendInstruction(regulatorinstruction order)
{
regulatorPort->write(order.head);
regulatorPort->write(order.address);
regulatorPort->write(order.commandtype);
regulatorPort->write(order.datalength);
regulatorPort->write(order.data);
regulatorPort->write(order.checkcode);
regulatorPort->write(order.tail);
timeoutTimer->start(TIMEOUT_INTERVAL);
}
//返回data异或
char Regulator::dataIntoString(QByteArray &data, DataPoint &voltage, DataPoint &newdata)
{
int tempbuffer;
char checkcode = 0;
tempbuffer = int(newdata.va * 10);//
data.append(((tempbuffer&0xff00)>>8));
checkcode = data.at(data.size()-1);
data.append(((tempbuffer&0xff)));
checkcode ^= data.at(data.size()-1);
tempbuffer = int(newdata.vb * 10);//
data.append(((tempbuffer&0xff00)>>8));
checkcode ^= data.at(data.size()-1);
data.append(((tempbuffer&0xff)));
checkcode ^= data.at(data.size()-1);
tempbuffer = int(newdata.vc * 10);//
data.append(((tempbuffer&0xff00)>>8));
checkcode ^= data.at(data.size()-1);
data.append(((tempbuffer&0xff)));
checkcode ^= data.at(data.size()-1);
tempbuffer = int(newdata.ia * 10);//
data.append(((tempbuffer&0xff00)>>8));
checkcode ^= data.at(data.size()-1);
data.append(((tempbuffer&0xff)));
checkcode ^= data.at(data.size()-1);
tempbuffer = int(newdata.ib * 10);//
data.append(((tempbuffer&0xff00)>>8));
checkcode ^= data.at(data.size()-1);
data.append(((tempbuffer&0xff)));
checkcode ^= data.at(data.size()-1);
tempbuffer = int(newdata.ic * 10);//
data.append(((tempbuffer&0xff00)>>8));
checkcode ^= data.at(data.size()-1);
data.append(((tempbuffer&0xff)));
checkcode ^= data.at(data.size()-1);
tempbuffer = int(newdata.epa / POWERRATE);//
data.append(((tempbuffer&0xff00)>>8));
checkcode ^= data.at(data.size()-1);
data.append(((tempbuffer&0xff)));
checkcode ^= data.at(data.size()-1);
tempbuffer = int(newdata.epb / POWERRATE);//
data.append(((tempbuffer&0xff00)>>8));
checkcode ^= data.at(data.size()-1);
data.append(((tempbuffer&0xff)));
checkcode ^= data.at(data.size()-1);
tempbuffer = int(newdata.epc / POWERRATE);//
data.append(((tempbuffer&0xff00)>>8));
checkcode ^= data.at(data.size()-1);
data.append(((tempbuffer&0xff)));
checkcode ^= data.at(data.size()-1);
tempbuffer = int(voltage.va * 10);//
data.append(((tempbuffer&0xff00)>>8));
checkcode ^= data.at(data.size()-1);
data.append(((tempbuffer&0xff)));
checkcode ^= data.at(data.size()-1);
tempbuffer = int(voltage.vb * 10);//
data.append(((tempbuffer&0xff00)>>8));
checkcode ^= data.at(data.size()-1);
data.append(((tempbuffer&0xff)));
checkcode ^= data.at(data.size()-1);
tempbuffer = int(voltage.vc * 10);//
data.append(((tempbuffer&0xff00)>>8));
checkcode ^= data.at(data.size()-1);
data.append(((tempbuffer&0xff)));
checkcode ^= data.at(data.size()-1);
return checkcode;
//qDebug<<"data is "<<(unsigned char)data.data();
}
|
#include "report.h"
#include "ui_report.h"
Report::Report(QWidget *parent) :
QDialog(parent),
ui(new Ui::Report)
{
ui->setupUi(this);
}
Report::~Report()
{
delete ui;
}
void Report::on_BackToGeneralWindow_clicked()
{
GeneralWindow gw;
this->close();
gw.setModal(true);
gw.exec();
}
|
#include "tilelayer.h"
TileLayer::TileLayer(sge::graphics::Shader* shader)
:Layer(new sge::graphics::Batch2DRenderer(), shader, sge::math::mat4::orthographic(0.0f, 16.0f,
0.0f, 9.0f, -1.0f, 1.0f)) {
}
TileLayer::~TileLayer(){
}
|
#include <iostream>
using namespace std;
int main(){
int h,m;
cin >> h >> m;
if(m > 44)
cout << h << " " << (m-45) << endl;
else{
h = (h + 24 - 1) % 24;
m = (m + 15) % 60;
cout << h << " " << m << endl;
}
return 0;
}
|
#include "common/buffer/buffer_impl.h"
#include "common/router/config_impl.h"
#include "common/router/router.h"
#include "common/router/upstream_request.h"
#include "extensions/common/proxy_protocol/proxy_protocol_header.h"
#include "extensions/upstreams/http/tcp/upstream_request.h"
#include "test/common/http/common.h"
#include "test/mocks/common.h"
#include "test/mocks/http/mocks.h"
#include "test/mocks/router/mocks.h"
#include "test/mocks/server/mocks.h"
#include "test/mocks/tcp/mocks.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using Envoy::Http::TestRequestHeaderMapImpl;
using Envoy::Router::UpstreamRequest;
using testing::_;
using testing::AnyNumber;
using testing::NiceMock;
using testing::Return;
using testing::ReturnRef;
namespace Envoy {
namespace Router {
namespace {
class MockRouterFilterInterface : public RouterFilterInterface {
public:
MockRouterFilterInterface()
: config_("prefix.", context_, ShadowWriterPtr(new MockShadowWriter()), router_proto) {
auto cluster_info = new NiceMock<Upstream::MockClusterInfo>();
cluster_info->timeout_budget_stats_ = absl::nullopt;
cluster_info_.reset(cluster_info);
ON_CALL(*this, callbacks()).WillByDefault(Return(&callbacks_));
ON_CALL(*this, config()).WillByDefault(ReturnRef(config_));
ON_CALL(*this, cluster()).WillByDefault(Return(cluster_info_));
ON_CALL(*this, upstreamRequests()).WillByDefault(ReturnRef(requests_));
EXPECT_CALL(callbacks_.dispatcher_, setTrackedObject(_)).Times(AnyNumber());
ON_CALL(*this, routeEntry()).WillByDefault(Return(&route_entry_));
ON_CALL(callbacks_, connection()).WillByDefault(Return(&client_connection_));
route_entry_.connect_config_.emplace(RouteEntry::ConnectConfig());
}
MOCK_METHOD(void, onUpstream100ContinueHeaders,
(Envoy::Http::ResponseHeaderMapPtr && headers, UpstreamRequest& upstream_request));
MOCK_METHOD(void, onUpstreamHeaders,
(uint64_t response_code, Envoy::Http::ResponseHeaderMapPtr&& headers,
UpstreamRequest& upstream_request, bool end_stream));
MOCK_METHOD(void, onUpstreamData,
(Buffer::Instance & data, UpstreamRequest& upstream_request, bool end_stream));
MOCK_METHOD(void, onUpstreamTrailers,
(Envoy::Http::ResponseTrailerMapPtr && trailers, UpstreamRequest& upstream_request));
MOCK_METHOD(void, onUpstreamMetadata, (Envoy::Http::MetadataMapPtr && metadata_map));
MOCK_METHOD(void, onUpstreamReset,
(Envoy::Http::StreamResetReason reset_reason, absl::string_view transport_failure,
UpstreamRequest& upstream_request));
MOCK_METHOD(void, onUpstreamHostSelected, (Upstream::HostDescriptionConstSharedPtr host));
MOCK_METHOD(void, onPerTryTimeout, (UpstreamRequest & upstream_request));
MOCK_METHOD(void, onStreamMaxDurationReached, (UpstreamRequest & upstream_request));
MOCK_METHOD(Envoy::Http::StreamDecoderFilterCallbacks*, callbacks, ());
MOCK_METHOD(Upstream::ClusterInfoConstSharedPtr, cluster, ());
MOCK_METHOD(FilterConfig&, config, ());
MOCK_METHOD(FilterUtility::TimeoutData, timeout, ());
MOCK_METHOD(Envoy::Http::RequestHeaderMap*, downstreamHeaders, ());
MOCK_METHOD(Envoy::Http::RequestTrailerMap*, downstreamTrailers, ());
MOCK_METHOD(bool, downstreamResponseStarted, (), (const));
MOCK_METHOD(bool, downstreamEndStream, (), (const));
MOCK_METHOD(uint32_t, attemptCount, (), (const));
MOCK_METHOD(const VirtualCluster*, requestVcluster, (), (const));
MOCK_METHOD(const RouteEntry*, routeEntry, (), (const));
MOCK_METHOD(const std::list<UpstreamRequestPtr>&, upstreamRequests, (), (const));
MOCK_METHOD(const UpstreamRequest*, finalUpstreamRequest, (), (const));
MOCK_METHOD(TimeSource&, timeSource, ());
NiceMock<Envoy::Http::MockStreamDecoderFilterCallbacks> callbacks_;
NiceMock<MockRouteEntry> route_entry_;
NiceMock<Network::MockConnection> client_connection_;
envoy::extensions::filters::http::router::v3::Router router_proto;
NiceMock<Server::Configuration::MockFactoryContext> context_;
FilterConfig config_;
Upstream::ClusterInfoConstSharedPtr cluster_info_;
std::list<UpstreamRequestPtr> requests_;
};
} // namespace
} // namespace Router
} // namespace Envoy
namespace Envoy {
namespace Extensions {
namespace Upstreams {
namespace Http {
namespace Tcp {
class TcpConnPoolTest : public ::testing::Test {
public:
TcpConnPoolTest() : host_(std::make_shared<NiceMock<Upstream::MockHost>>()) {
NiceMock<Router::MockRouteEntry> route_entry;
NiceMock<Upstream::MockClusterManager> cm;
EXPECT_CALL(cm, tcpConnPoolForCluster(_, _, _)).WillOnce(Return(&mock_pool_));
conn_pool_ = std::make_unique<TcpConnPool>(cm, true, route_entry, Envoy::Http::Protocol::Http11,
nullptr);
}
std::unique_ptr<TcpConnPool> conn_pool_;
Envoy::Tcp::ConnectionPool::MockInstance mock_pool_;
Router::MockGenericConnectionPoolCallbacks mock_generic_callbacks_;
std::shared_ptr<NiceMock<Upstream::MockHost>> host_;
NiceMock<Envoy::ConnectionPool::MockCancellable> cancellable_;
};
TEST_F(TcpConnPoolTest, Basic) {
NiceMock<Network::MockClientConnection> connection;
EXPECT_CALL(mock_pool_, newConnection(_)).WillOnce(Return(&cancellable_));
conn_pool_->newStream(&mock_generic_callbacks_);
EXPECT_CALL(mock_generic_callbacks_, upstreamToDownstream());
EXPECT_CALL(mock_generic_callbacks_, onPoolReady(_, _, _, _));
auto data = std::make_unique<NiceMock<Envoy::Tcp::ConnectionPool::MockConnectionData>>();
EXPECT_CALL(*data, connection()).Times(AnyNumber()).WillRepeatedly(ReturnRef(connection));
conn_pool_->onPoolReady(std::move(data), host_);
}
TEST_F(TcpConnPoolTest, OnPoolFailure) {
EXPECT_CALL(mock_pool_, newConnection(_)).WillOnce(Return(&cancellable_));
conn_pool_->newStream(&mock_generic_callbacks_);
EXPECT_CALL(mock_generic_callbacks_, onPoolFailure(_, _, _));
conn_pool_->onPoolFailure(Envoy::Tcp::ConnectionPool::PoolFailureReason::LocalConnectionFailure,
host_);
// Make sure that the pool failure nulled out the pending request.
EXPECT_FALSE(conn_pool_->cancelAnyPendingRequest());
}
TEST_F(TcpConnPoolTest, Cancel) {
// Initially cancel should fail as there is no pending request.
EXPECT_FALSE(conn_pool_->cancelAnyPendingRequest());
EXPECT_CALL(mock_pool_, newConnection(_)).WillOnce(Return(&cancellable_));
conn_pool_->newStream(&mock_generic_callbacks_);
// Canceling should now return true as there was an active request.
EXPECT_TRUE(conn_pool_->cancelAnyPendingRequest());
// A second cancel should return false as there is not a pending request.
EXPECT_FALSE(conn_pool_->cancelAnyPendingRequest());
}
class TcpUpstreamTest : public ::testing::Test {
public:
TcpUpstreamTest() {
mock_router_filter_.requests_.push_back(std::make_unique<UpstreamRequest>(
mock_router_filter_, std::make_unique<NiceMock<Router::MockGenericConnPool>>()));
auto data = std::make_unique<NiceMock<Envoy::Tcp::ConnectionPool::MockConnectionData>>();
EXPECT_CALL(*data, connection()).Times(AnyNumber()).WillRepeatedly(ReturnRef(connection_));
tcp_upstream_ =
std::make_unique<TcpUpstream>(mock_router_filter_.requests_.front().get(), std::move(data));
}
~TcpUpstreamTest() override { EXPECT_CALL(mock_router_filter_, config()).Times(AnyNumber()); }
protected:
NiceMock<Network::MockClientConnection> connection_;
NiceMock<Router::MockRouterFilterInterface> mock_router_filter_;
Envoy::Tcp::ConnectionPool::MockConnectionData* mock_connection_data_;
std::unique_ptr<TcpUpstream> tcp_upstream_;
TestRequestHeaderMapImpl request_{{":method", "CONNECT"},
{":path", "/"},
{":protocol", "bytestream"},
{":scheme", "https"},
{":authority", "host"}};
};
TEST_F(TcpUpstreamTest, Basic) {
// Swallow the request headers and generate response headers.
EXPECT_CALL(connection_, write(_, false)).Times(0);
EXPECT_CALL(mock_router_filter_, onUpstreamHeaders(200, _, _, false));
tcp_upstream_->encodeHeaders(request_, false);
// Proxy the data.
EXPECT_CALL(connection_, write(BufferStringEqual("foo"), false));
Buffer::OwnedImpl buffer("foo");
tcp_upstream_->encodeData(buffer, false);
// Metadata is swallowed.
Envoy::Http::MetadataMapVector metadata_map_vector;
tcp_upstream_->encodeMetadata(metadata_map_vector);
// Forward data.
Buffer::OwnedImpl response1("bar");
EXPECT_CALL(mock_router_filter_, onUpstreamData(BufferStringEqual("bar"), _, false));
tcp_upstream_->onUpstreamData(response1, false);
Buffer::OwnedImpl response2("eep");
EXPECT_CALL(mock_router_filter_, onUpstreamHeaders(_, _, _, _)).Times(0);
EXPECT_CALL(mock_router_filter_, onUpstreamData(BufferStringEqual("eep"), _, false));
tcp_upstream_->onUpstreamData(response2, false);
}
TEST_F(TcpUpstreamTest, V1Header) {
envoy::config::core::v3::ProxyProtocolConfig* proxy_config =
mock_router_filter_.route_entry_.connect_config_->mutable_proxy_protocol_config();
proxy_config->set_version(envoy::config::core::v3::ProxyProtocolConfig::V1);
mock_router_filter_.client_connection_.remote_address_ =
std::make_shared<Network::Address::Ipv4Instance>("1.2.3.4", 5);
mock_router_filter_.client_connection_.local_address_ =
std::make_shared<Network::Address::Ipv4Instance>("4.5.6.7", 8);
Buffer::OwnedImpl expected_data;
Extensions::Common::ProxyProtocol::generateProxyProtoHeader(
*proxy_config, mock_router_filter_.client_connection_, expected_data);
// encodeHeaders now results in the proxy proto header being sent.
EXPECT_CALL(connection_, write(BufferEqual(&expected_data), false));
tcp_upstream_->encodeHeaders(request_, false);
// Data is proxied as usual.
EXPECT_CALL(connection_, write(BufferStringEqual("foo"), false));
Buffer::OwnedImpl buffer("foo");
tcp_upstream_->encodeData(buffer, false);
}
TEST_F(TcpUpstreamTest, V2Header) {
envoy::config::core::v3::ProxyProtocolConfig* proxy_config =
mock_router_filter_.route_entry_.connect_config_->mutable_proxy_protocol_config();
proxy_config->set_version(envoy::config::core::v3::ProxyProtocolConfig::V2);
mock_router_filter_.client_connection_.remote_address_ =
std::make_shared<Network::Address::Ipv4Instance>("1.2.3.4", 5);
mock_router_filter_.client_connection_.local_address_ =
std::make_shared<Network::Address::Ipv4Instance>("4.5.6.7", 8);
Buffer::OwnedImpl expected_data;
Extensions::Common::ProxyProtocol::generateProxyProtoHeader(
*proxy_config, mock_router_filter_.client_connection_, expected_data);
// encodeHeaders now results in the proxy proto header being sent.
EXPECT_CALL(connection_, write(BufferEqual(&expected_data), false));
tcp_upstream_->encodeHeaders(request_, false);
// Data is proxied as usual.
EXPECT_CALL(connection_, write(BufferStringEqual("foo"), false));
Buffer::OwnedImpl buffer("foo");
tcp_upstream_->encodeData(buffer, false);
}
TEST_F(TcpUpstreamTest, TrailersEndStream) {
// Swallow the headers.
tcp_upstream_->encodeHeaders(request_, false);
EXPECT_CALL(connection_, write(BufferStringEqual(""), true));
Envoy::Http::TestRequestTrailerMapImpl trailers{{"foo", "bar"}};
tcp_upstream_->encodeTrailers(trailers);
}
TEST_F(TcpUpstreamTest, HeaderEndStreamHalfClose) {
EXPECT_CALL(connection_, write(BufferStringEqual(""), true));
tcp_upstream_->encodeHeaders(request_, true);
}
TEST_F(TcpUpstreamTest, ReadDisable) {
EXPECT_CALL(connection_, readDisable(true));
tcp_upstream_->readDisable(true);
EXPECT_CALL(connection_, readDisable(false));
tcp_upstream_->readDisable(false);
// Once the connection is closed, don't touch it.
connection_.state_ = Network::Connection::State::Closed;
EXPECT_CALL(connection_, readDisable(_)).Times(0);
tcp_upstream_->readDisable(true);
}
TEST_F(TcpUpstreamTest, UpstreamEvent) {
// Make sure upstream disconnects result in stream reset.
EXPECT_CALL(mock_router_filter_,
onUpstreamReset(Envoy::Http::StreamResetReason::ConnectionTermination, "", _));
tcp_upstream_->onEvent(Network::ConnectionEvent::RemoteClose);
}
TEST_F(TcpUpstreamTest, Watermarks) {
EXPECT_CALL(mock_router_filter_, callbacks()).Times(AnyNumber());
EXPECT_CALL(mock_router_filter_.callbacks_, onDecoderFilterAboveWriteBufferHighWatermark());
tcp_upstream_->onAboveWriteBufferHighWatermark();
EXPECT_CALL(mock_router_filter_.callbacks_, onDecoderFilterBelowWriteBufferLowWatermark());
tcp_upstream_->onBelowWriteBufferLowWatermark();
}
} // namespace Tcp
} // namespace Http
} // namespace Upstreams
} // namespace Extensions
} // namespace Envoy
|
//
// Created by payaln on 20.02.2019.
//
#pragma once
#include <G4VUserPrimaryGeneratorAction.hh>
#include <G4ParticleGun.hh>
#include <G4Event.hh>
#include <G4Gamma.hh>
#include <G4ParticleTable.hh>
#include <G4SystemOfUnits.hh>
#include <Randomize.hh>
#include "GlobalMessenger.h"
class PrimaryPartGenerator : public G4VUserPrimaryGeneratorAction {
public:
PrimaryPartGenerator();
void GeneratePrimaries(G4Event *anEvent) override;
void setSingleEnergy(G4bool singleEnergy);
private:
G4ParticleGun* GGamma;
G4bool singleEnergy;
void GenEnergy();
};
|
#include "machine_fixture.h"
namespace mix {
class MachineAddressesTestSuite : public MachineFixture {};
TEST_F(MachineAddressesTestSuite, enta) {
machine.enta(make_instruction(cmd_enta, 70));
EXPECT_EQ(70, get_reg_a_value());
}
TEST_F(MachineAddressesTestSuite, ent1) {
machine.ent1(make_instruction(cmd_ent1, 71));
EXPECT_EQ(71, get_reg_i_value(1));
}
TEST_F(MachineAddressesTestSuite, ent2) {
machine.ent2(make_instruction(cmd_ent2, 72));
EXPECT_EQ(72, get_reg_i_value(2));
}
TEST_F(MachineAddressesTestSuite, ent3) {
machine.ent3(make_instruction(cmd_ent3, 73));
EXPECT_EQ(73, get_reg_i_value(3));
}
TEST_F(MachineAddressesTestSuite, ent4) {
machine.ent4(make_instruction(cmd_ent4, 74));
EXPECT_EQ(74, get_reg_i_value(4));
}
TEST_F(MachineAddressesTestSuite, ent5) {
machine.ent5(make_instruction(cmd_ent5, 75));
EXPECT_EQ(75, get_reg_i_value(5));
}
TEST_F(MachineAddressesTestSuite, ent6) {
machine.ent6(make_instruction(cmd_ent6, 76));
EXPECT_EQ(76, get_reg_i_value(6));
}
TEST_F(MachineAddressesTestSuite, entx) {
machine.entx(make_instruction(cmd_entx, 77));
EXPECT_EQ(77, get_reg_x_value());
}
TEST_F(MachineAddressesTestSuite, enna) {
machine.enna(make_instruction(cmd_enna, 70));
EXPECT_EQ(-70, get_reg_a_value());
}
TEST_F(MachineAddressesTestSuite, enn1) {
machine.enn1(make_instruction(cmd_enn1, 71));
EXPECT_EQ(-71, get_reg_i_value(1));
}
TEST_F(MachineAddressesTestSuite, enn2) {
machine.enn2(make_instruction(cmd_enn2, 72));
EXPECT_EQ(-72, get_reg_i_value(2));
}
TEST_F(MachineAddressesTestSuite, enn3) {
machine.enn3(make_instruction(cmd_enn3, 73));
EXPECT_EQ(-73, get_reg_i_value(3));
}
TEST_F(MachineAddressesTestSuite, enn4) {
machine.enn4(make_instruction(cmd_enn4, 74));
EXPECT_EQ(-74, get_reg_i_value(4));
}
TEST_F(MachineAddressesTestSuite, enn5) {
machine.enn5(make_instruction(cmd_enn5, 75));
EXPECT_EQ(-75, get_reg_i_value(5));
}
TEST_F(MachineAddressesTestSuite, enn6) {
machine.enn6(make_instruction(cmd_enn6, 76));
EXPECT_EQ(-76, get_reg_i_value(6));
}
TEST_F(MachineAddressesTestSuite, ennx) {
machine.ennx(make_instruction(cmd_ennx, 77));
EXPECT_EQ(-77, get_reg_x_value());
}
TEST_F(MachineAddressesTestSuite, inca) {
set_reg_a_value(100);
machine.inca(make_instruction(cmd_inca));
EXPECT_EQ(101, get_reg_a_value());
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, inca_overflowed) {
set_reg_a_value(big_register::VALUES_IN_WORD - 1);
machine.inca(make_instruction(cmd_inca));
EXPECT_EQ(0, get_reg_a_value());
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, inc1) {
set_reg_i_value(1, 100);
machine.inc1(make_instruction(cmd_inc1));
EXPECT_EQ(101, get_reg_i_value(1));
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, inc1_overflowed) {
set_reg_i_value(1, small_register::VALUES_IN_WORD - 1);
machine.inc1(make_instruction(cmd_inc1));
EXPECT_EQ(0, get_reg_i_value(1));
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, inc2) {
set_reg_i_value(2, 100);
machine.inc2(make_instruction(cmd_inc2));
EXPECT_EQ(101, get_reg_i_value(2));
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, inc2_overflowed) {
set_reg_i_value(2, small_register::VALUES_IN_WORD - 1);
machine.inc2(make_instruction(cmd_inc2));
EXPECT_EQ(0, get_reg_i_value(2));
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, inc3) {
set_reg_i_value(3, 100);
machine.inc3(make_instruction(cmd_inc3));
EXPECT_EQ(101, get_reg_i_value(3));
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, inc3_overflowed) {
set_reg_i_value(3, small_register::VALUES_IN_WORD - 1);
machine.inc3(make_instruction(cmd_inc3));
EXPECT_EQ(0, get_reg_i_value(3));
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, inc4) {
set_reg_i_value(4, 100);
machine.inc4(make_instruction(cmd_inc4));
EXPECT_EQ(101, get_reg_i_value(4));
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, inc4_overflowed) {
set_reg_i_value(4, small_register::VALUES_IN_WORD - 1);
machine.inc4(make_instruction(cmd_inc4));
EXPECT_EQ(0, get_reg_i_value(4));
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, inc5) {
set_reg_i_value(5, 100);
machine.inc5(make_instruction(cmd_inc5));
EXPECT_EQ(101, get_reg_i_value(5));
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, inc5_overflowed) {
set_reg_i_value(5, small_register::VALUES_IN_WORD - 1);
machine.inc5(make_instruction(cmd_inc5));
EXPECT_EQ(0, get_reg_i_value(5));
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, inc6) {
set_reg_i_value(6, 100);
machine.inc6(make_instruction(cmd_inc6));
EXPECT_EQ(101, get_reg_i_value(6));
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, inc6_overflowed) {
set_reg_i_value(6, small_register::VALUES_IN_WORD - 1);
machine.inc6(make_instruction(cmd_inc6));
EXPECT_EQ(0, get_reg_i_value(6));
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, incx) {
set_reg_x_value(100);
machine.incx(make_instruction(cmd_incx));
EXPECT_EQ(101, get_reg_x_value());
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, incx_overflowed) {
set_reg_x_value(big_register::VALUES_IN_WORD - 1);
machine.incx(make_instruction(cmd_incx));
EXPECT_EQ(0, get_reg_x_value());
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, deca) {
set_reg_a_value(-100);
machine.deca(make_instruction(cmd_deca));
EXPECT_EQ(-101, get_reg_a_value());
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, deca_oveflowed) {
set_reg_a_value(-1 * big_register::VALUES_IN_WORD + 1);
machine.deca(make_instruction(cmd_deca));
EXPECT_EQ(0, get_reg_a_value());
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, dec1) {
set_reg_i_value(1, -100);
machine.dec1(make_instruction(cmd_dec1));
EXPECT_EQ(-101, get_reg_i_value(1));
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, dec1_overflowed) {
set_reg_i_value(1, -1 * small_register::VALUES_IN_WORD + 1);
machine.dec1(make_instruction(cmd_dec1));
EXPECT_EQ(0, get_reg_i_value(1));
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, dec2) {
set_reg_i_value(2, -100);
machine.dec2(make_instruction(cmd_dec2));
EXPECT_EQ(-101, get_reg_i_value(2));
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, dec2_overflowed) {
set_reg_i_value(2, -1 * small_register::VALUES_IN_WORD + 1);
machine.dec2(make_instruction(cmd_dec2));
EXPECT_EQ(0, get_reg_i_value(2));
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, dec3) {
set_reg_i_value(3, -100);
machine.dec3(make_instruction(cmd_dec3));
EXPECT_EQ(-101, get_reg_i_value(3));
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, dec3_overflowed) {
set_reg_i_value(3, -1 * small_register::VALUES_IN_WORD + 1);
machine.dec3(make_instruction(cmd_dec3));
EXPECT_EQ(0, get_reg_i_value(3));
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, dec4) {
set_reg_i_value(4, -100);
machine.dec4(make_instruction(cmd_dec4));
EXPECT_EQ(-101, get_reg_i_value(4));
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, dec4_overflowed) {
set_reg_i_value(4, -1 * small_register::VALUES_IN_WORD + 1);
machine.dec4(make_instruction(cmd_dec4));
EXPECT_EQ(0, get_reg_i_value(4));
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, dec5) {
set_reg_i_value(5, -100);
machine.dec5(make_instruction(cmd_dec5));
EXPECT_EQ(-101, get_reg_i_value(5));
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, dec5_overflowed) {
set_reg_i_value(5, -1 * small_register::VALUES_IN_WORD + 1);
machine.dec5(make_instruction(cmd_dec5));
EXPECT_EQ(0, get_reg_i_value(5));
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, dec6) {
set_reg_i_value(6, -100);
machine.dec6(make_instruction(cmd_dec6));
EXPECT_EQ(-101, get_reg_i_value(6));
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, dec6_overflowed) {
set_reg_i_value(6, -1 * small_register::VALUES_IN_WORD + 1);
machine.dec6(make_instruction(cmd_dec6));
EXPECT_EQ(0, get_reg_i_value(6));
EXPECT_TRUE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, decx) {
set_reg_x_value(-100);
machine.decx(make_instruction(cmd_decx));
EXPECT_EQ(-101, get_reg_x_value());
EXPECT_FALSE(machine.overflow);
}
TEST_F(MachineAddressesTestSuite, decx_oveflowed) {
set_reg_x_value(-1 * big_register::VALUES_IN_WORD + 1);
machine.decx(make_instruction(cmd_decx));
EXPECT_EQ(0, get_reg_x_value());
EXPECT_TRUE(machine.overflow);
}
} // namespace mix
|
/*****************************************************************************************************************
* File Name : mergeTwoSortedArray.h
* File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\arrays\page08\mergeTwoSortedArray.h
* Created on : Jan 2, 2014 :: 10:09:04 PM
* Author : AVINASH
* Testing Status : TODO
* URL : TODO
*****************************************************************************************************************/
/************************************************ Namespaces ****************************************************/
using namespace std;
using namespace __gnu_cxx;
/************************************************ User Includes *************************************************/
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <hash_map>
#include <stack>
#include <queue>
#include <limits.h>
#include <programming/ds/tree.h>
#include <programming/ds/linkedlist.h>
#include <programming/utils/treeutils.h>
#include <programming/utils/llutils.h>
/************************************************ User defined constants *******************************************/
#define null NULL
/************************************************* Main code ******************************************************/
#ifndef MERGETWOSORTEDARRAY_H_
#define MERGETWOSORTEDARRAY_H_
vector<int> mergeTwoSortedArrayBySorting(vector<int> sortedFirstArray,vector<int> sortedSecondArray){
if(sortedFirstArray.size() == 0 && sortedSecondArray.size() == 0){
return sortedFirstArray;
}
if(sortedFirstArray.size() == 0 || sortedSecondArray.size() == 0){
if(sortedFirstArray.size() != 0){
return sortedFirstArray;
}else{
return sortedSecondArray;
}
}
vector<int> mergedArray;
merge(sortedFirstArray.begin(),sortedFirstArray.end(),sortedSecondArray.begin(),sortedSecondArray.end(),mergedArray.begin());
sort(mergedArray.begin(),mergedArray.end());
return mergedArray;
}
vector<int> mergeTwoSortedArray(vector<int> sortedFirstArray,vector<int> sortedSecondArray){
if(sortedFirstArray.size() == 0 && sortedSecondArray.size() == 0){
return sortedFirstArray;
}
if(sortedFirstArray.size() == 0 || sortedSecondArray.size() == 0){
if(sortedFirstArray.size() != 0){
return sortedFirstArray;
}else{
return sortedSecondArray;
}
}
vector<int> mergedArray;
unsigned int firstCounter=0,secondCounter=0;
while(firstCounter < sortedFirstArray.size() && secondCounter < sortedSecondArray.size()){
if(sortedFirstArray[firstCounter] < sortedSecondArray[secondCounter]){
mergedArray.push_back(sortedFirstArray[firstCounter]);
firstCounter += 1;
}else{
mergedArray.push_back(sortedSecondArray[secondCounter]);
secondCounter += 1;
}
}
while(firstCounter < sortedFirstArray.size()){
mergedArray.push_back(sortedFirstArray[firstCounter]);
firstCounter++;
}
while(secondCounter < sortedSecondArray.size()){
mergedArray.push_back(sortedSecondArray[secondCounter]);
secondCounter++;
}
return mergedArray;
}
#endif /* MERGETWOSORTEDARRAY_H_ */
/************************************************* End code *******************************************************/
|
/**
* @copyright 2013 Christoph Woester
* @author Christoph Woester
*
* 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 "EfficientPortfolioWithRisklessAsset.h"
namespace fpo {
EfficientPortfolioWithRisklessAsset::EfficientPortfolioWithRisklessAsset(double riskless, Eigen::VectorXd& mean, Eigen::MatrixXd& variance)
: EfficientPortfolio(mean.size() + 1, mean, variance), _risklessRate(riskless), _riskyPortfolioModel(mean, variance)
{
alpha = _riskyPortfolioModel.getCoefficient(EfficientPortfolio::ALPHA);
beta = _riskyPortfolioModel.getCoefficient(EfficientPortfolio::BETA);
gamma = _riskyPortfolioModel.getCoefficient(EfficientPortfolio::GAMMA);
delta = _riskyPortfolioModel.getCoefficient(EfficientPortfolio::DELTA);
_computeTangencyPortfolio();
}
EfficientPortfolioWithRisklessAsset::~EfficientPortfolioWithRisklessAsset() {
}
/**
* Returns the expected return of the given portfolio structure.
*
* @param portfolio the portfolio structure
*
* @return the expected portfolio return
*/
double EfficientPortfolioWithRisklessAsset::portfolioReturn(const Eigen::VectorXd& portfolio)
{
Eigen::VectorXd riskyAssets = portfolio.head(dim - 1);
double riskReturn = riskyAssets.dot(mean);
double risklessReturn = portfolio(dim - 1) * _risklessRate;
return riskyAssets.dot(mean) + portfolio(dim - 1) * _risklessRate;
}
/**
* Returns the variance of the given portfolio structure.
*
* @param portfolio the portfolio structure
*
* @return the portfolio variance
*/
double EfficientPortfolioWithRisklessAsset::portfolioVariance(const Eigen::VectorXd& portfolio)
{
Eigen::VectorXd riskyAssets = portfolio.head(dim - 1);
return riskyAssets.dot(variance * riskyAssets);
}
/**
* Returns the portfolio variance for a given expected return.
*
* @param expectedReturn the required expected return
*
* @return the portfolio variance
*/
double EfficientPortfolioWithRisklessAsset::portfolioVariance(const double expectedReturn)
{
double excessReturn = expectedReturn - _risklessRate;
double x = _risklessRate * gamma - 2 * alpha;
return (excessReturn * excessReturn) / (beta + x * _risklessRate);
}
/**
* Returns the efficient portfolio for the given expected return.
*
* @param expectedReturn the required expected return
*
* @return the efficient portfolio
*/
Eigen::VectorXd EfficientPortfolioWithRisklessAsset::efficientPortfolio(const double expectedReturn)
{
if (expectedReturn <= _risklessRate) {
return minimumVariancePortfolio();
} else {
double theta = _riskyPortion(expectedReturn);
Eigen::VectorXd efficientPortfolio = theta * tangencyPortolio();
efficientPortfolio(dim - 1) = (1.0 - theta);
return efficientPortfolio;
}
}
/**
* Returns the minimum variance portfolio.
*
* HINT: this is not the MVP of the risky asset portfolio but the full investment in the
* riskless asset (zero variance)
*
* @return the minimum variance portfolio
*/
Eigen::VectorXd EfficientPortfolioWithRisklessAsset::minimumVariancePortfolio()
{
Eigen::VectorXd mvp = Eigen::VectorXd::Zero(dim);
mvp(dim - 1) = 1.0;
return mvp;
}
/**
* Returns the performance increasing portfolio structure; if a riskless asset exists the
* performance increasing portfolio is identical to the tangency portfolio (Tobin's separation
* theorem)
*
* @return the performance-increasing portfolio structure
*/
Eigen::VectorXd EfficientPortfolioWithRisklessAsset::performanceIncreasingPortfolio()
{
return tangencyPortolio();
}
/**
* Returns the tangency portfolio
*
* @return the tangency portfolio
*/
Eigen::VectorXd EfficientPortfolioWithRisklessAsset::tangencyPortolio()
{
return _tangencyPortfolio;
}
/**
* Returns the share to invest in risky assets
*
* @param expected return
*
* @return share to invest in risky assets
*/
double EfficientPortfolioWithRisklessAsset::_riskyPortion(double expectedReturn)
{
if (expectedReturn <= _risklessRate) {
return 0.0;
} else {
double x = gamma * _risklessRate - 2 * alpha;
return -(alpha + x) / (beta + x * _risklessRate) * (expectedReturn - _risklessRate);
}
}
/**
* Computes the structure and the expected return of the tangency portfolio;
*/
void EfficientPortfolioWithRisklessAsset::_computeTangencyPortfolio()
{
Eigen::LDLT<Eigen::MatrixXd> ldlt;
ldlt.compute(variance);
Eigen::VectorXd one = Eigen::VectorXd::Constant(dim - 1, 1.0);
Eigen::VectorXd excessReturn = mean - _risklessRate * one;
_inverseTimesExcessReturn = ldlt.solve(excessReturn);
_tangencyPortfolio = Eigen::VectorXd::Constant(dim, 0.0);
_tangencyPortfolio.head(dim - 1) = 1.0 / (alpha - gamma * _risklessRate) * _inverseTimesExcessReturn;
_tangencyPortfolioReturn = portfolioReturn(_tangencyPortfolio);
}
} /* namespace fpo */
|
/**
\file goalDetector.cpp
\author UnBeatables
\date LARC2018
\name goalDetector
*/
#include "goalDetector.hpp"
#define DEBUG_PERCEPTION 1
void GoalDetector::run(cv::Mat topImg, cv::Mat goalImg, PerceptionData *data)
{
// Goal detection on roi_field
cv::Mat goal = topImg.clone();
cv::Mat src_gray,src;
// Treshold for binary image
int t = 240;
cv::Mat campo = cv::Mat::zeros(goal.rows,goal.cols, CV_8UC1);
cv::cvtColor(goal, src_gray, CV_BGR2GRAY );
//Field roi mask creation
for (int w = 0; w < campo.rows; w++)
{
for (int q = 0; q < campo.cols ; q ++)
{
if(w < this->greenVerticalAvg)
{
campo.at<uchar>(w,q) = 255;
}
}
}
//Get goal ROI
cv::bitwise_and(src_gray,campo,src);
cv::GaussianBlur( src, src, cv::Size( 3,3 ), 0, 0 );
int scale = 1;
int delta = 0;
int ddepth = CV_16S;
cv::Mat grad;
//Get contours using sobel kernel
cv::Sobel( src, grad, ddepth, 1, 0, 3, scale, delta, cv::BORDER_DEFAULT );
cv::convertScaleAbs(grad, grad);
cv::threshold( grad, grad, t, 255,0 );
//Noise canceling
cv::dilate(grad,grad,cv::getStructuringElement(cv::MORPH_RECT,cv::Size(1,3)),cv::Point(-1,-1));
cv::erode(grad,grad,cv::getStructuringElement(cv::MORPH_RECT,cv::Size(1,9)),cv::Point(-1,-1));
//Uses hough to get lines in image
std::vector<cv::Vec4i> lines;
cv::HoughLinesP(grad,lines,1,CV_PI/180,10,10);
float gol_x = 0.0, nLines = 0.0;
for(size_t i = 0; i < lines.size(); i++)
{
// If lines is close to field its likely a goal.
cv::Vec4i aLine = lines[i];
if(aLine[1] > this->greenVerticalAvg - 50)
{
gol_x = gol_x + (float)((float)aLine[0]/(fabs((float)aLine[1] - (float)this->greenVerticalAvg)));
nLines = nLines + (float)(1/(fabs((float)aLine[1] - (float)this->greenVerticalAvg)));
#ifdef DEBUG_PERCEPTION
//std::cout << "linha_x:" << std::dec << aLine[0] << std::endl;
cv::line(goal,cv::Point(aLine[0],aLine[1]),cv::Point(aLine[2],aLine[3]),cv::Scalar(0,0,255),3,CV_AA);
#endif
}
}
if(nLines){
gol_x = gol_x/nLines; //The goal center line is the average of all the lines.
}
else{
gol_x = -1;
}
#ifdef DEBUG_PERCEPTION
cv::circle(goal,cv::Point(gol_x,this->greenVerticalAvg),4,cv::Scalar(255,0,0),2);
cv::imwrite("gol.jpg",goal);
cv::imwrite("gol_gradiente.jpg",grad);
#endif
this->bestGoal.imgPosX = gol_x;
updateData(data);
}
void GoalDetector::updateData(PerceptionData *data)
{
data->goalCenter = this->bestGoal.imgPosX;
}
|
// winmain.cxx
#include "mainwin.h"
// global-variables //////////////////////////////////////////////////////////////////////
HINSTANCE hAppInstance;
char HomeFolderName[MAX_PATH];
CRITICAL_SECTION c_section;
ID2D1Factory *pD2D_Factory;
IWICImagingFactory *pWIC_Factory;
IDWriteFactory *pDWR_Factory;
//////////////////////////////////////////////////////////////////////////////////////////
LONG WINAPI ExceptionFilter(EXCEPTION_POINTERS *ExceptionInfo)
{
SystemParametersInfo(SPI_SETCURSORS, 0, NULL, 0);
char mes[256];
sprintf(mes, "Unhandled error occurred.(address:0x%08x)",
PtrToUlong(ExceptionInfo->ExceptionRecord->ExceptionAddress));
MessageBox(NULL, mes, "ExceptionError", MB_OK|MB_TOPMOST|MB_APPLMODAL);
// return EXCEPTION_CONTINUE_SEARCH;
// return EXCEPTION_CONTINUE_EXECUTION;
return EXCEPTION_EXECUTE_HANDLER;
}
//////////////////////////////////////////////////////////////////////////////////////////
#ifdef USE_WPF
[System::STAThreadAttribute]
#endif
int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
// prevent multiple start
HANDLE hmutex;
{
SECURITY_DESCRIPTOR sd;
InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&sd, TRUE, 0, FALSE);
SECURITY_ATTRIBUTES secAttribute;
secAttribute.nLength=sizeof(SECURITY_ATTRIBUTES);
secAttribute.lpSecurityDescriptor=&sd;
secAttribute.bInheritHandle=TRUE;
hmutex=CreateMutex(&secAttribute, FALSE, MAINWIN_CLASS_NAME);
if((hmutex==NULL)||(GetLastError()==ERROR_ALREADY_EXISTS)){
HWND hwnd_fs=FindWindow(MAINWIN_CLASS_NAME, NULL);
if(hwnd_fs!=NULL){
ShowWindow(hwnd_fs, SW_SHOWNORMAL);
SetForegroundWindow(hwnd_fs);
SetActiveWindow(hwnd_fs);
}else{
hwnd_fs=FindWindow(NULL, MAINWIN_WINDOW_NAME);
if(hwnd_fs!=NULL){
SetForegroundWindow(hwnd_fs);
SetActiveWindow(hwnd_fs);
SetWindowPos(hwnd_fs, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
}
}
return 0;
}
}
// global variables
hAppInstance=hInstance;
GetModuleFileName(NULL, HomeFolderName, MAX_PATH); PathRemoveFileSpec(HomeFolderName);
InitializeCriticalSection(&c_section);
// Direct2D/DWrite/WIC
CoInitialize(NULL);
D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pD2D_Factory);
DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast<IUnknown **>(&pDWR_Factory));
CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory), reinterpret_cast<LPVOID *>(&pWIC_Factory));
// exception handler
HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
SetUnhandledExceptionFilter(ExceptionFilter);
// common library
INITCOMMONCONTROLSEX icex;
icex.dwSize=sizeof(INITCOMMONCONTROLSEX); icex.dwICC=ICC_COOL_CLASSES|ICC_WIN95_CLASSES;
InitCommonControlsEx(&icex);
HMODULE hre_dll=LoadLibrary("RichEd32.dll");
#ifdef USE_EXTERNALDLL
SetDllDirectory(dllfoldername);
#endif
// initialize
timeBeginPeriod(1);
mainWin *mainwin=new mainWin();
{
mainwin->Initialize();
mainwin->Show();
mainwin->RunMessageLoop();
mainwin->Uninitialize();
}
delete mainwin;
// finalize
timeEndPeriod(1);
SystemParametersInfo(SPI_SETCURSORS, 0, NULL, 0);
if(hre_dll!=NULL) FreeLibrary(hre_dll);
SafeRelease(&pWIC_Factory);
SafeRelease(&pDWR_Factory);
SafeRelease(&pD2D_Factory);
CoUninitialize();
DeleteCriticalSection(&c_section);
CloseHandle(hmutex);
return 0;
}
|
#pragma once
#ifndef __HI_MAYA_H__
#define __HI_MAYA_H__
#include <maya/MPxCommand.h>
//a very very basic Maya command;
class HiMaya : public MPxCommand
{
public:
HiMaya() = default;
//when call "HiMaya;" from mel or "Maya.cmds.HiMaya()" from python
virtual MStatus doIt(const MArgList&);
//called when the command is registered, return a pointer to a new instance of the class
static void* creator();
};
#endif
|
/*
This program uses an arduino to collect flight mission parameters
from a user. It then calculates and performs the correct timing of
shutter events given the input.
*/
#include <Arduino.h>
#include <LiquidCrystal.h>
#include <math.h>
enum Button { up, down, right, left, select, none, unknown };
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
const int PWM_PIN = 3;
const float TRIGGER_TIME_MS = 100;
const float FORWARD_OVERLAP = 70;
float time_ms;
Button readinput() {
int adc_key_in = analogRead(0);
Button pressed = unknown;
if (adc_key_in < 50) pressed = right;
if ((adc_key_in > 50) && (adc_key_in < 250)) pressed = up;
if ((adc_key_in > 250) && (adc_key_in < 400)) pressed = down;
if ((adc_key_in > 400) && (adc_key_in < 650)) pressed = left;
if ((adc_key_in > 650) && (adc_key_in < 800)) pressed = select;
if ((adc_key_in > 800) && (adc_key_in < 1150)) pressed = none;
return pressed;
}
void setup() {
float height_ft = 400;
float speed_mph = 15;
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("starting up");
delay(2000);
// get flight height and speed
Button status = none;
while (status != select) {
lcd.clear();
status = readinput();
lcd.setCursor(0, 0);
lcd.print("height speed");
lcd.setCursor(0, 1);
lcd.print(height_ft);
lcd.print(" ");
lcd.print(speed_mph);
if (status == up) height_ft += 10;
if (status == down) height_ft -= 10;
if (status == right) speed_mph += 1;
if (status == left) speed_mph -= 1;
delay(120);
}
// calculate trigger time
delay(1000);
// button pressed - save settings
// pwm_pin = 6;
float height = height_ft * 0.3048; // m
float speed = speed_mph * 0.44704; // m/s
// float s_width = 000; // mm
float s_focal = 55; // mm
// float img_width = 8280; // pix
float img_height = 6208; // pix
float pix_pitch = 0.0053; // mm
float gsd = pix_pitch * height / s_focal; // m
float length = img_height * gsd; // m
float distance = length * (100 - FORWARD_OVERLAP) / 100; // m
float time = distance / speed; // s
// confirm time interval, or manual change
status = none;
bool change_time = false;
while (status != select) {
status = readinput();
if (status == left) change_time = true;
lcd.clear();
lcd.setCursor(0, 0);
if (!change_time) {
lcd.print("time [s] | [<-]");
} else {
Button ch_status = none;
while (ch_status != select) {
ch_status = readinput();
lcd.clear();
lcd.print("time [^ | v]");
lcd.setCursor(0, 1);
lcd.print(time, 1);
if (ch_status == up) time += 0.1;
if (ch_status == down) time -= 0.1;
delay(120);
}
change_time = false;
status = none;
lcd.clear();
}
lcd.setCursor(0, 1);
lcd.print(time, 1);
}
delay(1000);
// convert time to milliseconds
time_ms = time * 1000;
// get time to wait before triggering
lcd.clear();
status = none;
int time_to_wait = 45;
while (status != select) {
status = readinput();
lcd.setCursor(0, 0);
lcd.print("delay [^ | v]");
lcd.setCursor(0, 1);
lcd.print(time_to_wait);
if (status == up) time_to_wait += 10;
if (status == down) time_to_wait -= 10;
delay(120);
}
delay(1000);
// confirm mission start
lcd.clear();
status = none;
lcd.setCursor(0, 0);
lcd.print("Press select to");
lcd.setCursor(0, 1);
lcd.print("start mission");
while (status != select) {
status = readinput();
}
delay(1000);
// start message
lcd.setCursor(0, 0);
lcd.print("triggering starts ");
lcd.setCursor(0, 1);
lcd.print("in ");
lcd.print(time_to_wait);
lcd.print(" seconds");
delay(time_to_wait * 1000.0);
lcd.noDisplay();
}
void loop() {
// wait calculated seconds
analogWrite(PWM_PIN, 255);
delay(time_ms);
// trigger
analogWrite(PWM_PIN, 0);
delay(TRIGGER_TIME_MS);
}
|
#ifndef NIKESHOES_H
#define NIKESHOES_H
#include "shoes.h"
#include <iostream>
class NikeShoes : public Shoes
{
public:
virtual void show() override
{
std::cout << "Just do it" << std::endl;
}
};
#endif // NIKESHOES_H
|
// $Id: lasvariablerecord_test.cpp 712 2008-05-14 22:47:43Z hobu $
//
// (C) Copyright Mateusz Loskot 2008, mateusz@loskot.net
// Distributed under the BSD License
// (See accompanying file LICENSE.txt or copy at
// http://www.opensource.org/licenses/bsd-license.php)
//
// liblas
#include <liblas/liblas.hpp>
// tut
#include <tut/tut.hpp>
// std
#include <string>
namespace tut
{
struct lasvariablerecord_data
{
liblas::VariableRecord m_default;
void test_default(liblas::VariableRecord const& h)
{
ensure_equals("wrong default reserved bytes",
h.GetReserved(), 0xAABB);
ensure_equals("wrong default record identifier",
h.GetRecordId(), boost::uint16_t());
ensure_equals("wrong default record length",
h.GetRecordLength(), boost::uint16_t());
ensure_equals("wrong default user identifier",
h.GetUserId(true).c_str(), std::string());
ensure_equals("wrong default description",
h.GetDescription(true).c_str(), std::string());
}
};
typedef test_group<lasvariablerecord_data> tg;
typedef tg::object to;
tg test_group_lasvariablerecord("liblas::VariableRecord");
// Test default constructor
template<>
template<>
void to::test<1>()
{
test_default(m_default);
}
// Test copy constructor
template<>
template<>
void to::test<2>()
{
liblas::VariableRecord hdr_copy(m_default);
test_default(hdr_copy);
}
// Test assignment operator
template<>
template<>
void to::test<3>()
{
liblas::VariableRecord hdr_copy;
test_default(hdr_copy);
hdr_copy = m_default;
test_default(hdr_copy);
}
// Test equal function
template<>
template<>
void to::test<4>()
{
liblas::VariableRecord hdr;
ensure("two default headers not equal", m_default.equal(hdr));
liblas::VariableRecord hdr_copy(m_default);
ensure("copy of default header not equal", hdr_copy.equal(m_default));
}
// Test equal-to operator
template<>
template<>
void to::test<5>()
{
liblas::VariableRecord hdr;
ensure("two default headers not equal", m_default == hdr);
liblas::VariableRecord hdr_copy(m_default);
ensure("copy of default header not equal", hdr_copy == m_default);
}
// Test not-equal-to operator
template<>
template<>
void to::test<6>()
{
liblas::VariableRecord hdr;
ensure_not("two default headers not equal", m_default != hdr);
liblas::VariableRecord hdr_copy(m_default);
ensure_not("copy of default header not equal", hdr_copy != m_default);
}
}
|
#include "GnSystemPCH.h"
#include "GnFrameSkip.h"
|
#include "EvaluationMap.h"
#include "Entities/Range/Appraised/AppraisedRange.h"
#include "JsonArraySerialization.h"
struct EvaluationMap::Implementation {
QList<AppraisedRange> appraisedRanges;
};
// :: Lifecycle ::
// :: Constructors ::
EvaluationMap::EvaluationMap() : pimpl(new Implementation()) {}
// :: Copy ::
EvaluationMap::EvaluationMap(const EvaluationMap &other)
: pimpl(new Implementation(*other.pimpl))
{ }
EvaluationMap &EvaluationMap::operator=(const EvaluationMap &other) {
*pimpl = *other.pimpl;
return *this;
}
// :: Move ::
EvaluationMap::EvaluationMap(EvaluationMap &&other) : pimpl(other.pimpl.take()) {}
EvaluationMap &EvaluationMap::operator=(EvaluationMap &&other) {
pimpl.swap(other.pimpl);
return *this;
}
// :: Destructor ::
EvaluationMap::~EvaluationMap() {}
// :: Accessors ::
void EvaluationMap::addAppraisedRange(const AppraisedRange &appraisedRange) {
pimpl->appraisedRanges.append(appraisedRange);
}
void EvaluationMap::addAppraisedRange(const Range &range,
const QString &result/*= ""*/) {
addAppraisedRange({range, result});
}
void EvaluationMap::setResultToLastRange(const QString &result) {
pimpl->appraisedRanges.last().setResult(result);
}
uint EvaluationMap::size() const {
return pimpl->appraisedRanges.size();
}
void EvaluationMap::removeAt(uint index) {
pimpl->appraisedRanges.removeAt(index);
}
// :: Методы индексации ::
const AppraisedRange &EvaluationMap::at(uint index) const {
return pimpl->appraisedRanges.at(index);
}
const AppraisedRange &EvaluationMap::operator[](uint index) const {
return pimpl->appraisedRanges[index];
}
AppraisedRange &EvaluationMap::operator[](uint index) {
return pimpl->appraisedRanges[index];
}
// :: Serializable ::
QJsonArray EvaluationMap::toJson() const {
return jsonArrayFromSerializableObjects(pimpl->appraisedRanges);
}
void EvaluationMap::initWithJsonArray(const QJsonArray &json) {
pimpl->appraisedRanges =
serializableObjectsFromJsonArray<QList, AppraisedRange>(json);
}
|
/*
* License:
* License does not expire.
* Can be distributed in infinitely projects
* Can be distributed and / or packaged as a code or binary product (sublicensed)
* Commercial use allowed under the following conditions :
* - Crediting the Author
* Can modify source-code
*/
/*
* File: VertexBufferObject.h
* Author: Suirad <darius-suirad@gmx.de>
*
* Created on 14. Januar 2018, 16:36
*/
#ifndef VERTEXARRAYOBJECT_H
#define VERTEXARRAYOBJECT_H
#include <vector>
#include "IndexBuffer.h"
class VertexArrayObject {
public:
//Creates newEmpty VAO
VertexArrayObject();
//Deletes VAO and VBOs
virtual ~VertexArrayObject();
//Add New Index Buffer
void addIndexBuffer(std::vector<unsigned int> indices, IndexBuffer &index);
//Add New VertexBuffer of Specific Dimension at Specific Row in the Vertex Array
void addVertexBuffer(std::vector<float> values, int dimension, int row);
//Bind Vao
void bind();
//Unbind Vao
void unbind();
//Id Of the VAO
unsigned int id;
private:
//List of All Vertex Buffer IDs
std::vector<unsigned int> vboIds;
//List of All Vertex Attributes
std::vector<unsigned int> attribs;
};
#endif /* VERTEXARRAYOBJECT_H */
|
//-------------------------------------------------------------------------------------------------
// File : s3d_testScene.h
// Desc : Test Scene.
// Copyright(c) Project Asura. All right reserved.
//-------------------------------------------------------------------------------------------------
#pragma once
//-------------------------------------------------------------------------------------------------
// Includes
//-------------------------------------------------------------------------------------------------
#include <s3d_scene.h>
#include <vector>
namespace s3d {
class TestScene : public Scene
{
public:
TestScene( const u32 width, const u32 height );
virtual ~TestScene();
private:
std::vector<IShape*> m_Shapes;
std::vector<IMaterial*> m_Material;
};
} // namespace s3d
|
#include "Infantry_Config.h"
#include "PID.h"
S_Infantry Infantry;
void Infantry_Config_Init()
{
Shoot_Init();
Pitch_Yaw_Init();
}
//发射pid参数设置
void Shoot_Init()
{
Shoot.pid_init(LEFT_FRI_SPEED,10.0f,0.5f,0.0f,0,30000.0f);
Shoot.pid_init(RIGHT_FRI_SPEED,10.0f,0.5f,0.0f,0,30000.0f);
Shoot.pid_init(TURNPLATE_SPEED,20.0f,0.0f,0.0f,7000.0,8000.0f);
Shoot.pid_init(TURNPLATE_ANGLE,10.0f,0.0f,0.05f,0,8000.0f);
Shoot.turnPlateSpeed.I_SeparThresh = 4000;
}
//云台pid参数设置
void Pitch_Yaw_Init()
{
Pitch_Yaw.pid_init(PITCH_SPEED,14.0f,180.0f,0,9000.0f,30000.0f);
Pitch_Yaw.pid_init(PITCH_ANGLE,12.0f,200.0f,0.0f,0.0f,10000.0f);
Pitch_Yaw.pid_init(YAW_SPEED,25.0f,850.0f,0.0f,9000.0f,30000.0f);
Pitch_Yaw.pid_init(YAW_ANGLE,200.0f,100.0f,0.0f,0.0f,15000.0f);
Pitch_Yaw.pitchAngle.Target = 8769;
Pitch_Yaw.pitchSpeed.I_SeparThresh = 15000;
Pitch_Yaw.yawSpeed.I_SeparThresh = 15000;
Pitch_Yaw.yawAngle.Target = 0;
Chassis.pid_init(10.0f,0,0.0f,0,1000.0f);
Infantry.chassisMode = NORMAL_C;
Infantry.chassisCtrlMode = REMOTE_CTRL_C;
Infantry.isLandFlag = 1;
}
|
#ifndef UTILS_H__
#define UTILS_H__
#include <iostream>
#include <iomanip>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cuda_runtime_api.h>
#include <cassert>
#include <cmath>
#define checkCudaErrors(val) check((val),#val,__FILE__,__LINE__)
using namespace std;
template<typename T>
void check( T err,
const char* const func,
const char* const file,
const int line){
if(err != cudaSuccess){
cerr << "CUDA error en: " << file << ":" << line << endl;
cerr << cudaGetErrorString(err)<< " " << func << endl;
exit(1);
}
}
#endif
|
/*
* @lc app=leetcode.cn id=712 lang=cpp
*
* [712] 两个字符串的最小ASCII删除和
*/
// @lc code=start
class Solution {
public:
int minimumDeleteSum2(string s1, string s2) {
int m = s1.length();
int n = s2.length();
vector<vector<int>> dp(m+1, vector<int>(n+1, 0));
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(s1[i-1]==s2[j-1])
{
dp[i][j] = dp[i-1][j-1] + s1[i-1];
}else{
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
}
int sum = 0;
for(int i=0;i<m;i++)sum+=s1[i];
for(int i=0;i<n;i++)sum+=s2[i];
return sum - 2 * dp[m][n];
}
int minimumDeleteSum(string s1, string s2) {
int m = s1.length();
int n = s2.length();
vector<vector<int>> dp(m+1, vector<int>(n+1, 0));
for(int i=1;i<=m;i++)
{
dp[i][0] = dp[i-1][0] + (int)s1[i-1];
}
for(int j=1;j<=n;j++)
{
dp[0][j] = dp[0][j-1] + (int)s2[j-1];
}
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(s1[i-1] == s2[j-1])
{
dp[i][j] = dp[i-1][j-1];
}else{
dp[i][j] = min(dp[i-1][j]+(int)s1[i-1], dp[i][j-1]+(int)s2[j-1]);
}
}
}
return dp[m][n];
}
};
// @lc code=end
|
#include <iostream>
#include "operaciones.h"
#include <iostream>
using namespace std;
bool primo(int numero)
{
int cont = 0;
for(int i = 1; i <= numero; i++)
{
if(numero % i == 0)
{
cont += 1;
}
else
{
cont += 0;
}
}
if(cont == 2)
{
return true;
}
else
{
return false;
}
}
int euclides(int a, int b)
{
int q = 0;
int r = 0;
while(b != 0)
{
q = a/b;
r = a - (q*b);//2
a = b;
b = r;
}
return a;
}
int inversa(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1){
return 1;
}
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int modulo(int a, int b)
{
int q = a/b;
int r = a - (q*b);
while(r < 0){
r += b;
}
return r;
}
int expModular(int base, int exp, int m)
{
int x = modulo(base,m);
int n = 1;
while(exp != 0){
if(modulo(exp,2)){
n = modulo(n*x,m);
}
x = modulo(x*x,m);
exp /= 2;
}
return n;
}
|
#include "linked_list.h"
#include "node.h"
#include <iostream>
using namespace std;
Linked_List::Linked_List(){
bool another = true;
string temp;
cout << "Please enter a number: ";
getline(cin, temp);
while(is_int(temp) == false){
cout << "Invalid integer, please enter a valid integer: ";
getline(cin, temp);
}
head = new Node;
head->val = stoi(temp);
length = 1;
cout << "Do you want to enter another number (y or n): ";
getline(cin, temp);
while(temp != "y" && temp != "n"){
cout << "Invalid choice! Please enter a 'y' or an 'n': ";
getline(cin, temp);
}
if(temp == "n"){
another = false;
}
while(another == true){
cout << "Please enter a number: ";
getline(cin, temp);
while(is_int(temp) == false){
cout << "Invalid integer, please enter a valid integer: ";
getline(cin, temp);
}
push_back(stoi(temp));
cout << "Do you want to enter another number (y or n): ";
getline(cin, temp);
while(temp != "y" && temp != "n"){
cout << "Invalid choice! Please enter a 'y' or an 'n': ";
getline(cin, temp);
}
if(temp == "n"){
another = false;
}
}
}
void Linked_List::prime_number_find(){
cout << "Your program contains the following prime numbers:" << endl;
bool temp;
Node * active = head;
for(int i = 0; i < length; i++){
temp = true;
for(int j = 2; j < active->val; j++){
if(active->val % j == 0){
temp = false;
}
}
if(temp == true){
cout << "\tPrime number: " << active->val << endl;
}
active = active->next;
}
}
bool Linked_List::is_int(string num){
if(num.at(0) != 45 && (num.at(0) > 57 || num.at(0) < 48))
return 0;
for(int i = 1; i < num.length(); i++){
if(num.at(i) > 57 || num.at(i) < 48){
return 0;
}
}
return 1;
}
bool Linked_List::again(){
string temp;
cout << "Would you like to do this again (yes or no): ";
getline(cin, temp);
while(temp != "yes" && temp != "no"){
cout << "Invalid choice! Please enter either 'yes' or 'no' to do this again: ";
getline(cin, temp);
}
if(temp == "yes"){
return true;
}else{
return false;
}
}
int Linked_List::get_length(){
return length;
}
void Linked_List::clear(){
Node * temp1 = head->next;
Node * temp2 = NULL;
delete head;
for(int i = 0; i < length - 1; i++){
temp2 = temp1->next;
delete temp1;
temp1 = temp2;
}
length = 0;
}
void Linked_List::print(){
Node * active = NULL;
for(int i = 0; i < length; i++){
active = get_node(i);
cout << active->val << " ";
}
cout << endl;
}
Node * Linked_List::get_node(int index){
Node * temp;
temp = head;
for(int i = 0; i < index; i++){
temp = temp->next;
}
return temp;
}
void Linked_List::choose_order(){
string temp;
cout << "Sort ascending or descending (a or d): ";
getline(cin, temp);
while(temp != "a" && temp != "d"){
cout << "Invalid choice, please select 'a' to sort in ascending order and 'd' to sort in descending: ";
getline(cin, temp);
}
if(temp == "a"){
sort_ascending();
}else{
sort_descending();
}
head = get_node(0);
}
unsigned int Linked_List::push_back(int new_value){
Node * end = get_node(length - 1);
end->next = new Node;
end->next->val = new_value;
length = length + 1;
return 0;
}
unsigned int Linked_List::push_front(int value){
Node * temp = head;
head = new Node;
head->val = value;
head->next = temp;
length = length + 1;
}
unsigned int Linked_List::insert(int value, unsigned int index){
Node * temp1 = new Node;
temp1->val = value;
Node * temp2 = get_node(index - 1);
Node * temp3 = temp2->next;
temp2->next = temp1;
temp1->next = temp3;
length = length + 1;
}
Node * Linked_List::merge(Node * Left, Node * Right, bool descending){
Node * temp1 = NULL;
if(Left == NULL){
return Right;
}else if(Right == NULL){
return Left;
}
if(descending == false){
if(Left->val <= Right->val){
temp1 = Left;
temp1->next = merge(Left->next, Right, descending);
}else{
temp1 = Right;
temp1->next = merge(Left, Right->next, descending);
}
}else if(descending == true){
if(Left->val >= Right->val){
temp1 = Left;
temp1->next = merge(Left->next, Right, descending);
}else{
temp1 = Right;
temp1->next = merge(Left, Right->next, descending);
}
}
return temp1;
}
void Linked_List::merge_sort(Node ** head_temp, bool descending){
Node * temp1 = *head_temp;
Node * Left;
Node * Right;
if((temp1 == NULL) || (temp1->next == NULL)){
return;
}
split_linked_list(temp1, &Left, &Right);
merge_sort(&Left, descending);
merge_sort(&Right, descending);
*head_temp = merge(Left, Right, descending);
}
void Linked_List::split_linked_list(Node * head_temp, Node ** Left_Head, Node ** Right_Head){
*Left_Head = head_temp;
Node * ptr1, * ptr2;
ptr1 = head_temp;
ptr2 = head_temp->next;
while(ptr2 != NULL){
ptr2 = ptr2->next;
if(ptr2 != NULL){
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
}
*Right_Head = ptr1->next;
ptr1->next = NULL;
}
void Linked_List::sort_ascending(){
Node * temp = get_node(0);
merge_sort(&temp, false);
head = temp;
}
void Linked_List::sort_descending(){
Node * temp = get_node(0);
merge_sort(&temp, true);
head = temp;
}
|
//----------------------------------------------------------------
// ClientAFEntity.h
//
// Copyright 2002-2006 Raven Software
//----------------------------------------------------------------
#ifndef __GAME_CLIENT_AFENTITY_H__
#define __GAME_CLIENT_AFENTITY_H__
/*
===============================================================================
rvClientAFEntity - a regular idAFEntity_Base spawned client-side
===============================================================================
*/
class rvClientAFEntity : public rvAnimatedClientEntity {
public:
CLASS_PROTOTYPE( rvClientAFEntity );
rvClientAFEntity( void );
virtual ~rvClientAFEntity( void );
void Spawn( void );
virtual void Think( void );
virtual void GetImpactInfo( idEntity *ent, int id, const idVec3 &point, impactInfo_t *info );
virtual void ApplyImpulse( idEntity *ent, int id, const idVec3 &point, const idVec3 &impulse, bool splash = false );
virtual void AddForce( idEntity *ent, int id, const idVec3 &point, const idVec3 &force );
virtual bool CanPlayImpactEffect ( idEntity* attacker, idEntity* target );
virtual bool Collide( const trace_t &collision, const idVec3 &velocity );
virtual bool GetPhysicsToVisualTransform( idVec3 &origin, idMat3 &axis );
virtual bool UpdateAnimationControllers( void );
virtual void FreeEntityDef( void );
virtual bool LoadAF( const char* keyname = NULL );
bool IsActiveAF( void ) const { return af.IsActive(); }
const char * GetAFName( void ) const { return af.GetName(); }
idPhysics_AF * GetAFPhysics( void ) { return af.GetPhysics(); }
void SetCombatModel( void );
idClipModel * GetCombatModel( void ) const;
// contents of combatModel can be set to 0 or re-enabled (mp)
void SetCombatContents( bool enable );
virtual void LinkCombat( void );
virtual void UnlinkCombat( void );
int BodyForClipModelId( int id ) const;
void SaveState( idDict &args ) const;
void LoadState( const idDict &args );
void AddBindConstraints( void );
void RemoveBindConstraints( void );
bool GetNoPlayerImpactFX( void );
protected:
idAF af; // articulated figure
idClipModel * combatModel; // render model for hit detection
int combatModelContents;
idVec3 spawnOrigin; // spawn origin
idMat3 spawnAxis; // rotation axis used when spawned
int nextSoundTime; // next time this can make a sound
};
/*
===============================================================================
rvClientAFAttachment - a regular idAFAttachment spawned client-side - links to an
idAnimatedEntity rather than rvClientAnimatedEntity
===============================================================================
*/
class rvClientAFAttachment : public rvClientAFEntity {
public:
CLASS_PROTOTYPE( rvClientAFAttachment );
rvClientAFAttachment( void );
virtual ~rvClientAFAttachment( void );
void Spawn( void );
void SetBody ( idAnimatedEntity* body, const char *headModel, jointHandle_t damageJoint );
void SetDamageJoint ( jointHandle_t damageJoint );
void ClearBody ( void );
idEntity * GetBody ( void ) const;
virtual void Think ( void );
virtual void Hide ( void );
virtual void Show ( void );
virtual bool UpdateAnimationControllers ( void );
void PlayIdleAnim( int channel, int blendTime );
virtual void GetImpactInfo( idEntity *ent, int id, const idVec3 &point, impactInfo_t *info );
virtual void ApplyImpulse( idEntity *ent, int id, const idVec3 &point, const idVec3 &impulse, bool splash = false );
virtual void AddForce( idEntity *ent, int id, const idVec3 &point, const idVec3 &force );
virtual bool CanPlayImpactEffect ( idEntity* attacker, idEntity* target );
virtual void AddDamageEffect( const trace_t &collision, const idVec3 &velocity, const char *damageDefName, idEntity* inflictor );
void SetCombatModel( void );
idClipModel * GetCombatModel( void ) const;
virtual void LinkCombat( void );
virtual void UnlinkCombat( void );
// Lipsync
void InitCopyJoints ( void );
void CopyJointsFromBody ( void );
protected:
idEntityPtr<idAnimatedEntity> body;
idClipModel * combatModel; // render model for hit detection of head
int idleAnim;
jointHandle_t damageJoint;
idList<copyJoints_t> copyJoints; // copied from the body animation to the head model
};
#endif
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
using namespace std;
string longestCommonPrefix(vector<string> &strs){
if(strs.size()==0) return "";
if(strs.size()==1) return strs[0];
int i=0;
string res;
bool find = false;
while(i<strs[0].length() && !find){
char c = strs[0][i];
for(int k=1;k<strs.size();k++){
if(strs[k][i] != c){
find = true;
break;
}
}
if(find) break;
res.push_back(c);
i++;
}
return res;
}
int main(){
}
|
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
vector <int> highScores;
class Game{
private:
int numOfPlayers;
int playerOneScore;
int playerTwoScore;
string playerOneName;
string playerTwoName;
public:
Game(){
numOfPlayers = 1;
playerOneScore = 0;
}
void setNumberOfPlayers(int n){
numOfPlayers = n;
}
void setPlayerOneName(string name){
playerOneName = name;
}
void setPlayerTwoName(string name){
playerTwoName = name;
}
};
class TicTacToe: public Game
{
//TicTacToe sub class of game - it also can't access private variables in Game
private:
int numOfPlayers;
//make these public? or make getter methods?
int playerOneScore;
int playerTwoScore;
string playerOneName;
string playerTwoName;
public:
//variables from TicTacToe3.cpp
char matrix[3][3] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
char symbol;
bool playerDidWin;
char symbols[2];
char winner;
int counter = 0;
int numOfGames;
//constructor
TicTacToe() : Game(){
numOfPlayers = 2;
playerOneScore = 0;
playerTwoScore = 0;
}
//inherited methods
//void setNumberOfPlayers(int num);
/* //methods to add
void introMenu();
void setPlayerNames();
void displayScores();
void drawMatrix();
void incrementOneScore();
void incrementTwoScore();
void updateGrid(int num);
*/
void introMenu(){
cout << "You have chosen 2-player game!" << endl;
cout << "How many games?" << endl;
cin >> numOfGames;
setPlayerNames();
}
void setPlayerNames(){
cout << "Player 1, please enter your screen name: " << endl;
cin >> playerOneName;
cout << "Player 2, please enter your screen name: " << endl;
cin >> playerTwoName;
}
// int* getPlayerScores(){
// int scores[2];
// scores[0] = playerOneScore;
// scores[1] = playerTwoScore;
// return scores;
// }
void getPlayerScores(int *oneScore, int *twoScore){
*oneScore = playerOneScore;
*twoScore = playerTwoScore;
}
void drawMatrix(){
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
cout << matrix[i][j] << " ";
if(j<2){
cout << "| ";
}
}
cout << endl;
if(i<2){
cout << "--|---|--" << endl;
}
}
}
void playerPrompt(){
int number;
cout << "Enter number on grid" << endl;
cin >> number;
updateGrid(number);
}
bool checkHorizontals(){
//check the three rows
for(int i=0; i<3; i++){
if((matrix[i][0] == matrix[i][1]) && (matrix[i][0] == matrix[i][2])){
winner = matrix[i][0];
return true;
}
}
return false;
}
bool checkVerticals(){
//check the three columns
for(int j = 0; j<3; j++){
if((matrix[0][j] == matrix[1][j]) && (matrix[0][j] == matrix[2][j])){
winner = matrix[0][j];
return true;
}
}
return false;
}
bool checkDiagonals(){
//check first diagonal
if((matrix[0][0] == matrix[1][1]) && (matrix[0][0] == matrix[2][2])){
winner = matrix[0][0];
return true;
}//check second diagonal
else if((matrix[0][2] == matrix[1][1]) && (matrix[0][2] == matrix[2][0])){
winner = matrix[0][2];
return true;
}else{
return false;
}
}
bool checkForWin(){
bool horizontalCheck = checkHorizontals();
bool verticalCheck = checkVerticals();
bool diagCheck = checkDiagonals();
if(horizontalCheck == true){
return true;
}else if(verticalCheck == true){
return true;
}else if(diagCheck == true){
return true;
}else{
return false;
}
}
void updateGrid(int num){
char* ptr = &matrix[0][0];
num = num-1;
if(*(ptr+num) == symbols[0] || *(ptr+num) == symbols[1]){
cout << "Cannot overwrite. Enter another number" << endl;
//keep the counter same. Shouldn't increment
counter = counter - 1;
//keep symbol same because it is the same turn
}else{
*(ptr+num) = symbol;
system("clear");//clear the screen before re-drawing
drawMatrix();
//add a check for win to prevent a message for next user's
//turn if game has ended
playerDidWin = checkForWin();
if((playerDidWin == false) && (counter < 8)){
changeSymbol();
}
}
}
void changeSymbol(){
if(symbol == symbols[0]){
symbol = symbols[1];
cout << "It's player " << symbol << "'s turn" << endl;
}else{
symbol = symbols[1];
cout << "It's player " << symbol << "'s turn" << endl;
}
}
void announceWinner(){
if(winner == symbols[0]){
cout << playerOneName << +"wins!" << endl;
playerOneScore++;
}else if(winner == symbols[1]){
cout << playerTwoName << +"wins!" << endl;
playerTwoScore++;
}else if(counter == 11){
cout << "Exited game." << endl;
}else{
cout << "No winner. It's a tie!" << endl;
}
}
void displayScores(){
cout << "After " << numOfGames << ", here are the scores: " << endl;
cout << playerOneName << ": " << playerOneScore << endl;
cout << playerTwoName << ": " << playerTwoScore << endl;
}
void ResetBoard(){
char* ptr = &matrix[0][0];
for(int i = 0; i<9; i++){
//*(ptr+i) = static_cast<char>(i+1);
//*(ptr+i) = (char)(i+1);
*(ptr+i) = (char)(i);
}
}
void executeGame(){
for(int i = 0; i<numOfGames; i++){
ResetBoard();
cout << matrix[0][1] << endl;
drawMatrix();//drawing the char matrix variable
//need to update the variable char matrix with 1,2,3,...
cout << playerOneName << ", choose symbol: " << endl;
cin >> symbols[0];
cout << playerTwoName << ", choose symbol: " << endl;
cin >> symbols[1];
symbol = symbols[0];
while(!(playerDidWin == true) && (counter < 9)){
playerPrompt();
playerDidWin = checkForWin();
counter++;
}
announceWinner();
}
displayScores();
}
};
void printMenu(){
cout << "Welcome!" << endl;
cout << "Please choose one of the options below:" << endl;
cout << "1. One Player Game" << endl;
cout << "2. Two Player Game" << endl;
cout << "3. See High Scores" << endl;
}
void printHighScores(){
}
int main(){
int option;
//create mutable data structure for high scores : vector??
printMenu();
cin >> option;
TicTacToe game1;
switch(option)
{
case 1: game1.setNumberOfPlayers(1);
break;
case 2: game1.introMenu();
break;
case 3:
default: game1.introMenu();
break;
}
game1.executeGame();
//std::max(game1.playerOneScore, game1.playerTwoScore);
int firstPlayerScore, secondPlayerScore;
game1.getPlayerScores(&firstPlayerScore, &secondPlayerScore);
int higherScore = std::max(firstPlayerScore, secondPlayerScore);
highScores.push_back(higherScore);
return 0;
}
|
#include "Engine.h"
class Gravity {
public:
void startJump() {
speedY = -5;
jumping = true;
}
bool isJumping() {
return jumping;
}
void nextStep() {
speedY += step;
}
int ChangeX() {
return speedX;
}
int ChangeY() {
return speedY;
}
void leftPress(int actPlayerX) {
speedX = 1;
if (actPlayerX == 0)
speedX = 0;
if (speedX < 3)
speedX += step;
}
void rightPress(int actPlayerX) {
speedX = 1;
if (actPlayerX == boardWidth)
speedX = 0;
if (speedX < 3)
speedX += step;
}
private:
double speedX;
double speedY;
bool jumping = false;
double step = 0.2;
int boardWidth = 200;
};
class Platform{
public:
Platform(int x,int y,int width){
this->x = x;
this->y = y;
this->width = width;
}
int getX(){
return x;
}
int getY(){
return y;
}
int getWidth(){
return width;
}
bool moveDown(int val){
y-=val;
return y >= 0;
}
private:
int x,y, width;
};
class Player : public Gravity {
public:
void playerStep() {
if (GetAsyncKeyState(VK_LEFT)) {
leftPress(x);
}
if (GetAsyncKeyState(VK_RIGHT)) {
rightPress(x);
}
if (GetAsyncKeyState(VK_SPACE) && isJumping() == false) {
startJump();
}
x += ChangeX();
nextStep();
y += ChangeY();
}
double getX() {
return x;
}
double getY() {
return y;
}
private:
double x, y;
};
class Board{
public:
int getPlayerX(){
return player.getX();
}
int getPlayerY(){
return player.getY() - totalMovedY;
}
void init(){
for (int i =20; i<150; i+=30){
platforms.push_back(Platform(rand()%150,i,50+rand()%50));
}
}
vector<Platform> getPlatforms(){
return platforms;
}
void moveBoard(int yMove){
totalMovedY += yMove;
for(int i=0; i<platforms.size();i++){
if(platforms[i].moveDown(yMove))
platforms[i] = Platform(rand()%150,150,50+rand()%50);
}
}
private:
Player player;
vector <Platform> platforms;
int totalMovedY = 0;
};
class Game : public Renderer {
public:
float SetFps(float fElapsedTime) {
this->fElapsedTime = fElapsedTime;
}
float GetFps() {
return fElapsedTime;
}
void Start() {
fontsize(8, 8, hConsole);
SetConsoleActiveScreenBuffer(hConsole);
m_bufScreen = new CHAR_INFO[sWidth*sHeight];
memset(m_bufScreen, 0, sizeof(CHAR_INFO) * sWidth*sHeight);
m_rectWindow = { 0, 0, (short)sWidth, (short)sHeight };
Cls(FG_GREY);
storag = new char*[16];
for (int i = 0; i < 16; i++)
storag[i] = new char[16];
}
void Refresh() {
DrawSprite(5, 5, Player_Sprite);
//DrawCircle(15, 15, 5, PIXEL_SOLID, FG_RED);
//Display The Frame ->
wchar_t s[256];
swprintf(s, 256, L"%s", m_sAppName.c_str());
SetConsoleTitleW(s);
WriteConsoleOutput(hConsole, m_bufScreen, { (short)sWidth, (short)sHeight }, { 0,0 }, &m_rectWindow);
}
void GraphicMaker() {
switch (actualc) {
case 0:
DrawString(20, 2, L"E", BG_GREY);
break;
case 1:
Draw(20, 2, PIXEL_SOLID, FG_BLACK);
break;
case 2:
Draw(20, 2, PIXEL_SOLID, FG_DARK_BLUE);
break;
case 3:
Draw(20, 2, PIXEL_SOLID, FG_DARK_GREEN);
break;
case 4:
Draw(20, 2, PIXEL_SOLID, FG_DARK_CYAN);
break;
case 5:
Draw(20, 2, PIXEL_SOLID, FG_DARK_RED);
break;
case 6:
Draw(20, 2, PIXEL_SOLID, FG_DARK_MAGENTA);
break;
case 7:
Draw(20, 2, PIXEL_SOLID, FG_DARK_YELLOW);
break;
case 8:
Draw(20, 2, PIXEL_SOLID, FG_GREY);
break;
case 9:
Draw(20, 2, PIXEL_SOLID, FG_DARK_GREY);
break;
case 10:
Draw(20, 2, PIXEL_SOLID, FG_BLUE);
break;
case 11:
Draw(20, 2, PIXEL_SOLID, FG_GREEN);
break;
case 12:
Draw(20, 2, PIXEL_SOLID, FG_CYAN);
break;
case 13:
Draw(20, 2, PIXEL_SOLID, FG_RED);
break;
case 14:
Draw(20, 2, PIXEL_SOLID, FG_MAGENTA);
break;
case 15:
Draw(20, 2, PIXEL_SOLID, FG_YELLOW);
break;
case 16:
Draw(20, 2, PIXEL_SOLID, FG_WHITE);
break;
}
for (int i = 0; i < 16; i++) {
for (int j = 0;j < 17; j++){
if(j == 16)
Draw(i, j, PIXEL_SOLID, FG_RED);
else
Draw(i, j, PIXEL_SOLID, FG_BLACK);
}
}
if (GetAsyncKeyState(VK_RIGHT) & 0x8000 && x < 15) {
x++;
}
else if(GetAsyncKeyState(VK_LEFT) & 0x8000 && x > 0) {
x--;
}
if (GetAsyncKeyState(VK_DOWN) & 0x8000 && y < 15) {
y++;
}
else if (GetAsyncKeyState(VK_UP) & 0x8000 && y > 0) {
y--;
}
if (GetAsyncKeyState(VK_SPACE) & 0x0001) {
storag[x][y] = actualc;
}
if (GetAsyncKeyState('E') & 0x0001 && actualc < 16) {
actualc++;
}
else if (GetAsyncKeyState('Q') & 0x0001 && actualc > 0) {
actualc--;
}
else if (GetAsyncKeyState('R') & 0x0001 && actualc > 0) {
for (int i = 0; i < 16; i++)
for (int j = 0; j < 16; j++)
storag[j][i] = 0;
}
for (int i = 0; i < 16; i++)
for (int j = 0; j < 16; j++)
switch ((int)storag[i][j]) {
case 0:
continue;
break;
case 1:
Draw(i , j , PIXEL_SOLID, FG_BLACK);
break;
case 2:
Draw(i , j , PIXEL_SOLID, FG_DARK_BLUE);
break;
case 3:
Draw(i , j , PIXEL_SOLID, FG_DARK_GREEN);
break;
case 4:
Draw(i , j , PIXEL_SOLID, FG_DARK_CYAN);
break;
case 5:
Draw(i , j , PIXEL_SOLID, FG_DARK_RED);
break;
case 6:
Draw(i , j , PIXEL_SOLID, FG_DARK_MAGENTA);
break;
case 7:
Draw(i , j , PIXEL_SOLID, FG_DARK_YELLOW);
break;
case 8:
Draw(i, j , PIXEL_SOLID, FG_GREY);
break;
case 9:
Draw(i , j , PIXEL_SOLID, FG_DARK_GREY);
break;
case 10:
Draw(i, j , PIXEL_SOLID, FG_BLUE);
break;
case 11:
Draw(i , j , PIXEL_SOLID, FG_GREEN);
break;
case 12:
Draw(i , j , PIXEL_SOLID, FG_CYAN);
break;
case 13:
Draw(i , j , PIXEL_SOLID, FG_RED);
break;
case 14:
Draw(i , j , PIXEL_SOLID, FG_MAGENTA);
break;
case 15:
Draw(i , j , PIXEL_SOLID, FG_YELLOW);
break;
case 16:
Draw(i , j , PIXEL_SOLID, FG_WHITE);
break;
}
Draw(x, y + 1, 0x2191, FG_GREEN);
Sleep(50);
wchar_t s[256];
swprintf(s, 256, L"%s - %d", m_sAppName.c_str(),actualc);
SetConsoleTitleW(s);
WriteConsoleOutput(hConsole, m_bufScreen, { (short)sWidth, (short)sHeight }, { 0,0 }, &m_rectWindow);
if (GetAsyncKeyState(VK_ESCAPE) & 0x0001) {
ofstream file("Player.txt");
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
file << (int)storag[i][j] << " ";
}
file << endl;
}
DrawString(20, 20, L"SAVED!", BG_GREY);
}
}
private:
Sprite* Player_Sprite = new Sprite("Player.txt");;
int x = 0, y = 0, actualc = 2;
char** storag;
float fElapsedTime = 60.f;
wstring m_sAppName = L"IcyTower";
SMALL_RECT m_rectWindow;
HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
wchar_t *screen = new wchar_t[sWidth*sHeight];
};
int main() {
//Basic Declarations ->
Board board;
board.init();
while (1) {
demo.Refresh();
demo.GraphicMaker();
board.moveBoard(1);
sleep(50); //20FPS
}
}
|
#include <iostream>
using namespace std;
int main(void)
{
ios::sync_with_stdio(false);
cout.tie(NULL); cin.tie(NULL);
int num, sum = 0;
string numbers;
cin >> num >> numbers;
for (char num : numbers)
sum += num - '0';
cout << sum << endl;
return 0;
}
|
#include<vector>
#include<iostream>
#include<cstdio>
#include <cstring>
#include<set>
using namespace std;
int main(){
int n;
int a;
set <int> v;
while(cin >>n){
for( int i = 0; i < n; i++){
cin >> a;
v.insert(a);
}
set <int> :: iterator p;
for(p = v.begin(); p != v.end(); p ++){
if(p != v.begin()) cout <<' ';
cout << *p;
}
v.clear();
cout << endl;
}
}
|
/*!
* \file Profiler.h
*
* \author Shiyang Ao
* \date November 2016
*
*
*/
#pragma once
namespace Hourglass
{
#define MAX_PROFILE_BLOCK_COUNT 64
#define ENABLE_PROFILER 0
#if (ENABLE_PROFILER == 1)
# define BEGIN_PROFILER() Hourglass::g_Profiler.BeginProfiling()
# define END_PROFILER() Hourglass::g_Profiler.EndProfiling()
# define BEGIN_PROFILER_BLOCK(name) Hourglass::g_Profiler.BeginBlock(Hourglass::StrIDUtil::GetStrID(name))
# define END_PROFILER_BLOCK(name) Hourglass::g_Profiler.EndBlock(Hourglass::StrIDUtil::GetStrID(name))
# define AUTO_PROFILER_BLOCK(name) Hourglass::AutoProfilerBlock sAutoProfilerBlock(Hourglass::StrIDUtil::GetStrID(name))
#else
# define BEGIN_PROFILER()
# define END_PROFILER()
# define BEGIN_PROFILER_BLOCK(name)
# define END_PROFILER_BLOCK(name)
# define AUTO_PROFILER_BLOCK(name)
#endif
class Profiler
{
public:
void Init();
void BeginProfiling();
void EndProfiling();
// Start profiling
void BeginBlock(StrID name);
// Stop profiling
void EndBlock(StrID name);
void PrintResult();
private:
StrID m_Names[MAX_PROFILE_BLOCK_COUNT];
long long m_CurrFrameTime[MAX_PROFILE_BLOCK_COUNT];
long long m_LastFrameTime[MAX_PROFILE_BLOCK_COUNT];
long long m_BlockStartTime[MAX_PROFILE_BLOCK_COUNT];
long long m_StartTime;
long long m_EndTime;
long long m_LastEndTime;
UINT m_CurrFrameCount;
UINT m_LastFrameCount;
UINT m_BlockCount;
UINT m_CurrBlockDepth;
UINT m_BlockDepth[MAX_PROFILE_BLOCK_COUNT];
bool m_IsProfiling;
double m_ClockFreq;
};
extern Profiler g_Profiler;
class AutoProfilerBlock
{
private:
StrID m_Name;
public:
AutoProfilerBlock(StrID name)
: m_Name(name)
{
g_Profiler.BeginBlock(name);
}
~AutoProfilerBlock()
{
g_Profiler.EndBlock(m_Name);
}
};
}
|
#include<cstdio>
#include<algorithm>
using namespace std;
int dui[30100];
int size=0;
void put(int x)//大根堆的put
{
dui[++size]=x;
int son=size,dad=size/2;
while(dad > 0)
{
if(dui[son]<=dui[dad]) break;
swap(dui[son],dui[dad]);
son=dad;
dad/=2;
}
}
int get()//大根堆的get
{
int top=dui[1];
dui[1]=dui[size--];
int dad=1,son=2;
while(son<=size)
{
if(son<size && dui[son+1]>dui[son]) son++;
if(dui[son]<=dui[dad]) break;
swap(dui[dad],dui[son]);
dad=son;
son*=2;
}
return top;
}
int main()
{
int n,m,a,b,c;
scanf("%d%d%d%d%d",&n,&m,&a,&b,&c);//先输入一组数据
for(int j=1;j<=m;j++)//对堆进行初始化
put(a*j*j+b*j+c);//放入堆
for(int i=2;i<=n;i++)
{
scanf("%d%d%d",&a,&b,&c);//继续输入数据
for(int j=1;j<=m;j++)
{
if(a*j*j+b*j+c <dui[1])//dui[1]为答案中最大的数据,若出现比它更小的数,则新数为答案
{
get();//将原先最大的数扔出去
put(a*j*j+b*j+c);//放入新的较小的数
}
else
break;//若新数比原来最大的数都大,则停止
}
}
int ans[500000];
for(int i=m;i>=1;i--)//将堆中元素倒序放入答案数组中
{
ans[i]=get();
}
for(int i=1;i<=m;i++)
printf("%d ",ans[i]);//输出
}
|
#ifndef MONSTER_H
#define MONSTER_H
#include <QObject>
#include <QString>
#include <math.h>
#include <QStringList>
class Monster : public QObject
{
Q_OBJECT
public:
explicit Monster(QObject *parent = 0);
Monster ( const Monster &monster);
Monster& operator= (const Monster &monster);
int id;
QString m_idString;
QString m_name;
int m_level;
int exp;
int levelUpExp;
int m_percentExp;
int life;
int m_percentHp;
Q_PROPERTY (QString name READ name)
Q_PROPERTY (QString idString READ idString)
Q_PROPERTY (int level READ level)
Q_PROPERTY (int percentExp READ percentExp)
Q_PROPERTY (int percentHp READ percentHp)
QString name() const {
return m_name;
}
QString idString() const {
return m_idString;
}
int level() const {
return m_level;
}
int percentExp() const {
return m_percentExp;
}
int percentHp() const {
return m_percentHp;
}
QString type1;
QString type2;
int ivs;
int nature;
int baseHpEv;
int baseAtkEv;
int baseDefEv;
int baseSatkEv;
int baseSdefEv;
int baseSpeEv;
double speciesExp;
double wild;
double trainer;
double luckyEgg;
int baseHp;
int baseAtk;
int baseDef;
int baseSatk;
int baseSdef;
int baseSpe;
int hpEv;
int atkEv;
int defEv;
int satkEv;
int sdefEv;
int speEv;
int hp;
int atk;
int def;
int satk;
int sdef;
int spe;
Move move1;
Move move2;
Move move3;
Move move4;
Q_INVOKABLE void levelUp();
Q_INVOKABLE void killedEnemy(const Monster *enemy);
Q_INVOKABLE QStringList getMove(Move &move);
signals:
public slots:
};
#endif // MONSTER_H
|
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmBinUtilsWindowsPEGetRuntimeDependenciesTool.h"
#include "cmRuntimeDependencyArchive.h"
cmBinUtilsWindowsPEGetRuntimeDependenciesTool::
cmBinUtilsWindowsPEGetRuntimeDependenciesTool(
cmRuntimeDependencyArchive* archive)
: Archive(archive)
{
}
void cmBinUtilsWindowsPEGetRuntimeDependenciesTool::SetError(
const std::string& error)
{
this->Archive->SetError(error);
}
|
#include <vector>
#include <numeric>
#include <algorithm>
#include <cmath>
#include "halide_benchmark.h"
//#include "Profiler.h"
std::vector<double> get_normal_dist_tuple(std::vector<double> v){
double sum = std::accumulate(v.begin(), v.end(), 0.0);
double mean = sum / v.size();
std::vector<double> diff(v.size());
std::transform(v.begin(), v.end(), diff.begin(),
std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
double stdev = std::sqrt(sq_sum / v.size());
return {mean, stdev};
}
std::vector<std::vector<double>> do_benchmarking(std::function<void()> op){
std::vector<double> iterations;
//std::vector<double> min, max, avg;
double min_t_auto = 0.0;
//for (int j = 0; j < 1; j++) {
// for (int i = 0; i < 1; i++){
for (int j = 0; j < 100; j++) {
for (int i = 0; i < 100; i++){
min_t_auto = Halide::Tools::benchmark(1, 1, [&]() { op(); }); // min_t_auto is in seconds [SD]
iterations.push_back(min_t_auto * 1e3); // ms
}
// min.push_back( *min_element(iterations.begin(), iterations.end()) );
// max.push_back( *max_element(iterations.begin(), iterations.end()) );
// avg.push_back( accumulate( iterations.begin(), iterations.end(), 0.0)/iterations.size() );
}
// std::vector<double> wc_tuple(2), avg_tuple(2), bc_tuple(2);
// bc_tuple = get_normal_dist_tuple(min);
// avg_tuple = get_normal_dist_tuple(avg);
// wc_tuple = get_normal_dist_tuple(max);
// return {bc_tuple, avg_tuple, wc_tuple};
return {iterations};
}
/*void do_instr_benchmarking(std::function<void()> op){
PROFILE_SCOPED()
op();
Profiler::dump();
}*/
|
/*
边双连通分量 POJ 3352
边双连通分量求法:
dfn[x]表示搜索到x的时间戳,low[x]表示以x为根的搜索子树能联系到的时间戳最小的
点,在搜索过程中把点压入栈中。
如果low[x]>dfn[fa],那么说明x连向父亲的边是桥,那么栈中到x为止的点构成一个边
双连通分量,把它们全部弹出来。
最后还剩下包含根节点的分量,这又是一个新的分量。
*/
#include<iostream>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define N 5001
#define M 20001
using namespace std;
int n,m,ans,tt,top,fl=1;
int sz,to[M],pre[M],last[N];
int dfn[N],low[N],stack[N],belong[N],du[N];
bool mark[N];
void Ins(int a,int b){
sz++;to[sz]=b;pre[sz]=last[a];last[a]=sz;
}
void Tarjan(int x,int from){
dfn[x]=++tt;low[x]=tt;stack[++top]=x;
for(int i=last[x];i;i=pre[i]){
if(to[i]==from) continue;
if(!dfn[to[i]]){
Tarjan(to[i],x);low[x]=min(low[x],low[to[i]]);
if(low[to[i]]>dfn[x]){
fl++;
while(stack[top]!=to[i]) belong[stack[top--]]=fl;
belong[stack[top--]]=fl;
}
}
else low[x]=min(low[x],dfn[to[i]]);
}
}
int main(){
int i,j,k,a,b;
scanf("%d%d",&n,&m);
for(i=1;i<=m;i++){
scanf("%d%d",&a,&b);
Ins(a,b);Ins(b,a);
}
Tarjan(1,0);
for(i=1;i<=n;i++) if(belong[i]==0) belong[i]=1;
for(i=1;i<=fl;i++){
memset(mark,0,sizeof(mark));
for(j=1;j<=n;j++) if(belong[j]==i){
for(k=last[j];k;k=pre[k]){
if(!mark[belong[to[k]]] && belong[to[k]]!=i){
mark[belong[to[k]]]=1;du[i]++;
}
}
}
}
for(i=1;i<=fl;i++) if(du[i]==1) ans++;
ans=(ans+1)/2;
printf("%d\n",ans);
return 0;
}
|
#include "Gugu.h"
#include <allegro5\allegro.h>
#include <allegro5\allegro_image.h>
Gugu::Gugu(){
this->x = 0;
this->y = 390;
this->curFrameX = 0;
this->curFrameY = 0;
this->frameWidth = 168;
this->frameHeight = 252;
this->image = NULL;
}
void Gugu::InitGugu(ALLEGRO_BITMAP *image){
this->x = 0; //posicao x na esquerda
this->y = 390; //posicao y na esquerda
this->curFrameX = 0;
this->curFrameY = 0;
this->frameWidth = 168;
this->frameHeight = 252;
this->image = image;
}
void Gugu::DrawGugu(){
al_draw_bitmap_region(image, curFrameX * frameWidth, curFrameY * frameHeight, frameWidth, frameHeight, x, y, 0);
}
void Gugu::Esquerda(){
this->x = 0; //posicao x na esquerda
this->y = 390; //posicao y na esquerda
this->curFrameY = 0;
}
void Gugu::Direita(){
this->x = 312; //posicao x na direita
this->y = 390; //posicao y na direita
this->curFrameY = 1;
}
void Gugu::setCurFrameX(int curFrameX){
this->curFrameX = curFrameX;
}
|
#ifndef TPOOL_H
#define TPOOK_H
#include <vector>
#include <deque>
#include <thread>
#include <mutex>
#include <algorithm>
#include <iterator>
#include <functional>
#include <condition_variable>
#include <iostream>
namespace tsk { namespace tpool
{
class no_thread_exception : public std::exception {
};
class ThreadPool;
class Thread {
public :
std::thread *_thrd;
bool _busy;
bool _done;
std::mutex _mutex;
std::condition_variable _cond;
std::function<void(void)> func;
ThreadPool *_pool;
public:
Thread(ThreadPool *parent) {
_busy = false;
_done = false;
_pool = parent;
_thrd = new std::thread(&Thread::threadBody, this);
}
// wait for underline thread to finish.
void join() {
std::cout << "Waiting for thread to join " << std::endl;
_thrd->join();
}
void markDone() {
std::lock_guard<std::mutex> lck(_mutex);
_done = true;
_cond.notify_all();
}
void setFunction(std::function<void(void)> func) {
this->func = func;
_cond.notify_all();
}
void threadBody();
};
class ThreadPool {
private:
std::deque<Thread*> threads;
std::deque<Thread*> free_threads;
int desiredSize;
std::mutex _tp_mutex;
std::condition_variable _tp_cond;
public:
ThreadPool(int size) {
_tp_mutex.lock();
desiredSize = size;
// pre initialize list of threads
for(int i =0; i < size; ++i) {
Thread *trd = new Thread(this);
free_threads.push_back(trd);
threads.push_back(trd);
}
_tp_mutex.unlock();
}
int size() { return threads.size(); }
int setSize(int s) {
desiredSize = s;
}
void markFree(Thread *thrd) {
if (desiredSize < size())
thrd->markDone();
else
free_threads.push_front(thrd);
}
Thread *getThread() {
std::lock_guard<std::mutex> lck(_tp_mutex);
// First try to get thread from from free list of threads.
if (!free_threads.empty()) {
Thread *thrd = free_threads.front();
free_threads.pop_front();
return thrd;
}
if (desiredSize > size())
return NULL;
Thread *thr = new Thread(this);
threads.push_back(thr);
return thr;
}
void startThread(std::function<void(void)> func)
{
Thread *thr = getThread();
thr->_busy = true;
if (thr == nullptr)
throw no_thread_exception();
thr->setFunction(func);
}
void cleanupAndWait() {
std::cout << "Cleanup and wait called " << std::endl;
desiredSize = 0;
std::for_each(threads.begin(), threads.end(),
[](Thread *th) {
th->markDone();
});
wait();
}
void wait() {
std::unique_lock<std::mutex> lck(_tp_mutex);
desiredSize = 0;
std::for_each(threads.begin(), threads.end(),
[](Thread *th) {
th->join();
});
}
void setDestroyed(Thread *th) {
// TODO remove from threads and free_threads
}
};
}}
#endif
|
#include<iostream>
#include<vector>
#include<list>
#include<stdlib.h>
#define Default_Chances 10
using namespace std;
class Guess{
public:
char guess[10];
int a,b;
Guess(char* s_guess, int s_a, int s_b):a(s_a),b(s_a){
for(int i=0; s_guess[i]; i++){
guess[i] = s_guess[i];
}
};
Guess() {
a = 0;
b = 0;
}
};
class Number_Guess {
private:
int n,m;
int guess_num;
Guess guess[Default_Chances];
list <int> poss;
void guess_init(){
guess_num = 0;
poss.clear();
}
bool suit_rulers(int x) {
int t = x;
char s[10] = "000000000";
int j = 0;
while(t!=0){
s[n-1-j] = char(t % 10 + 48);
t /= 10;
j++;
}
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n;j++){
if(s[i]==s[j]) return false;
}
}
for(int i=0; i<guess_num; i++){
int a = 0, b = 0;
for(int ii=0; ii<n; ii++){
a += (s[ii]==guess[i].guess[ii]);
for(int jj=0; jj<n; jj++){
b += (s[ii]==guess[i].guess[jj] && ii!=jj);
}
}
if (a!=guess[i].a || b!=guess[i].b) {
return false;
}
}
return true;
}
void add_poss() {
for(int i=0; i<10000; i++){
if (suit_rulers(i)) poss.push_back(i);
}
}
bool removeable(const int& x){
return suit_rulers(x);
}
public:
Number_Guess(int s_n, int s_m):n(s_n),m(s_m) {
guess_init();
}
Number_Guess() {
n = 4;
m = 10;
guess_init();
}
void add_rulers(char* _guess, int _a, int _b) {
for(int i=0; _guess[i]; i++){
guess[guess_num].guess[i] = _guess[i];
}
guess[guess_num].a = _a;
guess[guess_num].b = _b;
guess_num++;
}
int get_suggestion(){
// if(poss.size()==0){
// add_poss();
// }else{
// poss.remove_if(Number_Guess::removeable);
// }
poss.clear();
add_poss();
// for(auto i=poss.begin(); i!=poss.end(); i++){
// cout<<(*i)<<endl;
// }
if(poss.size()>0){
return *(poss.begin());
}else{
return -1;
}
}
void print_rulers(){
for(int i=0; i<guess_num; i++){
cout<<"guess: "<<guess[i].guess<<" "<<guess[i].a<<"A"<<guess[i].b<<"B\n";
}
}
int get_times(){
return guess_num;
}
};
// int main(){
// int n,m;
// // cin>>n>>m;
// Number_Guess test;
// while(true){
// char t[4];
// int a,b;
// int x;
// cin>>t>>a>>b;
// // t[0] = x/1000;
// // t[1] = (x/100) % 10;
// // t[2] = (x/10) % 10;
// // t[3] = x % 10;
// if (a==-1) {
// test.print_rulers();
// }else {
// test.add_rulers(t, a, b);
// cout<<"suggestion: "<<test.get_suggestion();
// }
// system("pause");
// }
// return 0;
// }
|
#include "glut.h"
#include "DisplayManager.h"
#include "Player.h"
#include "Bullet.h"
#include "DrawMap.h"
DisplayManager::DisplayManager()
{
bullet = new Bullet;
}
DisplayManager::~DisplayManager()
{
delete bullet; bullet = nullptr;
}
void DisplayManager::myDisplay()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// depth buffer를 비워주기
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
Player::Instance()->CameraCtrl(); //카메라
Player::Instance()->moveCtrl(); //이동 전반
DrawMap::Instance()->drawMap(); //맵그리기
bullet->drawBullet(); //총알 그리기
glutSwapBuffers();
}
void DisplayManager::reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, 16.0 / 9.0, 1, 1000);
glMatrixMode(GL_MODELVIEW);
}
|
/*
* File: calibration_check.cpp
* Date: 11/05/20
* Description: Testing of camera calibration using an object of known size
* Author: Athena Petropoulou
*/
#include <stdio.h>
#include "iostream"
#include <vector>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <math.h>
#include <fstream>
#include <sstream>
#include <iterator>
#include <webots/robot.h>
#include <webots/camera.h>
#include <webots/display.h>
#include <webots/keyboard.h>
#include <webots/motor.h>
#include <webots/device.h>
#include <webots/nodes.h>
#include <opencv2/opencv_modules.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgcodecs/imgcodecs.hpp>
#include <opencv2/videoio/videoio.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/video.hpp>
#define PI 3.14159265359
#define TIME_STEP 32
#define MAX_SPEED 5
#define CAMERA_HEIGHT 0.05
#define WHEEL_RADIUS 0.020
#define AXIS_LENGTH 0.052
#define MAP_STEP 0.1
using namespace std;
using namespace cv;
//using namespace Eigen;
/***********************************************************************************************************/
struct Position
{
double xPos, zPos, theta;
};
/***********************************************************************************************************/
// FUNCTIONS
static void compute_odometry(struct Position *pos, double Rspeed, double Lspeed);
void readMatrix(string img_path, Mat &matr);
double square(double val);
Rect findContours(Mat frame);
void thresh_callback(int, void *);
/***********************************************************************************************************/
int thresh = 100;
int max_thresh = 255;
/***********************************************************************************************************/
int main()
{
// BASIC ROBOT INIT
/********************************************************************************/
wb_robot_init();
int timestep = wb_robot_get_basic_time_step();
/* Initialize camera */
WbDeviceTag camera = wb_robot_get_device("camera");
wb_camera_enable(camera, timestep);
static int width = wb_camera_get_width(camera);
static int height = wb_camera_get_height(camera);
// get a handler to the motors and set target position to infinity (speed control)
WbDeviceTag left_motor = wb_robot_get_device("left wheel motor");
WbDeviceTag right_motor = wb_robot_get_device("right wheel motor");
wb_motor_set_position(left_motor, INFINITY);
wb_motor_set_position(right_motor, INFINITY);
// set up the motor speeds
wb_motor_set_velocity(left_motor, 0.1 * MAX_SPEED);
wb_motor_set_velocity(right_motor, 0.1 * MAX_SPEED);
/********************************************************************************/
// Camera parameters
double hor_FOV = wb_camera_get_fov(camera);
double ver_FOV = 2 * atan(tan(hor_FOV / 2) * height / width);
double deadzone = CAMERA_HEIGHT * tan(ver_FOV / 2);
Point2d principalPoint(width / 2, height / 2);
double focal_length = (double)width * 0.5 / tan(hor_FOV / 2);
Mat intrinsic = Mat(3, 3, CV_32FC1);
Mat distCoeffs;
readMatrix("intrinsic", intrinsic);
readMatrix("distCoeffs", distCoeffs);
/********************************************************************************/
Position mypos = {0, 0, 0};
//undistort(frame_old, frame_old, intrinsic, distCoeffs);
Rect object;
// object real coords
vector<Point3f> vec3d;
vec3d.push_back(Point3f(0, 0, 0));
vec3d.push_back(Point3f(0, 0.1, 0));
vec3d.push_back(Point3f(0.1, 0.1, 0));
vec3d.push_back(Point3f(0.1, 0, 0));
while (wb_robot_step(TIME_STEP) != -1)
{
// ground truth
compute_odometry(&mypos, 0.1 * MAX_SPEED, 0.1 * MAX_SPEED);
cout << "x=" << mypos.xPos << " y=" << 0.3 - mypos.zPos << endl;
Mat img = Mat(Size(width, height), CV_8UC4);
// grab frame
img.data = (uchar *)wb_camera_get_image(camera);
cvtColor(img, img, COLOR_BGR2GRAY);
namedWindow("Frame", WINDOW_NORMAL);
imshow("Frame", img);
createTrackbar(" Canny thresh:", "Frame", &thresh, max_thresh, thresh_callback);
object = findContours(img);
// object pixel coords
vector<Point2f> vec2d;
vec2d.push_back(Point2f(object.x, object.y));
vec2d.push_back(Point2f(object.x, object.y + object.height));
vec2d.push_back(Point2f(object.x + object.width, object.y + object.height));
vec2d.push_back(Point2f(object.x + object.width, object.y));
//The pose of the object: rvec is the rotation vector, tvec is the translation vector
Mat rvec, tvec;
solvePnP(vec3d, vec2d, intrinsic, distCoeffs, rvec, tvec);
double d = sqrt(square(tvec.at<double>(0)) + square(tvec.at<double>(2)));
cout << "Distance:" << d << endl;
cout << "Error is : " << fabs(d - (0.3 - fabs(sqrt(square(mypos.xPos) + square(mypos.zPos))))) << endl;
cout << " " << endl;
waitKey(TIME_STEP);
}
//CLEANUP
wb_robot_cleanup();
return 0;
}
/**************************************************************************************************************************/
void thresh_callback(int, void *)
{
}
/**************************************************************************************************************************/
void readMatrix(string img_path, Mat &matr)
{
ifstream inStream(img_path);
if (inStream)
{
uint16_t rows;
uint16_t columns;
inStream >> rows;
inStream >> columns;
matr = Mat(Size(columns, rows), CV_64F);
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < columns; c++)
{
double read = 0.0f;
inStream >> read;
matr.at<double>(r, c) = read;
}
}
inStream.close();
}
}
/**************************************************************************************************************************/
double square(double val)
{
return val * val;
}
/**************************************************************************************************************************/
static void compute_odometry(struct Position *pos, double Rspeed, double Lspeed)
{
double l = Lspeed * TIME_STEP * 0.001;
double r = Rspeed * TIME_STEP * 0.001;
// distance covered by left wheel in meter
double dl = l * WHEEL_RADIUS;
// distance covered by right wheel in meter
double dr = r * WHEEL_RADIUS;
// delta orientation in rad
double deltaTheta = (dl - dr) / (AXIS_LENGTH);
double deltaStep = (dl + dr) / 2; // Expressed in meters.
pos->xPos += deltaStep * sin(pos->theta + deltaTheta / 2); // Expressed in meters.
pos->zPos += deltaStep * cos(pos->theta + deltaTheta / 2); // Expressed in meters.
pos->theta += deltaTheta; // Expressed in rad.
}
/**************************************************************************************************************************/
Rect findContours(Mat frame)
{
Mat thresholded;
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
Mat frame2 = frame.clone();
blur(frame, thresholded, Size(3, 3));
Canny(thresholded, thresholded, thresh, 2 * thresh, 3);
// Find contours
findContours(thresholded, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
vector<Rect> boundRect(contours.size());
/// Draw contours
Mat drawing = Mat::zeros(thresholded.size(), CV_8UC3);
for (size_t i = 0; i < contours.size(); i++)
{
boundRect[i] = boundingRect(contours[i]);
rectangle(drawing, boundRect[i].tl(), boundRect[i].br(), Scalar(255, 0, 255), 2);
}
namedWindow("contours", WINDOW_NORMAL);
imshow("contours", drawing);
waitKey(TIME_STEP);
return boundRect[0];
}
|
/*
One acre of land is equivalent to 43,560 square feet. Write a program that calculates
the number of acres in a tract of land with 391,876 square feet.
Author: Aaron Maynard
*/
#include <iostream>
using namespace std;
int main()
{
// Declare variables
double conversion = 43560; //1 acre = 43560 sq ft
double land = 391876; // 391876 sq ft
double acre = land / conversion;
// Display on screen
cout << land << " sq ft = " << acre << " acres \n\n";
system("pause");
return 0;
}
|
#include <iostream>
using namespace std;
int main()
{
cout << "In Test.cpp" << endl;
cout << "Added in branch-1" << endl;
}
|
#include <gtest/gtest.h>
#include "shoc/hash/md2.h"
#include "shoc/hash/md4.h"
#include "shoc/hash/md5.h"
#include "shoc/hash/sha1.h"
#include "shoc/hash/sha2.h"
// #include "shoc/hash/sha3.h"
#include "shoc/hash/gimli.h"
using namespace shoc;
struct Data {
std::string_view msg;
std::string_view exp;
};
template<class Hash, size_t N>
static void check(const Data (&test)[N])
{
Hash hash;
byte bin[Hash::SIZE] = {};
char str[Hash::SIZE * 2 + 1] = {};
for (auto it : test) {
hash(it.msg.data(), it.msg.size(), bin);
utl::bin_to_str(bin, sizeof(bin), str, sizeof(str));
EXPECT_STREQ(it.exp.data(), str);
}
}
TEST(Hash, Md2)
{
const Data test[] = {
{ "",
"8350e5a3e24c153df2275c9f80692773" },
{ "a",
"32ec01ec4a6dac72c0ab96fb34c0b5d1" },
{ "abc",
"da853b0d3f88d99b30283a69e6ded6bb" },
{ "message digest",
"ab4f496bfb2a530b219ff33031fe06b0" },
{ "abcdefghijklmnopqrstuvwxyz",
"4e8ddff3650292ab5a4108c3aa47940b" },
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"da33def2a42df13975352846c30338cd" },
{ "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"d5976f79d83d3a0dc9806c3c66f3efd8" },
};
check<Md2>(test);
}
TEST(Hash, Md4)
{
const Data test[] = {
{ "",
"31d6cfe0d16ae931b73c59d7e0c089c0" },
{ "a",
"bde52cb31de33e46245e05fbdbd6fb24" },
{ "abc",
"a448017aaf21d8525fc10ae87aa6729d" },
{ "message digest",
"d9130a8164549fe818874806e1c7014b" },
{ "abcdefghijklmnopqrstuvwxyz",
"d79e1c308aa5bbcdeea8ed63df412da9" },
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"043f8582f241db351ce627e153e7f0e4" },
{ "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"e33b4ddc9c38f2199c3e7b164fcc0536" },
};
check<Md4>(test);
}
TEST(Hash, Md5)
{
const Data test[] = {
{ "",
"d41d8cd98f00b204e9800998ecf8427e" },
{ "a",
"0cc175b9c0f1b6a831c399e269772661" },
{ "abc",
"900150983cd24fb0d6963f7d28e17f72" },
{ "message digest",
"f96b697d7cb7938d525a2f31aaf161d0" },
{ "abcdefghijklmnopqrstuvwxyz",
"c3fcd3d76192e4007dfb496cca67e13b" },
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"d174ab98d277d9f5a5611c2c9f419d9f" },
{ "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"57edf4a22be3c955ac49da2e2107b67a" },
};
check<Md5>(test);
}
TEST(Hash, Sha1)
{
const Data test[] = {
{ "abc",
"a9993e364706816aba3e25717850c26c9cd0d89d" },
{ "",
"da39a3ee5e6b4b0d3255bfef95601890afd80709" },
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"84983e441c3bd26ebaae4aa1f95129e5e54670f1" },
{ "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"a49b2446a02c645bf419f995b67091253a04a259" },
{ "The quick brown fox jumps over the lazy dog",
"2fd4e1c67a2d28fced849ee1bb76e7391b93eb12" },
{ "The quick brown fox jumps over the lazy cog",
"de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3" },
};
check<Sha1>(test);
}
TEST(Hash, Sha224)
{
const Data test[] = {
{ "abc",
"23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7" },
{ "",
"d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f" },
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525" },
{ "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"c97ca9a559850ce97a04a96def6d99a9e0e0e2ab14e6b8df265fc0b3" },
};
check<Sha2<SHA_224>>(test);
}
TEST(Hash, Sha256)
{
const Data test[] = {
{ "abc",
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" },
{ "",
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" },
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" },
{ "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1" },
};
check<Sha2<SHA_256>>(test);
}
TEST(Hash, Sha384)
{
const Data test[] = {
{ "abc",
"cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7" },
{ "",
"38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b" },
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b" },
{ "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039" },
};
check<Sha2<SHA_384>>(test);
}
TEST(Hash, Sha512)
{
const Data test[] = {
{ "abc",
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f" },
{ "",
"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e" },
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445" },
{ "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909" },
};
check<Sha2<SHA_512>>(test);
}
TEST(Hash, Sha512_224)
{
const Data test[] = {
{ "abc",
"4634270f707b6a54daae7530460842e20e37ed265ceee9a43e8924aa" },
{ "",
"6ed0dd02806fa89e25de060c19d3ac86cabb87d6a0ddd05c333b84f4" },
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"e5302d6d54bb242275d1e7622d68df6eb02dedd13f564c13dbda2174" },
{ "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"23fec5bb94d60b23308192640b0c453335d664734fe40e7268674af9" },
};
check<Sha2<SHA_512_224>>(test);
}
TEST(Hash, Sha512_256)
{
const Data test[] = {
{ "abc",
"53048e2681941ef99b2e29b76b4c7dabe4c2d0c634fc6d46e0e2f13107e7af23" },
{ "",
"c672b8d1ef56ed28ab87c3622c5114069bdd3ad7b8f9737498d0c01ecef0967a" },
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"bde8e1f9f19bb9fd3406c90ec6bc47bd36d8ada9f11880dbc8a22a7078b6a461" },
{ "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"3928e184fb8690f840da3988121d31be65cb9d3ef83ee6146feac861e19b563a" },
};
check<Sha2<SHA_512_256>>(test);
}
TEST(Hash, Gimli)
{
const Data test[] = {
{ "There's plenty for the both of us, may the best Dwarf win.",
"4afb3ff784c7ad6943d49cf5da79facfa7c4434e1ce44f5dd4b28f91a84d22c8" },
{ "If anyone was to ask for my opinion, which I note they're not, I'd say we were taking the long way around.",
"ba82a16a7b224c15bed8e8bdc88903a4006bc7beda78297d96029203ef08e07c" },
{ "Speak words we can all understand!",
"8dd4d132059b72f8e8493f9afb86c6d86263e7439fc64cbb361fcbccf8b01267" },
{ "It's true you don't see many Dwarf-women. And in fact, they are so alike in voice and appearance, that they are often mistaken for Dwarf-men. And this in turn has given rise to the belief that there are no Dwarf-women, and that Dwarves just spring out of holes in the ground! Which is, of course, ridiculous.",
"8887a5367d961d6734ee1a0d4aee09caca7fd6b606096ff69d8ce7b9a496cd2f" },
{ "",
"b0634b2c0b082aedc5c0a2fe4ee3adcfc989ec05de6f00addb04b3aaac271f67" },
};
check<Gimli>(test);
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
(3>5) ? printf("3 bigger than 5!!!!\n") : printf("3 not bigger than 5!!!!\n");
}
|
#include "scenario_insert.hpp"
ScenarioInsert::~ScenarioInsert()
{
}
ScenarioInsert::ScenarioInsert(const std::vector<std::string>& word_list,
std::size_t nqueries)
: Scenario()
{
std::random_device rd;
std::mt19937 gen(rd());
this->m_impl->queries.reserve(nqueries);
this->m_impl->init_word_list = std::vector<std::string>();
std::uniform_int_distribution<> rand(0, nqueries);
for (std::size_t i = 0; i < nqueries; ++i)
this->m_impl->queries.push_back({query::insert, word_list[rand(gen)]});
// Shuffle everything
std::shuffle(this->m_impl->queries.begin(), this->m_impl->queries.end(), gen);
}
|
#include "gamewindow.h"
GameWindow::GameWindow(QWidget *parent)
: QMainWindow(parent)
{
gameWidget = new QWidget;
//LAYOUT PRINCIPAL
gameLayout = new QGridLayout;
//BACKGROUND DE LINTERFACE
QPixmap bkgnd("./Image/Background.jpg");
bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio);
QPalette palette;
palette.setBrush(QPalette::Background, bkgnd);
this->setPalette(palette);
//LCD SCORE ET LIGNES
scoreLCD = new QLCDNumber(5);
scoreLCD->setSegmentStyle(QLCDNumber::Filled);
//BOUTON DE GAME
quitButton = new QPushButton("Quitter");
QObject::connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
pauseButton = new QPushButton("Pause");
//QObject::connect(pauseButton,SIGNAL(clicked(), this, ));
//PLACEMENT LAYOUT PRINCIPAL
gameWidget->setLayout(gameLayout);
setCentralWidget(gameWidget);
}
GameWindow::~GameWindow()
{
delete gameLayout;
delete gameWidget;
}
|
// MainFrm.cpp: CMainFrame 클래스의 구현
//
#include "pch.h"
#include "framework.h"
#include "MFCPainter.h"
#include "CLeftToolBar.h"
#include "MFCPainterView.h"
#include "MFCPainterDoc.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMainFrame
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_CREATE()
ON_COMMAND(IDM_COLOR_EDIT, &CMainFrame::OnColorEdit)
ON_COMMAND(ID_FILE_OPEN, &CMainFrame::OnFileOpen)
END_MESSAGE_MAP()
// CMainFrame 생성/소멸
CMainFrame::CMainFrame() noexcept
{
// TODO: 여기에 멤버 초기화 코드를 추가합니다.
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("도구 모음을 만들지 못했습니다.\n");
return -1; // 만들지 못했습니다.
}
// TODO: 도구 모음을 도킹할 수 없게 하려면 이 세 줄을 삭제하십시오.
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);
return 0;
}
BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT /*lpcs*/,
CCreateContext* pContext)
{
m_wndSplitter.CreateStatic(this,1, 2);
m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CLeftToolBar), CSize(100,0), pContext);
m_wndSplitter.CreateView(0, 1, RUNTIME_CLASS(CMFCPainterView), CSize(0,0), pContext);
return TRUE;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: CREATESTRUCT cs를 수정하여 여기에서
// Window 클래스 또는 스타일을 수정합니다.
return TRUE;
}
// CMainFrame 진단
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
// CMainFrame 메시지 처리기
void CMainFrame::OnColorEdit()
{
// TODO: 여기에 명령 처리기 코드를 추가합니다.
CColorDialog colorDlg(RGB(255,255,255), CC_FULLOPEN);
CMainFrame* pFrame = (CMainFrame*)AfxGetMainWnd();
if (colorDlg.DoModal() == IDOK) {
COLORREF color = colorDlg.GetColor();
CMFCPainterDoc* pDoc = (CMFCPainterDoc *)(pFrame->GetActiveDocument());
pDoc->color = color;
Invalidate(FALSE);
}
}
void CMainFrame::OnFileOpen()
{
// TODO: 여기에 명령 처리기 코드를 추가합니다.
CFileDialog fileDlg(FALSE, _T("이미지(*.jpg, * bmp, *png)"),_T("*.jpg;*.bmp;*.png"), OFN_OVERWRITEPROMPT);
if (fileDlg.DoModal() == IDOK) {
CString path = fileDlg.GetPathName();
}
}
|
// BkGnuPG.cpp : DLL アプリケーション用のエントリ ポイントを定義します。
//
#include "stdafx.h"
#include "BkGnuPG.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// これはエクスポートされた変数の例です。
BKGNUPG_API int nBkGnuPG=0;
// これはエクスポートされた関数の例です。
BKGNUPG_API int fnBkGnuPG(void)
{
return 42;
}
// これはエクスポートされたクラスのコンストラクタです。
// クラスの定義については BkGnuPG.h を参照してください。
CBkGnuPG::CBkGnuPG()
{
return;
}
|
#include<bits/stdc++.h>
using namespace std;
main()
{
int n;
while(cin>>n)
{
int r;
r = n%4;
if(n==0)
cout<<"1"<<endl;
else if(r==1)
cout<<"8"<<endl;
else if(r==2)
cout<<"4"<<endl;
else if(r==3)
cout<<"2"<<endl;
else if(r==0 && n!=0)
cout<<"6"<<endl;
}
return 0;
}
|
#include <iostream>
#include <vector>
using namespace std;
int soliNumeros();
vector<int> Numeros();
int sumaNumeros( vector<int> );
int productoNumeros( vector<int> ) ;
int main()
{
vector<int> lista ;
int suma , producto ;
lista = Numeros();
suma = sumaNumeros( lista ) ;
producto = productoNumeros( lista ) ;
cout << "La suma de los numeros positivos es: " << suma << endl ;
cout << "El producto de los numeros negativos es: " << producto << endl ;
return 0 ;
} // fin main
vector<int> Numeros()
{
vector<int> lista ;
int valor = 0 ;
while( lista.size() != 10 )
{
lista.push_back( soliNumeros() ) ;
}
return lista ;
} // fin Numeros
int soliNumeros()
{
int valor ;
while( true )
{
cout << "Ingrese valor: " ; cin >> valor ;
if( valor != 0 ) break ;
else cout << "Valor ingresado no valido." << endl ;
}
return valor ;
} // fin soliNumeros
int sumaNumeros( vector<int> lista )
{
int resultado = 0 ;
for( int i = 0 ; i < lista.size() ; i++ )
{
if( lista.at(i) > 0 ) resultado += lista.at(i) ;
}
return resultado ;
} // fin sumaNumeros
int productoNumeros( vector<int> lista )
{
int producto = 1 ;
for( int i = 0 ; i < lista.size() ; i++ )
{
if( lista.at(i) < 0 ) producto *= lista.at(i) ;
}
return producto ;
} // fin productoNumeros
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#include "platforms/mac/model/MacServices.h"
#include "platforms/mac/util/systemcapabilities.h"
#include "platforms/mac/util/CTextConverter.h"
#include "adjunct/quick/Application.h"
#include "adjunct/m2_ui/windows/ComposeDesktopWindow.h"
#include "adjunct/desktop_util/mail/mailto.h"
#include "adjunct/desktop_util/mail/mailcompose.h"
#ifndef NO_CARBON
#ifdef SUPPORT_OSX_SERVICES
EventHandlerRef MacOpServices::sServicesHandler = NULL;
EventHandlerUPP MacOpServices::sServicesUPP = NULL;
MacOpServices::MacOpServices()
{
}
void MacOpServices::Free()
{
if(sServicesHandler)
{
::RemoveEventHandler(sServicesHandler);
sServicesHandler = NULL;
}
if(sServicesUPP)
{
::DisposeEventHandlerUPP(sServicesUPP);
sServicesUPP = NULL;
}
}
void MacOpServices::InstallServicesHandler()
{
// Only install if we're not embedded
if(g_application && g_application->IsEmBrowser())
return;
if(sServicesHandler)
return; // already installed
static EventTypeSpec servicesEventList[] =
{
{kEventClassService, kEventServicePerform}
};
sServicesUPP = NewEventHandlerUPP(ServicesHandler);
if(!sServicesUPP)
return;
InstallApplicationEventHandler( sServicesUPP,
GetEventTypeCount(servicesEventList),
servicesEventList,
/*userdata*/ 0,
&sServicesHandler);
}
pascal OSStatus MacOpServices::ServicesHandler(EventHandlerCallRef nextHandler, EventRef inEvent, void *inUserData)
{
UInt32 carbonEventClass = GetEventClass(inEvent);
UInt32 carbonEventKind = GetEventKind(inEvent);
bool eventHandled = false;
if((carbonEventClass == kEventClassService) && (carbonEventKind == kEventServicePerform))
{
CFStringRef message;
// CFStringRef userData;
ScrapRef specificScrap;
// ScrapRef currentScrap;
OSStatus err;
/*
*/
err = GetEventParameter (inEvent,
kEventParamServiceMessageName,
typeCFStringRef,
NULL,
sizeof (CFStringRef),
NULL,
&message);
if(err != noErr)
goto exithandler;
if(!message)
goto exithandler;
err = GetEventParameter (inEvent,
kEventParamScrapRef,
typeScrapRef,
NULL,
sizeof (ScrapRef),
NULL,
&specificScrap);
if(err != noErr)
goto exithandler;
OperaServiceProviderKind kind = GetServiceKind(message);
if(kind == kOperaServiceKindUnknown)
goto exithandler;
if((kind == kOperaServiceKindOpenURL) ||
(kind == kOperaServiceKindMailTo))
{
OpString text;
long textSize = 0;
Boolean gotData = false;
char *macbuffer;
err = GetScrapFlavorSize(specificScrap, kScrapFlavorTypeUnicode, &textSize);
if ((err == noErr) && (textSize > 0))
{
if (text.Reserve((textSize / 2) + 1))
{
err = GetScrapFlavorData(specificScrap, kScrapFlavorTypeUnicode, &textSize, text.CStr());
if (err == noErr)
{
text[(int)(textSize / 2)] = '\0';
gotData = true;
}
}
}
if (!gotData)
{
err = GetScrapFlavorSize(specificScrap, kScrapFlavorTypeText, &textSize);
if ((err == noErr) && (textSize > 0))
{
macbuffer = new char[textSize + 1];
if (macbuffer)
{
if (text.Reserve(textSize + 1))
{
err = GetScrapFlavorData(specificScrap, kScrapFlavorTypeText, &textSize, macbuffer);
if (err == noErr)
{
macbuffer[textSize] = '\0';
textSize = gTextConverter.ConvertStringFromMacC(macbuffer, text.CStr(), textSize + 1);
gotData = true;
}
}
delete [] macbuffer;
}
}
}
if(gotData)
{
if(text.HasContent())
{
eventHandled = true;
if(kind == kOperaServiceKindOpenURL)
{
g_application->OpenURL(text, MAYBE, MAYBE, MAYBE);
}
else if(kind == kOperaServiceKindMailTo)
{
OpString empty;
MailTo mailto;
mailto.Init(text, empty, empty, empty, empty);
MailCompose::ComposeMail(mailto);
}
}
}
}
else if((kind == kOperaServiceKindSendFiles) ||
(kind == kOperaServiceKindOpenFiles))
{
/**
* Due to limitations in the scrap manager we can only get single files.
* See http://lists.apple.com/archives/carbon-development/2001/Sep/21/carbonapplicationandthes.007.txt.
*
* 'furl' datatype described here: http://developer.apple.com/technotes/tn/tn2022.html
*/
long textSize = 0;
OpString text;
Boolean gotData = false;
err = GetScrapFlavorSize(specificScrap, 'furl', &textSize);
if ((err == noErr) && (textSize > 0))
{
char* utf8str = new char[textSize + 1];
if(utf8str)
{
err = GetScrapFlavorData(specificScrap, 'furl', &textSize, utf8str);
if (err == noErr)
{
utf8str[textSize] = '\0';
if(kind == kOperaServiceKindSendFiles)
{
// We want a filesystem path, not a file:// URL
CFURLRef cfurl = CFURLCreateWithBytes(NULL, (UInt8*)utf8str, textSize, kCFStringEncodingUTF8, NULL);
if(cfurl)
{
CFStringRef path = CFURLCopyFileSystemPath(cfurl, kCFURLPOSIXPathStyle);
if(path)
{
size_t strLen = CFStringGetLength(path);
if(text.Reserve(strLen+1) != NULL)
{
uni_char *dataPtr = text.DataPtr();
CFStringGetCharacters(path, CFRangeMake(0, strLen), (UniChar*)dataPtr);
dataPtr[strLen] = 0;
gotData = true;
}
CFRelease(path);
}
CFRelease(cfurl);
}
}
else
{
if(OpStatus::IsSuccess(text.SetFromUTF8(utf8str, KAll)))
{
gotData = true;
}
}
}
delete [] utf8str;
}
}
if(gotData)
{
if(text.HasContent())
{
eventHandled = true;
if(kind == kOperaServiceKindSendFiles)
{
OpString empty;
#if defined M2_SUPPORT
MailTo mailto;
mailto.Init(empty, empty, empty, empty, empty);
MailCompose::ComposeMail(mailto, FALSE, FALSE, FALSE, &text);
#endif
}
else if(kind == kOperaServiceKindOpenFiles)
{
g_application->OpenURL(text, MAYBE, MAYBE, MAYBE);
}
}
}
}
}
exithandler:
if (eventHandled)
return noErr;
else
return eventNotHandledErr;
}
MacOpServices::OperaServiceProviderKind MacOpServices::GetServiceKind(CFStringRef cfstr)
{
OperaServiceProviderKind kind = kOperaServiceKindUnknown;
if(CFStringCompare(cfstr, kOperaOpenURLString, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
{
kind = kOperaServiceKindOpenURL;
}
else if(CFStringCompare(cfstr, kOperaMailToString, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
{
kind = kOperaServiceKindMailTo;
}
else if(CFStringCompare(cfstr, kOperaSendFilesString, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
{
kind = kOperaServiceKindSendFiles;
}
else if(CFStringCompare(cfstr, kOperaOpenFilesString, kCFCompareCaseInsensitive) == kCFCompareEqualTo)
{
kind = kOperaServiceKindOpenFiles;
}
return kind;
}
#endif // SUPPORT_OSX_SERVICES
#endif // !NO_CARBON
|
// File: fullSample.cpp
// Library: SimpleOpt
// Author: Brodie Thiesfield <code@jellycan.com>
// Source: http://code.jellycan.com/simpleopt/
//
// MIT LICENCE
// ===========
// The licence text below is the boilerplate "MIT Licence" used from:
// http://www.opensource.org/licenses/mit-license.php
//
// Copyright (c) 2006, Brodie Thiesfield
//
// 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.
#if defined(_MSC_VER)
# include <windows.h>
# include <tchar.h>
#else
# define TCHAR char
# define _T(x) x
# define _tprintf printf
# define _tmain main
# define _ttoi atoi
#endif
#include <stdio.h>
#include <locale.h>
#include "SimpleOpt.h"
#include "SimpleGlob.h"
static void ShowUsage()
{
_tprintf(
_T("Usage: fullSample [OPTIONS] [FILES]\n")
_T("\n")
_T("--exact Disallow partial matching of option names\n")
_T("--noslash Disallow use of slash as an option marker on Windows\n")
_T("--shortarg Permit arguments on single letter options with no equals sign\n")
_T("--clump Permit single char options to be clumped as long string\n")
_T("--noerr Do not generate any errors for invalid options\n")
_T("--pedantic Generate an error for petty things\n")
_T("--icase Case-insensitive for all types\n")
_T("--icase-short Case-insensitive for short args\n")
_T("--icase-long Case-insensitive for long argsn")
_T("--icase-word Case-insensitive for word args\n")
_T("\n")
_T("-d -e -E -f -F -g -flag --flag Flag (no arg)\n")
_T("-s ARG -sep ARG --sep ARG Separate required arg\n")
_T("-S ARG -SEP ARG --SEP ARG Separate required arg (uppercase)\n")
_T("-cARG -c=ARG -com=ARG --com=ARG Combined required arg\n")
_T("-o[ARG] -o[=ARG] -opt[=ARG] --opt[=ARG] Combined optional arg\n")
_T("-man -mandy -mandate Shortcut matching tests\n")
_T("--man --mandy --mandate Shortcut matching tests\n")
_T("--multi0 --multi1 ARG --multi2 ARG1 ARG2 Multiple argument tests\n")
_T("--multi N ARG-1 ARG-2 ... ARG-N Multiple argument tests\n")
_T("open read write close zip unzip UPCASE Special words\n")
_T("\n")
_T("-? -h -help --help Output this help.\n")
_T("\n")
_T("If a FILE is `-', read standard input.\n")
);
}
CSimpleOpt::SOption g_rgFlags[] =
{
{ SO_O_EXACT, _T("--exact"), SO_NONE },
{ SO_O_NOSLASH, _T("--noslash"), SO_NONE },
{ SO_O_SHORTARG, _T("--shortarg"), SO_NONE },
{ SO_O_CLUMP, _T("--clump"), SO_NONE },
{ SO_O_NOERR, _T("--noerr"), SO_NONE },
{ SO_O_PEDANTIC, _T("--pedantic"), SO_NONE },
{ SO_O_ICASE, _T("--icase"), SO_NONE },
{ SO_O_ICASE_SHORT, _T("--icase-short"), SO_NONE },
{ SO_O_ICASE_LONG, _T("--icase-long"), SO_NONE },
{ SO_O_ICASE_WORD, _T("--icase-word"), SO_NONE },
SO_END_OF_OPTIONS
};
enum { OPT_HELP = 0, OPT_MULTI = 100, OPT_MULTI0, OPT_MULTI1, OPT_MULTI2 };
CSimpleOpt::SOption g_rgOptions[] =
{
{ OPT_HELP, _T("-?"), SO_NONE },
{ OPT_HELP, _T("-h"), SO_NONE },
{ OPT_HELP, _T("-help"), SO_NONE },
{ OPT_HELP, _T("--help"), SO_NONE },
{ 1, _T("-"), SO_NONE },
{ 2, _T("-d"), SO_NONE },
{ 3, _T("-e"), SO_NONE },
{ 4, _T("-f"), SO_NONE },
{ 5, _T("-g"), SO_NONE },
{ 6, _T("-flag"), SO_NONE },
{ 7, _T("--flag"), SO_NONE },
{ 8, _T("-s"), SO_REQ_SEP },
{ 9, _T("-sep"), SO_REQ_SEP },
{ 10, _T("--sep"), SO_REQ_SEP },
{ 11, _T("-c"), SO_REQ_CMB },
{ 12, _T("-com"), SO_REQ_CMB },
{ 13, _T("--com"), SO_REQ_CMB },
{ 14, _T("-o"), SO_OPT },
{ 15, _T("-opt"), SO_OPT },
{ 16, _T("--opt"), SO_OPT },
{ 17, _T("-man"), SO_NONE },
{ 18, _T("-mandy"), SO_NONE },
{ 19, _T("-mandate"), SO_NONE },
{ 20, _T("--man"), SO_NONE },
{ 21, _T("--mandy"), SO_NONE },
{ 22, _T("--mandate"), SO_NONE },
{ 23, _T("open"), SO_NONE },
{ 24, _T("read"), SO_NONE },
{ 25, _T("write"), SO_NONE },
{ 26, _T("close"), SO_NONE },
{ 27, _T("zip"), SO_NONE },
{ 28, _T("unzip"), SO_NONE },
{ 29, _T("-E"), SO_NONE },
{ 30, _T("-F"), SO_NONE },
{ 31, _T("-S"), SO_REQ_SEP },
{ 32, _T("-SEP"), SO_REQ_SEP },
{ 33, _T("--SEP"), SO_REQ_SEP },
{ 34, _T("UPCASE"), SO_NONE },
{ OPT_MULTI, _T("--multi"), SO_MULTI },
{ OPT_MULTI0, _T("--multi0"), SO_MULTI },
{ OPT_MULTI1, _T("--multi1"), SO_MULTI },
{ OPT_MULTI2, _T("--multi2"), SO_MULTI },
SO_END_OF_OPTIONS
};
void ShowFiles(int argc, TCHAR ** argv) {
// glob files to catch expand wildcards
CSimpleGlob glob(SG_GLOB_NODOT|SG_GLOB_NOCHECK);
if (SG_SUCCESS != glob.Add(argc, argv)) {
_tprintf(_T("Error while globbing files\n"));
return;
}
for (int n = 0; n < glob.FileCount(); ++n) {
_tprintf(_T("file %2d: '%s'\n"), n, glob.File(n));
}
}
static const TCHAR *
GetLastErrorText(
int a_nError
)
{
switch (a_nError) {
case SO_SUCCESS: return _T("Success");
case SO_OPT_INVALID: return _T("Unrecognized option");
case SO_OPT_MULTIPLE: return _T("Option matched multiple strings");
case SO_ARG_INVALID: return _T("Option does not accept argument");
case SO_ARG_INVALID_TYPE: return _T("Invalid argument format");
case SO_ARG_MISSING: return _T("Required argument is missing");
case SO_ARG_INVALID_DATA: return _T("Invalid argument data");
default: return _T("Unknown error");
}
}
static void
DoMultiArgs(
CSimpleOpt & args,
int nMultiArgs
)
{
TCHAR ** rgpszArg = NULL;
// get the number of arguments if necessary
if (nMultiArgs == -1) {
// first arg is a count of how many we have
rgpszArg = args.MultiArg(1);
if (!rgpszArg) {
_tprintf(
_T("%s: '%s' (use --help to get command line help)\n"),
GetLastErrorText(args.LastError()), args.OptionText());
return;
}
nMultiArgs = _ttoi(rgpszArg[0]);
}
_tprintf(_T("%s: expecting %d args\n"), args.OptionText(), nMultiArgs);
// get the arguments to follow
rgpszArg = args.MultiArg(nMultiArgs);
if (!rgpszArg) {
_tprintf(
_T("%s: '%s' (use --help to get command line help)\n"),
GetLastErrorText(args.LastError()), args.OptionText());
return;
}
for (int n = 0; n < nMultiArgs; ++n) {
_tprintf(_T("MultiArg %d: %s\n"), n, rgpszArg[n]);
}
}
int _tmain(int argc, TCHAR * argv[]) {
setlocale( LC_ALL, "Japanese" );
// get the flags to use for SimpleOpt from the command line
int nFlags = SO_O_USEALL;
CSimpleOpt flags(argc, argv, g_rgFlags, SO_O_NOERR|SO_O_EXACT);
while (flags.Next()) {
nFlags |= flags.OptionId();
}
// now process the remainder of the command line with these flags
CSimpleOpt args(flags.FileCount(), flags.Files(), g_rgOptions, nFlags);
while (args.Next()) {
if (args.LastError() != SO_SUCCESS) {
_tprintf(
_T("%s: '%s' (use --help to get command line help)\n"),
GetLastErrorText(args.LastError()), args.OptionText());
continue;
}
switch (args.OptionId()) {
case OPT_HELP:
ShowUsage();
return 0;
case OPT_MULTI:
DoMultiArgs(args, -1);
break;
case OPT_MULTI0:
DoMultiArgs(args, 0);
break;
case OPT_MULTI1:
DoMultiArgs(args, 1);
break;
case OPT_MULTI2:
DoMultiArgs(args, 2);
break;
default:
if (args.OptionArg()) {
_tprintf(_T("option: %2d, text: '%s', arg: '%s'\n"),
args.OptionId(), args.OptionText(), args.OptionArg());
}
else {
_tprintf(_T("option: %2d, text: '%s'\n"),
args.OptionId(), args.OptionText());
}
}
}
/* process files from command line */
ShowFiles(args.FileCount(), args.Files());
return 0;
}
|
#include <stdio.h>
int main() {
float c, f;
printf("Digite a temperatura em Graus Celcius: ");
scanf("%f", &c);
f = (9 * c + 160) / 5;
printf("Sua temperatura equivale a %.2f Graus Fahrenheit.", f);
}
|
#include "pch.h"
#include "IComponent.h"
#include "Core\ComponentFactory.h"
namespace Hourglass
{
IComponent::IComponent()
{
m_IsAlive = false;
m_IsEnabled = false;
m_Entity = nullptr;
}
IComponent* IComponent::Create( StrID name )
{
return ComponentFactory::GetFreeComponent( name );
}
IComponent* IComponent::MakeCopy()
{
IComponent* copy = MakeCopyDerived();
copy->m_IsEnabled = m_IsEnabled;
copy->m_IsAlive = m_IsAlive;
return copy;
}
/**
* Attaches this component to the passed in entity
*/
void IComponent::Attach( Entity* entity )
{
m_Entity = entity;
}
/**
* Detaches this component from it's owning owning entity
*/
void IComponent::Detach()
{
m_Entity = nullptr;
SetEnabled( false );
}
void IComponent::Shutdown()
{
m_IsAlive = false;
m_IsEnabled = false;
}
}
|
#include <iostream>
#include <cmath>
#include <Eigen/Core>
#include <Eigen/Geometry> //Eigen几何模块
using namespace std;
using namespace Eigen;
//本程序演示Eigen几何模块的使用方法
int main(int argc, char** argv)
{
//旋转向量使用AngleAxisd,它的底层不直接是Matrix
//但运算可以当作矩阵(因为重载了运算符)
//此旋转向量是沿z轴旋转45度
AngleAxisd rotation_vector(M_PI/4, Vector3d(0, 0, 1));
//旋转矩阵使用Matrix3d或Matrix3f
Matrix3d rotation_matrix = Matrix3d::Identity(); //用单位矩阵初始化
//用matrix()将旋转向量转换成旋转矩阵
rotation_matrix = rotation_vector.matrix();
cout << "rotation_matrix = \n" << rotation_vector.matrix() << endl;
//用toRotationMatrix()将旋转向量转换成旋转矩阵
rotation_matrix = rotation_vector.toRotationMatrix();
cout << "rotation_matrix = \n" << rotation_matrix << endl;
//变换矩阵使用Isometry3d,虽称3d,实质上是4*4的矩阵
Isometry3d T = Isometry3d::Identity();
T.rotate(rotation_vector); //旋转向量按照rotation_vector进行旋转
T.pretranslate(Vector3d::Zero()); //平移向量设置为0
//欧拉角使用Vector3d,将旋转矩阵转化为欧拉角
Vector3d euler_angles = rotation_matrix.eulerAngles(0, 1, 2);
//(0, 1, 2)是XYZ顺序,(2, 1, 0)是ZYX顺序
cout << "(roll, pitch, yaw) = \n" << euler_angles << endl;
//四元数使用Quaterniond,将旋转向量转化为四元数
Quaterniond qua1 = Quaterniond(rotation_vector);
cout << "quaternion1 = \n" << qua1.coeffs() << endl; //虚部在前,实部在后
//将旋转矩阵转化为四元数
Quaterniond qua2 = Quaterniond(rotation_matrix);
cout << "quaternion2 = \n" << qua2.coeffs() << endl; //虚部在前,实部在后
//试验所用的待旋转向量
Vector3d vector_3d(1, 0, 0);
Vector3d vector_3d_totated;
//使用旋转向量进行旋转
vector_3d_totated = rotation_vector * vector_3d;
cout << "(1, 0, 0) after rotation = \n" << vector_3d_totated << endl;
//使用旋转矩阵进行旋转
vector_3d_totated = rotation_matrix * vector_3d;
cout << "(1, 0, 0) after rotation = \n" << vector_3d_totated << endl;
//用变换矩阵进行坐旋转
Eigen::Vector3d vector_transformed = T * vector_3d;
cout << "vector_transformed = \n" << vector_transformed << endl;
//使用四元数进行旋转
vector_3d_totated = qua1 * vector_3d;
cout << "(1, 0, 0) after rotation = \n" << vector_3d_totated << endl;
return 0;
}
|
#include <iostream>
#include <stdlib.h>
#include <stdint.h>
#include "weights.h"
#ifdef __SDSCC__
#include "sds_lib.h"
#endif
#include "loss_HW.h"
#ifdef __SDSCC__
class perf_counter
{
public:
uint64_t tot, cnt, calls;
perf_counter() : tot(0), cnt(0), calls(0) {};
inline void reset() { tot = cnt = calls = 0; }
inline void start() { cnt = sds_clock_counter(); calls++; };
inline void stop() { tot += (sds_clock_counter() - cnt); };
inline uint64_t avg_cpu_cycles() { return (tot / calls); };
};
#endif
static void init_arrays(float X[BATCH_SIZE*FEATURE_SIZE],
float LABEL[BATCH_SIZE])
{
for (int i = 0; i < BATCH_SIZE;i++)
{
for (int j = 0; j < FEATURE_SIZE; j++)
{
X[i*FEATURE_SIZE+j] = rand() % (FEATURE_SIZE);
}
LABEL[i] = rand() % (BATCH_SIZE);
}
}
void loss_golden( float X[BATCH_SIZE*FEATURE_SIZE],
float LABEL[BATCH_SIZE],
float Loss[BATCH_SIZE])
{
float X_buffer[BATCH_SIZE][FEATURE_SIZE];
float LABEL_norm[BATCH_SIZE];
float X_norm[BATCH_SIZE][FEATURE_SIZE];
float sum = 0;
float denominator = 0;
for (int i=0; i<BATCH_SIZE; i++)
{
for (int j=0; j<FEATURE_SIZE; j++)
{
X_buffer[i][j] = X[i*FEATURE_SIZE+j];
}
if(LABEL[i] > 0)
LABEL_norm[i] = 1;
else
LABEL_norm[i] = 0;
}
for (int i=0; i<BATCH_SIZE; i++)
{
sum = 0;
for (int j=0; j<FEATURE_SIZE; j++)
{
sum += X_buffer[i][j]*X_buffer[i][j];
}
denominator = sqrt(sum);
for (int k=0; k<FEATURE_SIZE; k++)
{
X_norm[i][k] = X_buffer[i][k]/denominator;
}
}
for (int i=0; i<BATCH_SIZE; i++)
{
sum = 0;
for(int j=0; j<FEATURE_SIZE; j++)
{
sum += theta[j]*X_norm[i][j];
}
Loss[i] = (sum-LABEL_norm[i])*(sum-LABEL_norm[i])/2;
}
}
static int result_check(float Loss_SW[BATCH_SIZE], float Loss_HW[BATCH_SIZE])
{
for (int i = 0; i < BATCH_SIZE; i++)
{
if ((Loss_SW[i]-Loss_HW[i])/Loss_HW[i]>0.01 || (Loss_SW[i]-Loss_HW[i])/Loss_HW[i]<-0.01)
{
std::cout << "Mismeatch: data index=" << i << " d=" << Loss_SW[i]
<< ", dout=" << Loss_HW[i] << std::endl;
return 1;
}
}
return 0;
}
int main()
{
#ifdef __SDSCC__
float *X, *LABEL, *Loss_SW, *Loss_HW;
X = (float *)sds_alloc(BATCH_SIZE * FEATURE_SIZE * sizeof(float));
LABEL = (float *)sds_alloc(BATCH_SIZE * sizeof(float));
Loss_SW = (float *)sds_alloc(BATCH_SIZE * sizeof(float));
Loss_HW = (float *)sds_alloc(BATCH_SIZE * sizeof(float));
if (!X || !LABEL || !Loss_SW || !Loss_HW) {
if (X) sds_free(X);
if (LABEL) sds_free(LABEL);
if (Loss_SW) sds_free(Loss_SW);
if (Loss_HW) sds_free(Loss_HW);
return 2;
}
#else
float X[BATCH_SIZE * FEATURE_SIZE];
float LABEL[BATCH_SIZE];
float Loss_SW[BATCH_SIZE];
float Loss_HW[BATCH_SIZE];
#endif
init_arrays(X, LABEL);
loss_golden(X, LABEL, Loss_SW);
printf("\n\n\n\n\n\n\n");
loss_HW(X, LABEL, Loss_HW);
int test_failed = result_check(Loss_SW, Loss_HW);
std::cout << "TEST " << (test_failed ? "FAILED" : "PASSED") << std::endl;
#ifdef __SDSCC__
sds_free(X);
sds_free(LABEL);
sds_free(Loss_SW);
sds_free(Loss_HW);
#endif
return (test_failed ? -1 : 0);
}
|
#ifndef _BresserReceiver_h
#define _BresserReceiver_h
// enable DEBUG with:
//#define BresserReceiver_DEBUG_TIMINGS true
#include "Arduino.h"
#define BresserReceiver_PREAMBLE 3850 // (us) preamble is low
#define BresserReceiver_HIGH_PULSE 550
#define BresserReceiver_SHORT_LOW_PULSE 900
#define BresserReceiver_LONG_LOW_PULSE 1900
#define BresserReceiver_TOLERANCE 100
#define BresserReceiver_MAX_PULSES 80
#define BresserReceiver_NUM_BITS 36
#define BresserReceiver_NUM_BYTES 5
class BresserReceiver {
public:
BresserReceiver();
void handleInterrupt();
void handlePulse(word pulse);
bool takePacket(byte* out);
bool samePacket(byte* packet1, byte* packet2);
int deviceId(const byte* data);
byte channel(const byte* data);
float temperature(const byte* data);
byte humidity(const byte* data);
byte battery(const byte* data);
private:
enum { UNKNOWN, OK, T0, DONE };
byte receivedBits, state, data[BresserReceiver_NUM_BYTES];
bool packetReceived;
byte lastReceivedPacket[BresserReceiver_NUM_BYTES];
bool nextPulse(word width);
virtual void gotBit(byte bt);
void reset();
void done();
static inline unsigned int widthMatches(word width, word expectedWidth);
#ifdef BresserReceiver_DEBUG_TIMINGS
byte idx;
int timings[BresserReceiver_MAX_PULSES];
virtual void dumpTimings();
#endif
};
#endif
|
#pragma once
class MonAIPresetIcon :public GameObject
{
public:
void OnDestroy() override;
//デストラクタ
~MonAIPresetIcon();
//Start
bool Start();
//初期化関数
//args:
// monID: モンスターのID
// pyInd: pythonの番号
void init(int monID,const wchar_t* pypath,CVector3 pos);
void Setpos(CVector3 pos);
void Setrot(float rot,CVector3 pos);
void UpdateAIMON(int monID, const wchar_t* pypath);
//Update
void Update();
private:
SpriteRender* m_Icon = nullptr; //きっとモンスターの画像
FontRender* m_font = nullptr; //pythonのを表示するための
SpriteRender* m_back = nullptr; //後ろのやつ
int m_monID = 0; //モンスターのID
int m_pyInd = 0; //pythonの番号
int m_pre = 0; //プリセットの番号
int m_num = 0; //何番目か。
CVector3 m_pos = CVector3::Zero(); //position
CVector3 m_fontoffs = {-80,-20,0};
};
|
#include "playToneGenerator.h"
using namespace qReal;
using namespace robots::generator;
void PlayToneGenerator::generateBodyWithoutNextElementCall()
{
mNxtGen->mGeneratedStrings.append(SmartLine(
"ecrobot_sound_tone(" + mNxtGen->mApi->stringProperty(mElementId, "Frequency") + ", "
+ mNxtGen->mApi->stringProperty(mElementId, "Duration") + ", 50);", //50 - volume of a sound
mElementId));
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace std;
typedef long long ll;
#define INF 10e17 // 4倍しても(4回足しても)long longを溢れない
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
#define sorti(x) sort(x.begin(), x.end())
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
#define debug(x) std::cerr << (x) << std::endl;
#define roll(x) for (auto itr : x) { debug(itr); }
int main() {
int n;
cin >> n;
vector<string> str;
string t;
ll ans = 0;
map<int, int> mp;
rep(i, n) {
cin >> t;
int s = t.size();
rep(j, s-1) {
if (t[j] == 'A' and t[j + 1] == 'B') ans += 1;
}
str.push_back(t);
if (t.front() == 'B' and t.back() == 'A') mp[0] += 1;
else if (t.front() == 'B') mp[1] += 1;
else if (t.back() == 'A') mp[2] += 1;
else mp[3] += 1;
}
if (mp[0] > 0) {
ans += mp[0] - 1;
}
if (mp[0] > 0 and (mp[1] > 0 or mp[2] > 0)) {
mp[2] += 1; // 先頭Bを1つ追加
mp[1] += 1; // 末尾Aを1つ追加
}
ans += min(mp[2], mp[1]);
cout << ans << endl;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.