blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7922504f2b32a7a3ed6697daadb12d4e7063609b
|
62f68894747c3653ebc349bf1fa97a28d41ea75f
|
/A-dragons/main.cpp
|
a7011ed51284e6cfbc01d495e762c67b347539a3
|
[] |
no_license
|
AryanRaj315/CompetitiveProgrammingSolutions
|
017329cd0cfe32b636b4ef95e2585863854308f5
|
641561db53ad54c326d813f53e54a914963793a5
|
refs/heads/master
| 2022-11-14T12:25:48.149561
| 2020-07-08T05:07:48
| 2020-07-08T05:07:48
| 232,072,674
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 985
|
cpp
|
main.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define loop(i, start, end) for(int i = start; i <= end; i++)
#define ll long long int
#define arrayInput(arr, n) loop(i, 0, n-1){ cin >> arr[i];}
#define arrayDisplay(arr, n) loop(i, 0, n-1){ cout << arr[i] << " ";}
#define GODSPEED ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define mem(a, num) memset(a, num, sizeof(a))
// #define ll long long
#define vi vector<Int>
#define pb push_back
#define mp make_pair
// For sorting
#define sortva(v) sort(v.begin(),v.end())
#define sortvd(v) sort(v.rbegin(),v.rend())
int main() {
GODSPEED
int s, n;
cin >> s >> n;
int x, y;
vector<pair<int, int>> drag;
loop(i, 0, n-1){
cin >> x >> y;
drag.pb(mp(x, y));
}
sortva(drag);
loop(i, 0, n-1){
if(s > drag[i].first){
s+= drag[i].second;
}
else{
cout << "NO" ;
return 0;
}
}
cout << "YES";
return 0;
}
|
34043d757995a53ee9fd9f9e1257f930ad7e80d0
|
401e2729d36c466f0306a60cebc310ab34321180
|
/tests/GraphGeneratorFile/GraphGeneratorFileTest.cpp
|
645d62537b5f3ad9a49675381dc51cd9238c1d5d
|
[] |
no_license
|
hlscalon/TrabalhoTeoriaGrafos
|
073f83cf80ca98279280dbf6c315449dcf70316c
|
2b19c08276198ee45ad4de823d7e490354117cb7
|
refs/heads/master
| 2021-06-09T03:49:52.219127
| 2016-12-11T22:16:39
| 2016-12-11T22:16:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 189
|
cpp
|
GraphGeneratorFileTest.cpp
|
#include <iostream>
#include "../../src/GraphGeneratorFile.hpp"
int main()
{
GraphGeneratorFile g1{"graph1.g"};
std::cout << "graph1\n";
g1.getGraph().printGraphMatrix();
return 0;
}
|
99a335196fd66fb6a183a4743adf6e9c79a9bfa7
|
3e24f87bb9ffc5c733b98858ae380c267869e7ce
|
/ios/PSPClientKit/bridge/generated-src/cpp/clientsdk/VideoFrameOrientation.hpp
|
60efc9b003e4ffb935f4634c528e2ae6d1fd3396
|
[] |
no_license
|
proximax-storage/sirius-stream-client-mobile-sdk
|
b051892d5e71f28f5d12248654b0ef77596c1a8d
|
7544449c5d09e003034a80dc76282743e12a787c
|
refs/heads/master
| 2022-04-08T23:37:02.937024
| 2020-03-03T14:57:05
| 2020-03-03T14:57:05
| 195,406,885
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 525
|
hpp
|
VideoFrameOrientation.hpp
|
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from VideoStreamer.djinni
#pragma once
#include <functional>
namespace clientsdk {
enum class VideoFrameOrientation : int {
ROTATE0,
ROTATE90,
ROTATE180,
ROTATE270,
};
} // namespace clientsdk
namespace std {
template <>
struct hash<::clientsdk::VideoFrameOrientation> {
size_t operator()(::clientsdk::VideoFrameOrientation type) const {
return std::hash<int>()(static_cast<int>(type));
}
};
} // namespace std
|
bb9b0ed551830ee0028d4ccbd7589e6fc275d4b3
|
d0f57a1f699f5dea4a8c8aa4fd9b67a6b9141cfc
|
/Competitions/DeterminationOfSeries/DeterminationOfSeries/main.cpp
|
d05ad792a901223098e451651576749c643b293e
|
[] |
no_license
|
kawer/Competitive_Programming
|
315ebe86a078f99caba64ada5ffc6f5b35d54c30
|
d0441532c28ba399a7fa66c545c6df397b7abea0
|
refs/heads/master
| 2021-01-12T12:27:15.019533
| 2016-11-02T20:48:51
| 2016-11-02T20:48:51
| 72,497,551
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 775
|
cpp
|
main.cpp
|
////
//// main.cpp
//// Determinf0tionOfSeries
////
//// Created by Lazaro Kawer on 10/24/16.
//// Copyright © 2016 Kawer. All rights reserved.
////
//
#include <iostream>
#include <math.h>
using namespace std;
int main(int argc, const char * argv[]) {
int f0, f1, f2;
while(cin >> f0 >> f1 >> f2) {
int dif01 = f1 - f0;
int dif12 = f2 - f1;
int difFinal = dif12 - dif01;
if (difFinal) {
int d = f2;
for(int i = 0; i < 3; i++) {
dif12 += difFinal;
d += dif12;
cout << d << " \n"[i==2];
}
}
else {
cout << f2 + dif01 << " " << f2 + 2 * dif01 << " " << f2 + 3 * dif01 << endl;
}
}
return 0;
}
|
72d121758f208d8dfd0e2ea38b1a29ac72bb64f8
|
f43f7b91b4f782e463349f61f8fe63fafef94a88
|
/src/keva_lite.hpp
|
2693876f125c5da52f080a8efb6a2171d94fed6b
|
[] |
no_license
|
lawben/keva-lite
|
22ae66350c073317b8b1aac391bf92c5183841e4
|
9f1d1551a32b4640ac16dfc3bfe113846e92127d
|
refs/heads/master
| 2021-09-10T14:41:24.587953
| 2018-03-27T23:45:01
| 2018-03-27T23:45:01
| 118,145,239
| 4
| 0
| null | 2018-03-27T23:45:02
| 2018-01-19T15:53:05
|
C++
|
UTF-8
|
C++
| false
| false
| 1,384
|
hpp
|
keva_lite.hpp
|
#pragma once
#include <sstream>
#include <string>
#include "db_manager.hpp"
#include "utils.hpp"
namespace keva {
template <typename K, typename V>
class KevaLite : public Noncopyable {
public:
KevaLite();
explicit KevaLite(std::string db_file_name);
V get(const K& key);
void put(const K& key, const V& value);
void remove(const K& key);
protected:
DBManager _db_manager;
};
template <typename K, typename V>
KevaLite<K, V>::KevaLite() : _db_manager(get_type_size<V>()) {}
template <typename K, typename V>
KevaLite<K, V>::KevaLite(std::string db_file_name) : _db_manager(std::move(db_file_name), get_type_size<V>()) {}
template <typename K, typename V>
V KevaLite<K, V>::get(const K& key) {
const auto file_key = convert_to_file_key(key);
auto result = _db_manager.get(file_key);
if (result.empty()) {
std::stringstream msg;
msg << "Key '" << key << "' not found.";
throw std::runtime_error(msg.str());
}
return convert_from_file_value<V>(result);
}
template <typename K, typename V>
void KevaLite<K, V>::put(const K& key, const V& value) {
const auto file_key = convert_to_file_key(key);
_db_manager.put(file_key, convert_to_file_value(value));
}
template <typename K, typename V>
void KevaLite<K, V>::remove(const K& key) {
const auto file_key = convert_to_file_key(key);
_db_manager.remove(file_key);
}
} // namespace keva
|
37e810286338ea596d1a35c2f5a09a81b9987ee4
|
63a9fdb34e9aa87102c9ffef4fcf2f8925d17656
|
/ResponsiveGrassDemo/src/BoundingBox.h
|
bea856b76130b9961212706490bc6f8245aebbd0
|
[
"BSD-3-Clause"
] |
permissive
|
klejah/ResponsiveGrassDemo
|
3ab3fd31a67df5e6afca46377e6535585dcaecaa
|
6ce514717467acc80fd965a6f7695d5151ba8c03
|
refs/heads/master
| 2021-01-12T08:46:39.984454
| 2017-02-22T02:21:21
| 2017-02-22T02:21:21
| 76,689,713
| 12
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,366
|
h
|
BoundingBox.h
|
/**
* (c) Klemens Jahrmann
* klemens.jahrmann@net1220.at
*/
#ifndef BOUNDINGBOX_H
#define BOUNDINGBOX_H
#include "Common.h"
#include "BoundingObject.h"
#include "Plane.h"
#include "Camera.h"
class BoundingBox : public BoundingObject
{
public:
BoundingBox();
BoundingBox(float xMin, float xMax, float yMin, float yMax, float zMin, float zMax);
~BoundingBox();
float isVisibleF(const Camera& camera);
float isVisibleF2(const Camera& camera, const glm::mat4& transform);
virtual bool isVisible(const Camera& camera, const glm::mat4& transform);
virtual void inflate(const glm::vec3& value);
virtual void scale(const glm::vec3& factor);
glm::vec3 getNearestVertex(const Plane& p) const;
class TransformedBox
{
public:
TransformedBox();
TransformedBox(const glm::vec4& location, const glm::vec4& axis1, const glm::vec4& axis2, const glm::vec4& axis3);
TransformedBox(const TransformedBox& box);
virtual bool isVisible(const Camera& camera);
float isVisibleF2(const Camera& camera);
public:
glm::vec3 location, axis1, axis2, axis3;
glm::vec3 normalizedAxis1, normalizedAxis2, normalizedAxis3;
};
TransformedBox& transform(const glm::mat4& transform);
float xMin, xMax, yMin, yMax, zMin, zMax;
public:
glm::vec4 location;
glm::vec3 size;
unsigned short lastFail;
TransformedBox transformed;
glm::mat4 lastTransform;
};
#endif
|
4b6853bfcdbf70a4cf59ca2e34a4e9e3e6d0a663
|
6815633d4f1d06c8753da6aba85abbdf6a7b0aad
|
/Memo/Ini.cpp
|
ecff7aa99718e550728f0d961c659d0901860aff
|
[] |
no_license
|
XiaofengCode/Memo
|
73f591076b0972098209d716cc4ecb16a6975886
|
9684533f3fa9c1b6f66bc78067aa703203231cab
|
refs/heads/master
| 2022-11-19T12:55:28.838204
| 2020-07-14T04:55:21
| 2020-07-14T04:55:21
| 279,485,597
| 1
| 1
| null | null | null | null |
ISO-8859-15
|
C++
| false
| false
| 3,436
|
cpp
|
Ini.cpp
|
// Ini.cpp: implementation of the CIni class.
// Author: Bjarke Viksøe
//
// Description:
// Thin wrapper around the Win32 Windows Profile (Ini-file configuration)
// interface.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Ini.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CIni::CIni()
{
}
CIni::CIni(LPCTSTR IniFilename)
{
OpenIniFile(IniFilename);
}
CIni::~CIni()
{
Clear();
}
void CIni::Clear()
{
POSITION pos = m_mapSectionToKeyValue.GetStartPosition();
CString strKey;
CMapStringToString* pValue;
while (pos)
{
m_mapSectionToKeyValue.GetNextAssoc(pos, strKey, (PVOID&)pValue);
delete pValue;
}
m_mapSectionToKeyValue.RemoveAll();
}
BOOL CIni::OpenIniFile( LPCTSTR lpFileName )
{
Clear();
BOOL bRet = TRUE;
// CStdioFile file;
// if (!file.Open(lpFileName, CStdioFile::modeRead, NULL, NULL))
// return FALSE;
FILE* fp = _tfopen(lpFileName, _T("rt"));
if (!fp)
{
return FALSE;
}
char szLine[MAX_PATH * 2];
CString strLine;
CMapStringToString* pMapKey2Value = NULL;
while (!feof(fp))
{
strLine = fgets(szLine, sizeof(szLine), fp);
//strLine = (char*)strLine.GetBuffer(0);
int nComment = strLine.Find(';');
if (nComment >= 0)
{
strLine.Delete(nComment, strLine.GetLength() - nComment);
}
strLine.TrimLeft();
strLine.TrimRight();
if (strLine.GetLength() == 0)
{
continue;
}
if (strLine[0] == '[' && strLine[strLine.GetLength() - 1] == ']')
{
strLine.Delete(0);
strLine.Delete(strLine.GetLength() - 1);
pMapKey2Value = new CMapStringToString();
m_mapSectionToKeyValue[strLine] = pMapKey2Value;
continue;
}
if (!pMapKey2Value)
{
bRet = FALSE;
goto _exit;
}
int nPos = strLine.Find('=');
if (nPos <= 0)
{
bRet = FALSE;
goto _exit;
}
(*pMapKey2Value)[strLine.Left(nPos).TrimRight().MakeLower()] = strLine.Right(strLine.GetLength() - nPos - 1).TrimLeft();
}
_exit:
//file.Close();
fclose(fp);
m_strFileName = lpFileName;
return bRet;
}
CMapStringToString& CIni::operator[]( LPCTSTR lpszSection )
{
CMapStringToString* pMap = (CMapStringToString*)m_mapSectionToKeyValue[lpszSection];
if (!pMap)
{
POSITION pos = GetSectionStartPosition();
CString strSection;
while (pos)
{
GetNextSection(pos, strSection);
if (strSection.CompareNoCase(lpszSection) == 0)
{
pMap = (CMapStringToString*)m_mapSectionToKeyValue[strSection];
if (pMap)
{
return *pMap;
}
}
}
return m_mapEmpty;
}
return *pMap;
}
POSITION CIni::GetSectionStartPosition()
{
return m_mapSectionToKeyValue.GetStartPosition();
}
void CIni::GetNextSection( POSITION& pos, CString& strSection )
{
PVOID pValue;
m_mapSectionToKeyValue.GetNextAssoc(pos, strSection, pValue);
}
BOOL CIni::Write( LPCTSTR lpszSection, LPCTSTR lpszKey, LPCTSTR lpszValue, LPCTSTR lpszFile )
{
return WritePrivateProfileString(lpszSection, lpszKey, lpszValue, lpszFile);
}
BOOL CIni::Write(LPCTSTR lpszSection, LPCTSTR lpszKey, LPCTSTR lpszValue)
{
CMapStringToString* pMap = (CMapStringToString*)m_mapSectionToKeyValue[lpszSection];
if (!pMap)
{
(*pMap)[lpszKey] = lpszValue;
}
return Write(lpszSection, lpszKey, lpszValue, m_strFileName);
}
|
b39f0827a581b2d0c5150204a2ea8030914d6e1a
|
fe33e825f4bc31370e50cebcd322b5671eb5c113
|
/src/Selections/QCDConversionsAsymJetsSelection.cpp
|
bc2757e64920cd74ed593d2c7e898e74bb22d097
|
[
"Apache-2.0"
] |
permissive
|
jjacob/AnalysisSoftware
|
8acbfbc00639da2829b38977fea87bf176d046bc
|
670513bcde9c3df46077f906246e912627ee251a
|
refs/heads/master
| 2020-02-26T17:10:09.327556
| 2015-05-05T10:46:40
| 2015-05-05T10:47:17
| 7,603,134
| 0
| 0
| null | 2013-05-03T22:02:57
| 2013-01-14T11:30:13
|
C++
|
UTF-8
|
C++
| false
| false
| 674
|
cpp
|
QCDConversionsAsymJetsSelection.cpp
|
/*
* QCDEPlusJetsPlusMETConversionSelection.cpp
*
* Created on: 17 Apr 2012
* Author: kreczko
*/
#include "../../interface/Selections/QCDConversionsAsymJetsSelection.h"
namespace BAT {
QCDConversionsAsymJetsSelection::QCDConversionsAsymJetsSelection(unsigned int numberOfSelectionSteps) :
QCDConversionsSelection(numberOfSelectionSteps), //
TopPairEplusJetsRefAsymJetsSelection(numberOfSelectionSteps) {
}
QCDConversionsAsymJetsSelection::~QCDConversionsAsymJetsSelection() {
}
bool QCDConversionsAsymJetsSelection::passesConversionVeto(const EventPtr event) const{
return QCDConversionsSelection::passesConversionVeto(event);
}
} /* namespace BAT */
|
a06d25fb4ba81acd377639fe43ceb5e05d1bd6fa
|
e0bf5836e4f0d75b28b1f787446e655cdeeb8b03
|
/files/chapd.cpp
|
709d64142c744d67fa5dc8135b260d8b4f37651b
|
[] |
no_license
|
arunnsit/allcodes
|
3f0b73facdee06e802455c6c3fb5de7baae702c2
|
5e6a8bf3883d0c5f67dfa7cc3dc026dbb4c63a71
|
refs/heads/master
| 2021-01-10T13:58:24.900593
| 2017-10-03T18:11:34
| 2017-10-03T18:11:34
| 50,598,937
| 0
| 2
| null | 2019-09-30T20:16:32
| 2016-01-28T17:06:03
|
C++
|
UTF-8
|
C++
| false
| false
| 440
|
cpp
|
chapd.cpp
|
#include<stdio.h>
long long int gcd(long long int a,long long int b){
if(b==0)return a;
else return gcd(b,a%b);
}
int main(){
int t;
scanf("%d",&t);
while(t--){
long long int a,b,x;
scanf("%lld %lld",&a,&b);
while(b!=1){
x=gcd(a,b);
if(x==1)break;
else b=b/x;
}
if(b==1)printf("Yes\n");
else printf("No\n");
}
}
|
34b9112884aa1c17294f844fe7c7dc643e3c4c98
|
cdac9db245781ea60b9c5b56e1ae03ab7422613d
|
/q3_inheritance/couples.cpp
|
cbe76c99844e2a75dbea45501e7763b3723f08fb
|
[] |
no_license
|
PPL-IIITA/ppl-assignment-bd96
|
308035efa0a1ca57ce0e2b6fcd71d7d5241da221
|
6b50abb93b4ac2bf6dd9f1a8bc1a642be279732d
|
refs/heads/master
| 2021-01-21T06:24:22.449380
| 2017-04-09T22:53:38
| 2017-04-09T22:53:38
| 83,225,560
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,294
|
cpp
|
couples.cpp
|
#include <bits/stdc++.h>
#include "couples.hpp"
using namespace std;
void couples:: formcouples(couples c[], boy B[], girl G[], int number_of_boys, int number_of_girls, int *count)
{
int i,j;
int max,f;
for ( i = 1; i <= number_of_girls; i++ ) {
//cout << "Girl " << i <<" is " << G[i].committed << endl;
if (G[i].committed == false ) {
max = 0,f=0;
int parameter = G[i].criteria;
//cout << i << " " << parameter << endl;
if ( parameter == 1 ) {
for ( j = 1; j <= number_of_boys; j++ ) {
if ( !B[j].committed && B[j].budget >= G[i].maintenance && B[j].min_attract <= G[i].attract ) {
if ( B[max].attract < B[j].attract ) {
max = j;
f = 1;
}
}
}
if(f) {
//cout << i << " done" << endl;
B[max].committed = true;
G[i].committed = true;
c[(*count)++].add(B[max],G[i]);
}
} else if ( parameter == 2 ) {
for ( j = 1; j <= number_of_boys; j++ ) {
if ( !B[j].committed && B[j].budget >= G[i].maintenance && B[j].min_attract <= G[i].attract ) {
if ( B[max].budget < B[j].budget ) {
max = j;
f = 1;
}
}
}
if(f) {
//cout << i << " done" << endl;
B[max].committed = true;
G[i].committed = true;
c[(*count)++].add(B[max],G[i]);
}
} else if ( parameter == 3 ) {
for ( j = 1; j <= number_of_boys; j++ ) {
if ( !B[j].committed && B[j].budget >= G[i].maintenance && B[j].min_attract <= G[i].attract ) {
if ( B[max].intelligence < B[j].intelligence ) {
max = j;
f = 1;
}
}
}
if(f) {
//cout << i << " done" << endl;
B[max].committed = true;
G[i].committed = true;
c[(*count)++].add(B[max],G[i]);
}
}
}
}
}
void couples:: add(boy b, girl g)
{
B = b;
G = g;
}
void couples:: breakup(couples c[],boy B[], girl G[], int number_of_boys, int number_of_girls, couples newCouples[], boy breakup_boy[], girl breakup_girl[], int count_breakup, int countc)
{
//cout << "itne couples h " << countc << endl;
int i,j;
int flag[countc],flag_boy[10005];
for( i = 0; i < countc; i++ ) {
flag[i] = 0;
}
for( i = 0; i < 10005; i++ ) {
flag_boy[i] = 0;
}
// for( i = 0; i < count_breakup; i++ ) {
// cout << "ladka " << breakup_boy[i].name << " ladki " << breakup_girl[i].name << endl;
// }
for( i = 0; i < count_breakup; i++) {
flag_boy[breakup_boy[i].name] = breakup_girl[i].name;
for( j = 0; j < countc; j++) {
if ( c[j].B.name == breakup_boy[i].name ) {
//cout << "couple ka naam " << c[j].B.name << " breakp wala naam " << breakup_boy[i].name << endl;
flag[j] = 1 ;
//cout << "Flag of " << j << " ki value " << flag[j] << endl;
break;
}
}
}
//cout << "Loop ke andar jaate huye " << endl;
int k=0;
for( i = 0; i < countc; i++ ) {
//cout << "Flag of " << i << " ki value " << flag[i] << endl;
if ( flag[i] == 0 ) {
newCouples[k++] = c[i];
}
}
//cout << "before k " << k << endl;
couples caller;
for( i = 0; i < count_breakup; i++ ) {
for( j = 0; j < number_of_girls; j+=1) {
if ( breakup_girl[i].name == G[j].name ) {
G[j].committed = false;
break;
}
}
for( j = 0; j < number_of_boys; j+=1) {
if ( breakup_boy[i].name == B[j].name ) {
B[j].committed = false;
break;
}
}
}
// for( i = 0; i < number_of_boys; i++ ) {
// cout << "I " << i << " status " << B[i].committed << endl;
// }
caller.formnewcouples(newCouples,B,G,number_of_boys,number_of_girls,&k,flag_boy);
//cout << "k " << k << endl;
caller.printcouples(newCouples,k);
}
void couples:: printcouples( couples C[], int count)
{
freopen("couples_afterbreakup.txt","w+",stdout);
for( int i = 0; i < count; i++ ) {
cout << "Boy " << C[i].B.name << " and girl " << C[i].G.name << endl;
}
}
void couples:: formnewcouples(couples c[], boy B[], girl G[], int number_of_boys, int number_of_girls, int *count, int flag[])
{
int i,j;
int max,f;
for ( i = 1; i <= number_of_girls; i++ ) {
//cout << "Girl " << i <<" is " << G[i].committed << endl;
if (G[i].committed == false ) {
max = 0,f=0;
int parameter = G[i].criteria;
//cout << i << " " << parameter << endl;
if ( parameter == 1 ) {
for ( j = 1; j <= number_of_boys; j++ ) {
if ( !B[j].committed && B[j].budget >= G[i].maintenance && B[j].min_attract <= G[i].attract && flag[B[j].name] != G[i].name) {
if ( B[max].attract < B[j].attract ) {
max = j;
f = 1;
}
}
}
} else if ( parameter == 2 ) {
for ( j = 1; j <= number_of_boys; j++ ) {
if ( !B[j].committed && B[j].budget >= G[i].maintenance && B[j].min_attract <= G[i].attract && flag[B[j].name] != G[i].name ) {
if ( B[max].budget < B[j].budget ) {
max = j;
f = 1;
}
}
}
} else if ( parameter == 3 ) {
for ( j = 1; j <= number_of_boys; j++ ) {
if ( !B[j].committed && B[j].budget >= G[i].maintenance && B[j].min_attract <= G[i].attract && flag[B[j].name] != G[i].name ) {
if ( B[max].intelligence < B[j].intelligence ) {
max = j;
f = 1;
}
}
}
}
if(f) {
//cout << i << " done" << endl;
B[max].committed = true;
G[i].committed = true;
c[(*count)++].add(B[max],G[i]);
}
}
}
}
void couples:: form2(couples c[], boy B[], girl G[], int number_of_boys, int number_of_girls, int *count)
{
int i,j;
int max,f;
int k;
int gc=0,bc=0;
for ( i = 1; i <= number_of_girls + number_of_boys; i++ ) {
if ( i%2 == 0 && gc < number_of_girls ) {
//cout << "Inside Girl loop " << i << endl;
//cout << "Girl " << i <<" is " << G[i].committed << endl;
if (G[gc].committed == false ) {
max = 0,f=0;
int parameter = G[gc].criteria;
//cout << i << " " << parameter << endl;
if ( parameter == 1 ) {
for ( j = 1; j <= number_of_boys; j++ ) {
if ( !B[j].committed && B[j].budget >= G[gc].maintenance && B[j].min_attract <= G[gc].attract ) {
if ( B[max].attract < B[j].attract ) {
max = j;
f = 1;
}
}
}
} else if ( parameter == 2 ) {
for ( j = 1; j <= number_of_boys; j++ ) {
if ( !B[j].committed && B[j].budget >= G[gc].maintenance && B[j].min_attract <= G[gc].attract ) {
if ( B[max].budget < B[j].budget ) {
max = j;
f = 1;
}
}
}
} else if ( parameter == 3 ) {
for ( j = 1; j <= number_of_boys; j++ ) {
if ( !B[j].committed && B[j].budget >= G[gc].maintenance && B[j].min_attract <= G[gc].attract ) {
if ( B[max].intelligence < B[j].intelligence ) {
max = j;
f = 1;
}
}
}
}
if(f) {
//cout << i << " done" << endl;
B[max].committed = true;
G[gc].committed = true;
c[(*count)++].add(B[max],G[gc]);
}
gc++;
}
} else if (i%2 == 1 && bc < number_of_boys ){
//cout << "Inside Boy loop " << i << endl;
max = -1;
int index;
for( j = 0; j < number_of_girls; j++) {
if ( G[j].attract > max ) {
max = G[i].attract;
index = j;
}
}
if ( max > 0 ) {
B[bc].committed = true;
G[index].committed = true;
c[(*count)++].add(B[bc],G[max]);
}
bc++;
}
}
}
|
8bf50355bfb2373a358188c19bda3ebef3892ba4
|
183ef6fe7cf0cd78e823d9d63ff97882e83e272f
|
/hevent.h
|
4b8746e4cd7f04ca691aa4efc66b74a383590054
|
[] |
no_license
|
israel-fl/SimpleWeddingPlanner
|
155da4726a6df8156b7ba615726c2cd9326e9aa8
|
2bcf9116632028d0ca01c220cbb4ab519daa0035
|
refs/heads/master
| 2020-04-11T11:45:47.531890
| 2015-10-19T08:51:52
| 2015-10-19T08:51:52
| 44,522,487
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 871
|
h
|
hevent.h
|
#pragma once
#include <string>
#include <ostream>
#include "dateconv.h"
class HEvent
{
public:
// Parametrized Constructor
HEvent(unsigned long long& time, std::string& name,
std::string& type);
unsigned long long epochTime;
std::string holidayName;
std::string holidayType;
unsigned int year;
unsigned int month;
unsigned int day;
// Friend functions
// Overload << operator to display a HEvent object
friend std::ostream& operator<<(std::ostream& os, HEvent& obj);
// Overload a == operator to compare two HEvents for equality based on
// epoch seconds
friend bool operator==(HEvent first, HEvent second);
// Overload a > and a < operator to compare two HEvents for inequality based on
// epochh seconds
friend bool operator>(HEvent first, HEvent second);
friend bool operator<(HEvent first, HEvent second);
// Destructor
~HEvent();
};
|
be1a9638d825d4373bb8d94f402ef4945a8939d6
|
417bfea5338c7bf9f36ddac28767cdfdc02a1ed3
|
/swarmros/src/swarmros/bridge/TelemetryForwarder.cpp
|
ee59edbe0d293eeef89ff59b0b5974c0941ee062
|
[
"Apache-2.0"
] |
permissive
|
cpswarm/swarmio
|
02f9d5e174b8c1ff22984d9538fe8fa314564cb9
|
798ae469ec48b958f9e88cf89e4f88b3f5b519fe
|
refs/heads/master
| 2022-05-09T23:58:44.159895
| 2022-04-21T09:23:32
| 2022-04-21T09:23:32
| 173,924,826
| 7
| 1
|
Apache-2.0
| 2019-11-07T11:58:34
| 2019-03-05T10:23:27
|
C++
|
UTF-8
|
C++
| false
| false
| 1,700
|
cpp
|
TelemetryForwarder.cpp
|
#include <swarmros/bridge/TelemetryForwarder.h>
#include <swarmros/bridge/MessageMismatchException.h>
#include <swarmros/introspection/VariantMessage.h>
using namespace swarmros;
using namespace swarmros::bridge;
void TelemetryForwarder::UpdateReceived(const introspection::VariantMessage::ConstPtr& message)
{
if (message->GetType() == _message)
{
_telemetryService.SetValue(_name, message->GetValue());
}
else
{
throw MessageMismatchException("Invalid message type received from topic", _subscriber.getTopic(), _message, message->GetType());
}
}
TelemetryForwarder::TelemetryForwarder(ros::NodeHandle& nodeHandle, const std::string& source, const std::string& message, swarmio::services::telemetry::Service& telemetryService, const std::string& name, bool includeInStatus)
: _telemetryService(telemetryService), _name(name)
{
// Register schema
const auto& serializer = introspection::MessageSerializer::MessageSerializerForType(message, "swarmros");
swarmio::data::discovery::Field fieldDescriptor;
*fieldDescriptor.mutable_schema() = serializer.GetSchemaDescriptor(serializer.HasHeader() ? 1 : 0);
_telemetryService.SetFieldDefinitionForKey(name, fieldDescriptor, includeInStatus);
// Save message type
_message = serializer.GetFullName();
// Subscribe
_subscriber = nodeHandle.subscribe<introspection::VariantMessage>(source, 1, &TelemetryForwarder::UpdateReceived, this);
}
TelemetryForwarder::~TelemetryForwarder()
{
// Stop subscription
_subscriber.shutdown();
// Remove definition and value
_telemetryService.RemoveFieldDefinitionForKey(_name);
_telemetryService.RemoveValue(_name);
}
|
8bbf4210be70c9603ce6d018049d9fa00e8f298d
|
afb7006e47e70c1deb2ddb205f06eaf67de3df72
|
/third_party/wasm2c/src/sha256.cc
|
6ecdb2df1f5a717eb81f924a741dd9881fb62631
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
marco-c/gecko-dev-wordified
|
a66383f85db33911b6312dd094c36f88c55d2e2c
|
3509ec45ecc9e536d04a3f6a43a82ec09c08dff6
|
refs/heads/master
| 2023-08-10T16:37:56.660204
| 2023-08-01T00:39:54
| 2023-08-01T00:39:54
| 211,297,590
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,425
|
cc
|
sha256.cc
|
/
*
*
Copyright
2017
WebAssembly
Community
Group
participants
*
*
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
"
wabt
/
sha256
.
h
"
#
if
HAVE_OPENSSL_SHA_H
#
include
<
openssl
/
sha
.
h
>
#
else
#
include
"
picosha2
.
h
"
#
endif
namespace
wabt
{
/
*
*
*
SHA
-
256
the
"
input
"
sv
into
the
output
"
digest
"
.
*
*
Uses
OpenSSL
'
s
libcrypto
or
vendored
PicoSHA2
.
*
/
void
sha256
(
std
:
:
string_view
input
std
:
:
string
&
digest
)
{
digest
.
clear
(
)
;
#
if
HAVE_OPENSSL_SHA_H
digest
.
resize
(
SHA256_DIGEST_LENGTH
)
;
if
(
!
SHA256
(
reinterpret_cast
<
const
uint8_t
*
>
(
input
.
data
(
)
)
input
.
size
(
)
reinterpret_cast
<
uint8_t
*
>
(
digest
.
data
(
)
)
)
)
{
/
/
should
not
be
possible
to
fail
here
but
check
(
and
abort
)
just
in
case
abort
(
)
;
}
#
else
digest
.
resize
(
picosha2
:
:
k_digest_size
)
;
picosha2
:
:
hash256
(
input
digest
)
;
#
endif
}
}
/
/
namespace
wabt
|
0e476a2e95b04b10795496ba757dcafa094cd804
|
608174cf3981edd40d34ff7a2cee5b4f0d35bd59
|
/ScoreSegmentTable.cc
|
de883a7f1901b4f0b5629fac70c509552b1498b0
|
[] |
no_license
|
nachiket/ScoreRuntime
|
896e8797a349fb1110d9036e977a228b95fa2813
|
d8ed281a5baf19052161ae9fa1d1ac02754a7a1b
|
refs/heads/master
| 2016-09-01T21:14:01.047675
| 2013-05-09T05:15:15
| 2013-05-09T05:15:15
| 317,934
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 21,904
|
cc
|
ScoreSegmentTable.cc
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 1999 The Regents of the University of California
// Permission to use, copy, modify, and distribute this software and
// its documentation for any purpose, without fee, and without a
// written agreement is hereby granted, provided that the above copyright
// notice and this paragraph and the following two paragraphs appear in
// all copies.
//
// IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
// DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
// LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
// EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
//
// THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON
// AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO
// PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
//
//////////////////////////////////////////////////////////////////////////////
//
// BRASS source file
//
// SCORE runtime support
// $Revision: 1.20 $
//
//////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include "ScoreCustomLinkedList.h"
#include "ScoreSegmentTable.h"
#include "ScoreConfig.h"
using std::cout;
using std::endl;
using std::cerr;
///////////////////////////////////////////////////////////////////////////////
// ScoreSegmentBlock::ScoreSegmentBlock:
// Constructor for ScoreSegmentBlock.
// Initializes all internal structures.
//
// Parameters: None.
//
// Return value: None.
///////////////////////////////////////////////////////////////////////////////
ScoreSegmentBlock::ScoreSegmentBlock() {
type = 0;
start = 0;
size = 0;
owner = NULL;
parentTable = NULL;
parentBlockIndex = 0;
childBlockStartIndex = 0;
childBlockSize = 0;
childBlocksInUse = 0;
freeListItem = SCORECUSTOMLINKEDLIST_NULL;
unavailableListItem = SCORECUSTOMLINKEDLIST_NULL;
usedListItem = SCORECUSTOMLINKEDLIST_NULL;
cachedListItem = SCORECUSTOMLINKEDLIST_NULL;
}
///////////////////////////////////////////////////////////////////////////////
// ScoreSegmentBlock::~ScoreSegmentBlock:
// Destructor for ScoreSegmentBlock.
// Cleans up all internal structures.
//
// Parameters: None.
//
// Return value: None.
///////////////////////////////////////////////////////////////////////////////
ScoreSegmentBlock::~ScoreSegmentBlock() {
// do nothing!
}
///////////////////////////////////////////////////////////////////////////////
// ScoreSegmentLoadDumpBlock::ScoreSegmentLoadDumpBlock:
// Constructor for ScoreSegmentLoadDumpBlock.
// Initializes all internal structures.
//
// Parameters: None.
//
// Return value: None.
///////////////////////////////////////////////////////////////////////////////
ScoreSegmentLoadDumpBlock::ScoreSegmentLoadDumpBlock() {
owner = NULL;
blockStart = 0;
buffer = NULL;
bufferSize = 0;
bufferSizeDependsOnOwnerAddrs = 0;
}
///////////////////////////////////////////////////////////////////////////////
// ScoreSegmentLoadDumpBlock::~ScoreSegmentLoadDumpBlock:
// Destructor for ScoreSegmentLoadDumpBlock.
// Cleans up all internal structures.
//
// Parameters: None.
//
// Return value: None.
///////////////////////////////////////////////////////////////////////////////
ScoreSegmentLoadDumpBlock::~ScoreSegmentLoadDumpBlock() {
// do nothing!
}
///////////////////////////////////////////////////////////////////////////////
// ScoreSegmentTable::ScoreSegmentTable:
// Constructor for ScoreSegmentTable.
// Initializes all internal structures.
//
// Parameters:
// newLoc: memory segment physical location.
// newCMBSize: CMB physical size.
//
// Return value: None.
///////////////////////////////////////////////////////////////////////////////
ScoreSegmentTable::ScoreSegmentTable(unsigned int newLoc,
unsigned int newCMBSize) {
unsigned int i;
loc = newLoc;
cmbSize = newCMBSize;
{
unsigned int numLevel0InCMB =
cmbSize / SCORE_SEGMENTTABLE_LEVEL0SIZE;
unsigned int sizeLevel0CruftInCMB =
cmbSize % SCORE_SEGMENTTABLE_LEVEL0SIZE;
unsigned int numLevel1InLevel0 =
SCORE_SEGMENTTABLE_LEVEL0SIZE / SCORE_SEGMENTTABLE_LEVEL1SIZE;
unsigned int sizeLevel1CruftInLevel0 =
SCORE_SEGMENTTABLE_LEVEL0SIZE % SCORE_SEGMENTTABLE_LEVEL1SIZE;
unsigned int numLevel1InLevel0CruftInCMB =
sizeLevel0CruftInCMB / SCORE_SEGMENTTABLE_LEVEL1SIZE;
unsigned int sizeLevel1CruftInLevel0CruftInCMB =
sizeLevel0CruftInCMB % SCORE_SEGMENTTABLE_LEVEL1SIZE;
unsigned int actualNumLevel0InCMB;
unsigned int actualNumLevel1InLevel0;
unsigned int totalLevel0;
unsigned int totalLevel1;
if (sizeLevel0CruftInCMB == 0) {
actualNumLevel0InCMB = numLevel0InCMB;
} else {
actualNumLevel0InCMB = numLevel0InCMB + 1;
}
if (sizeLevel1CruftInLevel0 == 0) {
actualNumLevel1InLevel0 = numLevel1InLevel0;
} else {
actualNumLevel1InLevel0 = numLevel1InLevel0 + 1;
}
totalLevel0 = actualNumLevel0InCMB;
if (sizeLevel1CruftInLevel0CruftInCMB == 0) {
totalLevel1 = (actualNumLevel1InLevel0 * numLevel0InCMB) +
numLevel1InLevel0CruftInCMB;
} else {
totalLevel1 = (actualNumLevel1InLevel0 * numLevel0InCMB) +
numLevel1InLevel0CruftInCMB + 1;
}
// consider the worst-case load/dump requirements!
// NOTE: for loads: all of the level1 blocks each with config/state/fifo.
// NOTE: for dumps: all of the level1 blocks each with state/fifo.
loadBlocks = new ScoreSegmentLoadDumpBlock[totalLevel1*3];
loadBlocks_count = 0;
loadBlocks_capacity = totalLevel1*3;
dumpBlocks = new ScoreSegmentLoadDumpBlock[totalLevel1*2];
dumpBlocks_count = 0;
dumpBlocks_capacity = totalLevel1*2;
freeList_Level0Blocks =
new ScoreCustomLinkedList<ScoreSegmentBlock *>(totalLevel0);
freeList_Level1Blocks =
new ScoreCustomLinkedList<ScoreSegmentBlock *>(totalLevel1);
unavailableList_Level0Blocks =
new ScoreCustomLinkedList<ScoreSegmentBlock *>(totalLevel0);
unavailableList_Level1Blocks =
new ScoreCustomLinkedList<ScoreSegmentBlock *>(totalLevel1);
usedList_Level0Blocks =
new ScoreCustomLinkedList<ScoreSegmentBlock *>(totalLevel0);
usedList_Level1Blocks =
new ScoreCustomLinkedList<ScoreSegmentBlock *>(totalLevel1);
cachedList_Level0Blocks =
new ScoreCustomLinkedList<ScoreSegmentBlock *>(totalLevel0);
cachedList_Level1Blocks =
new ScoreCustomLinkedList<ScoreSegmentBlock *>(totalLevel1);
level0Blocks = new ScoreSegmentBlock[totalLevel0];
for (i = 0; i < totalLevel0; i++) {
if ((i == (totalLevel0 - 1)) &&
(sizeLevel0CruftInCMB != 0)) {
level0Blocks[i].type = SCORE_SEGMENTBLOCK_LEVEL0_CRUFT;
} else {
level0Blocks[i].type = SCORE_SEGMENTBLOCK_LEVEL0_FREE;
SCORECUSTOMLINKEDLIST_APPEND(freeList_Level0Blocks,
&(level0Blocks[i]),
level0Blocks[i].freeListItem);
}
level0Blocks[i].start = SCORE_SEGMENTTABLE_LEVEL0SIZE * i;
if ((i == (totalLevel0 - 1)) &&
(sizeLevel0CruftInCMB != 0)) {
level0Blocks[i].size = sizeLevel0CruftInCMB;
} else {
level0Blocks[i].size = SCORE_SEGMENTTABLE_LEVEL0SIZE;
}
level0Blocks[i].owner = NULL;
level0Blocks[i].parentTable = this;
level0Blocks[i].childBlockStartIndex = actualNumLevel1InLevel0 * i;
// NOTE: We purposefully do not want to include the cruft level1 block.
level0Blocks[i].childBlockSize = numLevel1InLevel0;
}
level1Blocks = new ScoreSegmentBlock[totalLevel1];
for (i = 0; i < totalLevel1; i++) {
if ((((i + 1) % actualNumLevel1InLevel0) == 0) &&
(sizeLevel1CruftInLevel0 != 0)) {
level1Blocks[i].type = SCORE_SEGMENTBLOCK_LEVEL1_CRUFT;
} else if ((i == (totalLevel1 - 1)) &&
(sizeLevel1CruftInLevel0CruftInCMB != 0)) {
level1Blocks[i].type = SCORE_SEGMENTBLOCK_LEVEL1_CRUFT;
} else {
level1Blocks[i].type = SCORE_SEGMENTBLOCK_LEVEL1_UNAVAILABLE;
SCORECUSTOMLINKEDLIST_APPEND(unavailableList_Level1Blocks,
&(level1Blocks[i]),
level1Blocks[i].unavailableListItem);
}
if (i == 0) {
level1Blocks[i].start = 0;
} else {
level1Blocks[i].start = level1Blocks[i-1].start +
level1Blocks[i-1].size;
}
if (((i % numLevel1InLevel0) == 0) && (i != 0) &&
(sizeLevel1CruftInLevel0 != 0)) {
level1Blocks[i].size = sizeLevel1CruftInLevel0;
} else {
level1Blocks[i].size = SCORE_SEGMENTTABLE_LEVEL1SIZE;
}
level1Blocks[i].owner = NULL;
level1Blocks[i].parentTable = this;
level1Blocks[i].parentBlockIndex = (i / actualNumLevel1InLevel0);
if ((level0Blocks[level1Blocks[i].parentBlockIndex].type ==
SCORE_SEGMENTBLOCK_LEVEL0_CRUFT) &&
(level1Blocks[i].type ==
SCORE_SEGMENTBLOCK_LEVEL1_UNAVAILABLE)) {
SCORECUSTOMLINKEDLIST_DELITEM(unavailableList_Level1Blocks,
level1Blocks[i].unavailableListItem);
level1Blocks[i].type = SCORE_SEGMENTBLOCK_LEVEL1_FREE;
SCORECUSTOMLINKEDLIST_APPEND(freeList_Level1Blocks,
&(level1Blocks[i]),
level1Blocks[i].freeListItem);
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
// ScoreSegmentTable::~ScoreSegmentTable:
// Destructor for ScoreSegmentTable.
// Cleans up all internal structures.
//
// Parameters: None.
//
// Return value: None.
///////////////////////////////////////////////////////////////////////////////
ScoreSegmentTable::~ScoreSegmentTable() {
delete(level0Blocks);
delete(level1Blocks);
delete(loadBlocks);
delete(dumpBlocks);
delete(freeList_Level0Blocks);
delete(freeList_Level1Blocks);
delete(unavailableList_Level0Blocks);
delete(unavailableList_Level1Blocks);
delete(usedList_Level0Blocks);
delete(usedList_Level1Blocks);
delete(cachedList_Level0Blocks);
delete(cachedList_Level1Blocks);
}
///////////////////////////////////////////////////////////////////////////////
// ScoreSegmentTable::allocateLevel0Block:
// Attempt to allocate a free level0 block.
// It will look at freeList_Level0Blocks for free blocks.
//
// Parameters: owner: the future owner of the block.
//
// Return value:
// If successful, a pointer to the block; else, NULL.
///////////////////////////////////////////////////////////////////////////////
ScoreSegmentBlock *ScoreSegmentTable::allocateLevel0Block(
ScoreGraphNode *owner) {
if (SCORECUSTOMLINKEDLIST_ISEMPTY(freeList_Level0Blocks)) {
return(NULL);
} else {
ScoreSegmentBlock *freeBlock;
SCORECUSTOMLINKEDLIST_POP(freeList_Level0Blocks, freeBlock);
freeBlock->type = SCORE_SEGMENTBLOCK_LEVEL0_USED;
freeBlock->owner = owner;
freeBlock->freeListItem = SCORECUSTOMLINKEDLIST_NULL;
SCORECUSTOMLINKEDLIST_APPEND(usedList_Level0Blocks, freeBlock,
freeBlock->usedListItem);
return(freeBlock);
}
}
///////////////////////////////////////////////////////////////////////////////
// ScoreSegmentTable::allocateLevel1Block:
// Attempt to allocate a free level1 block.
// It will look at freeList_Level1Blocks for free blocks. If no such block,
// exists, it will look at freeList_Level0Blocks for free blocks. Then,
// it will break up that level0 block and allocate a level1 block.
//
// Parameters: owner: the future owner of the block.
//
// Return value:
// If successful, a pointer to the block; else, NULL.
///////////////////////////////////////////////////////////////////////////////
ScoreSegmentBlock *ScoreSegmentTable::allocateLevel1Block(
ScoreGraphNode *owner) {
if (SCORECUSTOMLINKEDLIST_ISEMPTY(freeList_Level1Blocks)) {
if (SCORECUSTOMLINKEDLIST_ISEMPTY(freeList_Level0Blocks)) {
return(NULL);
} else if ((SCORECUSTOMLINKEDLIST_LENGTH(freeList_Level0Blocks)+
SCORECUSTOMLINKEDLIST_LENGTH(cachedList_Level0Blocks)+
SCORECUSTOMLINKEDLIST_LENGTH(usedList_Level0Blocks)) == 1) {
// to preserve the guarantee that we always have a level0 segment block
// in each CMB for a resident segment.
return(NULL);
} else {
ScoreSegmentBlock *freeLevel0Block;
unsigned int childBlockEndIndex;
unsigned int i;
SCORECUSTOMLINKEDLIST_POP(freeList_Level0Blocks, freeLevel0Block);
childBlockEndIndex =
freeLevel0Block->childBlockStartIndex +
freeLevel0Block->childBlockSize - 1;
freeLevel0Block->type = SCORE_SEGMENTBLOCK_LEVEL0_UNAVAILABLE;
freeLevel0Block->freeListItem = SCORECUSTOMLINKEDLIST_NULL;
SCORECUSTOMLINKEDLIST_APPEND(unavailableList_Level0Blocks,
freeLevel0Block,
freeLevel0Block->unavailableListItem);
for (i = freeLevel0Block->childBlockStartIndex;
i < childBlockEndIndex; i++) {
ScoreSegmentBlock *convertedBlock = &(level1Blocks[i]);
SCORECUSTOMLINKEDLIST_DELITEM(unavailableList_Level1Blocks,
convertedBlock->unavailableListItem);
convertedBlock->type = SCORE_SEGMENTBLOCK_LEVEL1_FREE;
SCORECUSTOMLINKEDLIST_APPEND(freeList_Level1Blocks, convertedBlock,
convertedBlock->freeListItem);
}
{
ScoreSegmentBlock *freeBlock = &(level1Blocks[childBlockEndIndex]);
SCORECUSTOMLINKEDLIST_DELITEM(unavailableList_Level1Blocks,
freeBlock->unavailableListItem);
freeBlock->type = SCORE_SEGMENTBLOCK_LEVEL1_USED;
freeBlock->owner = owner;
SCORECUSTOMLINKEDLIST_APPEND(usedList_Level1Blocks, freeBlock,
freeBlock->usedListItem);
level0Blocks[freeBlock->parentBlockIndex].childBlocksInUse++;
return(freeBlock);
}
}
} else {
ScoreSegmentBlock *freeBlock;
SCORECUSTOMLINKEDLIST_POP(freeList_Level1Blocks, freeBlock);
freeBlock->type = SCORE_SEGMENTBLOCK_LEVEL1_USED;
freeBlock->owner = owner;
freeBlock->freeListItem = SCORECUSTOMLINKEDLIST_NULL;
SCORECUSTOMLINKEDLIST_APPEND(usedList_Level1Blocks, freeBlock,
freeBlock->usedListItem);
level0Blocks[freeBlock->parentBlockIndex].childBlocksInUse++;
return(freeBlock);
}
}
void ScoreSegmentTable::freeCachedLevel0Block(ScoreSegmentBlock *block) {
block->type = SCORE_SEGMENTBLOCK_LEVEL0_FREE;
block->owner = NULL;
SCORECUSTOMLINKEDLIST_DELITEM(cachedList_Level0Blocks,
block->cachedListItem);
SCORECUSTOMLINKEDLIST_APPEND(freeList_Level0Blocks, block,
block->freeListItem);
}
void ScoreSegmentTable::freeCachedLevel1Block(ScoreSegmentBlock *block) {
block->type = SCORE_SEGMENTBLOCK_LEVEL1_FREE;
block->owner = NULL;
SCORECUSTOMLINKEDLIST_DELITEM(cachedList_Level1Blocks,
block->cachedListItem);
SCORECUSTOMLINKEDLIST_APPEND(freeList_Level1Blocks, block,
block->freeListItem);
if (level0Blocks[block->parentBlockIndex].type !=
SCORE_SEGMENTBLOCK_LEVEL0_CRUFT) {
level0Blocks[block->parentBlockIndex].childBlocksInUse--;
if (level0Blocks[block->parentBlockIndex].childBlocksInUse == 0) {
ScoreSegmentBlock *parentBlock =
&(level0Blocks[block->parentBlockIndex]);
unsigned int childBlockEndIndex =
parentBlock->childBlockStartIndex +
parentBlock->childBlockSize;
unsigned int i;
parentBlock->type = SCORE_SEGMENTBLOCK_LEVEL0_FREE;
SCORECUSTOMLINKEDLIST_DELITEM(unavailableList_Level0Blocks,
parentBlock->unavailableListItem);
SCORECUSTOMLINKEDLIST_APPEND(freeList_Level0Blocks, parentBlock,
parentBlock->freeListItem);
for (i = parentBlock->childBlockStartIndex;
i < childBlockEndIndex; i++) {
ScoreSegmentBlock *convertedBlock = &(level1Blocks[i]);
SCORECUSTOMLINKEDLIST_DELITEM(freeList_Level1Blocks,
convertedBlock->freeListItem);
convertedBlock->type = SCORE_SEGMENTBLOCK_LEVEL1_UNAVAILABLE;
SCORECUSTOMLINKEDLIST_APPEND(unavailableList_Level1Blocks,
convertedBlock,
convertedBlock->unavailableListItem);
}
}
}
}
void ScoreSegmentTable::freeCachedLevel1Block_nomerge(
ScoreSegmentBlock *block) {
block->type = SCORE_SEGMENTBLOCK_LEVEL1_FREE;
block->owner = NULL;
SCORECUSTOMLINKEDLIST_DELITEM(cachedList_Level1Blocks,
block->cachedListItem);
SCORECUSTOMLINKEDLIST_APPEND(freeList_Level1Blocks, block,
block->freeListItem);
if (level0Blocks[block->parentBlockIndex].type !=
SCORE_SEGMENTBLOCK_LEVEL0_CRUFT) {
level0Blocks[block->parentBlockIndex].childBlocksInUse--;
}
}
void ScoreSegmentTable::freeUsedLevel0Block(ScoreSegmentBlock *block) {
block->type = SCORE_SEGMENTBLOCK_LEVEL0_FREE;
block->owner = NULL;
SCORECUSTOMLINKEDLIST_DELITEM(usedList_Level0Blocks,
block->usedListItem);
SCORECUSTOMLINKEDLIST_APPEND(freeList_Level0Blocks, block,
block->freeListItem);
}
void ScoreSegmentTable::freeUsedLevel1Block(ScoreSegmentBlock *block) {
block->type = SCORE_SEGMENTBLOCK_LEVEL1_FREE;
block->owner = NULL;
SCORECUSTOMLINKEDLIST_DELITEM(usedList_Level1Blocks, block->usedListItem);
SCORECUSTOMLINKEDLIST_APPEND(freeList_Level1Blocks, block,
block->freeListItem);
if (level0Blocks[block->parentBlockIndex].type !=
SCORE_SEGMENTBLOCK_LEVEL0_CRUFT) {
level0Blocks[block->parentBlockIndex].childBlocksInUse--;
if (level0Blocks[block->parentBlockIndex].childBlocksInUse == 0) {
ScoreSegmentBlock *parentBlock =
&(level0Blocks[block->parentBlockIndex]);
unsigned int childBlockEndIndex =
parentBlock->childBlockStartIndex +
parentBlock->childBlockSize;
unsigned int i;
parentBlock->type = SCORE_SEGMENTBLOCK_LEVEL0_FREE;
SCORECUSTOMLINKEDLIST_DELITEM(unavailableList_Level0Blocks,
parentBlock->unavailableListItem);
SCORECUSTOMLINKEDLIST_APPEND(freeList_Level0Blocks, parentBlock,
parentBlock->freeListItem);
for (i = parentBlock->childBlockStartIndex;
i < childBlockEndIndex; i++) {
ScoreSegmentBlock *convertedBlock = &(level1Blocks[i]);
SCORECUSTOMLINKEDLIST_DELITEM(freeList_Level1Blocks,
convertedBlock->freeListItem);
convertedBlock->type = SCORE_SEGMENTBLOCK_LEVEL1_UNAVAILABLE;
SCORECUSTOMLINKEDLIST_APPEND(unavailableList_Level1Blocks,
convertedBlock,
convertedBlock->unavailableListItem);
}
}
}
}
void ScoreSegmentTable::markCachedLevel0Block(ScoreSegmentBlock *block) {
block->type = SCORE_SEGMENTBLOCK_LEVEL0_CACHED;
SCORECUSTOMLINKEDLIST_DELITEM(usedList_Level0Blocks,
block->usedListItem);
SCORECUSTOMLINKEDLIST_APPEND(cachedList_Level0Blocks, block,
block->cachedListItem);
}
void ScoreSegmentTable::markCachedLevel1Block(ScoreSegmentBlock *block) {
block->type = SCORE_SEGMENTBLOCK_LEVEL1_CACHED;
SCORECUSTOMLINKEDLIST_DELITEM(usedList_Level1Blocks,
block->usedListItem);
SCORECUSTOMLINKEDLIST_APPEND(cachedList_Level1Blocks, block,
block->cachedListItem);
}
void ScoreSegmentTable::markUsedLevel0Block(ScoreSegmentBlock *block) {
block->type = SCORE_SEGMENTBLOCK_LEVEL0_USED;
SCORECUSTOMLINKEDLIST_DELITEM(cachedList_Level0Blocks,
block->cachedListItem);
SCORECUSTOMLINKEDLIST_APPEND(usedList_Level0Blocks, block,
block->usedListItem);
}
void ScoreSegmentTable::markUsedLevel1Block(ScoreSegmentBlock *block) {
block->type = SCORE_SEGMENTBLOCK_LEVEL1_USED;
SCORECUSTOMLINKEDLIST_DELITEM(cachedList_Level1Blocks,
block->cachedListItem);
SCORECUSTOMLINKEDLIST_APPEND(usedList_Level1Blocks, block,
block->usedListItem);
}
void ScoreSegmentTable::addToLoadBlockList(ScoreSegmentBlock *block,
unsigned int blockOffset,
void *buffer,
unsigned int bufferSize) {
ScoreSegmentLoadDumpBlock *lBlock = &(loadBlocks[loadBlocks_count]);
lBlock->owner = block->owner;
lBlock->blockStart = block->start + blockOffset;
lBlock->buffer = buffer;
lBlock->bufferSize = bufferSize;
lBlock->bufferSizeDependsOnOwnerAddrs = 0;
loadBlocks_count++;
}
void ScoreSegmentTable::addToDumpBlockList(ScoreSegmentBlock *block,
unsigned int blockOffset,
void *buffer,
unsigned int bufferSize) {
ScoreSegmentLoadDumpBlock *dBlock = &(dumpBlocks[dumpBlocks_count]);
dBlock->owner = block->owner;
dBlock->blockStart = block->start + blockOffset;
dBlock->buffer = buffer;
dBlock->bufferSize = bufferSize;
dBlock->bufferSizeDependsOnOwnerAddrs = 0;
dumpBlocks_count++;
}
void ScoreSegmentTable::addToLoadBlockList_useOwnerAddrs(ScoreSegmentBlock *block,
unsigned int blockOffset,
void *buffer) {
ScoreSegmentLoadDumpBlock *lBlock = &(loadBlocks[loadBlocks_count]);
lBlock->owner = block->owner;
lBlock->blockStart = block->start + blockOffset;
lBlock->buffer = buffer;
lBlock->bufferSizeDependsOnOwnerAddrs = 1;
loadBlocks_count++;
}
void ScoreSegmentTable::addToDumpBlockList_useOwnerAddrs(ScoreSegmentBlock *block,
unsigned int blockOffset,
void *buffer) {
ScoreSegmentLoadDumpBlock *dBlock = &(dumpBlocks[dumpBlocks_count]);
dBlock->owner = block->owner;
dBlock->blockStart = block->start + blockOffset;
dBlock->buffer = buffer;
dBlock->bufferSizeDependsOnOwnerAddrs = 1;
dumpBlocks_count++;
}
// required by LEDA for use with lists/etc.
// provides comparison operation between ScoreSegmentBlocks.
// NOTE: Right now, we only say 2 segment blocks are equal if their pointers
// are equal. Otherwise, less than/greater than is determined
// simply by their pointer values.
int compare(ScoreSegmentBlock * const & left,
ScoreSegmentBlock * const & right) {
if (left == right) {
return(0);
} else if (left < right) {
return(-1);
} else {
return(1);
}
}
|
f6128338cbb8d52bd8526ed3934e9854a8b8f738
|
3c86117fc3bd2f1096b81d08f67fe2c249aa60cf
|
/coloredCircle.cpp
|
bfec48a3bde8a956d3ab1f23d903da3eec66c62e
|
[] |
no_license
|
dktdc91/Codefights
|
167037dec842422b16cdc03111602b9154b91bcf
|
7709bd9a55a6b4823f80b034e0a1bb707d294b5c
|
refs/heads/master
| 2021-01-25T09:32:16.635370
| 2018-05-29T03:59:21
| 2018-05-29T03:59:21
| 93,848,662
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 319
|
cpp
|
coloredCircle.cpp
|
int countCircleColorings(int points, int colors) {
int colorsArray[2] ={0, colors};
for (int i = 1; i < points; i++) {
int tmp = colorsArray[0];
colorsArray[0] = colorsArray[0] * (colors - 2) + colorsArray[1] * (colors - 1);
colorsArray[1] = tmp;
}
return colorsArray[0];
}
|
11de07ea4e380bfacca40faec615b5bc7fe3f07b
|
7c105b8d2c2dcf781292d47b0f464430e3028905
|
/problemset/PAT/Basic Level/1004.cpp
|
d9ab2c8418f01c88bea99aa66855033d9e2d2102
|
[] |
no_license
|
jiafeimao-gjf/BasicKnowledgeofCS
|
e0b751452c647aa068283a56640a06b58421a15f
|
49e4d80a7f1a0e9924b491f5e7dbe8ff6c84c02f
|
refs/heads/master
| 2023-07-06T14:07:40.552273
| 2023-07-02T04:59:28
| 2023-07-02T04:59:28
| 181,401,725
| 2
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 810
|
cpp
|
1004.cpp
|
// 1004. 成绩排名 (20)
#include <iostream>
#include <string>
using namespace std;
//学生信息结构体
typedef struct{
string name;
string id;
int score;
}STU_INFO;
int main(){
STU_INFO stu_info[1000];
int t;
cin >> t;
int i = 0;
while(t--){
cin>>stu_info[i].name>>stu_info[i].id>>stu_info[i].score;
i++;
}
//求最低分和最高分的序号
int maxS = stu_info[0].score,minS = stu_info[0].score;
int maxO = 0,minO = 0;
for(int j = 1;j < i;j++){
if(stu_info[j].score > maxS){
maxS = stu_info[j].score;
maxO = j;
}
if(stu_info[j].score < minS){
minS = stu_info[j].score;
minO = j;
}
}
cout<<stu_info[maxO].name<<' '<<stu_info[maxO].id<<endl;
cout<<stu_info[minO].name<<' '<<stu_info[minO].id<<endl;
return 0;
}
|
27853dbf05221fccbc698023c9bcbc02eadb1ea3
|
89016fcda83d19cf880a3671e7923d69b8cb7c39
|
/spriterengine/animation/animationinstance.h
|
86581da77f61d186a42795ac26a2e53ae00692d4
|
[
"Zlib"
] |
permissive
|
lucidspriter/SpriterPlusPlus
|
9f83e68cd81295642dd3814ab800cd92967ee6c0
|
8fb550e1633036b42acd1cce0e05cfe60a3041c0
|
refs/heads/master
| 2023-08-10T10:29:03.386422
| 2021-02-17T22:13:10
| 2021-02-17T22:13:10
| 45,448,363
| 97
| 55
|
NOASSERTION
| 2023-07-23T13:17:31
| 2015-11-03T07:09:45
|
C++
|
UTF-8
|
C++
| false
| false
| 2,194
|
h
|
animationinstance.h
|
#ifndef ANIMATIONINSTANCE_H
#define ANIMATIONINSTANCE_H
#include <vector>
#include <string>
#include "mainlinekeyinstance.h"
namespace SpriterEngine
{
class MainlineKeyInstance;
class EntityInstanceData;
class Animation;
class TimelineInstance;
typedef std::vector<MainlineKeyInstance*> MainlineKeyInstanceVector;
typedef MainlineKeyInstanceVector::iterator MainlineKeyInstanceVectorIterator;
typedef std::vector<TimelineInstance*>TimelineInstanceVector;
class AnimationInstance
{
public:
AnimationInstance(EntityInstance *entityInstance, EntityInstanceData *entityInstanceData, Animation *animation);
~AnimationInstance();
void findAndProcessKeys(real newTime, bool forward, ObjectInterfaceVector ** instanceZOrder);
void findCurrentKeys(real newTime, bool forward);
void processCurrentKeys(real newTime, ObjectInterfaceVector **instanceZOrder);
std::string getName();
bool looping();
real length();
real currentTime();
int currentMainlineKeyIndex();
void setCurrentTimeToPreviousKeyFrame(ObjectInterfaceVector **instanceZOrder);
void setCurrentTimeToNextKeyFrame(ObjectInterfaceVector **instanceZOrder);
void setCurrentTimeToKeyAtIndex(int newIndex, ObjectInterfaceVector **instanceZOrder);
real processRefKeys(real newTime);
void blendRefKeys(real newTime, real blendRatio);
void setZOrder(ObjectInterfaceVector ** instanceZOrder);
void processRefTransforms();
void processCurrentTimelineKeys(real newTime);
void blendCurrentTimelineKeys(real newTime, real blendRatio);
int mainlineKeyCount();
private:
void findCurrentTimelineKeys(real newTime, bool forward);
void findCurrentMainlineKey(real newTime, bool forward);
real processCurrentMainlineKey(real newTime, ObjectInterfaceVector **instanceZOrder);
void findMainlineKeyTimeForward(real newTime);
void findMainlineKeyTimeBackward(real newTime);
real time;
MainlineKeyInstanceVector mainlineKeys;
MainlineKeyInstanceVectorIterator mainlineKeyIterator;
MainlineKeyInstance *mainlineKeyAtIndex(int index);
TimelineInstanceVector timelines;
std::string name;
real animationLength;
bool isLooping;
};
}
#endif // ANIMATIONINSTANCE_H
|
06787d968b843f8318dc81b81d629b95ab45c80b
|
1d33665606a2006d75012d111984f29a18fe10ac
|
/src/drag_race_iarrc/src/LidarObstacleManager.cpp
|
8ed052da15f5a3b2414f84fbb942c47524c9a56e
|
[] |
no_license
|
WilliamGu98/Snowflake
|
7524ba7ddb8886ed24a6046528c2387ace84ceb7
|
7ad17ba393c601b66fd4db3eda8065d68d4fff29
|
refs/heads/master
| 2020-03-29T12:30:26.744321
| 2019-02-16T21:30:48
| 2019-02-16T21:30:48
| 149,903,103
| 1
| 0
| null | 2018-09-22T18:02:02
| 2018-09-22T18:02:02
| null |
UTF-8
|
C++
| false
| false
| 13,676
|
cpp
|
LidarObstacleManager.cpp
|
/*
* Created By: Gareth Ellis
* Created On: July 4, 2017
* Description: TODO
*/
// STD Includes
#include <cmath>
#include <numeric>
#include <stack>
// Snowbots Includes
#include <LidarObstacleManager.h>
// TODO: We should probably get rid of the default constructor here.....
LidarObstacleManager::LidarObstacleManager()
: max_obstacle_merging_distance(0.3), cone_grouping_tolerance(1.3){};
LidarObstacleManager::LidarObstacleManager(
double max_obstacle_merging_distance,
double max_distance_from_robot_accepted,
double cone_grouping_tolerance,
double min_wall_length,
double collision_distance,
double front_angle,
double side_angle_max,
double side_angle_min,
double region_fill_percentage,
bool front_collision_only)
: max_obstacle_merging_distance(max_obstacle_merging_distance),
max_distance_from_robot_accepted(max_distance_from_robot_accepted),
cone_grouping_tolerance(cone_grouping_tolerance),
min_wall_length(min_wall_length),
collision_distance(collision_distance),
front_angle(front_angle),
side_angle_max(side_angle_max),
side_angle_min(side_angle_min),
region_fill_percentage(region_fill_percentage),
front_collision_only(front_collision_only) {}
void LidarObstacleManager::addLaserScan(const sensor_msgs::LaserScan& scan) {
// Number of hits for each region
int left_side_hits = 0;
int right_side_hits = 0;
int front_side_hits = 0;
// Create an obstacle for every hit in the lidar scan
for (int i = 0; i < scan.ranges.size(); ++i) {
// Check that the lidar hit is within acceptable bounds
double angle = scan.angle_min + i * scan.angle_increment;
double range = scan.ranges[i];
if (range < scan.range_max && range > scan.range_min) {
addObstacle(LidarObstacle(min_wall_length, angle, range));
double abs_angle = std::abs(angle);
if (abs_angle < side_angle_max && abs_angle > side_angle_min) {
if (range < collision_distance * 2) {
if (angle > 0)
left_side_hits++;
else
right_side_hits++;
}
}
if (abs_angle < front_angle / 2) {
if (range < collision_distance) front_side_hits++;
}
}
}
int side_region_total_size =
(side_angle_max - side_angle_min) / scan.angle_increment;
int front_region_total_size = front_angle / scan.angle_increment;
if (front_collision_only) {
collision_detected =
(front_side_hits > (front_region_total_size * region_fill_percentage));
} else {
collision_detected =
(left_side_hits > (side_region_total_size * region_fill_percentage)) &&
(right_side_hits > (side_region_total_size * region_fill_percentage)) &&
(front_side_hits > (front_region_total_size * region_fill_percentage));
}
}
std::vector<LidarObstacle> LidarObstacleManager::getObstacles() {
return obstacles;
}
void LidarObstacleManager::clearObstacles() {
obstacles.clear();
}
void LidarObstacleManager::addObstacle(LidarObstacle obstacle) {
// See if this obstacle is close enough to any other saved obstacle to be
// the same
// TODO: Should we be instead checking for the CLOSEST saved obstcle?
for (LidarObstacle& saved_obstacle : obstacles) {
if (minDistanceBetweenObstacles(saved_obstacle, obstacle) <
max_obstacle_merging_distance) {
saved_obstacle.mergeInLidarObstacle(obstacle);
return;
}
}
obstacles.emplace_back(obstacle);
}
double
LidarObstacleManager::minDistanceBetweenObstacles(LidarObstacle obstacle1,
LidarObstacle obstacle2) {
// TODO: This is ABSURDLY ineffecient. We're doing n^2 operations on 2
// potentially
// TODO: very large objects. We should be able to do some sort of obstacle
// approx to
// TODO: circles or boxes and compare them that way (need to update
// LidarObstacle for that approx)
std::vector<Point> obstacle1_points = obstacle1.getReadingsAsPoints();
std::vector<Point> obstacle2_points = obstacle2.getReadingsAsPoints();
// Compare every point to.... *shudders slightly* every other point..
double min_distance = -1;
for (Point p1 : obstacle1_points) {
for (Point p2 : obstacle2_points) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
double distance = std::sqrt(std::pow(dx, 2.0) + std::pow(dy, 2.0));
if (min_distance < 0 || distance < min_distance)
min_distance = distance;
};
};
return min_distance;
}
std::vector<LineOfBestFit> LidarObstacleManager::getConeLines() {
// Get all our cones as points
std::vector<Point> points;
for (LidarObstacle obstacle : obstacles) {
if (obstacle.getObstacleType() == CONE) {
points.emplace_back(obstacle.getCenter());
}
}
// Get groups of lines
std::vector<std::vector<Point>> groups =
getPointGroupings(points, cone_grouping_tolerance);
// Fit a line of best fit to each group
std::vector<LineOfBestFit> lines;
for (std::vector<Point> group : groups)
if (group.size() >= 2) lines.emplace_back(getLineOfBestFit(group));
return lines;
}
std::vector<std::vector<Point>>
LidarObstacleManager::getPointGroupings(std::vector<Point> points,
double tolerance) {
std::vector<std::vector<Point>> groups;
// Go through every point
while (points.size() > 0) {
// Start the current group off with the last point
std::vector<Point> group;
std::stack<Point> to_visit;
to_visit.emplace(points.back());
points.pop_back();
while (to_visit.size() > 0) {
// Visit the first point in to_visit
Point curr_point = to_visit.top();
to_visit.pop();
// Figure out if there are any points within tolerance of the point
// we're visiting
for (int i = 0; i < points.size(); i++) {
Point p = points[i];
if (distanceBetweenPoints(curr_point, p) < tolerance) {
// Add point to to_visit and remove from the given list of
// points
to_visit.emplace(p);
points.erase(points.begin() + i);
}
}
// Add the current point to the group
group.emplace_back(curr_point);
// Keep going if we've got more points to visit
}
groups.emplace_back(group);
}
return groups;
}
LineOfBestFit
LidarObstacleManager::getLineOfBestFit(const std::vector<Point>& points) {
// Get line of best fit using linear regression formula
// http://www.statisticshowto.com/how-to-find-a-linear-regression-equation/
// TODO: Handle this more nicely
// WE SHOULD NEVER GET HERE
BOOST_ASSERT(points.size() >= 2);
double x_sum = std::accumulate(
points.begin(), points.end(), 0.0, [](double accum, Point p) {
return accum + p.x;
});
double y_sum = std::accumulate(
points.begin(), points.end(), 0.0, [](double accum, Point p) {
return accum + p.y;
});
double x_squared_sum = std::accumulate(
points.begin(), points.end(), 0.0, [](double accum, Point p) {
return accum + std::pow(p.x, 2.0);
});
double x_y_product_sum = std::accumulate(
points.begin(), points.end(), 0.0, [](double accum, Point p) {
return accum + p.x * p.y;
});
double y_intercept = (y_sum * x_squared_sum - x_sum * x_y_product_sum) /
(points.size() * x_squared_sum - std::pow(x_sum, 2.0));
double slope = (points.size() * x_y_product_sum - x_sum * y_sum) /
(points.size() * x_squared_sum - std::pow(x_sum, 2.0));
// Calculate means
double x_mean = x_sum / points.size();
double y_mean = y_sum / points.size();
// Calculate Variances
double x_var =
std::accumulate(points.begin(),
points.end(),
0.0,
[x_mean](double accum, Point p) {
return accum + std::pow((x_mean - p.x), 2.0);
}) /
(points.size() - 1);
double y_var =
std::accumulate(points.begin(),
points.end(),
0.0,
[y_mean](double accum, Point p) {
return accum + std::pow((y_mean - p.y), 2.0);
}) /
(points.size() - 1);
// Calculate standard deviations
double x_sd = sqrt(x_var);
double y_sd = sqrt(y_var);
// Calculate correlation coefficient using Slope = r*Sy/Sx
double r = slope * x_sd / y_sd;
return LineOfBestFit(slope, y_intercept, r);
}
LineOfBestFit LidarObstacleManager::getBestLine(bool lineToTheRight) {
LineOfBestFit bestLine(0, 0, 0);
std::vector<LineOfBestFit> lines = getConeLines();
for (size_t i = 0; i < lines.size(); i++) {
// Only check lines where the y-intercept is on the correct side.
if ((lineToTheRight && lines[i].getYIntercept() < 0) ||
(!lineToTheRight && lines[i].getYIntercept() >= 0)) {
// Don't accept lines that are too far from the robot.
if (fabs(lines[i].getYIntercept()) <=
max_distance_from_robot_accepted) {
// If correlation is stronger than the current best, update best
// line.
if (fabs(lines[i].correlation) > fabs(bestLine.correlation))
bestLine = lines[i];
}
}
}
return bestLine;
}
visualization_msgs::Marker LidarObstacleManager::getConeRVizMarker() {
visualization_msgs::Marker points;
// TODO: we shold differenetiat between walls and cones
// TODO: Should be a param (currently in the default LaserScan frame)
points.header.frame_id = "laser";
points.header.stamp = ros::Time::now();
points.ns = "debug";
points.action = visualization_msgs::Marker::ADD;
points.pose.orientation.w = 1.0;
points.id = 0;
// TODO: Make these round, not blocks
points.type = visualization_msgs::Marker::POINTS;
// TODO: Make the scale a param
points.scale.x = 0.1;
points.scale.y = 0.1;
// Points are green
// TODO: Make this a param
points.color.g = 1.0f;
points.color.a = 1.0;
for (LidarObstacle obstacle : obstacles) {
if (obstacle.getObstacleType() == CONE) {
Point center = obstacle.getCenter();
geometry_msgs::Point geom_point;
geom_point.x = center.x;
geom_point.y = center.y;
points.points.push_back(geom_point);
}
}
return points;
}
visualization_msgs::Marker LidarObstacleManager::getConeLinesRVizMarker() {
visualization_msgs::Marker lines;
// TODO: Should be a param (currently in the default LaserScan frame)
lines.header.frame_id = "laser";
lines.header.stamp = ros::Time::now();
lines.ns = "debug";
lines.action = visualization_msgs::Marker::ADD;
lines.pose.orientation.w = 1.0;
lines.id = 0;
lines.type = visualization_msgs::Marker::LINE_LIST;
lines.action = visualization_msgs::Marker::ADD;
// TODO: Make the scale a param
lines.scale.x = 0.1;
lines.scale.y = 0.1;
// TODO: Make this a param
lines.color.r = 1.0f;
lines.color.a = 1.0;
// Get the cone lines
std::vector<LineOfBestFit> cone_lines = getConeLines();
for (int i = 0; i < cone_lines.size(); i++) {
// Get two points to represent the line
geometry_msgs::Point p1, p2;
p1.x = -10;
p1.y = cone_lines[i].getYCoorAtX(p1.x);
// TODO: make length here a param
p2.x = 10;
p2.y = cone_lines[i].getYCoorAtX(p2.x);
lines.points.push_back(p1);
lines.points.push_back(p2);
}
return lines;
}
// TODO: See comments in above visualisation functions
visualization_msgs::Marker
LidarObstacleManager::getBestConeLineRVizMarker(bool line_to_the_right) {
// We'll just put a single line in this
visualization_msgs::Marker line;
// TODO: Should be a param (currently in the default LaserScan frame)
line.header.frame_id = "laser";
line.header.stamp = ros::Time::now();
line.ns = "debug";
line.action = visualization_msgs::Marker::ADD;
line.pose.orientation.w = 1.0;
line.id = 0;
line.type = visualization_msgs::Marker::LINE_LIST;
line.action = visualization_msgs::Marker::ADD;
// TODO: Make the scale a param
line.scale.x = 0.1;
line.scale.y = 0.1;
// TODO: Make this a param
line.color.b = 1.0f;
line.color.a = 1.0;
// TODO: Find a better way to sync this logic up. Copy pasting sucks
LineOfBestFit best_line = getBestLine(line_to_the_right);
// If no line found on desired side
if (best_line.correlation == 0) best_line = getBestLine(!line_to_the_right);
geometry_msgs::Point p1, p2;
p1.x = -10;
p1.y = best_line.getYCoorAtX(p1.x);
p2.x = 10;
p2.y = best_line.getYCoorAtX(p2.x);
line.points.push_back(p1);
line.points.push_back(p2);
return line;
}
bool LidarObstacleManager::collisionDetected() {
return collision_detected;
}
|
c321123165be4e50115d3786a8aee09e70c40677
|
976be5ede76c33d029b6606941cbe57507b10c86
|
/ini_parser/main.cc
|
735bd044fe3a452f915b503851eceb6c5cd6891d
|
[] |
no_license
|
wei-xu/interview
|
62ad19c0af1f33d4a255f4f29a43986cbb3bcafc
|
87f3fccc2d256bc8879ebc6e35f8b9154122022f
|
refs/heads/master
| 2021-01-17T06:01:05.799339
| 2014-08-08T03:52:57
| 2014-08-08T03:52:57
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 4,006
|
cc
|
main.cc
|
#include "ini_parser.h"
#include <iostream>
#include <assert.h>
void test1()
{
const char* ini_text= "a=1\nb=2\n";
qh::INIParser parser;
if (!parser.Parse(ini_text, strlen(ini_text), "\n", "=")) {
assert(false);
}
const std::string& a = parser.Get("a", NULL);
assert(a == "1");
std::string b = parser.Get("b", NULL);
assert(b == "2");
const std::string& c = parser.Get("c", NULL);
assert(c == "");
//std::cout<<c.data()<<std::endl;
}
void test2()
{
const char* ini_text= "a=1||b=2||c=3";
qh::INIParser parser;
if (!parser.Parse(ini_text, strlen(ini_text), "||", "=")) {
assert(false);
}
const std::string& a = parser.Get("a", NULL);
assert(a == "1");
std::string b = parser.Get("b", NULL);
assert(b == "2");
const std::string& c = parser.Get("c", NULL);
assert(c == "3");
}
void test3()
{
const char* ini_text= "||||a:1||b:2||||c:3||||||";
qh::INIParser parser;
if (!parser.Parse(ini_text, strlen(ini_text), "||", ":")) {
assert(false);
}
const std::string& a = parser.Get("a", NULL);
assert(a == "1");
std::string b = parser.Get("b", NULL);
assert(b == "2");
const std::string& c = parser.Get("c", NULL);
assert(c == "3");
}
void test4()
{
const char* ini_text= "str1=this||str2=is||str3=me";
qh::INIParser parser;
if (!parser.Parse(ini_text, strlen(ini_text), "||", "=")) {
assert(false);
}
const std::string& str1 = parser.Get("str1", NULL);
assert(str1 == "this");
std::string b = parser.Get("str2", NULL);
assert(b == "is");
const std::string& c = parser.Get("str3", NULL);
assert(c == "me");
}
void test5()
{
const char* ini_text= "a=1&&b=&&c=";
qh::INIParser parser;
if (!parser.Parse(ini_text, strlen(ini_text), "&&", "=")) {
assert(false);
}
const std::string& a = parser.Get("a", NULL);
assert(a == "1");
std::string b = parser.Get("b", NULL);
assert(b == "");
const std::string& c = parser.Get("c", NULL);
assert(c == "");
}
void test6()
{
const std::string& ini_text= "test.txt";//读硬盘数据
qh::INIParser parser;
if (!parser.Parse(ini_text)) {
assert(false);
}
if (!parser.Parse(parser.ini_data, strlen(parser.ini_data), "||", ":")) {
assert(false);
}
const std::string& a = parser.Get("a", NULL);
assert(a == "1");
std::string b = parser.Get("b", NULL);
assert(b == "2");
const std::string& c = parser.Get("c", NULL);
assert(c == "");
const std::string& hello = parser.Get("hello", NULL);
assert(hello == "4");
}
void test7()
{
const char* ini_text= "a=1&&b=&&c=&&";
qh::INIParser parser;
if (!parser.Parse(ini_text, strlen(ini_text), "&&", "=")) {
assert(false);
}
const std::string& a = parser.Get("a", NULL);
assert(a == "1");
std::string b = parser.Get("b", NULL);
assert(b == "");
const std::string& c = parser.Get("c", NULL);
assert(c == "");
}
void test8()
{
const std::string& ini_text= "a=1||b=2||isempty=false";
qh::INIParser parser;
const std::string& a = parser.Get(ini_text,"a", NULL);
assert(a == "1");
std::string b = parser.Get(ini_text,"b", NULL);
assert(b == "2");
const std::string& isempty = parser.Get(ini_text,"isempty", NULL);
assert(isempty == "false");
const std::string& empty = parser.Get(ini_text,"empty", NULL);
assert(empty == "");
}
int main(int argc, char* argv[])
{
//TODO 在这里添加单元测试,越多越好,代码路径覆盖率越全越好
test1();//"a=1\nb=2\n"
test2();//"a=1||b=2||c=3"
test3();//"||||a:1||b:2||||c:3||||||"
test4();//"str1=this||str2=is||str3=me"
test5();//"a=1&&b=&&c="
test6();//"||||a:1||b:2||||c:||||hello:4" from test.txt
test7();//"a=1&&b=&&c=&&"
test8();//"a=1||b=2||isempty=false"直接通过get获得value
printf("All tests passed!\n");
return 0;
}
|
e80341b600fcf086385f63e302f4e58e02e83cf3
|
9b4f4ad42b82800c65f12ae507d2eece02935ff6
|
/src/Media/TimedImageList.cpp
|
ee2c9a72a39394e1fafb1690d327b9c602b092ad
|
[] |
no_license
|
github188/SClass
|
f5ef01247a8bcf98d64c54ee383cad901adf9630
|
ca1b7efa6181f78d6f01a6129c81f0a9dd80770b
|
refs/heads/main
| 2023-07-03T01:25:53.067293
| 2021-08-06T18:19:22
| 2021-08-06T18:19:22
| 393,572,232
| 0
| 1
| null | 2021-08-07T03:57:17
| 2021-08-07T03:57:16
| null |
UTF-8
|
C++
| false
| false
| 4,203
|
cpp
|
TimedImageList.cpp
|
#include "Stdafx.h"
#include "Data/ByteTool.h"
#include "Media/TimedImageList.h"
void Media::TimedImageList::ScanFile()
{
UInt64 currOfst = 16;
UInt8 indexBuff[32];
this->flags &= ~2;
this->changed = true;
this->fs->SeekFromBeginning(16);
while (this->fs->Read(indexBuff, 32) == 32)
{
if (ReadUInt64(&indexBuff[16]) == currOfst + 32)
{
Int64 imgSize = ReadInt64(&indexBuff[24]);
this->indexStm->Write(indexBuff, 32);
currOfst += 32 + (UInt64)imgSize;
this->fs->SeekFromCurrent(imgSize);
}
else
{
break;
}
}
this->fs->SeekFromBeginning(currOfst);
this->currFileOfst = currOfst;
}
Media::TimedImageList::TimedImageList(const UTF8Char *fileName)
{
UInt8 hdr[16];
NEW_CLASS(this->indexStm, IO::MemoryStream((const UTF8Char*)"Media.TimedImageLIst.indexStm"));
NEW_CLASS(this->fs, IO::FileStream(fileName, IO::FileStream::FILE_MODE_APPEND, IO::FileStream::FILE_SHARE_DENY_NONE, IO::FileStream::BT_NO_WRITE_BUFFER));
if (this->IsError())
{
DEL_CLASS(this->fs);
this->fs = 0;
return;
}
UInt64 fileSize = this->fs->GetLength();
if (fileSize > 0 && fileSize < 16)
{
DEL_CLASS(this->fs);
this->fs = 0;
return;
}
else if (fileSize == 0)
{
hdr[0] = 'S';
hdr[1] = 'T';
hdr[2] = 'i';
hdr[3] = 'l';
WriteInt32(&hdr[4], 0x1);
WriteInt64(&hdr[8], 16);
this->fs->Write(hdr, 16);
this->flags = 1;
this->currFileOfst = 16;
this->changed = false;
}
else
{
this->fs->SeekFromBeginning(0);
this->fs->Read(hdr, 16);
if (hdr[0] != 'S' || hdr[1] != 'T' || hdr[2] != 'i' || hdr[3] != 'l')
{
DEL_CLASS(this->fs);
this->fs = 0;
return;
}
this->flags = ReadInt32(&hdr[4]);
this->currFileOfst = ReadUInt64(&hdr[8]);
if (this->flags & 2)
{
UInt64 indexSize = fileSize - this->currFileOfst;
if (fileSize >= this->currFileOfst && (indexSize & 31) == 0)
{
UInt8 *indexBuff = MemAlloc(UInt8, (UOSInt)indexSize);
this->fs->SeekFromBeginning(this->currFileOfst);
this->fs->Read(indexBuff, (UOSInt)indexSize);
this->indexStm->Write(indexBuff, (UOSInt)indexSize);
MemFree(indexBuff);
this->fs->SeekFromBeginning(this->currFileOfst);
}
else if (this->flags & 1)
{
ScanFile();
}
else
{
this->fs->SeekFromBeginning(16);
this->currFileOfst = 16;
this->changed = true;
}
}
else if (this->flags & 1)
{
ScanFile();
}
else
{
this->fs->SeekFromBeginning(16);
this->currFileOfst = 16;
this->changed = true;
}
}
}
Media::TimedImageList::~TimedImageList()
{
UInt8 hdr[16];
if (this->fs)
{
if (this->changed)
{
UOSInt indexSize;
UInt8 *indexBuff;
indexBuff = this->indexStm->GetBuff(&indexSize);
this->fs->Write(indexBuff, indexSize);
this->fs->SeekFromBeginning(0);
hdr[0] = 'S';
hdr[1] = 'T';
hdr[2] = 'i';
hdr[3] = 'l';
WriteInt32(&hdr[4], this->flags | 2);
WriteUInt64(&hdr[8], this->currFileOfst);
this->fs->Write(hdr, 16);
}
DEL_CLASS(this->fs);
this->fs = 0;
}
DEL_CLASS(this->indexStm);
}
Bool Media::TimedImageList::IsError()
{
return this->fs == 0;
}
Bool Media::TimedImageList::AddImage(Int64 captureTimeTicks, const UInt8 *imgBuff, UOSInt imgSize, ImageFormat imgFmt)
{
UInt8 indexBuff[32];
Bool succ = true;
if (!this->changed)
{
this->fs->SeekFromBeginning(0);
this->flags &= ~2;
indexBuff[0] = 'S';
indexBuff[1] = 'T';
indexBuff[2] = 'i';
indexBuff[3] = 'l';
WriteInt32(&indexBuff[4], this->flags);
WriteUInt64(&indexBuff[8], this->currFileOfst);
this->fs->Write(indexBuff, 16);
this->fs->SeekFromBeginning(this->currFileOfst);
this->changed = true;
}
WriteInt64(&indexBuff[0], captureTimeTicks);
WriteInt32(&indexBuff[8], 0); //flags
WriteInt32(&indexBuff[12], imgFmt);
WriteUInt64(&indexBuff[16], this->currFileOfst + 32);
WriteUInt64(&indexBuff[24], imgSize);
succ = succ && (this->fs->Write(indexBuff, 32) == 32);
this->indexStm->Write(indexBuff, 32);
succ = succ && (this->fs->Write(imgBuff, imgSize) == imgSize);
this->currFileOfst += 32 + imgSize;
return succ;
}
|
3f5994716dc4bcb1f1c30750cce6839b852d9b63
|
62917ce95d514e6404193acfc341bfc0e3e6b5af
|
/src/tools.cpp
|
e882955682f3f5851544cfaf02d03a1219c103cb
|
[] |
no_license
|
ssailer/ExpandingBEC2D
|
7db2756abc6643e9211a238eb56cdbef630fa21d
|
3eb1e5fdda01237fb6c102d46cfad467fb6320b1
|
refs/heads/master
| 2023-07-02T13:55:19.821817
| 2021-08-12T09:46:12
| 2021-08-12T09:46:12
| 51,006,853
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,790
|
cpp
|
tools.cpp
|
#define EIGEN_VECTORIZE
#define EIGEN_NO_DEBUG
#include "tools.h"
void toDimensionlessUnits(Options &opt){
if(!opt.isDimensionless){
const double m = 86.9091835 * 1.660538921 * 1.0e-27;
const double hbar = 1.0545718 * 1.0e-22;
const double epsilon = 0.1;
double a0 = sqrt(hbar / ( m * opt.omega_x.real() * 2.0 * M_PI));
opt.Ag = a0 / (epsilon * epsilon);
// opt.Ag = 2 * opt.min_x / opt.grid[1];
opt.OmegaG = hbar / ( m * opt.Ag * opt.Ag);
cout << currentTime() << " Stabilitycheck in physical units: " << endl;
double h1 = opt.min_x * 2 / opt.grid[1];
cout << "\t grid spacing = " << h1 << endl;
cout << "\t coordinate maximum = " << opt.min_x << endl;
double k1 = 2 * h1 * h1 / (M_PI * M_PI);
cout << "\t timestep < spectral resolution " << opt.RTE_step << " < " << k1 << " ";
if(opt.RTE_step < k1) cout << "Yes." << endl; else cout << "No." << endl;
cout << endl;
opt.min_x /= opt.Ag;
opt.min_y /= opt.Ag;
opt.ITP_step *= opt.OmegaG;
opt.RTE_step *= opt.OmegaG;
opt.omega_x *= 2.0 * M_PI / opt.OmegaG;
opt.omega_y *= 2.0 * M_PI / opt.OmegaG;
opt.omega_w *= 2.0 * M_PI / opt.OmegaG;
opt.dispersion_x *= 2.0 * M_PI / opt.OmegaG;
opt.dispersion_y *= 2.0 * M_PI / opt.OmegaG;
opt.isDimensionless = true;
cout << currentTime() << " Stabilitycheck in dimensionless units: " << endl;
double h = opt.min_x * 2 / opt.grid[1];
cout << "\t grid spacing = " << h << endl;
cout << "\t coordinate maximum = " << opt.min_x << endl;
double k = 2 * h * h / (M_PI * M_PI);
cout << "\t timestep < spectral resolution " << opt.RTE_step << " < " << k << " ";
if(opt.RTE_step < k) cout << "Yes." << endl; else cout << "No." << endl;
cout << endl;
cout << currentTime() << " Set timestep to maximum appropriate value: " << k << endl << endl;
opt.RTE_step = k;
} else {
cerr << " Trying to convert dimensionless Options to dimensionless Options. Check tools.h" << endl;
}
}
void toPhysicalUnits(Options &opt){
if(opt.isDimensionless){
opt.min_x *= opt.Ag;
opt.min_y *= opt.Ag;
opt.ITP_step /= opt.OmegaG;
opt.RTE_step /= opt.OmegaG;
opt.omega_x /= 2.0 * M_PI / opt.OmegaG;
opt.omega_y /= 2.0 * M_PI / opt.OmegaG;
opt.omega_w /= 2.0 * M_PI / opt.OmegaG;
opt.dispersion_x /= 2.0 * M_PI / opt.OmegaG;
opt.dispersion_y /= 2.0 * M_PI / opt.OmegaG;
opt.isDimensionless = false;
} else {
cerr << " Trying to convert non-dimensionless Options to non-dimensionless Options. Check tools.h" << endl;
}
}
|
b6816884574701799a18f30653be0006b267b65b
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_2692487_1/C++/xfighter/mote.cpp
|
d048ab164624d11d5b8748fe4f02a51b8523e48f
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 895
|
cpp
|
mote.cpp
|
#include <iostream>
#include <algorithm>
#include <cassert>
#define INF 100000000
using namespace std;
int M[101];
int WT;
int steps (int x, int N) {
WT = x;
if (N < x) return 0;
if (x == 1) return INF;
int st = 0;
while (x <= N) {
x += (x - 1);
++st;
}
WT = x;
return st;
}
int main () {
int T;
cin >> T;
for (int t = 1; t <= T; ++t) {
int A, N;
cin >> A >> N;
for (int i = 0; i < N; ++i) {
cin >> M[i];
}
sort(M, M + N);
int start_idx = 0;
int ans = N;
int count = 0;
int wt = A;
for (int j = 0; j < N; ++j) {
if (M[j] < wt) {
wt += M[j];
ans = std::min(ans, count + N - j - 1);
continue;
}
int st = steps(wt, M[j]);
count += st;
wt = WT + M[j];
ans = std::min(ans, count + N - j - 1);
}
cout << "Case #" << t << ": " << ans << endl;
}
}
|
7a27c68383ec98603e975b9fac4e3eee2bcaef28
|
4e003d375c712139c87993a9350f958d100365b9
|
/NightLightStudio_Engine/Source/Component/ComponentWayPointMap.h
|
ff9726d3cff0b7686950b257032a23647db863aa
|
[] |
no_license
|
calvin0116/NightLight-Studio
|
e19d72c53758e88ca6df8a4f2a116946d53f1ec6
|
fb77dd7f653847528192e1547e13f58377fc1002
|
refs/heads/master
| 2023-04-11T02:56:44.345964
| 2021-04-27T11:10:24
| 2021-04-27T11:10:24
| 294,657,463
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,878
|
h
|
ComponentWayPointMap.h
|
#pragma once
//#include "../Ai/WayPointManager.h"
#include "..\\..\ISerializable.h"
#include "ComponentWayPoint.h"
#include "../Ai/AiGraph.h"
//Component where it stores the list of way point and produce an map of paths
typedef class ComponentWayPointMap : public ISerializable //: public IComponent
{
LocalVector<WayPointComponent*> cur_path;
LocalVector<NS_AI::Edge*,256> cur_edge;
float rad_for_detect = 25.0f; //Default radius detection
public:
LocalVector<LocalString<DEF_STR_SIZE>> way_point_list; //Standard way point using entity to plot
ComponentWayPointMap()
{
strcpy_s(ser_name, "WayPointMapComponent");
}
void ClearCurPath()
{
cur_path.clear();
}
LocalVector<WayPointComponent*>& GetPath()
{
return cur_path;
}
LocalVector<NS_AI::Edge*, 256>& GetEdge()
{
return cur_edge;
}
//Converts list of entity name to real entity for way point traversing
void InitPath()
{
ClearCurPath();
for (LocalString<DEF_STR_SIZE> & wp_str : way_point_list)
{
if (wp_str.empty())
continue;
Entity ent = G_ECMANAGER->getEntityUsingEntName(wp_str);
if(ent.getId() != -1)
cur_path.push_back(ent.getComponent<WayPointComponent>());
}
}
int WPSize()
{
return (int)way_point_list.size();
}
virtual void Read(Value& val, NS_COMPONENT::ComponentManager::ComponentSetManager* g_ecman = G_ECMANAGER) override
{
g_ecman;
for (Value::ConstMemberIterator itr = val.MemberBegin(); itr != val.MemberEnd(); ++itr)
{
if (itr->name == "way_point_list")
{
auto string_list_val = itr->value.GetArray();
if (way_point_list.size() == 0)
for (unsigned i = 0; i < string_list_val.Size(); ++i)
{
way_point_list.push_back(LocalString(string_list_val[i].GetString()));
//WayPointComponent* wp_comp = G_ECMANAGER->getEntityUsingEntName(way_point_list.back()).getComponent<WayPointComponent>();
//cur_path.push_back(wp_comp);
}
else
for (unsigned i = 0; i < string_list_val.Size(); ++i)
{
way_point_list.at(i) = LocalString(string_list_val[i].GetString());
//cur_path.push_back(G_ECMANAGER->getEntityUsingEntName(way_point_list.at(i)).getComponent<WayPointComponent>());
}
}
if (itr->name == "radius_for_detection")
{
rad_for_detect = itr->value.GetFloat();
}
}
}
virtual Value Write() {
Value val(rapidjson::kObjectType);
Value string_list_val(rapidjson::kArrayType);
for (LocalString<DEF_STR_SIZE> & s : way_point_list)
string_list_val.PushBack(rapidjson::StringRef(s.c_str()), global_alloc);
NS_SERIALISER::ChangeData(&val, "way_point_list", string_list_val);
NS_SERIALISER::ChangeData(&val, "radius_for_detection", rad_for_detect);
return val;
}
virtual ComponentWayPointMap* Clone()
{
ComponentWayPointMap* newCWPM = new ComponentWayPointMap();
*newCWPM = *this;
return newCWPM;
}
} WayPointMapComponent;
|
b647a04df312e11730526be797d76b484cd69f17
|
3ce966f6bead3bf8854dd92539acf4a1ad168054
|
/libqicore-compat/src/behaviorexecuter.cpp
|
61a41925954012238804264d9ec2777165b3007f
|
[] |
no_license
|
gale320/libqicore
|
2a15188d48b67a2265331b48ae6206f655ef7ec6
|
47104d4f932cf4a89e9bd3b1e4b895258b5c59f2
|
refs/heads/master
| 2020-12-14T08:56:09.591864
| 2014-09-23T16:43:46
| 2014-09-23T16:43:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 20,528
|
cpp
|
behaviorexecuter.cpp
|
/**
* @author Aldebaran Robotics
* Aldebaran Robotics (c) 2013 All Rights Reserved
*/
#include <boost/python.hpp>
#include <qicore-compat/model/boxinterfacemodel.hpp>
#include <qicore-compat/model/boxinstancemodel.hpp>
#include <qicore-compat/model/linkmodel.hpp>
#include <qicore-compat/model/contentmodel.hpp>
#include <qicore-compat/model/contentsmodel.hpp>
#include <qicore-compat/model/parametermodel.hpp>
#include <qicore-compat/model/resourcemodel.hpp>
#include <qicore-compat/model/behaviorsequencemodel.hpp>
#include <qicore-compat/model/behaviorlayermodel.hpp>
#include <qicore-compat/model/behaviorkeyframemodel.hpp>
#include <qicore-compat/model/animationmodel.hpp>
#include <qicore-compat/behaviorexecuter.hpp>
#include <qicore-compat/timeline.hpp>
#include <qi/type/objectfactory.hpp>
#include <qi/type/dynamicobject.hpp>
#include <qipython/gil.hpp>
#include "behaviorexecuter_p.hpp"
#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH
#include <qi/log.hpp>
qiLogCategory("QiCore-Compat.BehaviorExecuter");
namespace qi
{
namespace compat
{
typedef std::map<std::string, int> FrameNameKey;
typedef std::map<std::string, qi::AnyObject> ObjectMap;
BehaviorExecuterPrivate::BehaviorExecuterPrivate(const std::string &dir, boost::shared_ptr<Session> session, bool debug) :
_project(dir),
_session(session),
_debug(debug),
_running(0)
{
std::stringstream p;
p << _session->url().port();
_pythonCreator = PythonBoxLoader();
_pythonCreator.initPython(session->url().host(), p.str(), dir, _session);
_behaviorService = session->service("BehaviorService").value().call<qi::AnyObject>("create");
_behaviorServiceId = _session->registerService("Behavior", _behaviorService);
_behaviorService.connect("onTaskError",
boost::function<void(const std::string&, const std::string&)>(
boost::bind(&BehaviorExecuterPrivate::onFailed, this, _1, _2)));
_alresourcemanager = session->service("ALResourceManager");
_almotion = session->service("ALMotion");
_almemory = session->service("ALMemory");
}
BehaviorExecuterPrivate::~BehaviorExecuterPrivate()
{
_session->unregisterService(_behaviorServiceId);
{
py::GILScopedLock l;
_timelines.clear();
_behaviorService = qi::AnyObject();
_alresourcemanager = qi::AnyObject();
_almotion = qi::AnyObject();
_almemory = qi::AnyObject();
}
_pythonCreator.terminate();
}
bool BehaviorExecuterPrivate::declaredBox(BoxInstanceModelPtr instance)
{
//If FlowDiagram
qi::AnyReference diagram = instance->content(ContentModel::ContentType_FlowDiagram);
if(diagram.isValid())
if(!loadFlowDiagram(diagram.ptr<FlowDiagramModel>()))
return false;
//If behaviorSequence
diagram = instance->content(ContentModel::ContentType_BehaviorSequence);
if(diagram.isValid())
if(!loadBehaviorSequence(diagram.ptr<BehaviorSequenceModel>()))
return false;
//Box no script or python box is same
return declaredPythonBox(instance);
}
bool BehaviorExecuterPrivate::declaredPythonBox(BoxInstanceModelPtr instance)
{
return _pythonCreator.registerPythonClass(instance);
}
bool BehaviorExecuterPrivate::loadBehaviorSequence(BehaviorSequenceModel *behaviorSequence)
{
const std::list<BehaviorLayerModelPtr> &layers = behaviorSequence->behaviorsLayer();
foreach(BehaviorLayerModelPtr layer, layers)
{
const std::list<BehaviorKeyFrameModelPtr> &keys = layer->behaviorsKeyFrame();
foreach(BehaviorKeyFrameModelPtr key, keys)
{
if(!loadFlowDiagram(key->diagram().get(), true, key->index(), key->name()))
return false;
}
}
return true;
}
bool BehaviorExecuterPrivate::loadFlowDiagram(FlowDiagramModel *diagram,
bool behaviorsequence,
int index,
const std::string &prefix)
{
//Construct a ControlFlow
if(behaviorsequence)
{
qi::BehaviorModel::Node n;
std::stringstream sindex;
sindex << index;
n.uid = diagram->findInstance(0)->uid() + "_controlflowdiagram_" + sindex.str();
n.factory = "ControlFlowdiagram";
n.interface = "";//not use
n.parameters["delay"] = qi::AnyValue(index);
_model.nodes[n.uid] = n;
}
//Loading box
BoxInstanceModelMap instances = diagram->boxsInstance();
foreach(BoxInstanceModelMap::value_type &val, instances)
{
BoxInstanceModelPtr instance = val.second;
if(!prefix.empty())
instance->setName(prefix + "_" + instance->name());
instance->setName(diagram->findInstance(0)->uid() + "_" + instance->name());
if(!declaredBox(instance))
return false;
qi::BehaviorModel::Node node;
node.uid = instance->uid();
node.factory = instance->uid();
node.interface = "";//not use
foreach(const boost::shared_ptr<ParameterModel>& param, instance->interface()->parameters())
node.parameters[param->metaProperty().name()] = param->defaultValue();
_model.nodes[node.uid] = node;
}
//Linking box
std::list<LinkModelPtr> links = diagram->links();
foreach(LinkModelPtr link, links)
{
int srcid = link->outputTowner();
int signalid = link->indexOfOutput();
int dstid = link->inputTowner();
int methodid = link->indexOfInput();
BoxInstanceModelPtr src = diagram->findInstance(srcid);
BoxInstanceModelPtr dst = diagram->findInstance(dstid);
std::string signal = src->interface()->findSignal(signalid);
if(signal.empty())
{
qiLogError() << "One of the output signal does not exist: " << signalid;
return false;
}
std::string method = dst->interface()->findMethod(methodid);
if(method.empty())
{
boost::shared_ptr<qi::ParameterModel> param = dst->interface()->findParameter(methodid);
if (param)
{
qiLogDebug() << methodid << " recognized as a parameter";
method = param->metaProperty().name();
}
else
{
qiLogError() << "One of the input method/property does not exist: " << methodid;
return false;
}
}
//If signalid is STM input
const InputModelMap &inputs = src->interface()->inputs();
InputModelMap::const_iterator it = inputs.find(methodid);
if( it != inputs.end())
{
InputModelPtr input = it->second;
if( input->nature() == InputModel::InputNature_STMValue)
{
//Connect QiCoreMemoryWatcher.almemoryEvent to srcid.handleSTM
qi::BehaviorModel::Transition tEvent;
tEvent.src = BehaviorModel::Slot("QiCoreMemoryWatcher", "almemoryEvent");
tEvent.dst = BehaviorModel::Slot(src->uid(), "handleSTM");
addTransition(tEvent);
//add STMValue in the subscriber list
_stmvalues.push_back(input->stmValueName());
}
}
//If srcid == 0 (srcid is the parent object) and this flowdiagram is part of behavior sequence
//then connect this flowdiagram with ControlFlowdiagram
if(srcid == 0 && behaviorsequence)
{
qi::BehaviorModel::Transition tStart;
std::stringstream sindex;
sindex << index;
tStart.src = BehaviorModel::Slot(src->uid() + "_controlflowdiagram_" + sindex.str(),
"startFlowdiagram");
tStart.dst = BehaviorModel::Slot(dst->uid(), method);
addTransition(tStart);
}
else
{
qi::BehaviorModel::Transition t;
t.src = BehaviorModel::Slot(src->uid(), signal);
t.dst = BehaviorModel::Slot(dst->uid(), method);
addTransition(t);
}
}
return true;
}
void BehaviorExecuterPrivate::addTransition(BehaviorModel::Transition &t)
{
static int i = 0;
std::stringstream ii;
ii << i;
t.uid = t.src.first + t.dst.first + ii.str();
i++;
_model.transitions[t.uid] = t;
qiLogDebug() << t.toString();
}
void BehaviorExecuterPrivate::initialiseBox(BoxInstanceModelPtr instance, qi::AnyObject timeline, bool rootBox)
{
//If FlowDiagram
qi::AnyReference diagram = instance->content(ContentModel::ContentType_FlowDiagram);
if(diagram.isValid())
initialiseFlowDiagram(diagram.ptr<FlowDiagramModel>(), timeline);
std::map<std::string, int> frames;
//If animation
qi::AnyReference behaviorAnimation = instance->content(ContentModel::ContentType_Animation);
if(behaviorAnimation.isValid())
{
qi::AnyObject timeline;
qi::Timeline* t = new qi::Timeline(_almotion);
timeline = qi::AnyReference::fromPtr(t).toObject();
timeline.call<void>("setAnimation",
behaviorAnimation.ptr<AnimationModel>());
_timelines[instance->uid()] = timeline;
}
//If behaviorSequence
qi::AnyReference behaviorSequence = instance->content(ContentModel::ContentType_BehaviorSequence);
if(behaviorSequence.isValid())
{
frames = initialiseBehaviorSequence(behaviorSequence.ptr<BehaviorSequenceModel>(), instance->uid());
}
//Set Parameter (todo parameter -> property)
std::list<ParameterModelPtr> parameters = instance->interface()->parameters();
foreach (ParameterModelPtr parameter, parameters) {
std::string name = parameter->metaProperty().name();
qi::AnyReference value = instance->parameter(parameter->metaProperty().uid());
std::vector<qi::AnyValue> param;
param.push_back(qi::AnyValue(name));
param.push_back(qi::AnyValue(value));
_behaviorService.call<void>("call", instance->uid(), "setParameter", param);
}
if(instance->interface()->hasResource())
{
std::list<ResourceModelPtr> resources = instance->interface()->resources();
std::vector<std::string> resourcesName;
foreach (ResourceModelPtr resource, resources) {
resourcesName.push_back(resource->name());
}
_alresourcemanager.call<void>("createResource",
_behaviorService.call<std::string>("call",
instance->uid(),
"getName",
std::vector<qi::AnyValue>()).value(),
"");
_alresourcemanager.call<void>("createResourcesList",
resourcesName,
_behaviorService.call<std::string>("call",
instance->uid(),
"getName",
std::vector<qi::AnyValue>()).value());
}
if(instance->interface()->hasTimeline())
{
qi::AnyObject timeline = _timelines[instance->uid()];
std::vector<qi::AnyValue> args;
args.push_back(qi::AnyValue(timeline));
args.push_back(qi::AnyValue(frames));
std::map<int, std::string> framesKey;
if(!frames.empty())
{
foreach(FrameNameKey::value_type &val, frames)
{
framesKey[val.second] = val.first;
}
}
timeline.call<void>("setFrames", framesKey);
timeline.call<void>("setFrameNames", frames);
_behaviorService.call<void>("call", instance->uid(), "setTimeline", args);
}
if(timeline)
{
std::vector<qi::AnyObject> args;
args.push_back(timeline);
_behaviorService.call<void>("call", instance->uid(), "setParentTimeline", args);
}
if (!_behaviorService.call<bool>("call", instance->uid(), "__onLoad__", std::vector<qi::AnyValue>()))
throw std::runtime_error("A box failed onLoad");
// connect to end output to know when the behavior is finished
if (rootBox)
{
boost::shared_ptr<BoxInterfaceModel> interface = instance->interface();
const std::map<int, boost::shared_ptr<OutputModel> >& outputs = interface->outputs();
for (std::map<int, boost::shared_ptr<OutputModel> >::const_iterator
iter = outputs.begin();
iter != outputs.end();
++iter)
{
// We suppose the object returned by behaviorService is always local
_behaviorService.call<AnyObject>("object", instance->uid()).value().connect(iter->second->metaSignal().name() + "Signal", boost::function<void(AnyValue)>(boost::bind(&BehaviorExecuterPrivate::onFinished, this, _1)));
}
}
}
void BehaviorExecuterPrivate::onFinished(AnyValue v)
{
_finished.setValue(0);
}
void BehaviorExecuterPrivate::onFailed(const std::string& box, const std::string& error)
{
_finished.setValue(0);
}
void BehaviorExecuterPrivate::connect(qi::AnyObject src,
qi::AnyObject dst,
const std::string &signal,
const std::string &method)
{
std::vector<qi::MetaMethod> methods = dst.metaObject().findMethod(method);
const qi::MetaSignal* sig = src.metaObject().signal(signal);
qi::Signature sigS = sig->parametersSignature();
float bestScore = 0.0;
unsigned best;
for(unsigned d = 0; d<methods.size(); d++)
{
qi::Signature sigD = methods[d].parametersSignature();
float score = sigS.isConvertibleTo(sigD);
if(score > bestScore)
{
bestScore = score;
best = d;
}
}
if(bestScore == 0)
throw std::runtime_error("Could not connect src." + signal + "with dst." + method);
src.connect(signal, qi::SignalSubscriber(dst, methods[best].uid()));
}
std::map<std::string, int> BehaviorExecuterPrivate::initialiseBehaviorSequence(BehaviorSequenceModel* seq,
const std::string &uid)
{
std::map<std::string, qi::AnyObject>::iterator it = _timelines.find(uid);
qi::AnyObject timeline;
if( it != _timelines.end())
timeline = it->second;
else
{
//create timeline
timeline = qi::AnyReference::fromPtr(new qi::Timeline(_almotion)).toObject();
_timelines[uid] = timeline;
}
std::map<std::string, int> ret;
const std::list<BehaviorLayerModelPtr> &layers = seq->behaviorsLayer();
foreach(BehaviorLayerModelPtr layer, layers)
{
const std::list<BehaviorKeyFrameModelPtr> &frames = layer->behaviorsKeyFrame();
foreach(BehaviorKeyFrameModelPtr key, frames)
{
ret[key->name()] = key->index();
//Connect timeline with ControlFlowdiagram
BoxInstanceModelPtr parent = key->diagram()->findInstance(0);
std::stringstream sindex;
sindex << key->index();
std::string uid = parent->uid() + "_controlflowdiagram_" + sindex.str();
ObjectMap objects = _behaviorService.call<ObjectMap>("objects");
qi::AnyObject boxdelay = objects[uid];
connect(timeline, boxdelay, "startFlowdiagram", "startDelay");
connect(timeline, boxdelay, "stopFlowdiagram", "stop");
//Load flowdiagram
initialiseFlowDiagram(key->diagram().get(), timeline);
}
}
return ret;
}
void BehaviorExecuterPrivate::initialiseFlowDiagram(FlowDiagramModel* diagram, qi::AnyObject timeline)
{
BoxInstanceModelMap instances = diagram->boxsInstance();
foreach(BoxInstanceModelMap::value_type &instance, instances)
{
initialiseBox(instance.second, timeline);
}
}
BehaviorExecuter::BehaviorExecuter(const std::string &dir, boost::shared_ptr<Session> session, bool debug)
: _p(new BehaviorExecuterPrivate(dir, session, debug))
{
}
BehaviorExecuter::~BehaviorExecuter()
{
delete _p;
}
void BehaviorExecuter::execute()
{
if (!_p->_running.setIfEquals(0, 1))
{
qiLogError() << "Cannot execute behavior, already running";
return;
}
//Search start input
BoxInstanceModelPtr root = _p->_project.rootBox();
std::string inputStart = root->interface()->findInput(InputModel::InputNature_OnStart);
if(inputStart.empty()) {
qiLogError() << "OnStart input not found, impossible to launch behavior.";
return;
}
qiLogDebug() << "Start Behavior " << root->behaviorPath();
std::vector<qi::AnyValue> args;
args.push_back(qi::AnyValue("args"));
_p->_finished = qi::Promise<void>();
_p->_behaviorService.call<void>("call", root->uid(), inputStart, args);
if(!_p->_timelines.empty())
{
foreach(TimlineMap::value_type &val, _p->_timelines)
{
val.second.call<void>("waitForTimelineCompletion");
}
}
_p->_finished.future().wait();
qiLogDebug() << "Behavior " << root->behaviorPath() << " finished";
ObjectMap objects = _p->_behaviorService.call<ObjectMap>("objects");
foreach(ObjectMap::value_type const &val, objects)
{
qi::AnyObject o = val.second;
o.call<void>("__onUnload__");
}
_p->_running = 0;
}
bool BehaviorExecuter::load()
{
if(!_p->_project.loadFromFile())
{
qiLogError() << "Failed to load project from file";
return false;
}
BoxInstanceModelPtr root = _p->_project.rootBox();
if(!root)
{
qiLogError() << "No root box";
return false;
}
//Register root box
BehaviorModel::Node node;
node.uid = root->uid();
node.factory = root->uid();
node.interface = "";//not use
_p->_model.nodes[node.uid] = node;
//Register QiCoreMemoryWatcher
BehaviorModel::Node nodeal;
nodeal.uid = "QiCoreMemoryWatcher";
nodeal.factory = "QiCoreMemoryWatcher";
nodeal.interface = "";
_p->_model.nodes[nodeal.uid] = nodeal;
if(!_p->declaredBox(root))
{
qiLogError() << "Failed to declare root box";
return false;
}
try {
_p->_behaviorService.call<void>("setModel", _p->_model);
_p->_behaviorService.call<void>("loadObjects", _p->_debug);
_p->_behaviorService.call<void>("setTransitions", _p->_debug, (int)qi::MetaCallType_Direct);
} catch (std::exception& e) {
qiLogError() << "A box failed to load: " << e.what();
return false;
}
//QiCoreMemoryWatcher set watching value
ObjectMap objects = _p->_behaviorService.call<ObjectMap>("objects");
qi::AnyObject qiCoreMemoryWatcher = objects["QiCoreMemoryWatcher"];
foreach(std::string const &s, _p->_stmvalues)
{
qiCoreMemoryWatcher.call<void>("subscribe", s);
}
try {
_p->initialiseBox(root, qi::AnyObject(), true);
} catch (std::exception& e) {
qiLogError() << "Failed to initialise boxes: " << e.what();
return false;
}
//Set ObjectThreadingModel to prevent deadlock.
//Infact, A.method trigger A.signal (so A is locked)
// B.method is a callback of A.signal and B.method trigger B.signal
// A.method2 is a callback of B.signal but A is already lock so deadlock
foreach(ObjectMap::value_type const &val, objects)
{
qi::AnyObject obj = val.second;
DynamicObject* dynamic = reinterpret_cast<DynamicObject*>(obj.asGenericObject()->value);
dynamic->setThreadingModel(ObjectThreadingModel_MultiThread);
}
return true;
}
}
}
|
c70053e7c2da1cf1adad90f65ddaccf435d1007e
|
59abad66e06665e3b58e8400bf94bb4b82adb87e
|
/FODRobot2015/src/Commands/PneumaticsAuto.cpp
|
83bd565ff16ea1c7d0554cbfc87538a1fd53a766
|
[] |
no_license
|
thedarknebula/2015code
|
a15aeb29a4be0b1175abb16986bbf8c6b771c2e2
|
55b95eb5124fa495bb81d2c24b8738fbf49c3c6f
|
refs/heads/master
| 2021-04-30T18:03:09.745992
| 2015-03-07T19:00:54
| 2015-03-07T19:00:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,206
|
cpp
|
PneumaticsAuto.cpp
|
#include <Commands/PneumaticsAuto.h>
PneumaticsAuto::PneumaticsAuto(bool left, bool right, bool oc)
{
// Use Requires() here to declare subsystem dependencies
Requires(Robot::gripperArm);
time_timer = 0;
time_run = PNEUMATIC_DELAY;
timer = new Timer();
PneumaticsDone = false;
leftArm = left;
rightArm = right;
open_close = oc;
printf("PneumaticsAuto const\n");
}
// Called just before this Command runs the first time
void PneumaticsAuto::Initialize()
{
printf("PneumaticsAuto init\n");
time_timer = 0;
time_run = PNEUMATIC_DELAY;
timer->Reset();
timer->Start();
PneumaticsDone = false;
}
// Called repeatedly when this Command is scheduled to run
void PneumaticsAuto::Execute()
{
printf("PneumaticsAuto execute\n");
time_timer = timer->Get();
if(time_timer >= time_run)
{
PneumaticsDone = true;
printf("time_timer >= time_run");
}
else
{
PneumaticsDone = false;
}
if(open_close == true)
{
printf("open_close = true\n");
if(leftArm == true)
{
Robot::gripperArm->leftGripper->Set(Robot::gripperArm->leftGripper->kForward);
printf("leftArm = true\n");
}
if(rightArm == true)
{
Robot::gripperArm->rightGripper->Set(Robot::gripperArm->rightGripper->kForward);
printf("rightArm = true\n");
}
}
if(open_close == false)
{
if(leftArm == true)
{
Robot::gripperArm->leftGripper->Set(Robot::gripperArm->leftGripper->kReverse);
printf("open left arm\n");
}
if(rightArm == true)
{
Robot::gripperArm->rightGripper->Set(Robot::gripperArm->rightGripper->kReverse);
printf("open right arm\n");
}
}
//printf("PnuematicsDone = %d", PneumaticsDone);
}
// Make this return true when this Command no longer needs to run execute()
bool PneumaticsAuto::IsFinished()
{
printf("PneumaticsAuto isFinished\n");
return PneumaticsDone;
}
// Called once after isFinished returns true
void PneumaticsAuto::End()
{
printf("PneumaticsAuto end\n");
timer->Stop();
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void PneumaticsAuto::Interrupted()
{
printf("PneumaticsAuto interuppted\n");
}
|
d2d20fe82ea071a361b9b016c049e808c737f954
|
c8a3f2f6f7eda6369a5c13f637a333be865a838c
|
/fsm_share/fsm_cpp_in_practice/jump_cpp/view/common/ShareToIntenet.cpp
|
3a5690cffd0935c1bc5d8f76692b87164c4673ce
|
[] |
no_license
|
PenpenLi/tools_script
|
e3a73775bb2b19fb13b7d15dce5d47c38566c6ca
|
8f0fce77799e4598ff00d408083597a306f8e22e
|
refs/heads/master
| 2021-06-07T22:38:17.214344
| 2016-11-21T02:10:50
| 2016-11-21T02:10:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,169
|
cpp
|
ShareToIntenet.cpp
|
//
// ShareToIntenet.cpp
// HiFly
//
// Created by Artuira on 14-7-16.
//
//
#include "ShareToIntenet.h"
#include "C2DXShareSDK.h"
#include "TextFloatLabelLayer.h"
USING_NS_CC;
using namespace cn::sharesdk;
ShareToIntenet* g_ShareToIntenet = nullptr;
ShareToIntenet* ShareToIntenet::getInstance()
{
if (nullptr == g_ShareToIntenet)
{
g_ShareToIntenet = new ShareToIntenet();
if (!g_ShareToIntenet->init())
{
g_ShareToIntenet = nullptr;
}
}
return g_ShareToIntenet;
}
bool ShareToIntenet::init()
{
if (LayerColor::init())
{
return true;
}
return false;
}
void authResultHandler(C2DXResponseState state, C2DXPlatType platType, CCDictionary *error)
{
switch (state) {
case C2DXResponseStateSuccess:
CCLog("授权成功");
break;
case C2DXResponseStateFail:
CCLog("授权失败");
break;
default:
break;
}
}
void getUserResultHandler(C2DXResponseState state, C2DXPlatType platType, CCDictionary *userInfo, CCDictionary *error)
{
if (state == C2DXResponseStateSuccess)
{
//输出用户信息
try
{
CCArray *allKeys = userInfo -> allKeys();
allKeys->retain();
for (int i = 0; i < allKeys -> count(); i++)
{
CCString *key = (CCString *)allKeys -> objectAtIndex(i);
CCObject *obj = userInfo -> objectForKey(key -> getCString());
CCLog("key = %s", key -> getCString());
if (dynamic_cast<CCString *>(obj))
{
CCLog("value = %s", dynamic_cast<CCString *>(obj) -> getCString());
}
else if (dynamic_cast<CCInteger *>(obj))
{
CCLog("value = %d", dynamic_cast<CCInteger *>(obj) -> getValue());
}
else if (dynamic_cast<CCDouble *>(obj))
{
CCLog("value = %f", dynamic_cast<CCDouble *>(obj) -> getValue());
}
}
allKeys->release();
}
catch(...)
{
CCLog("==============error");
}
}
}
void shareResultHandler(C2DXResponseState state, C2DXPlatType platType, CCDictionary *shareInfo, CCDictionary *error)
{
switch (state) {
case C2DXResponseStateSuccess:
TextFloatLabelLayer::getInstance()->show("分享成功!");
break;
case C2DXResponseStateFail:
{
TextFloatLabelLayer::getInstance()->show("分享失败!");
log("%s",error->objectForKey("errorDescription"));
}
break;
default:
break;
}
}
void ShareToIntenet::showShareBox()
{
TextFloatLabelLayer::getInstance()->show("分享功能暂未开放,敬请期待!");
return;
/*
CCDictionary *content = CCDictionary::create();
content -> setObject(CCString::create("这是一条测试内容"), "content");
content -> setObject(CCString::create("http://img0.bdstatic.com/img/image/shouye/systsy-11927417755.jpg"), "image");
content -> setObject(CCString::create("测试标题"), "title");
content -> setObject(CCString::create("测试描述"), "description");
content -> setObject(CCString::create("http://www.zhijianyou.com.cn"), "url");
content -> setObject(CCString::createWithFormat("%d", C2DXContentTypeNews), "type");
content -> setObject(CCString::create("http://www.zhijianyou.com.cn"), "siteUrl");
content -> setObject(CCString::create("ShareSDK"), "site");
content -> setObject(CCString::create("extInfo"), "extInfo");
C2DXShareSDK::showShareMenu(NULL, content, Point(100, 100), C2DXMenuArrowDirectionLeft, shareResultHandler);
*/
//我在这个萌萌哒游戏里获得了高分,小伙伴们一起来啊!
//我在这款炒鸡萌的游戏中又获胜了,不服?来战!
//我要让全世界知道,今年最清新的游戏被它承包了。不信来看看啊
float type = CCRANDOM_0_1()*3;
std::string title;
int number = (int)type;
if (number == 0) {
title = "我在这个萌萌哒游戏里获得了高分,小伙伴们一起来啊!";
}
else if (number == 1)
{
title = "我在这款炒鸡萌的游戏中又获胜了,不服?来战!";
}
else if (number == 2)
{
title = "我要让全世界知道,今年最清新的游戏被它承包了。不信来看看啊";
}
else
{
title = "我要让全世界知道,今年最清新的游戏被它承包了。不信来看看啊";
}
std::string tt = "我在《海马去哪儿》里邀请你来玩~";
CCDictionary *content = CCDictionary::create();
content -> setObject(CCString::create(title.c_str()), "content");
content -> setObject(CCString::create("http://115.29.194.242:8000/haima.png"), "image");
content -> setObject(CCString::create(tt.c_str()), "title");
content -> setObject(CCString::create("海马去哪儿"), "description");
content -> setObject(CCString::create("http://www.zhijianyou.com.cn"), "url");
content -> setObject(CCString::createWithFormat("%d", C2DXContentTypeNews), "type");
content -> setObject(CCString::create("http://www.zhijianyou.com.cn"), "siteUrl");
content -> setObject(CCString::create("zhijianyou"), "site");
content -> setObject(CCString::create("extInfo"), "extInfo");
auto plats = CCArray::create();
auto weixin = CCInteger::create(C2DXPlatTypeWeixiSession);
auto pengyouq = CCInteger::create(C2DXPlatTypeWeixiTimeline);
plats->addObject(weixin);
plats->addObject(pengyouq);
C2DXShareSDK::showShareMenu(plats, content, CCPointMake(100, 100), C2DXMenuArrowDirectionLeft, shareResultHandler);
//C2DXShareSDK::showShareView(C2DXPlatTypeWeixiSession, content, shareResultHandler);
//C2DXShareSDK::showShareView(C2DXPlatTypeWeixiTimeline, content, shareResultHandler);
}
|
edc4fa327e3742fa10e2fb1b741601721d537e8a
|
80b10a9a27c4db09ea6659be03e9bf7b12e80255
|
/uva/10935.cpp
|
5bede40dae3f9319db3a1d19996d449a49e69489
|
[] |
no_license
|
HhTtLllL/algorithm
|
e1d777672dc8abdac9207ed7ea4b17a4efcbe9f3
|
4e331cb6dd15d9a6b8ff6ce6b61fa3887a05f9f8
|
refs/heads/master
| 2021-09-06T20:50:24.157469
| 2021-08-11T11:49:41
| 2021-08-11T11:49:41
| 203,563,187
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 374
|
cpp
|
10935.cpp
|
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
queue<int> q;
int main()
{
int n;
while(cin >> n && n)
{
while(!q.empty()) q.pop();
for(int i = 1;i <= n;i++) q.push(i);
while(q.size() != 1)
{
cout << q.front() << " ";
q.pop();
int temp = q.front();
q.pop();
q.push(temp);
}
cout << endl << q.front() << endl;
}
}
|
8b79b69526f7801ee5983cc468915ef57ef277f0
|
8d705d8d3fb123cc4ec7e84e52821c5c1883d380
|
/ICPC.Regional.Preliminary/2008.Hefei.Preliminary/poj3697.cpp
|
8bf3199e3fe1234e0703dbe3e047fedb94363da7
|
[] |
no_license
|
ailyanlu1/ACM-ICPC-OJ-Code
|
446ceff5ad94d64391ce4d86bb706023323cb1f1
|
344b2c92f75b428d0241ba732c43de780d08df40
|
refs/heads/master
| 2020-03-22T21:09:01.656511
| 2015-03-11T00:10:27
| 2015-03-11T00:10:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 972
|
cpp
|
poj3697.cpp
|
// 2008 Hefei Preliminary: USTC campus network
// POJ 3697
#include <cstdio>
#include <vector>
#include <cstring>
#define N 10006
using namespace std;
int used[N];
vector<int> G[N];
int solve(int n) {
vector<int> v;
int i, j, ans = 0, nt;
v.push_back(1);
used[1] = 1;
while (1) {
int notgo[N];
for (i = 0; i <= n; i++)
notgo[i] = 0;
for (i = 0; i < v.size(); i++)
for (j = 0; j < G[v[i]].size(); j++)
notgo[G[v[i]][j]]++;
nt = v.size();
v.clear();
for (i = 1; i <= n; i++)
if (!used[i] && notgo[i] != nt)
used[i] = 1, v.push_back(i), ans++;
if (v.size() == 0)
return ans;
}
}
int main() {
int T = 0, i, a, b, m, n;
while (scanf("%d%d", &n, &m) && n) {
memset(used, 0, sizeof(used));
for (i = 0; i <= n; i++)
G[i].clear();
for (i = 0; i < m; i++) {
scanf("%d%d", &a, &b);
G[a].push_back(b), G[b].push_back(a);
}
printf("Case %d: %d\n", ++T, solve(n));
}
return 0;
}
|
d1f6ff82b3b8f5ac9a664826bc00954ace6f7861
|
62015a8056c46f16adbb885cdcbe4553c4e2c231
|
/Engine/core/inc/itpmath.h
|
c72d0ef8568565594ee495eb08635989d23644c0
|
[] |
no_license
|
bejado/Bengine
|
6e61e8131dc033eab0cc14040f1bf75b1c6abee0
|
07cfa2e344203772e99320d6f2a6f00a815b9ff4
|
refs/heads/master
| 2020-12-21T05:02:33.940907
| 2016-08-07T03:38:14
| 2016-08-07T03:38:14
| 56,739,193
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,207
|
h
|
itpmath.h
|
// math.h will tell our engine whether or not to use the SIMD library
#ifndef _MATH_H_
#define _MATH_H_
#include "fastmath.h"
namespace BNG
{
typedef FastVector3 Vector3;
typedef FastMatrix4 Matrix4;
typedef FastQuaternion Quaternion;
}
namespace BNG
{
//helper operator overloads to make using library not terrible. the clunkyness will all be optimized away...
__forceinline Vector3 operator+( const Vector3& inA, const Vector3& inB )
{
Vector3 toRet = inA;
toRet.Add( inB );
return toRet;
}
__forceinline Vector3 operator-( const Vector3& inA, const Vector3& inB )
{
Vector3 toRet = inA;
toRet.Sub( inB );
return toRet;
}
__forceinline Vector3 operator*( const Vector3& inA, const float inB )
{
Vector3 toRet = inA;
toRet.Multiply( inB );
return toRet;
}
__forceinline Vector3 operator*( const float inA, const Vector3& inB )
{
return operator*( inB, inA );
}
__forceinline Vector3 Dot( const Vector3& inA, const Vector3& inB )
{
Vector3 toRet = inA;
toRet.Dot( inB );
return toRet;
}
inline float RandomFloat(float LO, float HI)
{
return LO + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (HI - LO)));
}
}
#endif // _MATH_H_
|
791bf914a898a545867d65717b9388de54407583
|
2079c0bae0fd7289941b0825c0b3b93b87a02795
|
/Source/System.cpp
|
0a20d3629e4d078058bf480688df1ebe68ff747e
|
[] |
no_license
|
spacejumpunreal/Demo18
|
91bf7886ea51914f8f1fcdb0c1165c6d53d48d15
|
bf894714c11b29c2d600e3cfc6a30e62bdca5880
|
refs/heads/master
| 2021-04-27T04:54:01.417009
| 2018-02-24T01:37:06
| 2018-02-24T01:37:06
| 122,588,122
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,015
|
cpp
|
System.cpp
|
#include "Demo18.h"
#include "System.h"
#include "Time.h"
#include "Utils.h"
#include "Debug.h"
#include "TickModule.h"
#include "InputModule.h"
#include "TestMainModule.h"
#include "WindowModule.h"
#include "FileModule.h"
#include "RendererModule.h"
#include "RenderDeviceModule.h"
#define ADD_MODULE(TYPE)\
{\
auto m = Create##TYPE##Module();\
mModules.emplace_back(m);\
mName2Module[#TYPE] = m;\
}
#define ADD_MODULE2(TYPENAME, INSTANCE)\
{\
mModules.emplace_back(INSTANCE);\
mName2Module[#TYPENAME] = (INSTANCE);\
}
namespace Demo18
{
System* GSystem = nullptr;
struct System::SystemImp
{
SystemImp()
: mFrameDuration(1.0f / 60)
{
ADD_MODULE(File);
ADD_MODULE(Tick);
ADD_MODULE(Window);
ADD_MODULE(Input);
ADD_MODULE(Renderer);
ADD_MODULE(RenderDevice);
ADD_MODULE(TestMain);
}
void Initialize()
{
for (auto m : mModules)
{
m->InitializeModule();
}
for (auto m : mModules)
{
m->Start();
}
}
IModule* GetModule(const char* name)
{
return mName2Module[name];
}
void SetFPS(float fps) { mFrameDuration = 1.0f / fps; }
void Loop()
{
auto tickModule = static_cast<TickModule*>(mName2Module["Tick"]);
while (true)
{
auto t = TimeStamp::Now();
tickModule->Execute();
auto dt = TimeStamp::Now() - t;
auto dtsec = dt.ToSeconds();
auto dursec = mFrameDuration.ToSeconds();
auto d = mFrameDuration - dt;
auto sec = d.ToSeconds();
if (sec > 0)
Sleep(d);
}
}
protected:
std::vector<IModule*> mModules;
std::unordered_map<const char*, IModule*> mName2Module;
TimeDuration mFrameDuration;
};
System::System()
: mImp(new System::SystemImp())
{
Check(GSystem == nullptr, "initialize once");
GSystem = this;
}
void System::Initialize()
{
mImp->Initialize();
}
IModule * System::GetModule(const char * name)
{
return mImp->GetModule(name);
}
void System::SetFPS(float fps)
{
mImp->SetFPS(fps);
}
void System::Loop()
{
mImp->Loop();
}
}
|
16611c55365b98883923997f4cc83e8b0a6de9ea
|
91a882547e393d4c4946a6c2c99186b5f72122dd
|
/Source/XPSP1/NT/termsrv/admtools/winutils/tsadmin/badsrvvw.h
|
0cb462f46a60dcf2965d12631027631bbe77081a
|
[] |
no_license
|
IAmAnubhavSaini/cryptoAlgorithm-nt5src
|
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
|
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
|
refs/heads/master
| 2023-09-02T10:14:14.795579
| 2021-11-20T13:47:06
| 2021-11-20T13:47:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,680
|
h
|
badsrvvw.h
|
/*******************************************************************************
*
* badsrvvw.h
*
* declarations for the CBadServerView class
*
* copyright notice: Copyright 1997, Citrix Systems Inc.
* Copyright (c) 1998 - 1999 Microsoft Corporation
*
* $Author: butchd $ Don Messerli
*
* $Log: M:\NT\PRIVATE\UTILS\CITRIX\WINUTILS\WINADMIN\VCS\BADSRVVW.H $
*
* Rev 1.0 30 Jul 1997 17:11:00 butchd
* Initial revision.
*
*******************************************************************************/
/////////////////////////////////////////////////////////////////////////////
// CBadServerView form view
#ifndef __AFXEXT_H__
#include <afxext.h>
#endif
class CBadServerView : public CFormView
{
friend class CRightPane;
protected:
CBadServerView(); // protected constructor used by dynamic creation
DECLARE_DYNCREATE(CBadServerView)
// Form Data
public:
//{{AFX_DATA(CBadServerView)
enum { IDD = IDD_BAD_SERVER };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CBadServerView)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
virtual ~CBadServerView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
//{{AFX_MSG(CBadServerView)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
|
dd857917b2d3ceaef9a0ef4876c28e854c0eab7b
|
acbd77a818e640177187c594eac26cc744d0a296
|
/02-线性结构2 一元多项式的乘法与加法运算 (20分).cpp
|
13479d3e7bd997a6f5f7aed0aeb9bd3f49953317
|
[
"MIT"
] |
permissive
|
Wodnerstruck/Data-Structure
|
549cc8bba0182ca5e4fd7fc13a3fd4cb89c30d0c
|
8022dbeda1743005f26685c5b08e761fe34f32f2
|
refs/heads/master
| 2021-02-11T00:26:10.908117
| 2020-04-20T14:50:11
| 2020-04-20T14:50:11
| 244,433,361
| 0
| 0
| null | 2020-03-10T12:23:32
| 2020-03-02T17:33:07
|
C++
|
UTF-8
|
C++
| false
| false
| 3,619
|
cpp
|
02-线性结构2 一元多项式的乘法与加法运算 (20分).cpp
|
#include <cstdio>
using Polynomial = struct PolyNode*;
struct PolyNode
{
int coef;
int expon;
Polynomial link;
};
void Attach(int c, int e, Polynomial &Rear) {//传尾指针引用(或指针的指针也可)
Polynomial P;
P = new PolyNode;
P->coef = c;
P->expon = e;
P->link = nullptr;
Rear->link = P;
Rear = P;
}
//读入多项式
Polynomial ReadPoly() {
Polynomial P, Rear, Temp;
int N, c, e;
scanf("%d", &N);
P = new PolyNode;//新建空的头结点
P->link = nullptr;
Rear = P;
while (N--) {
scanf("%d%d", &c, &e);
Attach(c, e, Rear);
}
Temp = P;
P = P->link;
delete Temp;//删除空的头结点
return P;
}
//多项式乘法
Polynomial Mult(Polynomial P1, Polynomial P2) {
Polynomial P, Rear, t1, t2, t;
int c, e;
if (!P1 || !P2) return nullptr;//只要一个为空返回Null(一个为空就无法做乘法),而加法不用作此判断,即使两个都空也可以正确返回Null
t1 = P1; t2 = P2;
P = new PolyNode;
P->link = nullptr;
Rear = P;
while (t2) {//将P1第一项乘P2每一项得到一个多项式
Attach(t1->coef * t2->coef, t1->expon + t2->expon, Rear);//该多项式一定是指数递减的
t2 = t2->link;
}
t1 = t1->link;//P1后挪一位准备后续乘法插入计算
while (t1) {
t2 = P2; Rear = P;//每轮计算从P2头部开始
while (t2) {
c = t1->coef * t2->coef;//先求c, e值
e = t1->expon + t2->expon;
while (Rear->link&&Rear->link->expon > e)//多项式P中项指数大于e则不断后移
Rear = Rear->link;
if (Rear->link&&Rear->link->expon == e) {
if (Rear->link->coef + c) {
Rear->link->coef += c;//合并完成后Rear不做挪动
}
else {
t = Rear->link;
Rear->link = t->link;
delete t;
}
}
else {
t = new PolyNode;
t->coef = c;
t->expon = e;
t->link = Rear->link;
Rear->link = t;
Rear = Rear->link;
}
t2 = t2->link;
}
t1 = t1->link;
}
t2 = P;
P = P->link;
delete t2;
return P;//删除空的头结点并返回第一项
}
//比较函数
int Compare(int a, int b) {
if (a > b) return 1;
else if (a == b) return 0;
else if (a < b) return -1;
}
//多项式加法
Polynomial Add(Polynomial P1, Polynomial P2) {
Polynomial t1, t2, Rear, t;
t1 = P1; t2 = P2;//指针赋值给临时变量,避免对原多项式的修改
Polynomial P = new PolyNode;
P->link = nullptr;
Rear = P;
while (t1&&t2) {//判断指数大小,大者复制并指针后移,相等的系数相加不为零添加,两者指针后移
switch (Compare(t1->expon, t2->expon)) {
case 1:
Attach(t1->coef, t1->expon, Rear);
t1 = t1->link;
break;
case -1:
Attach(t2->coef, t2->expon, Rear);
t2 = t2->link;
break;
case 0:
if (t1->coef + t2->coef) Attach(t1->coef + t2->coef, t1->expon, Rear);
t1 = t1->link;
t2 = t2->link;
break;
}
}
for (; t1; t1 = t1->link) Attach(t1->coef, t1->expon, Rear);//复制剩余多项式
for (; t2; t2 = t2->link) Attach(t2->coef, t2->expon, Rear);
t = P;
P = P->link;
delete t;
return P;
}
//打印多项式
void PrintPoly(Polynomial P) {
int flag = 0;//控制空格输出
if (!P) { printf("0 0\n"); return; }//空多项式输出 0 0
while (P) {
if (!flag) flag = 1;
else printf(" ");
printf("%d %d", P->coef, P->expon);
P = P->link;//不要漏掉
}
printf("\n");
return;
}
int main() {
Polynomial P1, P2, PP, PS;
P1 = ReadPoly();
P2 = ReadPoly();
PP = Mult(P1, P2);
PrintPoly(PP);
PS = Add(P1, P2);
PrintPoly(PS);
return 0;
}
|
eb6aa2151643aa0717b7bc4b7afe3327865350ac
|
90474b456a59fbb16d96d1d08d151f292e7fc715
|
/czas.cpp
|
bc6e8b9ff3dc6ee3ef6768c7f18b8d4d75311b72
|
[] |
no_license
|
radmat/rektorat
|
cafabfb2545a4ca8d5034c6ee5d1f4c2ccdde3e6
|
af802e825c907e2224e6a17463fd89927a5746c2
|
refs/heads/master
| 2016-09-06T13:49:59.680789
| 2015-09-07T07:23:51
| 2015-09-07T07:23:51
| 42,002,373
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,056
|
cpp
|
czas.cpp
|
/*Radoslaw Matusik
Program bada czasy wyswietlania roznej liczby elementow*/
#include<iostream.h>
#include<conio.h>
#include<time.h>
main()
{
time_t start,stop;
int i;
start=clock();
for(i=0;i<10000;i++)
cout<<"x";
stop=clock();
cout<<"\nCzas wypisywania 10000 elementow: "<<(double)(stop-start)/CLOCKS_PER_SEC<<" sekund";
start=clock();
for(i=0;i<100000;i++)
cout<<"x";
stop=clock();
cout<<"\nCzas wypisywania 100000 elementow: "<<(double)(stop-start)/CLOCKS_PER_SEC<<" sekund";
getch();
start=clock();
for(i=0;i<1000000;i++)
cout<<"x";
stop=clock();
cout<<"\nCzas wypisywania 1000000 elementow: "<<(double)(stop-start)/CLOCKS_PER_SEC<<" sekund";
getch();
start=clock();
for(i=0;i<10000000;i++)
cout<<"x";
stop=clock();
cout<<"\nCzas wypisywania 10000000 elementow: "<<(double)(stop-start)/CLOCKS_PER_SEC<<" sekund";
getch();
start=clock();
for(i=0;i<100000000;i++)
cout<<"x";
stop=clock();
cout<<"\nCzas wypisywania 100000000 elementow: "<<(double)(stop-start)/CLOCKS_PER_SEC<<" sekund";
getch();
return 0;
}
|
6e8a7bf5cf48ab69f86b8ddf945426765d8c2169
|
ee27f8158e8c0302d6fb1ee775a98bef2b370c5d
|
/Uts_Mulmed/Unit2.h
|
6a73a06f0c750c4c53cf26c98d737d08a6bc4858
|
[] |
no_license
|
irfanheru66/Uts_Mulmed
|
d63f976ddf4cd9371ceb278da37939c3ece87f6c
|
b8bd0216c8f6ec772401d2307db6cfc1c4bd5bcb
|
refs/heads/master
| 2023-02-08T15:31:22.552988
| 2020-10-31T10:13:16
| 2020-10-31T10:13:16
| 308,825,188
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,193
|
h
|
Unit2.h
|
//---------------------------------------------------------------------------
#ifndef Unit2H
#define Unit2H
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ExtCtrls.hpp>
#include <MPlayer.hpp>
//---------------------------------------------------------------------------
class TFMateri : public TForm
{
__published: // IDE-managed Components
TImage *Background;
TPanel *DisplayPnl;
TImage *MateriImg;
TMediaPlayer *MediaVideo;
TMediaPlayer *MediaAnimasi;
TMediaPlayer *MediaVoice;
TMediaPlayer *MediaMusik;
TMemo *Teks;
TLabel *LblJdl;
TTimer *Timer1;
TTimer *Timer2;
TTimer *Timer3;
TTimer *Timer4;
TTimer *Timer5;
TTimer *Timer6;
private: // User declarations
public: // User declarations
__fastcall TFMateri(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TFMateri *FMateri;
//---------------------------------------------------------------------------
#endif
|
4718630cf8510f68e390e75fae043096bffd8477
|
865fe9e4cbfa2e9eeb5b7dc1144ff112331759d1
|
/Final Project/Bezier - main files/game2.h
|
b8f6abe4a63cbd43a604a4aed318e1191276a1d2
|
[] |
no_license
|
yotamolenik/Graphics
|
0b4fc2127407147ba1f1babbfe3de217f6e0cf42
|
e7cee5e9446e470a956dfbcf18598810e4a3215f
|
refs/heads/main
| 2023-03-16T17:36:55.928839
| 2021-03-07T19:29:02
| 2021-03-07T19:29:02
| 345,432,073
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,447
|
h
|
game2.h
|
#pragma once
#include "scene.h"
#include "Bezier1D.h"
#include "Bezier2D.h"
class Game2 : public Scene
{
public:
Game2();
void Init();
void Add3DBezier();
void AddControlPoint(int indx);
void MoveControlPoint(int indx, float x, float y);
void MoveControlPoint(int segment, int indx, float x, float y);
void RelocateControlPoint(int segment, int indx);
void HideControlPoint(int indx);
void Update(const glm::mat4& View, const glm::mat4& Projection, const glm::mat4 &Model,const int shaderIndx);
void WhenRotate(glm::mat4 View);
void WhenTranslate(glm::mat4 View);
void Motion();
void onScroll(int yoffset, bool isPressed); // added a function to move the shape when scrolling
unsigned int TextureDesine(int width, int height);
~Game2(void);
inline void ResetCounter() { tmp = counter; counter = 0; }
inline void SetCounter() { counter = tmp; }
void UpdatePosition( float xpos, float ypos);
void Update3DBezier();
void RemakeBezier(int segNum);
void FixControlPoints();
void ContinuityStateToggle();
void MoveFixToView(glm::mat4 View, glm::vec4 move, bool isTransform);
void movePlane(double x, double y);
private:
unsigned int counter;
unsigned int tmp;
float x, y;
float xprev, yprev;
bool isContinuityState;
int pointsStartIndx;
int pps;
int numOfBeziers;
float pointsScale;
float curveScale;
Bezier1D* bez;
Bezier2D* bez2;
Bezier2D* bez22;
};
|
3db6a3ae1f532291ba7614fe1cdf40a574166be7
|
b00f0208ac175b11dda2dd1cbcb7448ed9c6ed62
|
/code/lib/function.h
|
be44b28dcbf466d8512d39d8bcfd1209bab90fea
|
[] |
no_license
|
AjaniBilby/fiber
|
01accb2a9565d90bc452f1eee1fce66fab137a0d
|
aea43cbfb1d8d83108b28c46e7ac5cfec469e7c2
|
refs/heads/stable
| 2020-03-14T10:58:02.472837
| 2018-07-10T04:51:07
| 2018-07-10T04:51:07
| 131,579,984
| 1
| 0
| null | 2018-12-09T08:16:35
| 2018-04-30T09:54:24
|
C++
|
UTF-8
|
C++
| false
| false
| 1,940
|
h
|
function.h
|
#ifndef Function_H
#define Function_H
/*
Purpose:
To take tokens and simplify them into a form quicker to be interperted
These function also execute their code as part of their code,
However this execution is controlled by individual instances,
of which supply and hold register information, as well as linking information
into the stack tree.
*/
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include "register.h"
#include "segregate.h"
enum Commands {
invalid, // Unexpected Zero
blank, // Intensionally empty space
// Memory movement
memory,
push,
pull,
// Std io
standardStream,
// Register actions
translate,
mode,
copy,
move,
set,
// Calcuations
bitwise,
math,
// Comparators
longCompare,
compare,
// Scheduling
// Suspend,
// Flow Control
Continue,
Break,
GOTO,
stop,
END,
// If statement
IF,
ELSE,
Loop
};
enum MathOpperation {
add,
subtract,
divide,
multiply,
modulus,
exponent
};
enum Comparason{
equal,
less,
greater
};
enum BitOperator{
AND,
OR,
XOR,
LeftShift,
RightShift,
NOT
};
struct Action {
Commands command; // Command enum ID
std::vector<unsigned long long int> param; // Parameters encoded as ints
int line;
};
class Function{
public:
Function *parent;
std::string name;
unsigned int resultSize;
unsigned int localSize;
std::vector<Function *> children;
std::vector<Action> code;
Function(std::string name, unsigned int local, unsigned int result);
bool Parse(Segregate::StrCommands source);
int GetChildsID(std::string str); // Get the function ID number of a child
private:
bool Interpret(Segregate::StrCommands source);
bool SimplifyIF();
bool SimplifyLoop();
bool CheckBlockEndPoints();
};
#include "function.cpp"
#endif
|
0f8e92031c137dac2b6544bd1567a5322bde9c3c
|
05fe7532d69ac6126036cd84dec8248fc1288e6f
|
/Questions/206.cpp
|
a03acef9fc7683d146ea346808784978dce36bf6
|
[
"MIT"
] |
permissive
|
xianghn/LeetCode
|
ae143997f0848d0f6a51b1c98cd629b0c6e15169
|
fe8900cca6fad5ff5efe6311b30594c01661b4e7
|
refs/heads/master
| 2020-12-30T04:13:53.838560
| 2020-02-09T10:43:32
| 2020-02-09T10:43:32
| 238,856,591
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,249
|
cpp
|
206.cpp
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//检验参数
if(!head) return NULL;
ListNode * pre, * cur, * temp;
cur = head;
pre = NULL;
while(cur)
{
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
int main()
{
ListNode * head = new ListNode(1);
ListNode * node2 = new ListNode(2);
ListNode * node3 = new ListNode(3);
ListNode * node4 = new ListNode(4);
ListNode * node5 = new ListNode(5);
head->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node5;
node5->next = NULL;
Solution s;
ListNode * temp;
temp = s.reverseList(head);
while(temp)
{
cout << temp->val << " ";
temp = temp->next;
}
cout << endl;
return 0;
}
|
fd3ab23aca012370775d33bde6982b7b9a1e7c7a
|
bc677ff45c44383cfe9b4f3233d33c5dd6283dbc
|
/二进制插入/源.cpp
|
93dcc136cd388b17a8980326ed1e0805e9f15793
|
[] |
no_license
|
zh593245631/nowcoder
|
16a168fb470cb9134bfb2fb9ce764aecb559e670
|
695ca9f2c45a888bfb5d04d8ae416d3b0a0a6659
|
refs/heads/master
| 2022-02-22T02:51:03.570356
| 2019-09-11T10:15:24
| 2019-09-11T10:15:24
| 191,264,578
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 127
|
cpp
|
源.cpp
|
class BinInsert {
public:
int binInsert(int n, int m, int j, int i) {
// write code here
m = m << j;
return m + n;
}
};
|
41f6e4fdf7b2a97651bfd231c3c489e502d7f88c
|
5906f113f1d26f6786eac86b3b557987a42dc2d6
|
/DreamZEngine/Engine/Core/EngineClass.h
|
42cfb481896a9f33532fc455436ce9495b729e47
|
[] |
no_license
|
klixoft/DreamZEngine
|
4574a52fcac2f991a34de3a562be20ade5a39705
|
e58fe434c10fb4a88fb4f65f28ff974fccef6f2d
|
refs/heads/master
| 2020-04-26T06:17:56.009196
| 2019-04-03T11:31:08
| 2019-04-03T11:31:08
| 163,892,023
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,337
|
h
|
EngineClass.h
|
#pragma once
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
#ifndef EngineClass_H
#define EngineClass_H
#include <memory>
#include "Window.h"
#include "SceneManager.h"
#include "Timer.h"
#include "../Timers/MasterClock.h"
#include "../InputHandling/InputManager.h"
#include "../Debuging/Settings.h"
#include "../Debuging/Replay.h"
// SINGLETON CLASS
class EngineClass
{
public:
// Delete default constructors
EngineClass(const EngineClass&) = delete;
EngineClass(EngineClass&&) = delete;
EngineClass& operator=(const EngineClass&) = delete;
EngineClass& operator=(EngineClass&&) = delete;
bool Initialize();
void Run();
void UpdateState();
void FixedUpdate(const float deltaTime);
void Update(const float deltaTime);
void PreRender();
void Render();
void PostRender();
// Get the current version of this class
static EngineClass* GetInstance();
// Get the scene manager
SceneManager* GetSceneManager();
// Window option setters
void SetWindowName(std::string name);
void SetWindowDimensions(int width, int height);
// Clean up
static void TerminateGame();
// Networking
std::string receiveData();
void sendData(std::string data);
bool GetFirstLoad() { return firstLoad; }
private:
// Private Constructor and Destructor so no other class can create it
EngineClass();
~EngineClass();
static std::unique_ptr<EngineClass> EngineClassInstance;
friend std::default_delete<EngineClass>;
// Running check
bool isRunning;
bool firstLoad;
// Window
static Window* window;
// Scene Manager
SceneManager* sceneManager;
// Window options
std::string windowName;
int width;
int height;
// Interpolation between fixed game loop and rendering loop
double interpolation;
// Networking
WSADATA wsaData;
int iResult;
char connectedClientName[256];
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
SOCKADDR_IN client_info = { 0 };
int addrsize = sizeof(client_info);
std::vector<std::string> clientTable;
std::string spacer = "============================================";
bool setUpNetworkAsServer();
bool setUpNetworkAsClient();
int closeNetwork();
//struct pollfd ufds[1];
};
#endif
|
eb0e4ca46cc189e79112b5f6034fa778c656e3d9
|
3b6a98851480d7d4c0b32fbe83ac73710c2664ff
|
/Week4/Day3/18-1_김영훈_20210728.cpp
|
995dd76e229d2f30897a935b42666cd440ed9a50
|
[] |
no_license
|
yhoon5171/Algorithm-Problems
|
ac946c919ad48e4260690239a41bb4ff25661a41
|
7eee76f8f8b3bcc9c5e558972a0a63b9ac1790ec
|
refs/heads/main
| 2023-07-01T18:12:27.059892
| 2021-07-30T13:18:07
| 2021-07-30T13:18:07
| 383,520,071
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 410
|
cpp
|
18-1_김영훈_20210728.cpp
|
//https://leetcode.com/problems/counting-bits/
class Solution {
public:
vector<int> countBits(int n) {
vector<int> countBits(n + 1);
for (int i = 0; i < n + 1; i++){
int tmp = i , cnt = 0;
while(tmp != 0){
if (tmp % 2 == 1) cnt++;
tmp /= 2;
}
countBits[i] = cnt;
}
return countBits;
}
};
|
f2a4b764becd923ccf276ecb8176263a3391f507
|
5464cac5e8d7a4e2b27d6afbed1a95afb149bb87
|
/Rule-Grammar/rule_grammar_tester.cpp
|
6c22c259de015c01a33c39559836f5d9a945a386
|
[] |
no_license
|
dan-whelan/CLab1
|
e627a23c9c99293a4d7c91a6715cf931606aa14f
|
119f793504826ba35c33cc564f150cd341ee1e26
|
refs/heads/master
| 2023-04-28T08:08:21.761655
| 2021-05-25T17:26:24
| 2021-05-25T17:26:24
| 310,631,607
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 491
|
cpp
|
rule_grammar_tester.cpp
|
/***************Test for Rule and Grammar classes**********************/
#include "Rule-Grammar.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc, char *argv[]) {
if(argc != 2) {
cout << "Need to give a grammar filename\n";
return 0;
}
string fname;
fname = string(argv[1]);
Grammar g(fname);
if(g.rules.size() == 0) {
cout << "the file " << fname << " did not contain any rules" << endl;
return 0;
}
g.show();
return 0;
}
|
a9f2fc2256878132f966942d200a1b0ae0321c26
|
92dfebbd6715dcfbf8117546337dca3addd5278e
|
/src/observer/peerconnectionobserver.cc
|
7d52f7afdeb2cf315ea0c032794233093729986c
|
[
"Apache-2.0"
] |
permissive
|
aisouard/node-webrtc
|
5a80bb874d5489f73c70d9e2e280cd20a41fb935
|
c22586a47b7878e3eb4d870a8e2b8d85840e85a9
|
refs/heads/develop
| 2021-08-19T13:49:18.839693
| 2017-11-26T13:37:10
| 2017-11-26T13:37:10
| 81,979,226
| 24
| 3
| null | 2017-03-15T10:00:16
| 2017-02-14T19:06:01
|
C++
|
UTF-8
|
C++
| false
| false
| 2,649
|
cc
|
peerconnectionobserver.cc
|
/*
* Copyright (c) 2017 Axel Isouard <axel@isouard.fr>
*
* 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 <iostream>
#include "peerconnectionobserver.h"
PeerConnectionObserver::PeerConnectionObserver() {
}
PeerConnectionObserver::~PeerConnectionObserver() {
_peerConnection = NULL;
}
void PeerConnectionObserver::OnSignalingChange(
webrtc::PeerConnectionInterface::SignalingState new_state) {
std::cout << "OnSignalingChange" << std::endl;
}
void PeerConnectionObserver::OnAddStream(
rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {
std::cout << "OnAddStream" << std::endl;
}
void PeerConnectionObserver::OnRemoveStream(
rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {
std::cout << "OnRemoveStream" << std::endl;
}
void PeerConnectionObserver::OnDataChannel(
rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) {
std::cout << "OnDataChannel" << std::endl;
}
void PeerConnectionObserver::OnRenegotiationNeeded() {
std::cout << "OnRenegotiationNeeded" << std::endl;
}
void PeerConnectionObserver::OnIceConnectionChange(
webrtc::PeerConnectionInterface::IceConnectionState new_state) {
std::cout << "OnIceConnectionChange" << std::endl;
}
void PeerConnectionObserver::OnIceGatheringChange(
webrtc::PeerConnectionInterface::IceGatheringState new_state) {
std::cout << "OnIceGatheringChange" << std::endl;
}
void PeerConnectionObserver::OnIceCandidate(
const webrtc::IceCandidateInterface *candidate) {
std::cout << "OnIceCandidate" << std::endl;
}
void PeerConnectionObserver::OnIceCandidatesRemoved(
const std::vector<cricket::Candidate> &candidates) {
std::cout << "OnIceCandidatesRemoved" << std::endl;
}
void PeerConnectionObserver::OnIceConnectionReceivingChange(bool receiving) {
std::cout << "OnIceConnectionReceivingChange" << std::endl;
}
PeerConnectionObserver *PeerConnectionObserver::Create() {
return new rtc::RefCountedObject<PeerConnectionObserver>();
}
void PeerConnectionObserver::SetPeerConnection(
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection) {
_peerConnection = peerConnection;
}
|
d110820e0aa06e42e46f6b70c12124c689b9681b
|
9a437b4d67ecdc5ee0174773dff2e9825f5b1bb8
|
/lab3 q17.cpp
|
bdb91fd1d2e098dbe88e04bc94f189c06912491a
|
[] |
no_license
|
mackswane/Lab3
|
7cd715d838e954739182c0a6ab69331eb60c90af
|
341e61169942082eec22551966c706968159a8ba
|
refs/heads/master
| 2021-01-21T13:26:00.060814
| 2017-09-15T11:50:19
| 2017-09-15T11:50:19
| 102,121,212
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 848
|
cpp
|
lab3 q17.cpp
|
# Lab3
//ques 17
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
float a,b,c,r1,r2,d;
cout << "\nenter coefficient of x^2 :";
cin>>a;
cout << "\nenter coefficient of x :";
cin>>b;
cout << "\nenter the constant part :";
cin>>c;
d=b*b-4*a*c;
cout<<"\nd="<<d;
if(d>0)
{
cout<<"\nequation has real and distinct roots";
r1=(-b+sqrt(d))/(2*a);
cout<<"\n1st root is r1="<<r1;
r2=((-b-sqrt(d))/(2*a));
cout<<"\n2nd root is r2="<<r2;
}
else
if(d==0)
{
cout<<"\nequation has real and equal roots";
r1=(-b+sqrt(d))/(2*a);
cout<<"\n1st root is r1="<<r1;
r2=(-b-sqrt(d))/(2*a);
cout<<"\n2nd root is r2="<<r2;
}
else
if(d<0)
{cout<<"\nequation has no real roots";}
return 0;
}
|
50f155972257eefc2036885beb4763ebb589db99
|
d23712cc880949e0e090283240af1f4be356ab5f
|
/src/ccd_cpu_bvh_cd.cpp
|
0cf1a8136ebe73d497c43f581d1684fdd4a0c93c
|
[] |
no_license
|
lidan233/objCDchecker
|
4b093d9a83e18c4d589e990723bb519263a3b425
|
7f0360a5854e44a887838715c13343edc2d2dbf3
|
refs/heads/master
| 2023-03-08T13:00:56.483752
| 2023-02-19T17:03:53
| 2023-02-19T17:03:53
| 314,605,517
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,617
|
cpp
|
ccd_cpu_bvh_cd.cpp
|
//
// Created by lidan on 17/11/2020.
//
#include "ccd_cpu_bvh_cd.h"
inline static std::vector<int> isInteract(TreeBoundBox* bvh,BoundBox* box)
{
std::vector<int> stack ;
std::vector<int> result ;
stack.push_back(0) ;
while(stack.size()!=0)
{
int t = stack.at(stack.size()-1) ;
stack.pop_back() ;
if(bvh[t].box.interacted(*box))
{
if(bvh[t].id>=0){ result.push_back(bvh[t].id); continue; }
if (bvh[2*t+1].id!=-2) stack.push_back(2*t+1) ;
if (bvh[2*t+2].id!=-2) stack.push_back(2*t+2) ;
}
}
return result ;
}
inline static std::vector<int> isInteract_tree(BVHNode* bvh,BoundBox* box)
{
std::vector<BVHNode*> stack ;
std::vector<int> result ;
stack.push_back(bvh) ;
while(stack.size()!=0)
{
BVHNode* t = stack.at(stack.size()-1) ;
stack.pop_back() ;
if(t->node_box.interacted(*box))
{
if(t->nid>=0){ result.push_back(t->nid); continue; }
if(t->children[0]!= nullptr) stack.push_back(t->children[0]) ;
if(t->children[1]!= nullptr) stack.push_back(t->children[1]) ;
}
}
return result ;
}
ccd_cpu_bvh_cd::ccd_cpu_bvh_cd()
{
}
void ccd_cpu_bvh_cd::init()
{
collusion.clear() ;
}
std::set<int>* ccd_cpu_bvh_cd::checkCDByBVH(gpu_mesh* mesh1,gpu_mesh* mesh2)
{
return nullptr ;
}
set<int>* ccd_cpu_bvh_cd::checkSelfCDByBVH(gpu_mesh* mesh1)
{
TreeBoundBox* bvhs = mesh1->get_cpu_bvh();
BVHNode* root = mesh1->get_cpu_bvh_tree() ;
vec3fcu* tris_data = mesh1->cpu_get_alldata() ;
vec3icu* tris_id = mesh1->cpu_get_faceid();
map<int,BVHNode*> maps = mesh1->get_cpu_bvh_map() ;
int count = 0 ;
#pragma omp parallel for num_threads(24)
for(int i = 0 ; i< mesh1->get_face_size()*3;i+=3)
{
vec3fcu point1 = tris_data[i] ;
vec3fcu point2 = tris_data[i+1] ;
vec3fcu point3 = tris_data[i+2] ;
vec3icu id1 = tris_id[i/3] ;
BoundBox box = BoundBox(point1,point2,point3) ;
// std::cout<<box.interacted(box)<<std::endl ;
// std::cout<<box.interacted(maps[i/3]->node_box)<<std::endl ;
std::vector<int> t_face = isInteract(bvhs,&box) ;
// std::vector<int> t_face = isInteract_tree(root,&box) ;
// std::cout<<"there is "<<t_face.size()<<" collusion"<<" for face "<<i/3<<std::endl ;
for(auto j = t_face.begin() ; j!=t_face.end();j++)
{
if(*j<(i/3)) continue;
vec3fcu point4 = tris_data[(*j)*3] ;
vec3fcu point5 = tris_data[(*j)*3+1] ;
vec3fcu point6 = tris_data[(*j)*3+2] ;
vec3icu id2 = tris_id[(*j)] ;
bool cons = true ;
for(int g = 0 ; g< 3;g++)
{
for(int h = 0 ; h <3 ;h++)
{
if(id1[g]==id2[h])
{
cons = false ;
break ;
}
}
}
if(cons && cutri_contact(point1,point2,point3,point4,point5,point6) == true)
{
collusion.insert(i/3) ;
collusion.insert(*j) ;
std::cout<<"bvh cpu check there is collusion between ("<<i/3<<" ,"<<*j<<")"<<std::endl ;
#pragma omp atomic
count += 1 ;
}
}
}
std::cout<<" bvh cpu check there is collusion happened "<<count<<" collusion."<<std::endl ;
std::cout<<" bvh cpu check there is collusion face "<<collusion.size()<<" "<<std::endl;
return &collusion ;
}
|
8d88baf070e8bc747d65db5c3bfe32bea7d68e41
|
045d55e037339d1e2aa9ae1a05d59aa9e1ef62cc
|
/src/spatial/orientation.h
|
d285307897981260270d49fdd01256ae96209b96
|
[] |
no_license
|
PlumpMath/voxel_engine
|
cdd12f4330e3aa154f374f56130487019222b96c
|
737bba4959bb11fcba3d2de0f583e724d7907f60
|
refs/heads/master
| 2021-01-25T07:01:16.432201
| 2015-07-13T06:16:38
| 2015-07-13T06:16:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 607
|
h
|
orientation.h
|
#pragma once
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
class Orientation
{
public:
Orientation();
Orientation(const glm::quat& quaternion);
void rotate(const glm::vec3& axis, const float degreesOfRotation);
Orientation operator*(const Orientation& rhs) const;
glm::mat4 get_rotation_matrix() const;
glm::vec3 forward() const;
glm::vec3 backward() const;
glm::vec3 up() const;
glm::vec3 down() const;
glm::vec3 right() const;
glm::vec3 left() const;
private:
void update_direction_vectors();
glm::quat _quaternion;
glm::vec4 _forward;
glm::vec4 _up;
glm::vec4 _right;
};
|
335cea3587f90aa121758aeb02868645874fa370
|
187ea2e6d74edbe84532817515b7bd510356f046
|
/BloombergECN.hpp
|
a3d3a05a8af2834deaee970794749eb785855505
|
[] |
no_license
|
icprog/TestFactory
|
8182cabb75ae883c8f6da0a65622059df112df36
|
19291d73136bf8bb85917a0aefedfb28612cdb72
|
refs/heads/master
| 2020-04-07T01:23:04.896978
| 2016-06-20T10:43:19
| 2016-06-20T10:43:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 392
|
hpp
|
BloombergECN.hpp
|
//
// BloombergECN.hpp
// TestFactory
//
// Created by chris folan on 18/06/2016.
// Copyright © 2016 chris folan. All rights reserved.
//
#ifndef BloombergECN_hpp
#define BloombergECN_hpp
#include "ECN.hpp"
/*Derived class Reuters from Ecn */
class BloombergECN: public Ecn
{
public:
BloombergECN();
void connect();
void parseMessage();
};
#endif /* BloombergECN_hpp */
|
22df671f10ca48372b8482750ef0589180fecfea
|
62b440a501eab0cd4e7cc750df0d9e9a863b40d7
|
/Source/Core/Visualization/Object/LineObject.h
|
a04d61c863e18ae386ee4a8b3d592d9d2044365e
|
[
"BSD-3-Clause",
"MIT",
"Zlib",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
naohisas/KVS
|
b67d8adca623d1970e4cc4ab9c317d34d04800ff
|
4d652aadc9db816674b1dda57dd14f8e56ce0a42
|
refs/heads/develop
| 2023-07-06T05:00:41.766940
| 2023-06-27T07:26:21
| 2023-06-27T07:26:21
| 28,217,308
| 47
| 32
|
BSD-3-Clause
| 2021-04-28T15:16:03
| 2014-12-19T06:25:52
|
C++
|
UTF-8
|
C++
| false
| false
| 8,344
|
h
|
LineObject.h
|
/*****************************************************************************/
/**
* @file LineObject.h
* @author Naohisa Sakamoto
*/
/*****************************************************************************/
#pragma once
#include <kvs/GeometryObjectBase>
#include <kvs/ValueArray>
#include <kvs/Type>
#include <kvs/Vector2>
#include <kvs/Vector3>
#include <kvs/RGBColor>
#include <kvs/Module>
#include <kvs/Deprecated>
namespace kvs
{
class PolygonObject;
/*===========================================================================*/
/**
* @brief Line object class.
*/
/*===========================================================================*/
class LineObject : public kvs::GeometryObjectBase
{
kvsModule( kvs::LineObject, Object );
kvsModuleBaseClass( kvs::GeometryObjectBase );
public:
enum LineType
{
Strip,
Uniline,
Polyline,
Segment,
UnknownLineType
};
enum ColorType
{
VertexColor,
LineColor,
UnknownColorType
};
private:
LineType m_line_type = UnknownLineType; ///< line type
ColorType m_color_type = UnknownColorType; ///< line color type
kvs::ValueArray<kvs::UInt32> m_connections{}; ///< connection array
kvs::ValueArray<kvs::Real32> m_sizes{}; ///< size array
public:
LineObject();
virtual ~LineObject() = default;
explicit LineObject( const kvs::PolygonObject& polygon );
void shallowCopy( const LineObject& object );
void deepCopy( const LineObject& object );
void clear();
void print( std::ostream& os, const kvs::Indent& indent = kvs::Indent(0) ) const;
bool read( const std::string& filename );
bool write( const std::string& filename, const bool ascii = true, const bool external = false ) const;
void setLineType( const LineType line_type ) { m_line_type = line_type; }
void setLineTypeToStrip() { this->setLineType( Strip ); }
void setLineTypeToUniline() { this->setLineType( Uniline ); }
void setLineTypeToPolyline() { this->setLineType( Polyline ); }
void setLineTypeToSegment() { this->setLineType( Segment ); }
void setColorType( const ColorType color_type ) { m_color_type = color_type; }
void setColorTypeToVertex() { this->setColorType( VertexColor ); }
void setColorTypeToLine() { this->setColorType( LineColor ); }
void setConnections( const kvs::ValueArray<kvs::UInt32>& connections ) { m_connections = connections; }
void setSizes( const kvs::ValueArray<kvs::Real32>& sizes ) { m_sizes = sizes; }
void setColor( const kvs::RGBColor& color );
void setSize( const kvs::Real32 size );
LineType lineType() const { return m_line_type; }
ColorType colorType() const { return m_color_type; }
size_t numberOfConnections() const;
size_t numberOfSizes() const;
const kvs::Vec2ui connection( const size_t index = 0 ) const;
kvs::Real32 size( const size_t index = 0 ) const;
const kvs::ValueArray<kvs::UInt32>& connections() const { return m_connections; }
const kvs::ValueArray<kvs::Real32>& sizes() const { return m_sizes; }
public:
KVS_DEPRECATED( LineObject(
const kvs::ValueArray<kvs::Real32>& coords,
const kvs::ValueArray<kvs::UInt32>& connections,
const kvs::ValueArray<kvs::UInt8>& colors,
const kvs::ValueArray<kvs::Real32>& sizes,
const LineType line_type,
const ColorType color_type ) )
{
setGeometryType( Line );
this->setCoords( coords );
this->setColors( colors );
this->setLineType( line_type );
this->setColorType( color_type );
this->setConnections( connections );
this->setSizes( sizes );
}
KVS_DEPRECATED( LineObject(
const kvs::ValueArray<kvs::Real32>& coords,
const kvs::ValueArray<kvs::UInt32>& connections,
const kvs::ValueArray<kvs::UInt8>& colors,
const kvs::Real32 size,
const LineType line_type,
const ColorType color_type ) )
{
setGeometryType( Line );
this->setCoords( coords );
this->setColors( colors );
this->setLineType( line_type );
this->setColorType( color_type );
this->setConnections( connections );
this->setSize( size );
}
KVS_DEPRECATED( LineObject(
const kvs::ValueArray<kvs::Real32>& coords,
const kvs::ValueArray<kvs::UInt32>& connections,
const kvs::RGBColor& color,
const kvs::ValueArray<kvs::Real32>& sizes,
const LineType line_type ) )
{
setGeometryType( Line );
this->setCoords( coords );
this->setColor( color );
this->setLineType( line_type );
this->setColorType( LineObject::LineColor );
this->setConnections( connections );
this->setSizes( sizes );
}
KVS_DEPRECATED( LineObject(
const kvs::ValueArray<kvs::Real32>& coords,
const kvs::ValueArray<kvs::UInt32>& connections,
const kvs::RGBColor& color,
const kvs::Real32 size,
const LineType line_type ) )
{
setGeometryType( Line );
this->setCoords( coords );
this->setColor( color );
this->setLineType( line_type );
this->setColorType( LineObject::LineColor );
this->setConnections( connections );
this->setSize( size );
}
KVS_DEPRECATED( LineObject(
const kvs::ValueArray<kvs::Real32>& coords,
const kvs::ValueArray<kvs::UInt8>& colors,
const kvs::ValueArray<kvs::Real32>& sizes,
const ColorType color_type ) )
{
setGeometryType( Line );
this->setCoords( coords );
this->setColors( colors );
this->setLineType( LineObject::Strip );
this->setColorType( color_type );
this->setSizes( sizes );
}
KVS_DEPRECATED( LineObject(
const kvs::ValueArray<kvs::Real32>& coords,
const kvs::ValueArray<kvs::UInt8>& colors,
const kvs::Real32 size,
const ColorType color_type ) )
{
setGeometryType( Line );
this->setCoords( coords );
this->setColors( colors );
this->setLineType( LineObject::Strip );
this->setColorType( color_type );
this->setSize( size );
}
KVS_DEPRECATED( LineObject(
const kvs::ValueArray<kvs::Real32>& coords,
const kvs::RGBColor& color,
const kvs::ValueArray<kvs::Real32>& sizes ) )
{
setGeometryType( Line );
this->setCoords( coords );
this->setColor( color );
this->setLineType( LineObject::Strip );
this->setColorType( LineObject::LineColor );
this->setSizes( sizes );
}
KVS_DEPRECATED( LineObject(
const kvs::ValueArray<kvs::Real32>& coords,
const kvs::RGBColor& color,
const kvs::Real32 size ) )
{
setGeometryType( Line );
this->setCoords( coords );
this->setColor( color );
this->setLineType( LineObject::Strip );
this->setColorType( LineObject::LineColor );
this->setSize( size );
}
KVS_DEPRECATED( LineObject(
const kvs::ValueArray<kvs::Real32>& coords ) )
{
setGeometryType( Line );
this->setCoords( coords );
this->setColor( kvs::RGBColor( 255, 255, 255 ) );
this->setLineType( LineObject::Strip );
this->setColorType( LineObject::LineColor );
this->setSize( 1.0f );
}
KVS_DEPRECATED( size_t nconnections() const ) { return this->numberOfConnections(); }
KVS_DEPRECATED( size_t nsizes() const ) { return this->numberOfSizes(); }
KVS_DEPRECATED( friend std::ostream& operator << ( std::ostream& os, const LineObject& object ) );
};
} // end of namespace kvs
|
8dcda22a25a1254e8f7a7325858f1a7ae26a2991
|
432193d5910d61a13cfa8bf342f69c36ec6facec
|
/hashtable.cpp
|
8a56d532b65127995482721715561b52b7400694
|
[] |
no_license
|
Yonhoo/hash_table
|
05601a20474602cf4a084523c45f89408d8d209e
|
900e21cb8d7d6a885ada5af77f341106d7aef0df
|
refs/heads/master
| 2020-09-15T06:12:03.066963
| 2019-11-22T09:16:21
| 2019-11-22T09:16:21
| 223,364,958
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 296
|
cpp
|
hashtable.cpp
|
#include "hashtable.h"
int main(int argc, char const *argv[])
{
hashtable<string, string> abb(20);
auto it=abb.insert_unique("sda");
auto it2=abb.insert_unique("sdfdfsdfsdfa");
cout<<it.first.cur->val<<" "<<it.second<<endl;
cout<<it2.first.cur->val<<" "<<it2.second<<endl;
return 0;
}
|
f9d054815b5b427dbdbce5b667180b4f951bc6b3
|
0ac37e503ddc7d412ef18e79324092263907599e
|
/a244/a244.cpp
|
ecbf964f0b59f4212b829ddc7c098a18b983891c
|
[] |
no_license
|
IvanaGyro/ZeroJudge-Answers
|
4c554a75c396f5a82bb136102155c10dfd3174f7
|
f8d4257b1890aae476316dbbe8fd098b43158a16
|
refs/heads/master
| 2021-06-02T12:53:19.510283
| 2016-08-08T17:25:47
| 2016-08-08T17:25:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 914
|
cpp
|
a244.cpp
|
#include <iostream>
using namespace std;
int read_int(int& n){
static char c;
static int neg;
n = 0;
while ((c = getchar()) != '-' && (c < '0' || c > '9')) if (c == EOF) return 0;
if (c == '-') neg = -1;
else{
neg = 0;
n = static_cast<int>(c - '0');
}
while ((c = getchar()) >= '0' && c <= '9'){
n = (n << 3) + (n << 1) + static_cast<int>(c - '0');
}
if (neg) n = -n;
ungetc(c, stdin);
return 1;
}
int main(){
int lines;
int a, b, c;
while (read_int(lines)){
while (lines--){
read_int(a);
read_int(b);
read_int(c);
switch (a){
case 1:
printf("%lld\n", static_cast<long long>(b)+static_cast<long long>(c));
break;
case 2:
printf("%d\n", b - c);
break;
case 3:
printf("%lld\n", static_cast<long long>(b) * static_cast<long long>(c));
break;
case 4:
printf("%d\n", b / c);
break;
default:
break;
}
}
}
system("pause");
}
|
b9ab5f709841e1e27b6a6391ae617e2ffaa11249
|
03dc4128478a970b32911d7bc74e2b4dd2e46e65
|
/inc/mmsgui/mmsimagewidget.h
|
2c3a58bb4f384855f55ee097d0e6de0b88be2cdc
|
[] |
no_license
|
RomTok/disco-light
|
4046337dfedff3a18eb7c72fe9f1ab5c2b6b14b8
|
507c0e0d78770027bd757db777e73d7d251b0237
|
refs/heads/master
| 2021-01-02T08:45:36.406162
| 2014-02-19T13:08:39
| 2014-02-19T13:08:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,134
|
h
|
mmsimagewidget.h
|
/***************************************************************************
* Copyright (C) 2005-2007 Stefan Schwarzer, Jens Schneider, *
* Matthias Hardt, Guido Madaus *
* *
* Copyright (C) 2007-2008 BerLinux Solutions GbR *
* Stefan Schwarzer & Guido Madaus *
* *
* Copyright (C) 2009-2013 BerLinux Solutions GmbH *
* *
* Authors: *
* Stefan Schwarzer <stefan.schwarzer@diskohq.org>, *
* Matthias Hardt <matthias.hardt@diskohq.org>, *
* Jens Schneider <jens.schneider@diskohq.org>, *
* Guido Madaus <guido.madaus@diskohq.org>, *
* Patrick Helterhoff <patrick.helterhoff@diskohq.org>, *
* René Bählkow <rene.baehlkow@diskohq.org> *
* *
* 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. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
**************************************************************************/
#ifndef MMSIMAGEWIDGET_H_
#define MMSIMAGEWIDGET_H_
#include "mmsgui/mmswidget.h"
//! With this class you can display pictures and animations.
/*!
All widgets derived from the base widget class can display pictures at its background.
This image class additionally can display pictures over the background.
As special feature the image class can play animations. Currently the GIF format will be supported.
The image widget cannot be focused.
\author Jens Schneider
*/
class MMSImageWidget : public MMSWidget {
private:
string className;
MMSImageWidgetClass *imageWidgetClass;
MMSImageWidgetClass myImageWidgetClass;
bool imagepath_set;
bool selimagepath_set;
bool imagepath_p_set;
bool selimagepath_p_set;
bool imagepath_i_set;
bool selimagepath_i_set;
MMSFBSurface *image;
MMSIM_DESC_SUF *image_suf;
unsigned int image_curr_index;
MMSFBSurface *selimage;
MMSIM_DESC_SUF *selimage_suf;
unsigned int selimage_curr_index;
MMSFBSurface *image_p;
MMSIM_DESC_SUF *image_p_suf;
unsigned int image_p_curr_index;
MMSFBSurface *selimage_p;
MMSIM_DESC_SUF *selimage_p_suf;
unsigned int selimage_p_curr_index;
MMSFBSurface *image_i;
MMSIM_DESC_SUF *image_i_suf;
unsigned int image_i_curr_index;
MMSFBSurface *selimage_i;
MMSIM_DESC_SUF *selimage_i_suf;
unsigned int selimage_i_curr_index;
bool image_loaded;
bool image_p_loaded;
bool image_i_loaded;
bool selimage_loaded;
bool selimage_p_loaded;
bool selimage_i_loaded;
class MMSImageWidgetThread *imageThread;
//! current foreground values set?
bool current_fgset;
//! current foreground image
MMSFBSurface *current_fgimage;
//! current foreground image2
MMSFBSurface *current_fgimage2;
bool create(MMSWindow *root, string className, MMSTheme *theme);
bool init();
bool release();
void getForeground(MMSFBSurface **image, MMSFBSurface **image2);
bool enableRefresh(bool enable = true);
bool checkRefreshStatus();
bool draw(bool *backgroundFilled = NULL);
void loadMyImage(string path, string filename, MMSFBSurface **surface, MMSIM_DESC_SUF **surfdesc,
unsigned int *index, unsigned int mirror_size, bool gen_taff);
void workWithRatio(MMSFBSurface *suf, MMSFBRectangle *surfaceGeom);
public:
MMSImageWidget(MMSWindow *root, string className, MMSTheme *theme = NULL);
virtual ~MMSImageWidget();
MMSWidget *copyWidget();
void setVisible(bool visible, bool refresh = true);
public:
/* theme access methods */
string getImagePath();
string getImageName();
string getSelImagePath();
string getSelImageName();
string getImagePath_p();
string getImageName_p();
string getSelImagePath_p();
string getSelImageName_p();
string getImagePath_i();
string getImageName_i();
string getSelImagePath_i();
string getSelImageName_i();
bool getUseRatio();
bool getFitWidth();
bool getFitHeight();
MMSALIGNMENT getAlignment();
unsigned int getMirrorSize();
bool getGenTaff();
void setImagePath(string imagepath, bool load = true, bool refresh = true);
void setImageName(string imagename, bool load = true, bool refresh = true);
void setImage(string imagepath, string imagename, bool load = true, bool refresh = true);
void setSelImagePath(string selimagepath, bool load = true, bool refresh = true);
void setSelImageName(string selimagename, bool load = true, bool refresh = true);
void setSelImage(string selimagepath, string selimagename, bool load = true, bool refresh = true);
void setImagePath_p(string imagepath_p, bool load = true, bool refresh = true);
void setImageName_p(string imagename_p, bool load = true, bool refresh = true);
void setImage_p(string imagepath_p, string imagename_p, bool load = true, bool refresh = true);
void setSelImagePath_p(string selimagepath_p, bool load = true, bool refresh = true);
void setSelImageName_p(string selimagename_p, bool load = true, bool refresh = true);
void setSelImage_p(string selimagepath_p, string selimagename_p, bool load = true, bool refresh = true);
void setImagePath_i(string imagepath_i, bool load = true, bool refresh = true);
void setImageName_i(string imagename_i, bool load = true, bool refresh = true);
void setImage_i(string imagepath_i, string imagename_i, bool load = true, bool refresh = true);
void setSelImagePath_i(string selimagepath_i, bool load = true, bool refresh = true);
void setSelImageName_i(string selimagename_i, bool load = true, bool refresh = true);
void setSelImage_i(string selimagepath_i, string selimagename_i, bool load = true, bool refresh = true);
void setUseRatio(bool useratio, bool refresh = true);
void setFitWidth(bool fitwidth, bool refresh = true);
void setFitHeight(bool fitheight, bool refresh = true);
void setAlignment(MMSALIGNMENT alignment, bool refresh = true);
void setMirrorSize(unsigned int mirrorsize, bool refresh = true);
void setGenTaff(bool gentaff, bool refresh = true);
void updateFromThemeClass(MMSImageWidgetClass *themeClass);
friend class MMSImageWidgetThread;
};
#endif /*MMSIMAGEWIDGET_H_*/
|
71f6b8d79c8581be0bd2bf90b09d9d0504513401
|
031f7354f569f118d73b5bf9ce0d4f860fb5eabf
|
/libkroll/net/proxy_config.h
|
46cf2cc245cbe249a0fc0e9a5ebe92e391822fb9
|
[
"Apache-2.0"
] |
permissive
|
psycho-pas/kroll
|
706e3a55bf390e3f447d619ad158c840ff176506
|
12fc8ead138984a84681b7d7a526d58f5b44e3bc
|
refs/heads/master
| 2020-05-24T08:15:08.637812
| 2019-05-19T09:29:16
| 2019-05-19T09:29:16
| 187,138,484
| 0
| 0
|
NOASSERTION
| 2019-05-17T03:12:14
| 2019-05-17T03:12:14
| null |
UTF-8
|
C++
| false
| false
| 1,454
|
h
|
proxy_config.h
|
/*
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#ifndef _KR_PROXY_CONFIG_H_
#define _KR_PROXY_CONFIG_H_
namespace kroll
{
class KROLL_API BypassEntry
{
public:
BypassEntry() : port(0) {}
std::string scheme;
std::string host;
unsigned short port;
};
enum ProxyType { HTTP, HTTPS, FTP, SOCKS };
class KROLL_API Proxy
{
public:
ProxyType type;
std::string host;
unsigned port;
std::string username;
std::string password;
std::string ToString();
static ProxyType SchemeToProxyType(std::string);
};
namespace ProxyConfig
{
KROLL_API void SetHTTPProxyOverride(SharedProxy);
KROLL_API void SetHTTPSProxyOverride(SharedProxy);
KROLL_API SharedProxy GetHTTPProxyOverride();
KROLL_API SharedProxy GetHTTPSProxyOverride();
KROLL_API SharedProxy GetProxyForURL(std::string& url);
KROLL_API SharedProxy ParseProxyEntry(std::string proxyEntry,
const std::string& urlScheme, const std::string& entryScheme);
SharedProxy GetProxyForURLImpl(Poco::URI& uri);
bool ShouldBypass(Poco::URI& uri,
std::vector<SharedPtr<BypassEntry> >& bypassList);
SharedPtr<BypassEntry> ParseBypassEntry(std::string entry);
void ParseProxyList(std::string proxyListString,
std::vector<SharedProxy>& proxyList, const std::string& scheme="");
Logger* GetLogger();
};
}
#endif
|
9d56ae029c309443c8f6aa9cfed08e1fd891c0d6
|
c40baa933e17d65ba9b8fb07fbc85a232c6d5958
|
/syncitbaby/communicatorXP/PESParser.cpp
|
215593f025a764a4321812d9291612c106d6ff55
|
[] |
no_license
|
BackupTheBerlios/mobicar
|
62ba0a8053422f19b96c8b1e59bffdfade86aa61
|
ceaf49157eac67b5bfc3b168afc9484319e25f02
|
refs/heads/master
| 2021-01-20T07:10:26.348042
| 2005-11-02T19:26:06
| 2005-11-02T19:26:06
| 40,040,049
| 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 17,402
|
cpp
|
PESParser.cpp
|
/******************************************************
**
** Video at Home; SEP SS 2005
**
**
** Description:
** Own implementation of a MPEGII-Parser !
** Copyright (C) 2005 by Michael Golebski
**
**
**
** Modifications:
** Date: Name: Changes:
** 2005-07-04 Golebski Initial Version (C)
**
**
**
******************************************************/
#include <../server/basics.c>
#include "../server/CommunicatorXP.cpp"
#include "../server/RTCP.cpp"
typedef unsigned char uint8_t;
typedef unsigned int uint32_t;
typedef unsigned short uint16_t;
/* the maximum rtp packet size (UDP_SIZE(1490) MINUS HEADERS(42)...*/
#define PACKET_MAX_SIZE 1448
#define myDEBUG 0
#define VIDEODEBUG 0
/* Attention: if RAW_UDP_SEND is set to 1, RTP_SEND cannot be set to 1 ! */
#define RAW_UDP_SEND 0
#define RTP_SEND 1
#define FRAMEDEBUG 0
/* some var definitions here */
bool haveComputedVideoSeqNumber = 0;
bool haveComputedAudioSeqNumber = 0;
uint16_t vidSeqNumber;
uint16_t audSeqNumber;
bool haveComputedVideoSSID = 0;
bool haveComputedAudioSSID = 0;
uint32_t sourceIdentifier;
uint32_t sourceIdentifier2;
/* Audio buffer definitions here */
uint32_t lastOffset;
uint8_t audioOffsetBuffer[10000]; // 10kB
uint8_t audioSendBuffer[10000]; // 10kB
uint32_t testit;
/* FUNCTIONS COME HERE */
uint16_t videoSequenceNumber() {
/* our random function to calculate the sequence number (packet number) increments every packet ... */
if(!haveComputedVideoSeqNumber)
vidSeqNumber = (u_int16_t)our_random();
vidSeqNumber++;
haveComputedVideoSeqNumber = 1;
return vidSeqNumber;
}
uint16_t audioSequenceNumber() {
/* our random function to calculate the sequence number (packet number) increments every packet ... */
if(!haveComputedAudioSeqNumber)
audSeqNumber = (u_int16_t)our_random();
audSeqNumber++;
haveComputedAudioSeqNumber = 1;
return audSeqNumber;
}
uint32_t videoSSID() {
/* our random function to calculate the synchronisation source identifier (SSID) ... always the same for one medium (VIDEO) */
if(!haveComputedVideoSSID)
sourceIdentifier = our_random32();
haveComputedVideoSSID = 1;
return sourceIdentifier;
}
uint32_t audioSSID() {
/* our random function to calculate the synchronisation source identifier (SSID) ... always the same for one medium (VIDEO) */
if(!haveComputedAudioSSID)
sourceIdentifier2 = our_random32();
haveComputedAudioSSID = 1;
return sourceIdentifier2;
}
void doAudioVideoRTPFrame(uint8_t *inSlice, uint32_t inSliceLength, bool isLastPicture, uint16_t temp_ref, uint8_t picture_type, uint32_t inRTPTimestamp, uint8_t mediaType, CommunicatorXP *test) {
if(FRAMEDEBUG)
printf("Length: %u - isLastPicture: %u - temp_ref: %u - picture-type: %u - timestamp: %u\n",inSliceLength, isLastPicture, temp_ref, picture_type, inRTPTimestamp);
/* we have something new here .. the mediatype var ...
* 0x01 => MPEG2 Video
* 0x02 => MPEG2 Audio
* ... nothing else for now ..
*/
bool fitsInOnePacket = 0;
uint32_t numOfPackets; // when frames has to be fragmentated into X rtppackets we have to know how many ...
uint32_t sameFramePacketCounter = 1; // we do not begin with ZERO ... THINK OF IT !!!
uint8_t *startCode;
if(inSliceLength <= PACKET_MAX_SIZE) {
//printf("Slice Length: %u\n",inSliceLength);
fitsInOnePacket = 1; // we know it fits into one rtp packet ...
numOfPackets = 1;
}
else {
/* we have to compute the amout of needed rtp-frames */
uint32_t roundedAmount = inSliceLength / PACKET_MAX_SIZE;
double exactAmount = (double)inSliceLength / (double)PACKET_MAX_SIZE;
if(exactAmount>(double)roundedAmount)
numOfPackets = roundedAmount + 1; // we know there have to be roundedAmount+1 Packets ...
else if(exactAmount==(double)roundedAmount)
numOfPackets = roundedAmount; // crazy, it exactly fits into X Frames
}
//printf("SIZE IS: %u - Number of Packets is: %u\n",inSliceLength, numOfPackets);
/* BEGIN TO STUFF THE RTPHEADER */
uint8_t rtpHeader[16];
rtpHeader[0] = 0x80; // RTP Version, Padding, Extension, Contrib. Count
if(mediaType == 0x01) { // it's a video frame ...
if(isLastPicture)
rtpHeader[1] = 0xA0; // Set the "last picture of I/B/P-Frame" marker to TRUE && set Payload Type MPEG2 (32)
else
rtpHeader[1] = 0x20; // Set it FALSE && set Payload Type MPEG2 (32)
}
else if(mediaType == 0x02) {
rtpHeader[1] = 0x0E;
}
// the sequence numbers will be computed and set later on ...
enqueue32(rtpHeader,inRTPTimestamp,4);
//memcpy(rtpHeader+4,&inRTPTimestamp,4); // Let's copy the RTPTimestamp into the RTP-Packet
uint32_t fsourceIdentifier;
if(mediaType == 0x01) {
fsourceIdentifier = videoSSID();
}
else if(mediaType == 0x02) {
fsourceIdentifier = audioSSID();
}
enqueue32(rtpHeader,fsourceIdentifier,8);
//memcpy(rtpHeader+8,&fsourceIdentifier,4);
/* END STUFFING RTPHEADER */
/* BEGIN TO STUFF THE MPEGHEADER */
uint8_t mpegHeader[4];
enqueue16(mpegHeader,temp_ref,0);
//memcpy(mpegHeader,&temp_ref,2); // set MBZ and Temporal Picture Reference ...
// we are continuing to calculate the infoByte later on ...
if(mediaType==0x01) {
uint8_t infoByte2;
if(picture_type==0x02)
infoByte2 = 0x07; // is P-Frame
else if(picture_type==0x03)
infoByte2 = 0x77; // is B-Frame
else if(picture_type==0x01)
infoByte2 = 0x00; // is I-Frame ... runtime optimized :D
mpegHeader[3] = infoByte2;
/* MPEG HEADER COMPUTED SUCCESSFULLY */
//printf("HEADER COMPUTED SUCCESSFULLY \n");
/* lets split the rtp-packet now ... */
uint8_t videoRTPFrame[1500]; // malloc makes fucking fun ... we set it hardcoded.. dunno
uint32_t bufferSize;
uint32_t offset;
for(uint32_t i=0; i<numOfPackets; i++) {
//printf("Bin in Schleife\n");
if(fitsInOnePacket) {
bufferSize = inSliceLength+16;
offset=0;
}
else if(sameFramePacketCounter<numOfPackets) { // not the last packet so we fill it to the maximum
offset = (sameFramePacketCounter-1) * PACKET_MAX_SIZE;
bufferSize = PACKET_MAX_SIZE;
}
else if((sameFramePacketCounter)==numOfPackets) { // last packet
offset = ((sameFramePacketCounter-1) * PACKET_MAX_SIZE) - 16;
bufferSize = inSliceLength +16 - ((sameFramePacketCounter-1) * (PACKET_MAX_SIZE - 16));
}
//videoRTPFrame = (uint8_t*)malloc((int)bufferSize);
if(videoRTPFrame == 0)
printf("Could not allocate \n");
uint16_t fsequenceNumber = videoSequenceNumber(); // Let's get the Sequence Number
enqueue16(rtpHeader,fsequenceNumber,2);
//memcpy(rtpHeader+2,&fsequenceNumber,2);
memcpy(videoRTPFrame,rtpHeader,12);
/* infoByte Information:
* 7 | 6 | 5 | 4 | 3 | 2 1 0
* ALWAYS 0 (AN) | New Picture Header | Sequence-Header-Present | Slice begins | Slice ends | Picture-Type
*/
uint8_t infoByte = picture_type; // first we set infoByte to picture_type cause pic_type is least significant bit(s) ...
if(picture_type==0x01 && sameFramePacketCounter==0)
infoByte = infoByte + 0x20; // this is only true if frame is I-Frame and first Packet of I-Frame sent
if(fitsInOnePacket)
infoByte = infoByte + 0x18; // begin of slice and end of slice .. "else" we have to compute later ...
else if(sameFramePacketCounter==1)
infoByte = infoByte + 0x10; // its fragmentated, but its the first packet ...
else if(sameFramePacketCounter==numOfPackets)
infoByte = infoByte + 0x08; // its fragmentated, but its the last packet ...
mpegHeader[2] = infoByte;
if(FRAMEDEBUG) {
for(int j=0;j<16;j++)
printf("%02X", rtpHeader[j]);
printf("\n\n");
for(int j=0;j<4;j++)
printf("%02X", mpegHeader[j]);
printf("\n\n");
}
memcpy(videoRTPFrame+12, mpegHeader, 4);
memcpy(videoRTPFrame+16,inSlice+offset,bufferSize);
test->senddata(videoRTPFrame,bufferSize);
//videoUDPSend(videoRTPFrame,bufferSize);
sameFramePacketCounter++;
}
//free((void *)videoRTPFrame);
}
else if(mediaType == 0x02) { //isAudio !
uint8_t audioRTPFrame[1500]; // malloc makes fucking fun ... we set it hardcoded.. dunno
uint16_t fsequenceNumber = audioSequenceNumber(); // Let's get the Sequence Number
enqueue16(rtpHeader,fsequenceNumber,2);
memcpy(audioRTPFrame,rtpHeader,12);
enqueue32(audioRTPFrame, 0x00000000, 12);
memcpy(audioRTPFrame+16,inSlice, inSliceLength);
test->senddata(audioRTPFrame, inSliceLength+16);
}
}
void parseVideoPacket(uint8_t *inBuffer, uint32_t length, uint32_t timeStamp, struct timeval timeOftimeStamp, CommunicatorXP *test, CommunicatorXP *testRTCP) {
/* First we have to define the vars for start_sequence_code checking routine */
uint8_t firstByte;
uint8_t secondByte;
uint8_t thirdByte;
uint8_t fourthByte;
uint32_t next4Bytes;
uint32_t lastSeen = 0;
uint32_t i;
uint32_t sliceLength;
uint32_t sliceLengthSum = 0;
uint16_t temporal_reference;
uint8_t picture_coding_type;
bool sawSomeStartCode = 0;
bool sawCode2 = 0;
uint32_t headerLength = 0;
/* the start codes are the following ...
* VIDEO_SEQUENCE_HEADER_START_CODE 0x000001B3
* GROUP_START_CODE 0x000001B8
* PICTURE_START_CODE 0x00000100
* SEQUENCE_END_CODE 0x000001B7
* EXTENSION_START_CODE 0x000001B5
*/
for(i=0;i<length;i++) {
if(i>=3) {
//read of course 4 bytes ...
firstByte = inBuffer[i-3];
secondByte = inBuffer[i-2];
thirdByte = inBuffer[i-1];
fourthByte = inBuffer[i];
}
if(firstByte==0x00 && secondByte==0x00 &&thirdByte==0x01 && fourthByte==0xB3) {
sawSomeStartCode = 1;
struct timeval lala;
gettimeofday(&lala, NULL);
//buildSRPacket(videoSSID(), 0, timeStamp, timeOftimeStamp, uint32_t packetCounter, uint32_t octetCounter, CommunicatorXP *test) {
buildSRPacket(videoSSID(), lala, timeStamp, timeOftimeStamp, 0x11998822, 0x55111188, testRTCP);
if(VIDEODEBUG)
printf("Video Sequence Header Start Code\n");
/* noting really important to get here ... */
}
else if(firstByte==0x00 && secondByte==0x00 &&thirdByte==0x01 && fourthByte==0xB8) {
if(!sawSomeStartCode)
sawSomeStartCode = 1;
if(VIDEODEBUG)
printf("Group Start Code\n");
/* noting really important to get here, too ... */
}
else if(firstByte==0x00 && secondByte==0x00 &&thirdByte==0x01 && fourthByte==0x00) {
if(!sawSomeStartCode)
sawSomeStartCode = 1;
/* lets extract the temporal reference and the picture-coding type out of the picture header ... */
if(VIDEODEBUG)
printf("Picture Start Code\n");
next4Bytes = (inBuffer[i+1]<<24) + (inBuffer[i+2]<<16) + (inBuffer[i+3]<<8) + (inBuffer[i+4]);
temporal_reference = (next4Bytes&0xFFC00000)>>(32-10);
picture_coding_type = (next4Bytes&0x00380000)>>19;
if(VIDEODEBUG)
printf("Temporal reference: %d, picture_coding_type: %d\n",temporal_reference, picture_coding_type);
}
else if(firstByte==0x00 && secondByte==0x00 &&thirdByte==0x01 && fourthByte==0xB7) {
/* this never gonna happen .. dunno */
if(VIDEODEBUG)
printf("Sequence End Code\n");
}
else if(firstByte==0x00 && secondByte==0x00 &&thirdByte==0x01 && fourthByte==0xB5) {
if(!sawSomeStartCode)
sawSomeStartCode = 1;
if(VIDEODEBUG)
printf("Extension Start Code\n");
/* we have to do it to correcly parse the code ... you can call it HACK as you want */
}
else if(firstByte==0x00 && secondByte==0x00 &&thirdByte==0x01) {
/* found a slice ... we have to encapsulate it, so first we have to get its length */
sliceLength = i - lastSeen;
sliceLengthSum = sliceLengthSum + sliceLength;
if(VIDEODEBUG) {
printf("We think the slice length is: %u - lastseen is: %u\n", sliceLength, lastSeen);
/* here we encapsulate the start code .. and nothing but ONLY the start code !!! */
for(unsigned j=0;j<sliceLength;j++)
printf("%02X ", inBuffer[i+j-3-sliceLength]);
printf("\n\n");
}
if(sawSomeStartCode) {
/* dirty HACK ! We think the startcode begins always at "inBuffer[0]" but for sure it has to be checked ! */
if(RAW_UDP_SEND)
test->senddata(inBuffer,sliceLength-3);
if(RTP_SEND)
//doVideoRTPFrame(inBuffer, sliceLength-3, 0, temporal_reference, picture_coding_type, timeStamp, test);
//startCode = (uint8_t *)malloc(sliceLength-3);
//memcpy(startCode,
headerLength = sliceLength - 3;
sawSomeStartCode = 0;
sawCode2 = 1;
}
else {
if(RAW_UDP_SEND)
test->senddata(inBuffer+i-3-sliceLength,sliceLength);
if(RTP_SEND) {
if(sawCode2) {
doAudioVideoRTPFrame(inBuffer+i-3-sliceLength-headerLength, sliceLength+headerLength, 0, temporal_reference, picture_coding_type, timeStamp, 0x01, test);
sawCode2 = 0;
}
else {
doAudioVideoRTPFrame(inBuffer+i-3-sliceLength, sliceLength, 0, temporal_reference, picture_coding_type, timeStamp, 0x01, test);
}
}
}
//doVideoRTPFrame(inBuffer[i-3-sliceLength], sliceLength, temporalreference, picture_coding_type, timestamp);
lastSeen = i;
}
}
/* now we get the last frame in this packet ;) */
//for(unsigned j=0;j<(length - sliceLengthSum);j++)
// printf("%02X ",inBuffer[j+sliceLengthSum-3]);
//printf("\n\n");
if(RAW_UDP_SEND)
test->senddata(inBuffer+sliceLengthSum-3,length - sliceLengthSum);
if(RTP_SEND)
doAudioVideoRTPFrame(inBuffer+sliceLengthSum-3, length - sliceLengthSum, 1, temporal_reference, picture_coding_type, timeStamp, 0x01, test);
/* isLastPicture = 1 ;) */
}
void parseAudioPacket(uint8_t *inBuffer, uint32_t length, uint32_t timeStamp, CommunicatorXP *test, CommunicatorXP *testRTCP2) {
/* INFO AN MICH SELBST: Audio Frames haben immer die gleiche Größe (sollten sie haben).
* Ein Paket beginnt nie mit einem Audio-Frame! Deshalb muss man das Offset des letzten Paketes
* speichern und den RTP-Timestamp auch vom alten Paket nehmen ...
*/
/* First we have to define the vars for start_sequence_code checking routine */
uint8_t firstByte;
uint8_t secondByte;
uint8_t thirdByte;
uint8_t fourthByte;
uint32_t i;
uint32_t next4Bytes;
/* Berechnung der Offsets */
uint32_t currOffset = 0;
/* PRINT THE WHOLE INCOMING PACKET .. DEBUG ONLY
for(unsigned u=0;u<length;u++)
printf("%02X ",inBuffer[u]);
printf("\n\n");
*/
for(i=0;i<length;i++) {
if(i>=3) {
//read of course 4 bytes ...
firstByte = inBuffer[i-3];
secondByte = inBuffer[i-2];
thirdByte = inBuffer[i-1];
fourthByte = inBuffer[i];
}
next4Bytes = (firstByte<<24) + (secondByte<<16) + (thirdByte<<8) + (fourthByte);
//if((next4Bytes&0xFFE00000)==0xFFE00000) { // THIS SHIT AIN'T GONNA WORK .. DUNNO WHY .. MPEG BITLOOSE PROBLEMS ?!
if(next4Bytes==0XFFFCA400) {
currOffset = i-3;
if(myDEBUG) {
printf("Found mpeg audio header .. Length: %u\n",length);
printf("First %02X, Second %02X, Third %02X, Fourth %02X\n",firstByte, secondByte, thirdByte, fourthByte);
/* well we know the difference (=framesize) 'cause this doesn't vary .. if it does we have a corrupt packet (maybe ?!) */
printf("last offset was %u - offset now is %u - difference is %u\n",lastOffset,currOffset, currOffset+lastOffset);
}
uint32_t audioLength = currOffset + lastOffset;
memcpy(audioSendBuffer,audioOffsetBuffer, lastOffset); // lets copy the last offset into the audioBuffer
memcpy(audioSendBuffer+lastOffset,inBuffer,currOffset); // lets copy the offset from the actual frame into the audioBuffer
/* NOW WE SHOULD HAVE A COMPLETE AUDIO FRAME IN THE BUFFER */
//printf("TRYING TO SEND ..\n");
//test->senddata(audioSendBuffer,audioLength);
doAudioVideoRTPFrame(audioSendBuffer, audioLength, 0, 0, 0, timeStamp, 0x02, test);
//for(unsigned a=0;a<audioLength;a++)
// printf("%02X ",audioSendBuffer[a]);
//printf("\n\n");
/* ATTENTION ... THIS HACK IS DIRTY 'CAUSE WE EXPECT ONLY ONE COMPLETE FRAME INTO THIS PACKET ... */
memcpy(audioOffsetBuffer,inBuffer+currOffset,length-currOffset); // copy the actual "beginning" of frame into buffer
struct timeval lala;
gettimeofday(&lala, NULL);
if((testit%10)==0)
buildSRPacket(audioSSID(), lala, timeStamp, lala, 0x11998822, 0x55111188, testRTCP2);
testit++;
lastOffset = length-(i-3); // there is a new audio header at this position so the last offset was from zero up to here
}
if(myDEBUG) {
if((i+1)==length)
printf("LENGTH WAS: %u \n\n", length);
}
}
}
|
1211322da27207ec91e60a616b56a0db1fefb688
|
528bfd13b020fa7022f160bf32214534dfed86a1
|
/Socket/Socket/selectServer2.cpp
|
7dec18f7f73d6404283e69e6650171d3df677521
|
[] |
no_license
|
hyunkin2127/SocketProgram
|
16e37babaf18fa57c5eda3e3c7d31937ad244918
|
4d15d021084a59f60b8ef1f9d561436f5742f61d
|
refs/heads/master
| 2020-03-19T04:15:14.029103
| 2018-07-12T15:05:40
| 2018-07-12T15:05:40
| 135,810,234
| 0
| 3
| null | 2018-07-10T06:29:43
| 2018-06-02T10:56:51
|
C++
|
UHC
|
C++
| false
| false
| 5,807
|
cpp
|
selectServer2.cpp
|
#include "main.h"
#define MAXBUF 1024
#define MAX 100
#define ALL 1
#define USER 20
char greet[] = "접속 되었습니다";
char no_greet[] = "접속 되지 않았습니다";
//메세지 전송 함수
void writeMessage(void * client_message, void * num, int basefd, int maxfd);
//클라이언트가 보낸 메세지와 전송받을 클라이언트의 이름을 저장
struct message {
char user[USER];
char sbuf[MAXBUF];
};
//서버에 접속한 클라이언트의 디스크립터와 거기에 매치되는 해당 클라이언트의 이름을 저장
struct add_num {
int anum;
char name[MAXBUF];
};
int main() {
int optval = 1; //소켓옵션의 설정값
int ssock, csock; //소켓
struct sockaddr_in server_addr, client_addr; //IP와 Port값(즉 주소값)
int clen, data_len;
fd_set read_fds, tmp_fds; //디스크립터 셋트(단일 비트 테이블)
int fd;
struct add_num add_num[USER]; //서버에접속하는 클라이언트의 정보를 저장하는 객체
int index, maxfd;
struct message read_message; //클라이언트로 부터 받은 메세지 구조체
/*
* 클라이언트와 연결할 소켓을 생성
* 도메인, 타입, 프로토콜을 인자로 가짐.
*/
if ((ssock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))<0) {
perror("socket error : ");
exit(1);
}
//소켓 옵션을 설정(옵션 해석을 위한 커널 내 시스템 코드의 구분, 옵션이름, 옵션의 값 등--SO_SNDBUF,SO_BROADCAST,SO_KEEPALIVE)
setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
//해당 변수를 초기화, 주소를 저장
memset(add_num, 0, sizeof(add_num));
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(3333);
//소켓을 해당 주소로 연결
if (bind(ssock, (struct sockaddr *)&server_addr, sizeof(server_addr))<0)
{
perror("bind error: ");
exit(1);
}
//클라이언트의 접속을 기다림~
if (listen(ssock, 5)<0) {
perror("listen error : ");
exit(1);
}
clen = sizeof(client_addr);
//FD_SET 디스크립터의 세팅
FD_ZERO(&read_fds);
FD_SET(ssock, &read_fds);
maxfd = ssock;
while (1) {
//fd_set디스크립터 테이블은 일회성. 그렇기 때문에 해당값을 미리 옮겨 놓고 시작해야 한다. 그렇기 때문에 복사를 먼져 하고 시작해야 한다.
tmp_fds = read_fds;
//인터페이스 상에서 디바이스에 들어온 입력에 대한 즉각적인 대응이 필요.
if (select(maxfd + 1, &tmp_fds, 0, 0, (struct timeval *)0)<1) {
perror("select error : ");
exit(1);
}
for (fd = 0; fd<maxfd + 1; fd++) {
if (FD_ISSET(fd, &tmp_fds)) {
if (fd == ssock) {
if ((csock = accept(ssock, (struct sockaddr *)&client_addr, &clen))<0) {
perror("accept error : ");
exit(0);
}
FD_SET(csock, &read_fds);
printf("새로운 클라이언트 %d번 파일 디스크립터 접속\n", csock);
for (index = 0; index<MAX; index++) {
if (add_num[index].anum == 0) {
add_num[index].anum = csock;
maxfd++;
break;
}
}
if (csock>maxfd) {
maxfd = csock;
}
}
else {
memset(&read_message, 0, sizeof(read_message));
//클라이언트로 부터 메세지를 수신받는다.
data_len = read(fd, (struct message*)&read_message, sizeof(read_message));
//클라이언트로부터 메시지가 들어왔다면 메시지 전송
if (data_len>0) {
writeMessage((void*)&read_message, (void*)add_num, fd, maxfd);
}
else if (data_len == 0) {
for (index = 0; index<USER; index++) {
if (add_num[index].anum == fd) {
add_num[index].anum = 0;
strcpy(add_num[index].name, "");
break;
}
}
close(fd);
FD_CLR(fd, &read_fds);
if (maxfd == fd)
maxfd--;
printf("클라이언트 %d번 파일 디스크립터 해제\n", fd);
}
else if (data_len<0) {
perror("read error : ");
exit(1);
}
}
}
}
}
return 0;
}
//사용자로부터 받은 메시지를 해당 클라이언트에 전송해 주는 함수
void writeMessage(void *client_message, void *num, int basefd, int maxfd) {
int index;
struct message *cl_message;
struct add_num *index_num;
char all[] = "ALL";
cl_message = (struct message*)client_message;
index_num = (struct add_num*)num;
//클라이언트가 접속했다고 메시지를 보냈을때
if (strcmp(cl_message->sbuf, "") == 0) {
printf("등록 하겠습니다.\n");
for (index = 0; index<USER; index++) {
if (((index_num + index)->anum) == basefd) {
strcpy((index_num + index)->name, (cl_message->user));
}
}
write(basefd, greet, sizeof(greet));
//클라이언트가 다른 클라이언트에 메시지를 전송 할 때
}
else {
//모든 사용자에게 메시지를 전송한다.
all[strlen(all)] = '\0';
if (strcmp(cl_message->user, all) == 0) {
for (index = 0; index<maxfd; index++) {
if ((index_num + index)->anum != 0)
write(((index_num + index)->anum), cl_message->sbuf, MAXBUF);
}
//지정된 사용자에게 메시지를 전송한다.
}
else {
for (index = 0; index<USER; index++) {
if (strcmp(((index_num + index)->name), cl_message->user) == 0) {
if (write(((index_num + index)->anum), cl_message->sbuf, MAXBUF)<0) {
perror("write error : ");
exit(1);
}
break;
}
//유저가 존재하지 않는다면
if (index + 1 == USER)
write(basefd, no_greet, sizeof(no_greet));
}
}
}
}
|
92987e7670aeab320b55d60a8d6021ee5ce4fc68
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/ui/gl/gl_surface_egl_unittest.cc
|
c98029bdc7f328e2d6026acc0aa970bbec878917
|
[
"BSD-3-Clause"
] |
permissive
|
chromium/chromium
|
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
|
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
|
refs/heads/main
| 2023-08-24T00:35:12.585945
| 2023-08-23T22:01:11
| 2023-08-23T22:01:11
| 120,360,765
| 17,408
| 7,102
|
BSD-3-Clause
| 2023-09-10T23:44:27
| 2018-02-05T20:55:32
| null |
UTF-8
|
C++
| false
| false
| 4,140
|
cc
|
gl_surface_egl_unittest.cc
|
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gl/gl_surface_egl.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/gl_context.h"
#include "ui/gl/gl_implementation.h"
#include "ui/gl/init/gl_factory.h"
#include "ui/gl/test/gl_surface_test_support.h"
#if BUILDFLAG(IS_WIN)
#include "ui/platform_window/platform_window_delegate.h"
#include "ui/platform_window/win/win_window.h"
#endif
// TODO(crbug.com/969798): Fix memory leaks in tests and re-enable on LSAN.
#ifdef LEAK_SANITIZER
#define MAYBE_SurfaceFormatTest DISABLED_SurfaceFormatTest
#else
#define MAYBE_SurfaceFormatTest SurfaceFormatTest
#endif
namespace gl {
namespace {
class GLSurfaceEGLTest : public testing::Test {
protected:
void SetUp() override {
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_IOS)
display_ = GLSurfaceTestSupport::InitializeOneOffImplementation(
GLImplementationParts(kGLImplementationEGLANGLE), true);
#else
display_ = GLSurfaceTestSupport::InitializeOneOffImplementation(
GLImplementationParts(kGLImplementationEGLGLES2), true);
#endif
}
void TearDown() override { GLSurfaceTestSupport::ShutdownGL(display_); }
GLDisplay* GetTestDisplay() {
EXPECT_NE(display_, nullptr);
return display_;
}
private:
raw_ptr<GLDisplay> display_ = nullptr;
};
#if !defined(MEMORY_SANITIZER)
// Fails under MSAN: crbug.com/886995
TEST_F(GLSurfaceEGLTest, MAYBE_SurfaceFormatTest) {
GLSurfaceFormat surface_format = GLSurfaceFormat();
surface_format.SetDepthBits(24);
surface_format.SetStencilBits(8);
surface_format.SetSamples(0);
scoped_refptr<GLSurface> surface = init::CreateOffscreenGLSurfaceWithFormat(
GetTestDisplay(), gfx::Size(1, 1), surface_format);
EGLConfig config = surface->GetConfig();
EXPECT_TRUE(config);
EGLint attrib;
eglGetConfigAttrib(surface->GetGLDisplay()->GetDisplay(), config,
EGL_DEPTH_SIZE, &attrib);
EXPECT_LE(24, attrib);
eglGetConfigAttrib(surface->GetGLDisplay()->GetDisplay(), config,
EGL_STENCIL_SIZE, &attrib);
EXPECT_LE(8, attrib);
eglGetConfigAttrib(surface->GetGLDisplay()->GetDisplay(), config, EGL_SAMPLES,
&attrib);
EXPECT_EQ(0, attrib);
}
#endif
#if BUILDFLAG(IS_WIN)
class TestPlatformDelegate : public ui::PlatformWindowDelegate {
public:
// ui::PlatformWindowDelegate implementation.
void OnBoundsChanged(const BoundsChange& change) override {}
void OnDamageRect(const gfx::Rect& damaged_region) override {}
void DispatchEvent(ui::Event* event) override {}
void OnCloseRequest() override {}
void OnClosed() override {}
void OnWindowStateChanged(ui::PlatformWindowState old_state,
ui::PlatformWindowState new_state) override {}
void OnLostCapture() override {}
void OnAcceleratedWidgetAvailable(gfx::AcceleratedWidget widget) override {}
void OnWillDestroyAcceleratedWidget() override {}
void OnAcceleratedWidgetDestroyed() override {}
void OnActivationChanged(bool active) override {}
void OnMouseEnter() override {}
};
TEST_F(GLSurfaceEGLTest, FixedSizeExtension) {
TestPlatformDelegate platform_delegate;
gfx::Size window_size(400, 500);
ui::WinWindow window(&platform_delegate, gfx::Rect(window_size));
scoped_refptr<GLSurface> surface =
InitializeGLSurface(base::MakeRefCounted<NativeViewGLSurfaceEGL>(
GLSurfaceEGL::GetGLDisplayEGL(), window.hwnd(), nullptr));
ASSERT_TRUE(surface);
EXPECT_EQ(window_size, surface->GetSize());
scoped_refptr<GLContext> context = init::CreateGLContext(
nullptr /* share_group */, surface.get(), GLContextAttribs());
ASSERT_TRUE(context);
EXPECT_TRUE(context->MakeCurrent(surface.get()));
gfx::Size resize_size(200, 300);
surface->Resize(resize_size, 1.0, gfx::ColorSpace(), false);
EXPECT_EQ(resize_size, surface->GetSize());
}
#endif
} // namespace
} // namespace gl
|
d3afaa69e387976641fda5da52391f5d2d9fd649
|
126bad2f4eb070378100985d27b1dce8c61d7dec
|
/question5.cpp
|
43f0ad81bfc30cec771c7ba7c3b8ec610d932083
|
[] |
no_license
|
pamitduggal/work-in-c-plus-plus
|
1a56569cd48568a1f068517438082e4d701817da
|
a65bb404ec14e37a791d78e1c232b196d52d5110
|
refs/heads/main
| 2023-04-18T23:09:11.559618
| 2021-04-30T12:06:19
| 2021-04-30T12:06:19
| 363,127,876
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 458
|
cpp
|
question5.cpp
|
#include <iostream>
using namespace std;
int number(int val)
{
if(val<=100) {
cout<<"\t"<<val;
number(val+1);
}
}
int numberrev(int valrev)
{
if(valrev>=1)
{
cout<<"\t"<<valrev;
numberrev(valrev-1);
}
}
int main() {
int val = 1;
int valrev=100;
cout<<"Numbers 1-100\n\n\n";
number(val);
cout<<"\n\n\nNumbers 100-1\n\n\n";
numberrev(valrev);
return 0;
}
|
08ca78c9f93359a3c86d6d5d031c8900e06dc54f
|
69abc9415e7e5644c4f52420d5eb7441f43c7010
|
/deprecated-code/compress.cpp
|
f4ae36e7c8484a77a7545ade4ef180bd5e4d6b32
|
[] |
no_license
|
dajmcdon/cplr
|
059ec023b988ef3fc9f37c3bf929c227c0434887
|
f60de399a837ec46c107c9ba05f78ba439d15de9
|
refs/heads/master
| 2021-01-23T04:09:38.688327
| 2019-01-08T21:13:04
| 2019-01-08T21:13:04
| 86,161,946
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 919
|
cpp
|
compress.cpp
|
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List compressCpp(NumericMatrix const &X, int q, NumericVector const &Y, int s) {
int p = X.ncol();
int n = X.nrow();
NumericMatrix QX(q, p);
NumericVector QY(q);
double u1, u2;
double rescale = sqrt(q/s);
double prob = 1.0 - 1.0/s;
RNGScope scope;
for(int qiter = 0; qiter < q; qiter++){
for(int niter = 0; niter < n; niter++){
u1 = runif(1)[0];
if(u1 < prob) continue;
u2 = runif(1)[0];
if(u2 < 0.5){
QY[qiter] += Y[niter];
for(int jiter = 0; jiter < p; jiter++){
QX(qiter, jiter) += X(niter, jiter);
}
}else{
QY[qiter] -= Y[niter];
for(int jiter = 0; jiter < p; jiter++){
QX(qiter, jiter) -= X(niter, jiter);
}
}
}
}
return List::create(Named("QX") = QX / rescale,
Named("QY") = QY / rescale);
}
|
4c578a3e62bfa71f18af06150b7847ca9eda2835
|
3211ef2ce88b13ad2cbbc3c7307017e52ff2cb51
|
/eDataServer/LogProc.cpp
|
9fa83b7061bbb23c8be23a5878a0ff27e41318b6
|
[] |
no_license
|
YucelCeyhun/KingMuOnline
|
887d84fe6bf688679f0bd45920a2b1e3eff33222
|
f0191fb4b99b6f5b04ac6c5834a6dff0014059e6
|
refs/heads/master
| 2022-04-10T19:14:51.778327
| 2020-03-26T07:53:24
| 2020-03-26T07:53:24
| 249,654,970
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,486
|
cpp
|
LogProc.cpp
|
#include "StdAfx.h"
#include "LogProc.h"
int m_cline; // Current Line of Log
static FILE* logfp; // FILE Variable for LOG
static char m_szLogFileName[100]; // Log Name
char LogText[LOG_TEXT_LINE][LOG_TEXT_LENGTH];
short LogTextLength[LOG_TEXT_LINE];
BYTE LogTextViewType[LOG_TEXT_LINE];
// Functions Pointers to Log Variables
void (*LogAdd)(char* szLog,...);
void (*LogAddC)(BYTE, char*, ...);
void (*LogAddTD)(char* szLog, ...);
void (*LogAddHeadHex)(char*, unsigned char*, int);
void (*LogAddL)(char* szLog, ...);
void (*LogTextPaint)(HWND);
CRITICAL_SECTION LogCritical;
// Log Set Internals
int LogMDay;
int LogMonth;
int LogMYear;
int gLogOutType = 1;
void LogInit(int logprint)
{
InitializeCriticalSection(&LogCritical);
// ----
if(logprint!=0)
{
LogAdd=LogAddFunc;
LogAddC=LogAddFuncColor;
LogAddTD=LogAddTimeDateFunc;
LogAddHeadHex=LogAddStrHexFunc;
LogTextPaint=LogTextPaintProc;
LogAddL=LogAddLocalFunc;
// ----
for(int n=0;n<LOG_TEXT_LINE;n++)
{
memset(&LogText[n],0,sizeof(LogText[0]));
LogTextLength[n]=0;
LogTextViewType[n]=0;
}
if(gLogOutType==0)
{
return;
}
else
{
LogDataSet();
}
}
else
{
LogAdd=LogAddFuncVoid;
LogAddHeadHex=LogAddHeadHexFuncVoid;
LogTextPaint=LogTextPaintProcVoid;
LogAddTD=LogAddTimeDateVoid;
LogAddL=LogAddLocalFuncVoid;
}
}
void LogDataSet()
{
char szTemp[250];
// ----
struct tm *today;
time_t ltime;
// ----
time(<ime);
today=localtime(<ime);
// ----
today->tm_year=today->tm_year + 1900;
LogMYear=today->tm_year;
LogMonth=today->tm_mon+1;
LogMDay=today->tm_mday;
// ----
wsprintf(szTemp,"Log\\%02d%02d%02d_%s.log",LogMYear,LogMonth,LogMDay,AIOSRV_LOG);
// ----
if(logfp != 0)
{
fclose(logfp);
logfp=0;
}
// ----
logfp=fopen(szTemp,"a+t");
// ----
if(logfp==0)
{
LogAdd("Log file create error");
}
strcpy(m_szLogFileName,szTemp);
}
int LogDateChange()
{
char szTemp[250];
// ----
tm* today;
time_t ltime;
time(<ime);
// ----
today=localtime(<ime);
today->tm_year =today->tm_year+1900;
today->tm_mon = today->tm_mon +1;
// ----
if(today->tm_year <= LogMYear)
{
if(today->tm_mon <= LogMonth)
{
if(today->tm_mday <= LogMDay)
{
return 0;
}
}
}
// ----
LogMYear = today->tm_year;
LogMonth = today->tm_mon;
LogMDay = today->tm_mday;
// ----
wsprintf(szTemp,"Log\\%02d%02d%02d_%s.log",LogMYear,LogMonth,LogMDay,AIOSRV_LOG);
// ----
EnterCriticalSection(&LogCritical);
// ----
if(logfp!=0)
{
fclose(logfp);
logfp=0;
}
// ----
logfp=fopen(szTemp,"a+t");
strcpy(m_szLogFileName,szTemp);
LeaveCriticalSection(&LogCritical);
// ----
return 1;
}
void LogTextAdd(BYTE type,char* msg,int len)
{
if(len>LOG_TEXT_LENGTH-1)
{
len=LOG_TEXT_LENGTH-1;
}
// ----
m_cline++;
// ----
if(m_cline>LOG_TEXT_LINE-1)
{
m_cline=0;
}
// ----
LogText[m_cline][0]=0;
memcpy(&LogText[m_cline],msg,len);
LogText[m_cline][1+len]=0;
LogText[m_cline][len]=0;
LogTextLength[m_cline]=len;
LogTextViewType[m_cline]=type;
}
void LogAddFuncVoid(char* szLog, ...)
{
// Nothing to Add
}
void LogAddTimeDateVoid(char* szLog, ...)
{
// Log Disabled
}
void LogAddFunc(char* szLog, ...)
{
char szBuffer[512]="";
// ----
va_list pArguments;
// ----
va_start( pArguments,szLog);
vsprintf(szBuffer,szLog,pArguments);
va_end(pArguments);
LogTextAdd(0,szBuffer,strlen(szBuffer));
// ----
if(gLogOutType==0)
{
return;
}
else
{
EnterCriticalSection(&LogCritical);
fprintf(logfp,"%s\n",szBuffer);
LeaveCriticalSection(&LogCritical);
}
}
void LogAddFuncColor(BYTE Color,char* szLog, ...)
{
char szBuffer[1024]="";
va_list pArguments;
// ----
va_start(pArguments,szLog);
vsprintf(szBuffer,szLog,pArguments);
va_end(pArguments);
LogTextAdd(Color,szBuffer,strlen(szBuffer));
// ----
if(!gLogOutType)
{
return;
}
else
{
EnterCriticalSection(&LogCritical);
fprintf(logfp,"%s\n",szBuffer);
LeaveCriticalSection(&LogCritical);
}
}
void LogAddLocalFunc(char* szLog, ...)
{
char szBuffer[512];
va_list pArguments;
}
void LogAddLocalFuncVoid(char* szLog, ...)
{
}
void LogAddTimeDateFunc(char* szLog, ...)
{
char szBuffer[1024]="";
va_list pArguments;
tm * today;
time_t ltime;
char tmpbuf[512];
// ----
time(<ime);
today=localtime(<ime);
wsprintf(tmpbuf,"%.8s ",asctime(today)+11);
// ----
va_start(pArguments,szLog);
vsprintf(szBuffer,szLog,pArguments);
va_end(pArguments);
// ----
strcat(tmpbuf,szBuffer);
// ----
LogTextAdd(0,tmpbuf,strlen(tmpbuf));
// ----
if(gLogOutType==0)
{
return;
}
else
{
if(logfp==0)
{
LogAdd("error-L2 : file create error %s %d",__FILE__,__LINE__);
}
else
{
EnterCriticalSection(&LogCritical);
fprintf(logfp,"%s\n",&tmpbuf);
LeaveCriticalSection(&LogCritical);
}
}
}
void LogAddHeadHexFuncVoid(char* str,unsigned char* data,int len)
{
// Log Disabled
}
void LogAddHeadHexFunc(int Type,char* data,int len)
{
if(gLogOutType==0)
{
return;
}
else
{
if(logfp==0)
{
return;
}
else
{
EnterCriticalSection(&LogCritical);
// ----
switch(Type)
{
case 2:
fprintf(logfp,"Send:[%d] : (",len);
break;
case 3:
fprintf(logfp,"FDWrite:[%d] : (",len);
break;
case 4:
fprintf(logfp,"Recv:[%d] : (",len);
break;
default:
fprintf(logfp,"%d[%d] : (",Type,len);
break;
}
// ----
for(signed int n=0; n<len; n++)
{
fprintf(logfp,"0x%02x ",*(BYTE*)(data+n));
}
// ----
fprintf(logfp,")\n");
// ----
LeaveCriticalSection(&LogCritical);
}
}
}
void LogAddStrHexFunc(char* str,unsigned char* data, int len)
{
tm* today;
time_t ltime;
// ----
time(<ime);
today=localtime(<ime);
// ----
if(gLogOutType==0)
{
return;
}
else
{
if(logfp==0)
{
return;
}
else
{
EnterCriticalSection(&LogCritical);
fprintf(logfp,"%.08s",asctime(today)+11);
fprintf(logfp,"[%s][%d] : (",str,len);
// ----
for(signed int n=0; n<len; n++)
{
fprintf(logfp,"0x%02x ",*(BYTE*)(data+n));
}
fprintf(logfp,")\n");
// ----
LeaveCriticalSection(&LogCritical);
}
}
}
void LogTextClear()
{
for(int n=0; n<LOG_TEXT_LINE; n++)
{
memset(&LogText[n],0,LOG_TEXT_LENGTH);
LogTextLength[n]=0; // WORD
LogTextViewType[n]=0; // BYTE
}
}
void LogTextPaintProcVoid(HWND hWnd)
{
// Log Disabled
}
void LogTextPaintProc(HWND hWnd)
{
HDC hdc;
int total;
// ----
hdc=GetDC(hWnd);
total= LOG_TEXT_LINE;
// ----
int n = m_cline;
// ----
while(total-- != 0)
{
switch(LogTextViewType[n])
{
case 2:
SetTextColor(hdc,RGB(255,0,0));
break;
case 3:
SetTextColor(hdc,RGB(0,100,0));
break;
case 4:
SetTextColor(hdc,RGB(0,0,255));
break;
case 5:
SetTextColor(hdc,RGB(155,0,0));
break;
case 6:
SetTextColor(hdc,RGB(0,0,100));
break;
case 7:
SetTextColor(hdc,RGB(210,30,150));
break;
default:
SetTextColor(hdc,RGB(0,0,0));
break;
}
// ----
if(strlen(LogText[n])>1)
{
TextOut(hdc,0,total*15+100,LogText[n],strlen(LogText[n]));
}
// ----
n--;
// ----
if(n<0)
{
n=LOG_TEXT_LINE-1;
}
}
// ----
ReleaseDC(hWnd,hdc);
}
int LogGetFileName()
{
return 0;
}
void LogClose()
{
if(logfp!=0)
{
fclose(logfp);
}
DeleteCriticalSection(&LogCritical);
}
void MsgBox(char *szlog, ...)
{
char szBuffer[512]="";
va_list pArguments;
va_start(pArguments,szlog);
vsprintf(szBuffer,szlog,pArguments);
va_end(pArguments);
MessageBox(NULL,szBuffer,"error",MB_OK|MB_APPLMODAL);
}
|
7ba85b0ba892fe6355ca876e333fe02cf004f597
|
f3a35f1e9d803a1ad409bec1e58024e825f87141
|
/08/GraduDeMIS/ChoiStatusDlg.h
|
c12ce96840afe3246245d56ab7e1504497d12fc5
|
[] |
no_license
|
xuezchuang/C-Project
|
ed4406f913e853b981063e726ab505ada36b1f90
|
4d5a64429fde2d37ba77974dd6cf7526833e55be
|
refs/heads/master
| 2020-03-24T20:04:26.082584
| 2017-11-14T10:11:40
| 2017-11-14T10:11:40
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,353
|
h
|
ChoiStatusDlg.h
|
#if !defined(AFX_CHOISTATUSDLG_H__7AE2883B_B24D_405A_9D9B_E38375766610__INCLUDED_)
#define AFX_CHOISTATUSDLG_H__7AE2883B_B24D_405A_9D9B_E38375766610__INCLUDED_
#include "ChoiceSubSet.h"
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// ChoiStatusDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CChoiStatusDlg dialog
class CChoiStatusDlg : public CDialog
{
// Construction
public:
CChoiStatusDlg(CWnd* pParent = NULL); // standard constructor
CChoiceSubSet choisubSet; //定义记录集对象
// Dialog Data
//{{AFX_DATA(CChoiStatusDlg)
enum { IDD = IDD_ChoiStatusShow_DLG };
CString m_strChoiSubStatus;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CChoiStatusDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CChoiStatusDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSeeChoisubInfoBTN();
afx_msg void OnEnterChoiSubBTN();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_CHOISTATUSDLG_H__7AE2883B_B24D_405A_9D9B_E38375766610__INCLUDED_)
|
2cd86ab1f4e1d7338405730098bd46e4b540fea1
|
0d542294bbc3ba3176a2065b2dd593fb897e8647
|
/GraphicsEngine/Common/Common/IncludeReplacer.cpp
|
c7241830f19da4f92ff102887717851a4777c66b
|
[] |
no_license
|
JPMMaia/Graphics-Engine
|
2d6e4ae706c9e291ec90e1a0253c3d538647cd60
|
8ae3cb94fe7c5032fcd5a9cbbc9d8eeaf7a2ffcd
|
refs/heads/master
| 2020-12-07T03:57:51.647732
| 2017-08-31T19:20:21
| 2017-08-31T19:20:21
| 48,298,893
| 0
| 2
| null | 2016-10-09T20:04:13
| 2015-12-19T22:11:49
|
C++
|
UTF-8
|
C++
| false
| false
| 1,763
|
cpp
|
IncludeReplacer.cpp
|
#include "IncludeReplacer.h"
#include "Helpers.h"
using namespace Common;
using namespace std;
void IncludeReplacer::ReplaceIncludes(const std::wstring& inputFilename, const std::wstring& outputFilename)
{
auto filePath = Helpers::GetFilePath(inputFilename);
vector<char> content;
Helpers::ReadData(inputFilename, content);
vector<char>::iterator location;
wstring includedFile;
while (FindAndEraseIncludeTag(content, includedFile, location))
{
vector<char> includedContent;
Helpers::ReadData(filePath + includedFile, includedContent);
content.insert(location, includedContent.begin(), includedContent.end());
}
Helpers::WriteData(outputFilename, content);
}
bool IncludeReplacer::FindAndEraseIncludeTag(std::vector<char>& content, std::wstring& includedFile, std::vector<char>::iterator& location)
{
auto iterator = content.begin();
std::vector<char>::iterator begin;
do
{
iterator = std::find(iterator, content.end(), '#');
if (iterator == content.end())
return false;
// Create iterator to the begin of the line:
begin = std::vector<char>::iterator(iterator);
} while (
*(++iterator) != 'i' ||
*(++iterator) != 'n' ||
*(++iterator) != 'c' ||
*(++iterator) != 'l' ||
*(++iterator) != 'u' ||
*(++iterator) != 'd' ||
*(++iterator) != 'e' ||
*(++iterator) != ' ' ||
*(++iterator) != '"'
);
string includedFileTmp;
includedFileTmp.reserve(48);
while (*(++iterator) != '"')
includedFileTmp.push_back(*iterator);
includedFile = Helpers::StringToWString(includedFileTmp);
// Skip end of line:
do { ++iterator; } while (*iterator == ' ' || *iterator == '\r');
do { ++iterator; } while (*iterator == '\n');
// Erase #include "...":
location = content.erase(begin, iterator);
return true;
}
|
df604d529674c4ce74bd53cf3e1e9d6ac7d0825c
|
e22dcc1db07006337aa73c30fa41c954c46bbd53
|
/Phase 1/video.cpp
|
9d7b9a810bf9bb91e93588b8feec189b98b7d14b
|
[] |
no_license
|
ESE-Class-2017/Embedded-Controller-Robot
|
39854767289e095ebb4ec2ac77efc1ca302d5e0f
|
1ef8c85ec38cc970c0337fdcc625fa6f8d2a7467
|
refs/heads/master
| 2021-01-18T23:10:19.967276
| 2016-06-06T22:56:16
| 2016-06-06T22:56:16
| 45,561,081
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,124
|
cpp
|
video.cpp
|
#include <iostream>
#include <cv.h>
#include <highgui.h>
#include <imgproc.hpp>
#include <opencv2/opencv.hpp>
#include "opencv2/core.hpp"
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include "video.h"
#include <unistd.h>
using namespace std;
char key;
int video_cap()
{
int i;
int j;
int a;
int b;
int c;
double Area;
double thresh = 92;
double maxValue = 255;
//cv::Mat image;
cv::Mat gray;
cv::Mat BW;
cv::Mat frame;
cv::Mat shot1;
cv::Mat canny_out;
vector<vector<cv::Point> > contours;
vector<cv::Vec4i> hierarchy;
// create window so that a new window is not created for each frame
cv::namedWindow("Camera_Output", 1);
cv::namedWindow("Image_Output", 1);
//Open camera for capturing
cv::VideoCapture capture(CV_CAP_ANY);
// Create infinte loop for live streaming
while(1)
{
capture >> frame;
cv::imshow("Camera_Output", frame); // Show image frames on created window
key = cvWaitKey(10); // Capture Keyboard stroke
if(image_quit == true)
{
//Ends the loop
break;
}
else if(image_capture == true)
{
//Capture image
capture >> shot1;
cv::imshow("Image_Output", shot1);
cv::imwrite("image.bmp", shot1);
//Convert to grayscale
cvtColor(shot1, gray, CV_BGR2GRAY);
cv::imwrite("BW.bmp", gray);
//Set grayscale thresholds
threshold(gray, BW, thresh, maxValue, 1);
//Blur the image
GaussianBlur(BW, BW, cv::Size(5,5), 2, 2);
//Used for more accuracy but caused bug in code
//Detect edges with Canny
//Canny(BW, canny_out, 100, 200, 3);
//Find contours
findContours( BW, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );
//Draw contours
cv::Mat drawing = cv::Mat::zeros( BW.size(), CV_8UC3 );
for( i = 0; i< contours.size(); i++ )
{
cv::Scalar color = cv::Scalar( 255, 255, 255 );
drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, cv::Point() );
}
vector<vector<cv::Point> > contours_poly( contours.size() );
for(i = 0; i < contours.size(); i++)
{
// Gets the points for the contours
approxPolyDP(contours[i], contours_poly[i], cv::arcLength(cv::Mat(contours[i]), true) *0.05, true);
}
//Draw points and lines for shapes
for(i = 0; i < contours_poly.size(); i++)
{
for(j = 0; j < contours_poly[i].size(); j++)
{
cv::line(drawing, contours_poly[i][j], contours_poly[i][(j+1)%3], cv::Scalar(0, 255, 0), 2, 8);
cv::circle(drawing, contours_poly[i][j], 5, cv::Scalar (255, 0 , 0), 1, 8, 0);
//cout << contours_poly[i][j] << endl;
}
Area = contourArea(contours_poly[i], false);
//cout << "Area: " << Area << endl;
//shows what shapes were found
if(contours_poly[i].size() == 3 && Area > 15000)
{
a = fabs(contours_poly[i][0].x - contours_poly[i][1].x);
b = fabs(contours_poly[i][1].x - contours_poly[i][2].x);
c = fabs(contours_poly[i][2].x - contours_poly[i][0].x);
if(a < b && a < c)
{
if((contours_poly[i][0].x - contours_poly[i][2].x) > 0)
cout << "A left triangle" << endl;
else
cout << "A right triangle" << endl;
}
else if(b < a && b < c)
{
if((contours_poly[i][1].x - contours_poly[i][0].x) > 0)
cout << "A left triangle" << endl;
else
cout << "A right triangle" << endl;
}
else
{
if((contours_poly[i][0].x - contours_poly[i][1].x) > 0)
cout << "A left triangle" << endl;
else
cout << "A right triangle" << endl;
}
}
else if(contours_poly[i].size() == 4 && Area > 15000)
cout << "A rectangle was detected" << endl;
}
// Save the contours image
cv::imwrite("drawing.bmp", drawing);
// reset the image capture
image_capture = false;
}
}
cv::destroyWindow("Camera_Output"); //Destroy Window
cv::destroyWindow("Image_Output");
return 0;
}
|
d97be710443564d3876a6647d89b992c4d761c24
|
81a942d959f8712491be7a92e535020f24c7096d
|
/source/extensions/filters/http/jwt_authn/filter_config.cc
|
82d0fdd3ae425bfc26c8e4dceed7e713c5b3142a
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
siepkes/envoy-smartos
|
c83d4498a11eb6e866f81b19bfe0b439af9a3a8b
|
e5ffbbb24f7b53d594f6acf6b3f74df82b1c972d
|
refs/heads/smartos-v1.18.4
| 2023-08-16T11:33:19.306548
| 2021-10-21T07:58:51
| 2021-10-21T07:58:51
| 135,030,335
| 7
| 0
|
Apache-2.0
| 2021-10-05T23:36:57
| 2018-05-27T08:51:09
|
C++
|
UTF-8
|
C++
| false
| false
| 3,591
|
cc
|
filter_config.cc
|
#include "extensions/filters/http/jwt_authn/filter_config.h"
#include <algorithm> // std::sort
#include "common/common/empty_string.h"
using envoy::extensions::filters::http::jwt_authn::v3::RequirementRule;
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace JwtAuthn {
void FilterConfigImpl::init() {
ENVOY_LOG(debug, "Loaded JwtAuthConfig: {}", proto_config_.DebugString());
// Note: `this` and `context` have a a lifetime of the listener.
// That may be shorter of the tls callback if the listener is torn shortly after it is created.
// We use a shared pointer to make sure this object outlives the tls callbacks.
auto shared_this = shared_from_this();
tls_->set([shared_this](Event::Dispatcher&) -> ThreadLocal::ThreadLocalObjectSharedPtr {
return std::make_shared<ThreadLocalCache>(shared_this->proto_config_, shared_this->time_source_,
shared_this->api_);
});
std::vector<std::string> names;
for (const auto& it : proto_config_.requirement_map()) {
names.push_back(it.first);
name_verifiers_.emplace(it.first,
Verifier::create(it.second, proto_config_.providers(), *this));
}
// sort is just for unit-test since protobuf map order is not deterministic.
std::sort(names.begin(), names.end());
all_requirement_names_ = absl::StrJoin(names, ",");
for (const auto& rule : proto_config_.rules()) {
switch (rule.requirement_type_case()) {
case RequirementRule::RequirementTypeCase::kRequires:
rule_pairs_.emplace_back(Matcher::create(rule),
Verifier::create(rule.requires(), proto_config_.providers(), *this));
break;
case RequirementRule::RequirementTypeCase::kRequirementName: {
// Use requirement_name to lookup requirement_map.
auto map_it = proto_config_.requirement_map().find(rule.requirement_name());
if (map_it == proto_config_.requirement_map().end()) {
throw EnvoyException(fmt::format("Wrong requirement_name: {}. It should be one of [{}]",
rule.requirement_name(), all_requirement_names_));
}
rule_pairs_.emplace_back(Matcher::create(rule),
Verifier::create(map_it->second, proto_config_.providers(), *this));
} break;
case RequirementRule::RequirementTypeCase::REQUIREMENT_TYPE_NOT_SET:
rule_pairs_.emplace_back(Matcher::create(rule), nullptr);
break;
default:
NOT_REACHED_GCOVR_EXCL_LINE;
}
}
if (proto_config_.has_filter_state_rules()) {
filter_state_name_ = proto_config_.filter_state_rules().name();
for (const auto& it : proto_config_.filter_state_rules().requires()) {
filter_state_verifiers_.emplace(
it.first, Verifier::create(it.second, proto_config_.providers(), *this));
}
}
}
std::pair<const Verifier*, std::string>
FilterConfigImpl::findPerRouteVerifier(const PerRouteFilterConfig& per_route) const {
if (per_route.config().disabled()) {
return std::make_pair(nullptr, EMPTY_STRING);
}
const auto& it = name_verifiers_.find(per_route.config().requirement_name());
if (it != name_verifiers_.end()) {
return std::make_pair(it->second.get(), EMPTY_STRING);
}
return std::make_pair(
nullptr, absl::StrCat("Wrong requirement_name: ", per_route.config().requirement_name(),
". It should be one of [", all_requirement_names_, "]"));
}
} // namespace JwtAuthn
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
|
def128f2cec606b07c594b9e514fbfd7154996c1
|
283dbaa2586d69a19822f3047f2cca1106fa20ce
|
/point.h
|
7acbaab4f14b9fa92959f64d22904649661a7277
|
[] |
no_license
|
altimosk/boostgraph
|
5c1aaa8a6ab09734c17fd2ebe1eb76ec4bc19db2
|
414d789d683fcacbb0be6fdf72701de821da18e5
|
refs/heads/master
| 2016-08-12T05:54:59.604814
| 2016-02-04T12:21:58
| 2016-02-04T12:21:58
| 51,073,963
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,529
|
h
|
point.h
|
#pragma once
#include "geom_base.h"
#include <utility>
class tPoint : public std::pair<int, int>
{
public:
tPoint() { SetXY(0, 0); }
tPoint(int x, int y) { SetXY(x, y); }
void SetXY(int x, int y) { first = x; second = y; }
void Set(int i, int z) { (i ? second : first) = z; }
int Coord(int i) const { return (i ? second : first); }
int X() const { return first; }
int Y() const { return second; }
double ELength() const { return std::hypot(X(), Y()); }
tPoint& operator += (const tPoint& a) { first += a.first; second += a.second; return *this; }
tPoint& operator -= (const tPoint& a) { first -= a.first; second -= a.second; return *this; }
tPoint& operator *= (int n) { first *= n; second *= n; return *this; }
bool operator == (const tPoint& a) const { return first == a.first && second == a.second; }
bool operator != (const tPoint& a) const { return !(*this == a); }
};
inline tPoint operator + (const tPoint &a, const tPoint &b) { tPoint t = a; t += b; return t; }
inline tPoint operator - (const tPoint &a, const tPoint &b) { tPoint t = a; t -= b; return t; }
inline tPoint operator * (int n, const tPoint &a) { tPoint t = a; t *= n; return t; }
inline long long VectorProduct(tPoint v, tPoint w) { return VectorProduct(v.X(), v.Y(), w.X(), w.Y()); }
inline long long InnerProduct(tPoint v, tPoint w) { return InnerProduct(v.X(), v.Y(), w.X(), w.Y()); }
|
bcb4b85d5c96de43ba31da7086195483fbd200a1
|
3f870f239f01d02dbd157bb26c2e366a0c8cd842
|
/UVa1225-Digit Counting.cpp
|
d3d9ef6b8f7d98d109fe171de1c27afc7e6956d8
|
[] |
no_license
|
daisp92/AlgorithmContest
|
f3ded100e21db2fd08ca09c457c64be5f4cca236
|
6686f4158a4d7875dc19e6502e77681d7635cfc4
|
refs/heads/master
| 2021-09-08T02:59:47.013066
| 2018-03-06T10:16:41
| 2018-03-06T10:16:41
| 120,171,261
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 785
|
cpp
|
UVa1225-Digit Counting.cpp
|
#define LOCAL
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main() {
#ifdef LOCAL
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,t,tmp;
cin>>t; //t为案例个数;
while(t--){
cin>>n;
int ans[10]={0};//初始化,ans[10]保存的是0-9每个数字出现的次数;
for (int i = 1; i <= n; ++i) {//统计从1到n,1-9数字出现次数;
tmp=i;
while(tmp){
ans[tmp%10]++; //tmp个位数字次数+1;
tmp/=10;//tmp除以10
}
}
for (int j = 0; j <= 8; ++j) {//数字0-8中间用空格隔开;
cout<<ans[j]<<' ';
}
cout<<ans[9]<<endl;
}
return 0;
}
|
78fa64fa2311dfb7006a5ff2bdc6b82a2c3049f2
|
aa2ac425a8bb957a26763ae17e50d50f1cce8956
|
/src/Addons/GeoWay/gwXML_StandardMetaData/type_gmi.CMI_RequestedDate_Type.h
|
9db5b21cea15c53d9e2b7560df33d4fb78c8abde
|
[] |
no_license
|
radtek/CGISS
|
c7289ed19d912c432aae81d0cdbb6b080b4f5458
|
3f7cfa19d8024a67a5350d51e3f2f40a5e203576
|
refs/heads/master
| 2023-03-16T21:23:56.948744
| 2017-06-17T14:14:09
| 2017-06-17T14:14:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,284
|
h
|
type_gmi.CMI_RequestedDate_Type.h
|
#ifndef _ALTOVA_INCLUDED_gie_ALTOVA_gmi_ALTOVA_CMI_RequestedDate_Type
#define _ALTOVA_INCLUDED_gie_ALTOVA_gmi_ALTOVA_CMI_RequestedDate_Type
#include "type_gco.CAbstractObject_Type.h"
namespace gie
{
namespace gmi
{
class CMI_RequestedDate_Type : public ::gie::gco::CAbstractObject_Type
{
public:
gie_EXPORT CMI_RequestedDate_Type(xercesc::DOMNode* const& init);
gie_EXPORT CMI_RequestedDate_Type(CMI_RequestedDate_Type const& init);
void operator=(CMI_RequestedDate_Type const& other) { m_node = other.m_node; }
static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_gmi_altova_CMI_RequestedDate_Type); }
MemberElement<gco::CDateTime_PropertyType, _altova_mi_gmi_altova_CMI_RequestedDate_Type_altova_requestedDateOfCollection> requestedDateOfCollection;
struct requestedDateOfCollection { typedef Iterator<gco::CDateTime_PropertyType> iterator; };
MemberElement<gco::CDateTime_PropertyType, _altova_mi_gmi_altova_CMI_RequestedDate_Type_altova_latestAcceptableDate> latestAcceptableDate;
struct latestAcceptableDate { typedef Iterator<gco::CDateTime_PropertyType> iterator; };
gie_EXPORT void SetXsiType();
};
} // namespace gmi
} // namespace gie
#endif // _ALTOVA_INCLUDED_gie_ALTOVA_gmi_ALTOVA_CMI_RequestedDate_Type
|
02fa23aa2fbd3aa3ef2ef10fe7c9d00d24d1e94a
|
96a616b0502afb035dced40726b57ddf330ef05e
|
/Lab9/lab_9.cpp
|
89d086a3dbf6ea448e6fe98f44d2aa6264c40f4a
|
[] |
no_license
|
GalaxyHorder/CSCI-21-FALL-2015
|
e7c3f9958ef01ac916d890cde8928403fafd3ffb
|
100117c156414fe34177fef64abcb15522007524
|
refs/heads/master
| 2021-01-10T16:43:02.376910
| 2016-05-17T00:31:25
| 2016-05-17T00:31:25
| 50,547,652
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,267
|
cpp
|
lab_9.cpp
|
/*
* Name : lab_9.cpp
* Author : Xavier Winsor
* Description : Building a Spaceship Class
*/
#include "lab_9.h"
// CODE HERE -- CLASS FUNCTION DEFINITIONS
void Spaceship::set_name(string name){
name_=name;
}
void Spaceship::set_top_speed(double top_speed){
top_speed_=top_speed;
}
void Spaceship::set_fuel_source(string fuel_source){
fuel_source_=fuel_source;
}
void Spaceship::set_crew_capacity(int crew_capacity){
crew_capacity_=crew_capacity;
}
string Spaceship::name()const{
return name_;
}
double Spaceship::top_speed()const{
return top_speed_;
}
string Spaceship::fuel_source()const{
return fuel_source_;
}
int Spaceship::crew_capacity()const{
return crew_capacity_;
}
string Spaceship::ToString()const{
string names = name(), fuel_sources = fuel_source(), put_together;
double top_speeds = top_speed();
int crew_capacitys = crew_capacity();
stringstream speed, capacity;
speed.setf(ios::fixed|ios::showpoint);
speed.precision(2);
speed << top_speeds;
capacity << crew_capacitys;
put_together = names + "\nTop Speed: Warp " + speed.str() + "\nFuel Source: "+ fuel_sources + "\nCrew Capacity: " + capacity.str();
string final=put_together;
return final;
}
|
7a147bc2d96b745a2def72a6dce705843f034132
|
0af13c6830fdf1694e78613261ecbf1dfeeb76db
|
/Chapter03/Section-3.5.4/section-exercises/exercise-3.38/src/main.cpp
|
a4ac1d77c16d80ec4f04359e211a79c3f6560bf1
|
[] |
no_license
|
djtorel/cpp-primer
|
28bfb57929f8d6ee0c66c20779d05e63200e133c
|
7a2d728910eef2437f19ca610d14a5336958e342
|
refs/heads/master
| 2021-01-01T20:45:19.858189
| 2018-05-22T21:36:47
| 2018-05-22T21:36:47
| 98,927,234
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 371
|
cpp
|
main.cpp
|
/**
* Exercise 3.38: In this section, we noted that it was not only illegal but
* meaningless to try to add two pointers. Why would adding two pointers be
* meaningless?
*
* A: A pointer is an address in memory. Adding two addresses would have almost
* no use, as there isn't a real scenerio where that would return a predictable
* address that could be used.
*/
|
f69e8f47981ee33c89e60e1069478e2690676ae5
|
18e123ed01ba0cc7e4af1ae8fa7f290ce09efb1f
|
/所有学习程序/语言/CppTest_1/CppTest_1/FixedSet.cpp
|
ab05c9bbce6d9d440d8fc8b909f87b274e813a15
|
[] |
no_license
|
phpkangwang/test
|
afbe881d17c1eb61e5f55de438935e0e5250f0a9
|
76a952197f85d8bfb90e2d15badf21290c69e69d
|
refs/heads/master
| 2021-01-10T05:34:13.269095
| 2015-06-02T06:23:33
| 2015-06-02T06:23:33
| 36,422,858
| 0
| 1
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 1,184
|
cpp
|
FixedSet.cpp
|
#include "StdAfx.h"
#include "FixedSet.h"
#include<iostream>
using namespace std;
CFixedSet::CFixedSet(void)
{
m_nCount = 0;
}
CFixedSet::~CFixedSet(void)
{
}
void CFixedSet::Print(void)
{
if(m_nCount <= 0)
return;
cout<<"{";
for(int i =0;i <m_nCount-1;i++)
cout<<m_nBuf[i]<<",";
cout<<m_nBuf[m_nCount -1]<<"}"<<endl;
}
ostream& operator<<(ostream& os,CFixedSet& set)
{
if(set.m_nBuf>0)
{
os<<"{";
for(int i = 0;i<set.m_nCount-1;i++)
os<<set.m_nBuf[i]<<",";
os<<set.m_nBuf[set.m_nCount -1]<<"}"<<endl;
}
return os;
}
void CFixedSet::AddData(int data)
{
//ÊÇ·ñÂú£¬ÊÇ·ñ´æÔÚ
if( IsFull() || IsExist(data) )
return;
//Ìí¼Ó
m_nBuf[m_nCount] = data;
m_nCount++;
}
void CFixedSet::DeleteData(int data)
{
if(!IsExist(data))
return;
for(int i =0;i <m_nCount; i++)
if(m_nBuf[i] == data)
{
for(int j=i;j<m_nCount -1;j++)
m_nBuf[j] = m_nBuf[j+1];
m_nCount--;
break;
}
}
bool CFixedSet::IsExist(int n)
{
for(int i =0;i<m_nCount;i++)
if(m_nBuf[i] == n)
return true;
return false;
}
bool CFixedSet::IsFull(void)
{
return m_nCount == NUMBER;
}
int& CFixedSet::operator[](int index)
{
return m_nBuf[index];
}
|
8178c7951cf43b6c5c4bf47bfb8382ba590072cb
|
08ff892af644642d3d75c727d52200443e39796c
|
/module-03/ex02/main.cpp
|
5c629e523f34ec1cea5c2701ee355d81ccce627e
|
[
"MIT"
] |
permissive
|
kotabrog/CPP-module
|
9bf0f1866a34fb42e1ae949b6e88a90cddaef80e
|
db858e57ac194d4ca9b38667ff3820418b42e9c8
|
refs/heads/main
| 2023-07-02T06:28:53.931788
| 2021-08-14T07:03:54
| 2021-08-14T07:03:54
| 387,164,790
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 484
|
cpp
|
main.cpp
|
#include "FragTrap.hpp"
int main()
{
FragTrap a;
std::cout << "hitpoints: " << a.getHitpoints() << std::endl;
std::cout << "energyPoints: " << a.getEnergyPoints() << std::endl;
std::cout << "attackDamage: " << a.getAttackDamage() << std::endl;
a.takeDamage(3);
FragTrap b(a);
b.takeDamage(3);
FragTrap c;
c = b;
b.takeDamage(3);
FragTrap d("crap");
d.attack("tag");
d.takeDamage(4);
d.beRepaired(10);
d.highFivesGuys();
}
|
7c219864ab67566c762dc13538bba7e6487e66b9
|
76c54c8d1de7e8f8b34993cee5dea4084eff01c5
|
/Utils/DimensionSizes.h
|
51a0cbe152f51819179819515d6eaa929eb6ddf1
|
[] |
no_license
|
jacobwjs/AO-KWave-MCBoost
|
f05d130568e80380b7ed61c05036f0dafb7a0840
|
25af3707ea8f10e47ebae1a420993451cfae31bd
|
refs/heads/master
| 2021-05-01T06:49:42.330836
| 2013-08-17T09:40:57
| 2013-08-17T09:40:57
| 7,180,789
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,378
|
h
|
DimensionSizes.h
|
/**
* @file DimensionSizes.h
* @author Jiri Jaros \n
* CECS, ANU, Australia \n
* jiri.jaros@anu.edu.au \n
*
* @brief The header file containing the structure with 3D dimension sizes
*
* @version kspaceFirstOrder3D 2.13
* @date 9 August 2011, 12:34 (created) \n
* 14 September 2012, 14:20 (revised)
*
* @section License
* This file is part of the C++ extension of the k-Wave Toolbox (http://www.k-wave.org).\n
* Copyright (C) 2012 Jiri Jaros and Bradley Treeby
*
* This file is part of k-Wave. k-Wave is free software: you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* k-Wave is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with k-Wave. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DIMENSIONSIZES_H
#define DIMENSIONSIZES_H
#include <stdlib.h>
#include <stdio.h>
using namespace std;
/**
* @var SSE_ALIGNMENT
* @brief memory alignment for SSE2 (16B)
*/
const int SSE_ALIGNMENT = 16;
/**
* @struct TDimensionSizes
* @brief Structure with 3D dimension sizes
*/
struct TDimensionSizes {
/// X dimension size
size_t X;
/// Y dimension size
size_t Y;
/// Z dimension size
size_t Z;
/// default constructor
TDimensionSizes(): X(0), Y(0), Z(0) {};
/**
* @brief Constructor
* @param [in] x
* @param [in] y
* @param [in] z
*/
TDimensionSizes(size_t x, size_t y, size_t z): X(x), Y(y), Z(z) {};
/**
* @brief Copy constructor
* @param src
*/
TDimensionSizes(const TDimensionSizes & src) :
X(src.X), Y(src.Y), Z(src.Z) {};
/**
* @brief Get element count
* @return element count
*/
size_t GetElementCount () const {return X * Y * Z; };
/**
* Operator =
* @param src
* @return new value of the element
*/
TDimensionSizes& operator = (const TDimensionSizes & src){
if (this != &src){
X = src.X;
Y = src.Y;
Z = src.Z;
}
return *this;
};
/**
* @brief Operator ==
* @param [in] other - the second operand to compare with
* @return true if ==
*/
bool operator== (const TDimensionSizes &other) const {
return ((X == other.X) && (Y == other.Y) && (Z == other.Z));
}
/**
* @brief Operator !=
* @param [in] other - the second operand to compare with
* @return true if !=
*/
bool operator!= (const TDimensionSizes &other) const {
return ((X != other.X) || (Y != other.Y) || (Z != other.Z));
}
}; // end of TDimensionSizes
//------------------------------------------------------------------------------
#endif /* DIMENSIONSIZES_H */
|
481a397d5f91fc0c7f13dfc1987896fb82e6a9f6
|
89019d6fc0b0d41105222adb3cdb41f23ca93e9a
|
/str_vec/str_vec.hh
|
a39569e309c395ce5b98a2845103fcf6531d3555
|
[] |
no_license
|
vitmy0000/cpp_primer_example
|
d21a259c8bce96583795cf40f7a07f1c982049c5
|
fe4b05b5798751ea524ea643fd97bfbc56f0f5fb
|
refs/heads/master
| 2020-12-02T18:06:08.407213
| 2017-08-28T20:24:07
| 2017-08-28T20:24:07
| 96,473,208
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,547
|
hh
|
str_vec.hh
|
#ifndef STR_VEC_HH
#define STR_VEC_HH
#include <memory>
#include <string>
namespace cpp_primer {
class StrVec {
public:
StrVec();
StrVec(const StrVec&);
StrVec(StrVec&&) noexcept;
StrVec& operator=(const StrVec&);
StrVec& operator=(StrVec&&) noexcept;
~StrVec();
void push_back(const std::string&); // copy the element
void push_back(std::string&&); // move the element
// getters & setters
size_t size() const;
size_t capacity() const;
std::string* begin() const;
std::string* end() const;
private:
static std::allocator<std::string> alloc; // allocate the elements
void check_and_alloc(); // used by functions that add elements to a StrVec
// return pair of pointers:
// pointing to the beginning of the new space
// and one pass the element it copied
std::pair<std::string*, std::string*> alloc_and_copy(
const std::string*, const std::string*);
void free(); // destroy the elements and free the space
void reallocate(); // get more space and copy the exsisting elements
std::string* elements_; // pointer to the first element in the array
std::string* first_free_; // pointer to the first free element in the array
std::string* cap_; // pointer to one past the end of the array
};
inline std::size_t StrVec::size() const { return first_free_ - elements_; }
inline std::size_t StrVec::capacity() const { return cap_ - elements_; }
inline std::string* StrVec::begin() const { return elements_; }
inline std::string* StrVec::end() const { return first_free_; }
} // cpp_primer
#endif
|
7422b91458241161091113238702ac56ba6e2aa5
|
883c7ddf58c4dbc99285c923d71af95320f1353f
|
/lab2/insertion.cc
|
c41a72bf36b455f28560f1b91baece5122d17a74
|
[] |
no_license
|
lorenzodb1/ubc-cpsc221-labs-projects
|
5fc9de8f3ec5c9966727534a7a8e765a2a797a24
|
9b3a05692f401dbb6f761c5f134908bfc7f9bd45
|
refs/heads/master
| 2016-09-14T06:38:47.708129
| 2016-05-04T01:46:46
| 2016-05-04T01:46:46
| 58,007,450
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,553
|
cc
|
insertion.cc
|
#include <iostream>
#include <cstdlib>
#include "insertion.h"
// insertion sort with several errors
// store command-line arguments in x[] array
void getArgs( int argc, char **argv ) {
x_size = argc - 1;
for(int ii = 0; ii < x_size; ii++ )
x[ii] = atoi( argv[ ii + 1 ] );
}
void scootOver( int jj ) {
for(int kk = y_size; kk > jj; kk-- ){ //k++ -> k-- && kk = y_size - 1 -> kk = y_size
y[kk] = y[ kk - 1 ];
}
}
void insert( int xx ) {
if( y_size == 0 ) { //y_size = 0 -> y_size == 0
y[0] = xx;
return;
}
// Need to insert just before the first y element that xx is less than
int jj = 0;
for(jj = 0; jj < y_size; jj++ ) {
if( xx < y[jj] ) {
// shift y[jj], y[ jj+1 ], ... rightward before inserting xx
scootOver( jj );
y[jj] = xx;
return;
}
}
if ( xx >= y[jj] ) { //added if statement to take care of the situation when the number inserted is greater than the ones in the array
y[jj] = xx;
}
}
void processData() {
for(int ii = 0; ii < x_size; ii++ ) {
y_size = ii;
// put x[ ii ] in the proper place among y[0],....,y[ y_size - 1 ]
insert( x[ ii ] );
}
}
void printResults() {
for(int ii = 0; ii < x_size; ii++ ){
std::cout << y[ii] << " ";
}
std::cout << std::endl;
}
int main( int argc, char ** argv ) {
x = new int[argc - 1]; //added this line to make array x dynamic
y = new int[argc - 1]; //added this line to make array y dynamic
getArgs( argc, argv );
processData();
printResults();
delete[] x;
delete[] y;
}
|
4d6fae73afcaea8e328ae5cfadceacec316bc69a
|
5abd571c3d803d1a6a69bac0b6edddd422cc7fb4
|
/snake.cpp
|
25a4efed1ec73da8d55897434fd2f9a8e15f3a3d
|
[
"MIT"
] |
permissive
|
AInoob/HA
|
5693fd612ebf871f6094a5eaa2bf3b90a3d2386c
|
713bcbe0c475668fb180a52d70cea4b6fa8f8495
|
refs/heads/master
| 2020-05-17T02:53:45.567708
| 2014-05-20T01:09:00
| 2014-05-20T01:09:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,404
|
cpp
|
snake.cpp
|
#include "stdafx.h"
using namespace std;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
boolean ask(string question)
{
char response = 'x';
cout << question << "enter y or n to choose" << endl;
cin >> response;
response = tolower(response);
while (!(response == 'y' || response == 'n'))
{
cout << "invalid input, enter y or n to choose" << endl;
cin >> response;
response = tolower(response);
}
if (response == 'y')
{
return true;
}
return false;
}
int ask(int min, int max, string question)
{
int r;
string input;
cout << question << endl;
char *temp;
cin >> input;
temp = const_cast<char*>(input.c_str());
r = atoi(temp);
while (r < min || r>max)
{
cout << "invalid input, try again" << endl;
cin >> input;
temp = const_cast<char*>(input.c_str());
r = atoi(temp);
}
return r;
}
int** matrix(int x, int y, int value)
{
int **m = new int*[x];
for (int i = 0; i < x; i++)
{
m[i] = new int[y];
}
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
m[i][j] = value;
}
}
return m;
}
void changeSize(int a, int b)
{
SMALL_RECT windowSize = { 0, 0, a, b };
SetConsoleWindowInfo(hConsole, TRUE, &windowSize);
}
void gotoxy(int x, int y)
{
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(hConsole, pos);
}
void gotoxy(COORD p)
{
gotoxy(p.X, p.Y);
}
void show(int x, int y, string show)
{
gotoxy(x * 2, y);
cout << show;
}
class Node
{
private:
COORD pos;
public:
Node* next;
Node* prev;
Node(int x, int y)
{
pos.X = x;
pos.Y = y;
}
COORD getPos()
{
return pos;
}
};
class Snake
{
int **map;
int MAX_W = 39, MAX_H = 24;
int times = 0;
int point = 0;
int length = 0;
char direction;
boolean dead = false;
Node *head;
Node *tail;
COORD food;
public:
void loadMap()
{
Node *current = head;
while (current != NULL)
{
map[current->getPos().X][current->getPos().Y] = 1;
length++;
current = current->next;
}
}
Snake()
{
show(3, 5, "■");
show(3, 4, "■");
head = new Node(3, 5);
tail = new Node(3, 4);
head->next = tail;
head->prev = NULL;
tail->next = NULL;
tail->prev = head;
}
boolean isDead()
{
return dead;
}
void setWH(int a, int b)
{
MAX_W = a;
MAX_H = b;
map = matrix(a+1, b+1, 0);
loadMap();
}
void end()
{
delete map;
}
boolean paintItSelf(int x, int y)
{
Node *current = head;
while (current->next != NULL)
{
if ((x == current->getPos().X) && (y == current->getPos().Y))
{
return true;
}
current = current->next;
}
return false;
}
boolean eatItSelf(int x, int y)
{
if (paintItSelf(x, y))
{
dead = true;
return true;
}
else
{
return false;
}
}
void makeFood()
{
times++;
point = point + times;
int r = rand() % (MAX_W*MAX_H-length);
for (int i = 0; i < MAX_W; i++)
{
for (int j = 0; j < MAX_H; j++)
{
if (map[i][j] == 0)
{
r--;
if (r == -1)
{
food.X = i;
food.Y = j;
show(food.X, food.Y, "★");
return;
}
}
}
}
return;
}
boolean hitWall(int x, int y)
{
if (x<0 || y<0 || x>MAX_W || y>MAX_H)
{
dead = true;
return true;
}
return false;
}
void move(int x, int y)
{
gotoxy(0, 0);
cout << "Score: " << point;
Node *newHead = new Node(x, y);
head->prev = newHead;
newHead->next = head;
head = newHead;
map[head->getPos().X][head->getPos().Y] = 1;
show(head->getPos().X, head->getPos().Y, "■");
if ((food.X == x) && (food.Y == y))
{
makeFood();
length++;
}
else
{
if (!paintItSelf(tail->getPos().X, tail->getPos().Y))
{
map[tail->getPos().X][tail->getPos().Y] = 0;
show(tail->getPos().X, tail->getPos().Y, " ");
}
tail = tail->prev;
tail->next = NULL;
}
}
void headTo(char d)
{
direction = d;
COORD headPos;
headPos = head->getPos();
switch (direction)
{
case 'w':
headPos.Y = headPos.Y - 1;
break;
case 's':
headPos.Y = headPos.Y + 1;
break;
case 'a':
headPos.X = headPos.X - 1;
break;
case 'd':
headPos.X = headPos.X + 1;
break;
}
if ((!eatItSelf(headPos.X, headPos.Y)) && (!hitWall(headPos.X, headPos.Y)))
{
move(headPos.X, headPos.Y);
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
SetConsoleTitle(L"SNAKE");
int w, h, temp = 0;
srand((int)time(NULL));
double speed = 100;
gotoxy(0, 0);
if (ask("Do you want to customize settings?"))
{
cout << "input width(max 39, min 10) and height(max 24, min 10)" << endl;
w=ask(10, 39, "input the width");
h=ask(10, 24, "input the height");
changeSize(w*2+1, h);
}
else
{
w = 39;
h = 24;
}
cout << "j and k can change the speed of snake" << endl << "enter space to pause, then press any move key to resume" << endl;
cout << "enter q to exit" << endl;
while (temp < 3)
{
Sleep(1000);
temp++;
cout << 4 - temp << endl;
}
system("cls");
while (true)
{
Snake s;
s.setWH(w, h);
char direction = 'd';
char newDirection = 'x';
s.makeFood();
while (!s.isDead())
{
gotoxy(0, 1);
cout << "Speed: " << speed;
if (_kbhit())
newDirection = _getch();
while (newDirection == ' ')
{
if (_kbhit())
newDirection = _getch();
}
if (newDirection == 224 || newDirection == 0 || newDirection == -32)
{
newDirection = _getch();
switch (newDirection)
{
case 72:
newDirection = 'w';
break;
case 80:
newDirection = 's';
break;
case 75:
newDirection = 'a';
break;
case 77:
newDirection = 'd';
break;
}
}
newDirection = (char)towlower(newDirection);
if (newDirection == 'j')
{
speed = 1.1*speed;
newDirection = 'x';
}
else if (newDirection == 'k')
{
if (speed >= 3)
speed = speed / 1.1;
newDirection = 'x';
}
else if (newDirection == 'q')
{
return 0;
}
else if (newDirection == 'w' || newDirection == 'a' || newDirection == 's' || newDirection == 'd')
{
if ((direction == 'w'&&newDirection != 's') || (direction == 's'&&newDirection != 'w') || (direction == 'a'&&newDirection != 'd') || (direction == 'd'&&newDirection != 'a'))
{
direction = newDirection;
}
}
s.headTo(direction);
Sleep((int)speed);
}
gotoxy(0, 6);
s.end();
cout << "Game over! Press enter to restart";
while (newDirection != 13)
{
if (_kbhit())
newDirection = _getch();
}
system("cls");
}
return 0;
}
|
5bee4a7d7ac06df9ac0d39c53e7670e71146b1d0
|
e8fa46e0e5318c229a49b2803910e12e4d29884e
|
/leetcode/347.cpp
|
1252ca649cce9116abbb55fcf296b6e6f74ec801
|
[] |
no_license
|
igorbragaia/algorithms
|
e6bc71b0612a65b2650c259aa2cdec593b9f6c53
|
0b4204c5a11d736c7299bd8c485e325eed630a19
|
refs/heads/master
| 2021-12-12T13:49:13.226739
| 2021-11-27T02:51:23
| 2021-11-27T02:51:23
| 106,027,078
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 659
|
cpp
|
347.cpp
|
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> hashing;
for(int num : nums){
if(hashing.find(num) != hashing.end())
hashing[num]++;
else
hashing[num] = 1;
}
priority_queue<pair<int,int>>pq;
for(unordered_map<int,int>::iterator it = hashing.begin(); it != hashing.end(); it++){
pq.push(make_pair(it->second,it->first));
}
vector<int>response;
while(k--){
response.push_back(pq.top().second);
pq.pop();
}
return response;
}
};
|
75bda07eaee08f08610d561e397176e289f1e868
|
cc843c464b8c52c947782efc8131f6e978f902a2
|
/CaptionPanel.h
|
07080c4ccc57103ac43b2fecb20c0db79564b3e3
|
[] |
no_license
|
ntxbaby/broswer
|
81f32e90a6b904139341155ae604e6b153ba4265
|
3d1670b311ff58516961efcce41d4479edf10ccf
|
refs/heads/master
| 2020-04-09T05:47:44.933129
| 2013-12-07T06:39:27
| 2013-12-07T06:39:27
| 15,001,523
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 478
|
h
|
CaptionPanel.h
|
#pragma once
#include "Panel.h"
#include "LeftCaption.h"
#include "CenterCaption.h"
#include "RightCaption.h"
class CCaptionPanel :
public CPanel
{
public:
CCaptionPanel(void);
public:
~CCaptionPanel(void);
DECLARE_MESSAGE_MAP()
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
private:
CLeftCaption m_leftCaption;
CCenterCaption m_centerCaption;
CRightCaption m_RightCaption;
afx_msg void OnPaint();
public:
afx_msg void OnSize(UINT nType, int cx, int cy);
};
|
ff7e2c78a394fa0538a5ea2ab00c15382d47198c
|
f6d271233b8a91f63c30148cdcdb86341ba45c2f
|
/external/TriBITS/tribits/examples/TribitsExampleProject/packages/mixed_lang/src/MixedLang.cpp
|
7b1bd60171d0d80f1f109b08f672f01de126efa0
|
[
"BSD-2-Clause",
"BSD-3-Clause",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive",
"MIT"
] |
permissive
|
wawiesel/BootsOnTheGround
|
09e7884b9df9c1eb39a4a4f3d3f8f109960aeca0
|
bdb63ae6f906c34f66e995973bf09aa6f2999148
|
refs/heads/master
| 2021-01-11T20:13:10.304516
| 2019-10-09T16:44:33
| 2019-10-09T16:44:33
| 79,069,796
| 4
| 1
|
MIT
| 2019-10-09T16:44:34
| 2017-01-16T00:47:11
|
CMake
|
UTF-8
|
C++
| false
| false
| 96
|
cpp
|
MixedLang.cpp
|
#include "MixedLang.hpp"
std::string tribits_mixed::mixedLang()
{
return "Mixed Language";
}
|
257eaddc90f14389e1342cdf4e3b86a73b0d8733
|
28e7d0e0dbc0d38cf5c4d823af1c0b1ef42cf343
|
/Solutions/136.cpp
|
2200cd3fae28d44a5a5c525680d0895f71866f0e
|
[] |
no_license
|
tr0j4n034/Project-Euler
|
33a530c6ad3a4eb5ec29c2962ee6f7576ccaac15
|
7da7a23f4b95d831d63ee6c55a575506c0f138e7
|
refs/heads/master
| 2020-05-09T21:07:06.732358
| 2019-04-15T07:12:57
| 2019-04-15T07:12:57
| 181,430,393
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 807
|
cpp
|
136.cpp
|
//
// main.cpp
// practice
//
// Created by Mahmud on 6/10/18.
// Copyright © 2018 Mahmud. All rights reserved.
//
#include <iostream>
#include <cmath>
using namespace std;
const int MAX = 50000000;
int ways[MAX];
int main() {
cerr << "done in: " << 1. * clock() / CLOCKS_PER_SEC << endl;
for (int i = 1; i < MAX; i ++) {
for (int j = i, k = 1; j < MAX; j += i, k ++) {
if ((i + k) % 4 == 0) {
int d = (i + k) / 4;
int z = 3 * d - i;
if (z > 0) ways[j] ++;
}
}
}
int s = 0;
for (int i = 1; i < MAX; i ++) {
if (ways[i] == 1) {
s ++;
}
}
cout << s << endl;
cerr << "done in: " << 1. * clock() / CLOCKS_PER_SEC << endl;
return 0;
}
|
c09276c6b1db8b587f428b905641c879429f7552
|
8e75847867a2ab519b6b9472d5af970e57447391
|
/Source/OperationCode/Interpreter/Lexer/Tokens/Keywords/T_For.cpp
|
2a0d7b3813e0b9fc6434e1702bbe365eb958c29a
|
[] |
no_license
|
glitchhunter/OperationCode
|
d06ef5979a275368988b4c26eeb01774e60d4e2b
|
5a32862ab15702ab454e5322513f1dd57ddc4f9b
|
refs/heads/master
| 2023-01-06T16:05:05.082126
| 2019-03-22T14:09:28
| 2019-03-22T14:09:28
| 147,513,982
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 149
|
cpp
|
T_For.cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "T_For.h"
UT_For::UT_For()
{
TokenName = TEXT("For");
}
|
508534e8c4f666e0b2249e43c86b02f5a031bb21
|
05f6ae92ac91a49039851311707d0f695f6c4167
|
/LeerXML.cpp
|
b353d254c9603dc5caecab5f14f9a30b6d514f3e
|
[] |
no_license
|
ablasco86/Real-time-RGB-D-data-processing-on-GPU-architecture
|
41753abfc95505b74371f11ff8110f1c2e7f4d76
|
c36d249e3b7168f7444ebac57d44f769135a80ff
|
refs/heads/master
| 2021-01-16T01:01:41.877242
| 2014-02-18T13:34:28
| 2014-02-18T13:34:28
| 16,948,919
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,419
|
cpp
|
LeerXML.cpp
|
#include "LeerXML.h"
/* Leer un fichero XML
*
* Carga un fichero de tipo XML donde se almacenan los valores de los parámetros que usaremos en cada prueba
* del sistema.
*
*/
float ReturnFloat (TiXmlDocument &doc, const char* nameVariable)
{
TiXmlNode* node = 0;
float valor = 0.0;
String variable;
node = doc.RootElement();
node = node->FirstChild("float");
node = node->FirstChild(nameVariable);
node = node->FirstChild();
variable = node->Value();
valor = atof(variable.c_str());
return valor;
}
int ReturnInt (TiXmlDocument &doc, const char* nameVariable)
{
TiXmlNode* node = 0;
int valor = 0;
String variable;
node = doc.RootElement();
node = node->FirstChild("int");
node = node->FirstChild(nameVariable);
node = node->FirstChild();
variable = node->Value();
valor = atoi(variable.c_str());
return valor;
}
String ReturnString(TiXmlDocument &doc, const char* nameVariable)
{
TiXmlNode* node = 0;
String valor;
node = doc.RootElement();
node = node->FirstChild("string");
node = node->FirstChild(nameVariable);
node = node->FirstChild();
valor = node->Value();
return valor;
}
QString ReturnQString(TiXmlDocument &doc, const char* nameVariable)
{
TiXmlNode* node = 0;
QString valor;
node = doc.RootElement();
node = node->FirstChild("qstring");
node = node->FirstChild(nameVariable);
node = node->FirstChild();
valor = node->Value();
return valor;
}
|
b7018c54851911b9e2ffd76b6e96b830bfe62a18
|
29693ceaa63ffcc47a69253a063c39f6dafa0b24
|
/Buttons/Game/physics constants.hpp
|
783db548971cf0f82b78b62334ba1de135d27a1a
|
[] |
no_license
|
indianakernick/Buttons
|
cd4c5d7647cca9e3a1978ab6c0c039e96631c9b8
|
3e010f2626c0a6d7335c5cb7c2125588641bfc45
|
refs/heads/master
| 2022-05-16T18:43:09.120460
| 2018-10-06T09:20:59
| 2018-10-06T09:20:59
| 109,796,074
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 644
|
hpp
|
physics constants.hpp
|
//
// physics constants.hpp
// Buttons
//
// Created by Indi Kernick on 7/11/17.
// Copyright © 2017 Indi Kernick. All rights reserved.
//
#ifndef physics_constants_hpp
#define physics_constants_hpp
#include <Box2D/Common/b2Math.h>
const b2Vec2 GRAVITY = {0.0f, -9.80665f};
constexpr int32 VELOCITY_ITER = 16;
constexpr int32 POSITION_ITER = 8;
constexpr float DEBUG_DRAW_STROKE_WIDTH = 1.0f / 32.0f;
constexpr bool ENABLE_SHAPE_RENDER = true;
constexpr bool ENABLE_JOINT_RENDER = true;
constexpr bool ENABLE_AABB_RENDER = false;
constexpr bool ENABLE_PAIR_RENDER = false;
constexpr bool ENABLE_CENTER_OF_MASS_RENDER = false;
#endif
|
fccb89a18bcf0beff3e5cf59bb3b73aa48a88112
|
e759afc08c16a4a85a2dba283e5fd1d6ea3b5c05
|
/acm.1110.cpp
|
b9b685607c903d2babbd440160348ce9008efb4e
|
[] |
no_license
|
ZNWhahaha/C-Cpp
|
35a2cd50e046776b1c30125a81a18c47b91aaafb
|
23029d002e14f34c0419206703c919b11891a563
|
refs/heads/master
| 2020-07-24T22:51:41.868010
| 2016-11-15T06:55:29
| 2016-11-15T06:55:29
| 73,784,085
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 103
|
cpp
|
acm.1110.cpp
|
#include<stdio.h>
main()
{ int a,b,t;
scanf("%d %d",&a,&b);
t=a;
a=b;
b=t;
printf("%d %d",a,b);
}
|
6b580503a33e5ac2b9e472fec1c63685f3e4872a
|
bde14002d00d0a46a760ad7d301c40da9dacdb44
|
/src/Node.cpp
|
d883aa1baeb9c1d85c6618c309b09b3d9f65affb
|
[] |
no_license
|
BackupTheBerlios/glui-ng
|
7a77ed9ed47bead8e5b731d6a3ea80d383a0feaa
|
73c2cb2b9c54bca90c71bf2d72252b6b5b4ec51e
|
refs/heads/master
| 2020-04-26T19:11:23.343505
| 2010-04-04T09:04:27
| 2010-04-04T09:04:27
| 39,715,137
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,257
|
cpp
|
Node.cpp
|
/*
GLUI-ng, an openGL widget toolkit. Copyright (C) 2010 MALET Jean-Luc
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License,
or (at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this library;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
based on the work of Paul Rademacher (orignal software http://glui.sourceforge.net/)
*/
#include <GL/glui/Node.h>
#include <GL/glui/debug.h>
#include <GL/glui/MasterObject.h>
#include <GL/glui/Exception.h>
using namespace GLUI;
#define MODULE_KEY "GLUI_DEBUG_NODE"
/********************************************* Node::Node() *******/
Node::Node()
{
_level = 0;
ChildCount = 0;
}
Node::Node(const char* name)
{
NodeName = name;
_level = 0;
ChildCount = 0;
}
Node::~Node()
{
if (this->ChildCount != GetCount())
{
GLUI_THROW(ENOTSUP,
"trying to delete a node that have still owners...");
}
if (this->next_sibling != NULL)
{
this->next_sibling->prev_sibling = this->prev_sibling;
}
if (this->prev_sibling != NULL)
{
this->prev_sibling->next_sibling = this->next_sibling;
}
while (this->child_head != NULL)
{
RemoveChild(this->child_head);
}
}
////////////////////////////////////////////////////////////////////////
const char* Node::Name()
{
return this->NodeName;
}
/********************************************* Node::first() *******/
/* Returns first sibling in 'this' node's sibling list */
NCRC_AutoPtr<Node> Node::first_sibling( void )
{
if ( parent_node == NULL )
return this; /* root node has no siblings */
else
return parent_node->child_head;
}
/********************************************* Node::last() *******/
/* Returns last sibling in 'this' node's sibling list */
NCRC_AutoPtr<Node> Node::last_sibling( void )
{
if ( parent_node == NULL )
return this; /* root node has no siblings */
else
return parent_node->child_tail;
}
/******************************************** Node::prev() ********/
/* Returns prev sibling in 'this' node's sibling list */
NCRC_AutoPtr<Node> Node::prev( void )
{
return prev_sibling;
}
/******************************************** Node::next() ********/
/* Returns next sibling in 'this' node's sibling list */
NCRC_AutoPtr<Node> Node::next( void )
{
return next_sibling;
}
///////////////////////////////////////////////////////////////////////
// returns root node or NULL if already the root node
NCRC_AutoPtr<Node> Node::GetRootNode()
{
NCRC_AutoPtr<Node> current = this->parent_node;
if(current == NULL || current == MasterObject::Instance() ) return this;
while (current != NULL && current->parent() != NULL)
{
current = current->parent();
}
return current;
}
////////////////////////////////////////////////////////////////////////
int Node:: RemoveParent( NCRC_AutoPtr<Node> parent )
{
if (parent_node == parent)
{
parent_node = NULL;
delete this;
}
else
{
GLUI_THROW(EINVAL,
"trying to remove a parent that isn't in parent list");
}
return 0;
}
/////////////////////////////////////////////////////////////////////////
void Node::removeReference()
{
if (ChildCount == (GetCount()-1))
{
while (child_head != NULL)
{
RemoveChild(child_head);
}
}
NonCopyableReferenceCountedClass::removeReference();
}
/************************************ Node::add_control() **************/
int Node::add_control( NCRC_AutoPtr<Node> child )
{
LinkLast( child );
ChildCount ++;
return 0;
}
int Node::RemoveChild( NCRC_AutoPtr<Node> child )
{
NCRC_AutoPtr<Node> curr = this->child_head;
this->ChildCount--;
while ( curr != NULL && curr != child)
{
curr = curr->next();
}
if (curr != NULL)
{
// if the node is in middle of the chain
if ( curr->prev_sibling != NULL && curr->next_sibling != NULL)
{
curr->prev_sibling->next_sibling = curr->next_sibling;
curr->next_sibling->prev_sibling = curr->prev_sibling;
}
else
{
if (curr == this->child_head )
{ //first child
this->child_head = curr->next_sibling;
if (this->child_head != NULL)
{
this->child_head->prev_sibling = NULL;
}
}
if (curr == this->child_tail)
{ // last child
this->child_tail = curr->prev_sibling;
if (this->child_tail != NULL)
{
this->child_tail->next_sibling = NULL;
}
}
}
curr->_level = 0;
curr->parent_node = NULL;
curr->next_sibling = NULL;
curr->prev_sibling = NULL;
}
else
{
GLUI_THROW(EINVAL,
"trying to unlink a node that isn't in the childs list");
}
}
/*************************** Node::link_this_to_parent_last() *******/
/* Links as last child of parent */
void Node::LinkLast( NCRC_AutoPtr<Node> new_child )
{
if ( this->child_tail == NULL ) { /* parent has no children */
this->child_head = new_child;
}
else { /* parent has children */
this->child_tail->next_sibling = new_child;
new_child->prev_sibling = this->child_tail;
}
this->child_tail = new_child;
new_child->parent_node = this;
new_child->_level = this->_level+1;
}
/*************************** Node::link_this_to_parent_first() *******/
/* Links as first child of parent */
void Node::link_this_to_parent_first( NCRC_AutoPtr<Node> new_parent )
{
if ( new_parent->child_head == NULL ) { /* parent has no children */
new_parent->child_tail = this;
}
else { /* parent has children */
new_parent->child_head->prev_sibling = this;
this->next_sibling = new_parent->child_head;
}
new_parent->child_head = this;
this->parent_node = new_parent;
this->_level = parent_node->level()+1;
}
/**************************** Node::link_this_to_sibling_next() *****/
void Node::link_this_to_sibling_next( NCRC_AutoPtr<Node> sibling )
{
if ( sibling->next_sibling == NULL ) { /* node has no next sibling */
sibling->next_sibling = this;
this->prev_sibling = sibling;
/* This was the parent's last child, so update that as well */
if ( sibling->parent_node != NULL ) {
sibling->parent_node->child_tail = this;
}
}
else { /* node already has a next sibling */
sibling->next_sibling->prev_sibling = this;
this->next_sibling = sibling->next_sibling;
sibling->next_sibling = this;
this->prev_sibling = sibling;
}
this->parent_node = sibling->parent_node;
this->_level = parent_node->level()+1;
}
/**************************** Node::link_this_to_sibling_prev() *****/
void Node::link_this_to_sibling_prev( NCRC_AutoPtr<Node> sibling )
{
if ( sibling->prev_sibling == NULL ) { /* node has no prev sibling */
sibling->prev_sibling = this;
this->next_sibling = sibling;
/* This was the parent's first child, so update that as well */
if ( sibling->parent_node != NULL ) {
sibling->parent_node->child_head = this;
}
}
else { /* node already has a prev sibling */
sibling->prev_sibling->next_sibling = this;
this->prev_sibling = sibling->prev_sibling;
sibling->prev_sibling = this;
this->next_sibling = sibling;
}
this->parent_node = sibling->parent_node;
this->_level = parent_node->level()+1;
}
/**************************************** Node::dump() **************/
void Node::dump( FILE *out, const char *name )
{
MSG( "node: " << name << endl );
MSG(" parent: " << (void *) parent_node.getPointee()
<<" child_head: " << (void *) child_head.getPointee()
<<" child_tail: " << (void *) child_tail.getPointee()
<< endl);
MSG(" next: " << (void *) next_sibling.getPointee()
<< " prev: " << (void *) prev_sibling.getPointee() << endl);
}
const char* Node::whole_tree(int start)
{
static std::string tree;
if (start) {
tree.clear();
tree += "\"";
}
if (parent_node != NULL) {
parent_node->whole_tree(0);
tree += ".";
}
if (NodeName)
{
tree += NodeName;
}
else
{
tree += "some widget have no name!";
}
if (start) {
tree += "\"";
}
return tree.c_str();
}
|
d523e7797ee32da365fb8f0870f498118b3f45b4
|
492976adfdf031252c85de91a185bfd625738a0c
|
/src/Game/AI/AI/aiAttackGraveChase.cpp
|
233f23df66a40f7b1b3c09242473d1e02d6c3c45
|
[] |
no_license
|
zeldaret/botw
|
50ccb72c6d3969c0b067168f6f9124665a7f7590
|
fd527f92164b8efdb746cffcf23c4f033fbffa76
|
refs/heads/master
| 2023-07-21T13:12:24.107437
| 2023-07-01T20:29:40
| 2023-07-01T20:29:40
| 288,736,599
| 1,350
| 117
| null | 2023-09-03T14:45:38
| 2020-08-19T13:16:30
|
C++
|
UTF-8
|
C++
| false
| false
| 789
|
cpp
|
aiAttackGraveChase.cpp
|
#include "Game/AI/AI/aiAttackGraveChase.h"
namespace uking::ai {
AttackGraveChase::AttackGraveChase(const InitArg& arg) : ksys::act::ai::Ai(arg) {}
AttackGraveChase::~AttackGraveChase() = default;
bool AttackGraveChase::init_(sead::Heap* heap) {
return ksys::act::ai::Ai::init_(heap);
}
void AttackGraveChase::enter_(ksys::act::ai::InlineParamPack* params) {
ksys::act::ai::Ai::enter_(params);
}
void AttackGraveChase::leave_() {
ksys::act::ai::Ai::leave_();
}
void AttackGraveChase::loadParams_() {
getStaticParam(&mActionTime_s, "ActionTime");
getStaticParam(&mNearTime_s, "NearTime");
getStaticParam(&mEndHeight_s, "EndHeight");
getStaticParam(&mEndNear_s, "EndNear");
getDynamicParam(&mTargetActor_d, "TargetActor");
}
} // namespace uking::ai
|
58e749ca791beda4278213a352336a88d2fd69c7
|
ea658fac119b77892bb4ac316364edf4d2102bbe
|
/APL/Heap/src/BinomialHeap.h
|
a1fb905531ce89a1c87cb778901849904edd0110
|
[
"MIT"
] |
permissive
|
abilng/MTech-Assignments
|
fc9aef4a3b410062d5b7e7344a7b3c97a410f6c5
|
edb7a468eef6d8364551e8b6c04acf7c79831138
|
refs/heads/master
| 2020-04-17T11:34:34.714564
| 2014-05-03T17:14:58
| 2014-05-03T17:14:58
| 18,207,633
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,066
|
h
|
BinomialHeap.h
|
#ifndef BINOMIALHEAP_H_
#define BINOMIALHEAP_H_
#include "Heap.h"
#include <fstream>
using namespace std;
class BinomialHeap: public Heap
{
private:
struct BinomialNode
{
Priority key;
BinomialNode *parent;
BinomialNode *child;
BinomialNode *sibling;
int degree;
};
BinomialNode *head;
void link(BinomialNode*, BinomialNode*);
BinomialNode* getMin();
BinomialNode* mergeList(BinomialNode*, BinomialNode*);
BinomialNode* reverseList(BinomialNode *);
BinomialNode* heapUnion(BinomialNode*, BinomialNode*);
void printDOT(BinomialNode *root,fstream& out);
void clear(BinomialNode*);
public:
BinomialHeap();
~BinomialHeap();
void makeHeap();
bool isEmpty();
Location insertKey(Priority key);
bool deleteKey(Location nodeAddress);
Priority extractMin();
Priority findMin();
bool updateKey(Location nodeAddress, Priority newKey);
bool increaseKey(Location nodeAddress, Priority newKey);
bool decreaseKey(Location nodeAddress, Priority newKey);
bool displayHeap(char const* fileName);
};
#endif
|
649df3204fffc5b1e6c74447667775cbe1da8f16
|
eec6fc365c7415835b4a69eaceb23a224f2abc47
|
/BaekJoon/2020/회장뽑기 (2660번).cpp
|
4e478ef866f4f9325b7876fc1f20885b36a380c2
|
[] |
no_license
|
chosh95/STUDY
|
3e2381c632cebecc9a91e791a4a27a89ea6491ea
|
0c88a1dd55d1826e72ebebd5626d6d83665c8431
|
refs/heads/master
| 2022-04-30T23:58:56.228240
| 2022-04-18T13:08:01
| 2022-04-18T13:08:01
| 166,837,216
| 3
| 1
| null | 2019-06-20T10:51:49
| 2019-01-21T15:32:03
|
C++
|
UTF-8
|
C++
| false
| false
| 898
|
cpp
|
회장뽑기 (2660번).cpp
|
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int N;
int p[51][51];
vector<int> res;
int main()
{
cin >> N;
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
p[i][j] = 51;
while (true) {
int a, b;
cin >> a >> b;
if (a == b && a == -1) break;
p[a][b] = p[b][a] = 1;
}
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
for (int k = 1; k <= N; k++)
if (p[j][i] != 51 && p[i][k] != 51)
p[j][k] = min(p[j][k], p[j][i] + p[i][k]);
int minNum = 52;
for (int i = 1; i <= N; i++) {
int cur = 0;
for (int j = 1; j <= N; j++) {
if (i == j) continue;
cur = max(cur, p[i][j]);
}
if (minNum > cur) {
res.clear();
res.push_back(i);
minNum = cur;
}
else if (minNum == cur) {
res.push_back(i);
}
}
cout << minNum << " " << res.size() << "\n";
for (int x : res)
cout << x << " ";
}
|
0d7470833f375983c476eba197ce709316bff0e7
|
658129adb8f10b4cccdb2e432430d67c0977d37e
|
/cpp/cs311/profs_examples/selection_sort.cpp
|
932e0cc2ade0b868c3ba942a91c64924d44cb387
|
[] |
no_license
|
amiel/random-useless-scripts
|
e2d473940bdb968ad0f8d31514654b79a760edd4
|
166195329bc93c780d7c8fd088d93e3a697062a0
|
refs/heads/master
| 2020-12-24T13:21:37.358940
| 2009-03-29T06:08:26
| 2009-03-29T06:14:02
| 140,835
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,488
|
cpp
|
selection_sort.cpp
|
// selection_sort.cpp
// Glenn G. Chappell
// 9 Oct 2006
//
// For CS 311
// Selection Sort on an Array
#include <iostream>
using std::cout;
using std::endl;
#include <algorithm> // for std::swap
// selectionSort
// Do Selection Sort on a given array.
// Requirements on Types:
// operator< must be a total order on T.
// T must have a copy ctor and copy assignment.
// Pre:
// p points to an array of at least n items of type T
// Post:
// p[0 .. n-1] contains the same items as it did initially,
// but now sorted by <.
template <typename T>
void selectionSort(T p[], int n)
{
for (int endMark = n; endMark >= 2; --endMark) // Passes
// endMark is subscript of one-past end
{
// Find the item that goes in position endMark-1
int biggest = 0; // Holds subscript of biggest item found
for (int i = 1; i < endMark; ++i)
{
if (!(p[i] < p[biggest])) // Comparison is done this way for stability
biggest = i;
}
// p[biggest] goes in position p[endMark-1]
// So put it there
std::swap(p[biggest], p[endMark-1]);
}
}
// main
// Test function selectionSort (takes array)
int main()
{
const int SIZE = 11;
int arr[SIZE] = { 5, 3, 2, 8, 5, 9, 10, 4, 6, 1, -4 };
selectionSort(arr, SIZE);
for (int i = 0; i < SIZE; ++i)
cout << arr[i] << " ";
cout << endl;
return 0;
}
|
6eadfc47e00bf9b42c6ec894a0b08851049ca678
|
983786cac7fccdbfde0ecf549f9d43101e6daacb
|
/Source/BehaviorUnit.h
|
05432f9fdbe20c6f6c68a1b08fb3f34fc68533f7
|
[] |
no_license
|
Saftur/pow
|
a31ed7a90eb1e061418c2c010179737e10ffd3bf
|
ff992ccffacf807a44bea61950e99dd70cc3c336
|
refs/heads/master
| 2018-09-08T14:37:50.956036
| 2018-08-24T01:53:01
| 2018-08-24T01:53:01
| 120,832,124
| 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 7,116
|
h
|
BehaviorUnit.h
|
//------------------------------------------------------------------------------
//
// File Name: BehaviorUnit.h
// Author(s): Doug Schilling (dschilling)
// Project: MyGame
// Course: CS230S17
//
// Copyright © 2017 DigiPen (USA) Corporation.
//
//------------------------------------------------------------------------------
#pragma once
//------------------------------------------------------------------------------
// Include Files:
//------------------------------------------------------------------------------
#include "Behavior.h"
#include "BehaviorProjectile.h"
#include <vector>
#include "Pathfinder.h"
typedef class BehaviorArmy BehaviorArmy;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Public Consts:
//------------------------------------------------------------------------------
// An example of the enums to be defined in BehaviorUnit.cpp.
#if 0
enum UnitState
{
};
#endif
enum SpecialtyType { Basic, Advanced, Special };
enum WeaponType { cWeaponDrillsaw, cWeaponHandcannon, cWeaponBeamRifle, cNumWeapons };
enum EquipmentType { cEquipNone, cEquipArmor, cEquipStrobebang, cEquipEMP, cNumEquips };
enum Ability { cAbilityNone, cAbilityTechnician, cAbilityEngineer, cAbilityScientist, cNumAbilities };
enum AttackGroup { cGroupAircraft, cGroupInfantry, cGroupArtillary };
enum WeaponGroup { cGroupMelee, cGroupRanged, cGroupLongRanged };
//------------------------------------------------------------------------------
// Public Structures:
//------------------------------------------------------------------------------
// An example of the class to be defined in BehaviorUnit.h
class BehaviorUnit : public Behavior
{
public:
/////////////////////
// Items
/////////////////////
struct Weapon
{
std::string name;
WeaponGroup group;
float cooldown;
int range;
int damage;
BehaviorProjectile::ProjectileTypes projectileArchetype;
// TODO: Pointers for sounds & maybe art?
};
struct Equipment
{
std::string name;
int count;
void(*use)();
float deployTime;
float cooldown;
// TODO: Pointers for sounds & maybe art?
};
/////////////////////
// Stats
/////////////////////
struct Traits
{
int strength, agility, defense;
int ability;
AttackGroup group;
int weapon, item1, item2;
unsigned GetCost();
std::string name;
} traits;
//------------------------------------------------------------------------------
// Public Functions:
//------------------------------------------------------------------------------
// Allocate a new (Unit) behavior component.
// Params:
// parent = The object that owns this behavior.
BehaviorUnit();
BehaviorArmy* GetArmy() const;
enum states { cUnitIdle, cUnitError, cUnitMove, cUnitAttack, cUnitSoftChase, cUnitReturn, cUnitGuard, cUnitFollow, cUnitBuild, cUnitEndBuild };
// Clone an advanced behavior and return a pointer to the cloned object.
// Params:
// behavior = Reference to the behavior that will be destroyed.
// parent = A reference to the parent object (the object that owns this component).
// Returns:
// A pointer to an advanced behavior.
Component* Clone() const;
void Init(Traits& data, BehaviorArmy* army);
// Initialize the current state of the behavior component.
// (Hint: Refer to the lecture notes on finite state machines (FSM).)
// Params:
// behavior = Pointer to the behavior component.
void OnEnter();
// Update the current state of the behavior component.
// (Hint: Refer to the lecture notes on finite state machines (FSM).)
// Params:
// behavior = Pointer to the behavior component.
// dt = Change in time (in seconds) since the last game loop.
void OnUpdate(float dt);
void OnExit();
void OnDestroy();
// The collision handling function for Units.
// Params:
// stub = The stub object.
// other = The object the asteroid is colliding with.
static void CollisionHandler(GameObject& unit, GameObject& other);
void Load(rapidjson::Value& obj);
void SetPath(vector<Node*> path);
vector<Node*> GetPath() const;
Vector2D GetGridPos() const;
void SetGridPos(Vector2D newPos);
Node* GetNode() const;
int GetHP() const;
void ModifyHP(int amt);
bool IsMoving() const;
void BuildBuilding(GameObject *archetype, Node *pos); //Tell the unit to build a new building.
GameObject *buildingArchetype; //The archetype of the building we are currently trying to build. nullptr if we are not building.
Node *buildingPos; //The position of the building we are trying to build. nullptr if we are not building.
bool isBuilding = false; //If we made it to the spot and are actively building the building.
static vector<GameObject*> allUnits;
static Weapon Weapons[cNumWeapons];
static string AbilityNames[cNumAbilities];
static Equipment Equips[cNumEquips];
private:
//------------------------------------------------------------------------------
// Private Functions:
//------------------------------------------------------------------------------
bool FindTarget(GameObject** enemy, Vector2D pos = { -1, -1 }) const;
// Checks if the unit can target an enemy.
// Params:
// enemy - the enemy we're checking.
// Returns:
// True if the unit can be targeted, false if not.
bool CanTarget(GameObject* enemy) const;
void UpdatePath();
// Calculates velocity based off of movement speed, target pos, and current pos.
void CalculateVelocity();
// Builds the weapon and equipment arrays.
void BuildArrays();
// Equipment use functions.
static void UseNone();
static void UseArmor();
static void UseStrobebang();
static void UseEMP();
void Attack();
//------------------------------------------------------------------------------
// Stats
//------------------------------------------------------------------------------
struct BaseStats
{
int maxHP;
int defense;
int detectRange;
int disengageRange;
int inventorySize;
float speed;
int baseCost;
};
static BaseStats defaultStats;
struct
{
int maxHP;
int currHP;
float defense;
int detectRange; // increase on high ground
int attackRange; // increase on high ground
int inventorySize;
} stats;
/////////////////////
// Misc/placeholder
/////////////////////
//------------------------------------------------------------------------------
// Data
//------------------------------------------------------------------------------
GameObject* target;
int prevHP;
Vector2D targetPos, lastMoveTarget, guardingPos;
vector<Node*> path;
Node* currMoveTarget;
states prevState;
float stuckTimer, attackTimer;
Vector2D gridPos;
bool isMoving = false;
bool changePath = false;
vector<Node*> changedPath;
BehaviorArmy* army;
};
//------------------------------------------------------------------------------
|
2e0e5c6714179ce85d45cfba669de3d1e057f924
|
adbf3ae9a2c8db8c60dd12efe3612e360f833da3
|
/Algorithm in Cpp/WARSHLL1.cpp
|
fe448705027e5a90c12a9b837566ee672ba25d19
|
[
"MIT"
] |
permissive
|
mdabdullahibnaharun/Algorithms
|
74369bf071361b536c3469d7e3036cbc9eca95e8
|
a64763d1609af5f1a1b6b1ac0ee52910f23952e1
|
refs/heads/main
| 2023-04-09T18:09:30.472063
| 2021-04-26T03:02:09
| 2021-04-26T03:02:09
| 327,311,867
| 5
| 1
|
MIT
| 2021-03-23T10:56:14
| 2021-01-06T12:57:02
|
C++
|
UTF-8
|
C++
| false
| false
| 1,781
|
cpp
|
WARSHLL1.cpp
|
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
using namespace std;
#define TRUE 1
#define FALSE 0
#define MAX_VERTEX 20
int main()
{
int i = 0,
j = 0,
k = 0,
vertices = 0,
path[MAX_VERTEX][MAX_VERTEX],
adjacency[MAX_VERTEX][MAX_VERTEX];
system("CLS");
printf("\nHow many VERTICES in the graph : ");
scanf("%d",&vertices);
printf("\nEnter EDGE information : \n\n");
for(i = 1 ; i < vertices+1 ; ++i)
{
for(j = 1 ; j < vertices+1 ; ++j)
{
printf(" Edge from Vertex %d to %d : ",i,j);
scanf("%d",&adjacency[i][j]);
}
printf("\n");
}
/*print the matrix*/
printf("\n\nThe Given Adjacency Matrix is :\n");
for(i = 1 ; i < vertices+1 ; ++i)
{
for(j = 1 ; j < vertices+1 ; ++j)
{
printf("%5d",adjacency[i][j]);
}
printf("\n");
}
/*now creating path matrix by using the Warshals algorithms*/
for(i = 1 ; i < vertices+1 ; ++i)
{
for(j = 1 ; j < vertices+1 ; ++j)
{
path[i][j] = adjacency[i][j] ? 1 : 0;
}
}
for(k = 1 ; k < vertices+1 ; ++k)
{
for(i = 1 ; i < vertices+1 ; ++i)
{
for(j = 1 ; j < vertices+1 ; ++j)
{
path[i][j] = (path[i][j] | (path[i][k] & path[k][j]));
}
}
}
/*now printing the path matrix*/
printf("\n\nThe PATH matrix is :\n\n");
for(i = 1 ; i < vertices+1; ++i)
{
for(j = 1 ; j < vertices+1 ; ++j)
{
printf("%5d",path[i][j]);
}
printf("\n");
}
putchar('\n');
getch();
return 0;
}
|
bf7c4b6e312ea582e2f825842a85fcb0d5c14938
|
d9f1cc8e697ae4d1c74261ae6377063edd1c53f8
|
/src/misc/Color.h
|
59d7da2e659ec2e22a74f0fb03189409802add28
|
[] |
no_license
|
commel/opencombat2005
|
344b3c00aaa7d1ec4af817e5ef9b5b036f2e4022
|
d72fc2b0be12367af34d13c47064f31d55b7a8e0
|
refs/heads/master
| 2023-05-19T05:18:54.728752
| 2005-12-01T05:11:44
| 2005-12-01T05:11:44
| 375,630,282
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 514
|
h
|
Color.h
|
#pragma once
struct ColorModifier {
int Red;
int Green;
int Blue;
};
struct ColorModifiers {
char Name[256];
ColorModifier Body;
ColorModifier Legs;
ColorModifier Head;
ColorModifier Belt;
ColorModifier Boots;
ColorModifier Weapon;
};
extern ColorModifiers g_ColorModifiers[];
extern int g_NumColorModifiers;
class Color
{
public:
Color(void);
Color(int r, int g, int b);
virtual ~Color(void);
void Parse(unsigned int c);
unsigned char alpha,red,green,blue;
};
|
c73a26c52f892b2540c18484b5e0d7d2730ac43f
|
775f05d41ccfb35980818691255d9bb1fd08ec36
|
/include/Utils.h
|
fa3fcda1e202abd90fc22371df7b0a5e7ddeee4e
|
[
"BSD-3-Clause"
] |
permissive
|
lvchigo/rt-cqt
|
b55afb0c48ef1bd869b64c32e129c132bb1e1fe1
|
bd33116fcc279f8f8e06b74a0867e2023d374dcd
|
refs/heads/main
| 2023-07-18T06:30:03.463550
| 2021-08-19T21:08:43
| 2021-08-19T21:08:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 986
|
h
|
Utils.h
|
/*
==============================================================================
This file is part of the rt-cqt library. Copyright (C) the rt-cqt developers.
See LICENSE.txt for more info.
==============================================================================
*/
#pragma once
namespace Cqt
{
template<typename FloatType>
static inline FloatType Pi()
{
return static_cast<FloatType>(3.14159265358979323846);
}
template<typename FloatType>
static inline FloatType TwoPi()
{
return static_cast<FloatType>(6.283185307179586476925286766);
}
template<typename T>
static inline T Clip(const T input, const T lowerBound, const T upperBound)
{
T y = input > upperBound ? upperBound : input;
y = y < lowerBound ? lowerBound : y;
return y;
}
template<typename T>
static inline T ClipDelete(const T input, const T lowerBound, const T upperBound)
{
T y = input > upperBound ? static_cast<T>(-1) : input;
y = y < lowerBound ? static_cast<T>(-1) : y;
return y;
}
}
|
0004e809ef3133b1f9bf9a5373f61f0288f36ea5
|
0aa8eb62eb56f0c1679e57ea54fb8ccd4d7a4e8a
|
/CabbageGame/Elements/Blocks/CElementBlockFlag.h
|
bd78ca20a87c0deb4e2283f6b81948b95714c52f
|
[] |
no_license
|
iondune/HappyCabbageAdventure
|
03f15d6bd3529ef6a5d7bcad52b99d0a89d94788
|
1c031c982834a0f8ec6f5cb0069d77919109caab
|
refs/heads/master
| 2022-09-05T18:35:14.744242
| 2017-01-17T21:46:01
| 2017-01-17T21:46:01
| 266,990,924
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 744
|
h
|
CElementBlockFlag.h
|
#ifndef __CFLAG_H____
#define __CFLAG_H____
#include "../CGameplayElement.h"
#include "CElementBlock.h"
class CElementBlockFlag : public CElementBlock {
public:
enum FlagRole {
NEXT = 0,
SECRET = 1
};
private:
FlagRole Role;
public:
virtual void OnCollision(const SCollisionEvent& Event);
virtual void setupPhysicsEngineObject();
virtual void setupSceneObject();
virtual void update(float);
virtual void writeXML(xmlwriter *);
CElementBlockFlag(SRect2f, FlagRole);
CElementBlockFlag(SRect2f nArea, int role); //So we don't need a block loader
virtual void printInformation();
CElementBlockFlag::FlagRole getRole();
};
#endif
|
8b3c5d133e16e1ef516de7fa5493df1300ce0cd1
|
5042603e9ced3a23a6058f5e77ba4c1e7fe27ef2
|
/test/testRegionModelChecker.cpp
|
0248be11cf7488b8a9e9cd5f168b44b0dbfeccc4
|
[] |
no_license
|
jannikhuels/hpnmg
|
378647f17c52113e01cf61dd4f1bae30b738cca9
|
eb366c6043dbb3ac59a6f9fb2c157b1ec66a1b9c
|
refs/heads/master
| 2021-06-06T02:54:59.894465
| 2020-03-25T11:43:47
| 2020-03-25T11:43:47
| 114,992,963
| 1
| 0
| null | 2019-11-11T12:21:13
| 2017-12-21T10:21:20
|
C++
|
UTF-8
|
C++
| false
| false
| 23,969
|
cpp
|
testRegionModelChecker.cpp
|
#include "gtest/gtest.h"
#include "modelchecker/Conjunction.h"
#include "modelchecker/ContinuousAtomicProperty.h"
#include "modelchecker/DiscreteAtomicProperty.h"
#include "modelchecker/Formula.h"
#include "modelchecker/Negation.h"
#include "modelchecker/RegionModelChecker.h"
#include "modelchecker/Until.h"
#include "ParametricLocationTree.h"
#include "ParseHybridPetrinet.h"
#include "ReadHybridPetrinet.h"
#include "PLTWriter.h"
#include <chrono>
#include <memory>
using namespace hpnmg;
TEST(RegionModelChecker, ContinuousAtomicPropertyTest1GTFoldedNormal) {
auto modelChecker = RegionModelChecker(*ReadHybridPetrinet{}.readHybridPetrinet("example.xml"), 50);
auto result = modelChecker.satisfies(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 0)), 0);
// Place is empty at t = 0
EXPECT_NEAR(1.0, round(result.first*10)/10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 3)), 3);
// out-transition is deterministically disabled at t=5, so the place's level cannot exceed t' at time t'<=5
EXPECT_NEAR(1.0, round(result.first*10)/10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 2)), 3);
// folded normal distribution with mu = 5 and sigma = 3
// cdf(2.5) = 0.5 * (erf((2.5 + 5) / sqrt(18)) + erf((2.5 - 5) / sqrt(18))) ~ 0.196119
EXPECT_NEAR(0.1961187156378668902015554951380463273568632340661803, result.first, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 7)), 10);
// folded normal distribution with mu = 5 and sigma = 3
// (1 - cdf(6)) = (0.5 * (erf((6 + 5) / sqrt(18)) + erf((6 - 5) / sqrt(18)))) ~ 0.630436
EXPECT_NEAR(0.6304357934282712096662251163331139441485145682519407, result.first, result.second);
}
TEST(RegionModelChecker, ContinuousAtomicPropertyTest1GTUniform) {
// TG1: uniform distribution over [0, 10]
auto hpn = ReadHybridPetrinet{}.readHybridPetrinet("norep_1_1.xml");
auto modelChecker = RegionModelChecker(*hpn, 20);
auto result = modelChecker.satisfies(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 0)), 0);
// Place is empty at t = 0
EXPECT_NEAR(1.0, round(result.first*10)/10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 2)), 5);
EXPECT_NEAR(0.45, round(result.first*100)/100, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 5)), 10);
// one out-transition is deterministically disabled at t=12, so the place's level cannot exceed t'/2 at time t'<=12
EXPECT_NEAR(1.0, round(result.first*10)/10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 2)), 10);
EXPECT_NEAR(0.7, round(result.first*10)/10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 0)), 15);
EXPECT_NEAR(0.675, round(result.first*1000)/1000, result.second);
}
TEST(RegionModelChecker, ContinuousAtomicPropertyTest2ConflictGTUniform) {
// TG1 and TG2: uniform distribution over [0, 100]
auto hpn = ReadHybridPetrinet{}.readHybridPetrinet("heated_tank_minimized.xml");
auto modelChecker = RegionModelChecker(*hpn, 1000);
auto result = modelChecker.satisfies(Formula(std::make_shared<ContinuousAtomicProperty>("H", 100)), 0);
// Place is at level 100 at time 0
EXPECT_NEAR(1.0, round(result.first*10)/10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<ContinuousAtomicProperty>("H", 97)), 10);
EXPECT_NEAR(0.00202083, round(result.first*100000000)/100000000, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<ContinuousAtomicProperty>("H", 103)))), 10);
EXPECT_NEAR(0.0, round(result.first*10)/10, result.second);
}
TEST(RegionModelChecker, DiscreteAtomicPropertyTest1GT) {
auto modelChecker = RegionModelChecker(*ReadHybridPetrinet{}.readHybridPetrinet("example.xml"), 50);
auto formula = Formula(std::make_shared<DiscreteAtomicProperty>("pd1", 1));
const auto result = modelChecker.satisfies(formula, 1);
// folded normal distribution with mu = 5 and sigma = 3
// (1 - cdf(1)) = 1 - (0.5 * (erf((1 + 5) / sqrt(18)) + erf((1 - 5) / sqrt(18)))) ~ 0.931539
EXPECT_NEAR(0.9315389122223113373664299671527104472835967852691848, result.first, result.second);
}
TEST(RegionModelChecker, DiscreteAtomicPropertyTest2GT) {
auto hpng = ReadHybridPetrinet{}.readHybridPetrinet("norep_1_2.xml");
auto modelChecker = RegionModelChecker(*hpng, 20);
auto result = modelChecker.satisfies(Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 2)), 0);
EXPECT_NEAR(1.0, round(result.first*10)/10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 0)), 5);
EXPECT_NEAR(0.125, round(result.first*1000)/1000, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 1)), 10);
EXPECT_NEAR(0.5, round(result.first*10)/10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 0)), 13);
EXPECT_NEAR(0.755, round(result.first*1000)/1000, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 1)), 13);
EXPECT_NEAR(0.245, round(result.first*1000)/1000, result.second);
}
TEST(RegionModelChecker, ConjunctionTest) {
auto modelChecker = RegionModelChecker(*ReadHybridPetrinet{}.readHybridPetrinet("example.xml"), 50);
auto result = modelChecker.satisfies(Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("pd1", 1)),
Formula(std::make_shared<DiscreteAtomicProperty>("pd2", 1))
)), 0);
EXPECT_NEAR(1.0, round(result.first*10)/10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("pd1", 1)),
Formula(std::make_shared<DiscreteAtomicProperty>("pd2", 1))
)), 2.5);
// folded normal distribution with mu = 5 and sigma = 3
// (1 - cdf(2.5)) = 1 - (0.5 * (erf((2.5 + 5) / sqrt(18)) + erf((2.5 - 5) / sqrt(18)))) ~ 0.803881
EXPECT_NEAR(0.8038812843621331097984445048619536726431367659338196, result.first, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("pd1", 0)),
Formula(std::make_shared<DiscreteAtomicProperty>("pd2", 1))
)), 2.5);
// folded normal distribution with mu = 5 and sigma = 3
// cdf(2.5) = 0.5 * (erf((2.5 + 5) / sqrt(18)) + erf((2.5 - 5) / sqrt(18))) ~ 0.196119
EXPECT_NEAR(0.1961187156378668902015554951380463273568632340661803, result.first, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("pd1", 1)),
Formula(std::make_shared<DiscreteAtomicProperty>("pd2", 1))
)), 6);
EXPECT_NEAR(0.0, result.first, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("pd1", 0)),
Formula(std::make_shared<DiscreteAtomicProperty>("pd2", 0))
)), 6);
// folded normal distribution with mu = 5 and sigma = 3
// cdf(6) = 0.5 * (erf((6 + 5) / sqrt(18)) + erf((6 - 5) / sqrt(18))) ~ 0.499571
EXPECT_NEAR(0.6304357934282712096662251163331139441485145682519407, result.first, result.second);
}
TEST(RegionModelChecker, DiscreteAtomicPropertyNegationTest1GT) {
auto hpng = ReadHybridPetrinet{}.readHybridPetrinet("example.xml");
auto modelChecker = RegionModelChecker(*hpng, 50);
auto result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<DiscreteAtomicProperty>("pd1", 1)))), 1);
// folded normal distribution with mu = 5 and sigma = 3
// (cdf(1)) = (0.5 * (erf((1 + 5) / sqrt(18)) + erf((1 - 5) / sqrt(18)))) ~ 1 - 0.931539
EXPECT_NEAR(0.0684610877776886626335700328472895527164032147308151, result.first, result.second);
}
TEST(RegionModelChecker, ContinuousAtomicPropertyNegationTest1GTFoldedNormal) {
auto modelChecker = RegionModelChecker(*ReadHybridPetrinet{}.readHybridPetrinet("example.xml"), 50);
// This test is especially important, as it also covers the openFacet problem.
auto result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 0)))), 0);
// Place is not empty at t = 0
EXPECT_NEAR(0.0, round(result.first*10)/10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 3)))), 3);
// out-transition is deterministically disabled at t=5, so the place's level cannot exceed t' at time t'<=5
EXPECT_NEAR(0.0, round(result.first*10)/10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 2)))), 3);
// folded normal distribution with mu = 5 and sigma = 3
// cdf(2.5) = 0.5 * (erf((2.5 + 5) / sqrt(18)) + erf((2.5 - 5) / sqrt(18))) ~ 1 - 0.1961
EXPECT_NEAR(0.8039, round(result.first * 10000) / 10000, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 7)))), 10);
// folded normal distribution with mu = 5 and sigma = 3
// (1 - cdf(6)) = (1 - 0.5 * (erf((6 + 5) / sqrt(18)) + erf((6 - 5) / sqrt(18)))) ~ 1 - 0.630436
EXPECT_NEAR(0.369564, round(result.first * 1000000) / 1000000, result.second);
}
TEST(RegionModelChecker, ConjunctionNegationTest) {
auto modelChecker = RegionModelChecker(*ReadHybridPetrinet{}.readHybridPetrinet("example.xml"), 50);
auto result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("pd1", 1)),
Formula(std::make_shared<DiscreteAtomicProperty>("pd2", 1))
)))), 0);
EXPECT_NEAR(0.0, round(result.first * 10000) / 10000, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("pd1", 1)),
Formula(std::make_shared<DiscreteAtomicProperty>("pd2", 1))
)))), 2.5);
// folded normal distribution with mu = 5 and sigma = 3
// 1 - (1 - cdf(2.5)) = 1 - (1 - (0.5 * (erf((2.5 + 5) / sqrt(18)) + erf((2.5 - 5) / sqrt(18))))) ~ 1 - 0.803881
EXPECT_NEAR(0.1961, round(result.first * 10000) / 10000, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("pd1", 0)),
Formula(std::make_shared<DiscreteAtomicProperty>("pd2", 1))
)))), 2.5);
// folded normal distribution with mu = 5 and sigma = 3
// 1 - cdf(2.5) = 1 - (0.5 * (erf((2.5 + 5) / sqrt(18)) + erf((2.5 - 5) / sqrt(18)))) ~ 1 - 0.196119
EXPECT_NEAR(0.8039, round(result.first * 10000) / 10000, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("pd1", 1)),
Formula(std::make_shared<DiscreteAtomicProperty>("pd2", 1))
)))), 6);
EXPECT_NEAR(1.0, round(result.first * 10000) / 10000, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("pd1", 0)),
Formula(std::make_shared<DiscreteAtomicProperty>("pd2", 0))
)))), 6);
// folded normal distribution with mu = 5 and sigma = 3
// 1 - cdf(6) = 1 - (0.5 * (erf((6 + 5) / sqrt(18)) + erf((6 - 5) / sqrt(18)))) ~ 1 - 0.630436
EXPECT_NEAR(0.3696, round(result.first * 10000) / 10000, result.second);
}
TEST(RegionModelChecker, DiscreteAtomicPropertyNegationTest2GT) {
auto hpng = ReadHybridPetrinet{}.readHybridPetrinet("norep_1_2.xml");
auto modelChecker = RegionModelChecker(*hpng, 20);
auto result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 2)))), 0);
EXPECT_NEAR(0.0, round(result.first*10)/10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 0)))), 5);
EXPECT_NEAR(0.875, round(result.first*1000)/1000, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 1)))), 10);
EXPECT_NEAR(0.5, round(result.first*10)/10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 0)))), 13);
EXPECT_NEAR(0.245, round(result.first*1000)/1000, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<Negation>(Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 1)))), 13);
EXPECT_NEAR(0.755, round(result.first*1000)/1000, result.second);
}
TEST(RegionModelChecker, UntilUniform) {
const double maxTime = 20;
// TG1: uniform distribution over [0, 10]
auto hpn = ReadHybridPetrinet{}.readHybridPetrinet("norep_1_1.xml");
auto modelChecker = RegionModelChecker(*hpn, maxTime);
// Place is empty until it finally is not empty anymore.
auto result = modelChecker.satisfies(Formula(std::make_shared<Until>(
Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 0)),
Formula(std::make_shared<Negation>(Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 0)))),
maxTime
)), 0);
EXPECT_NEAR(1.0, round(result.first*10)/10, result.second);
// The place's level does not exceed 2 until the input transition is finally disabled with the level still being low
result = modelChecker.satisfies(Formula(std::make_shared<Until>(
Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 2)),
Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 2)),
Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 0))
)),
maxTime
)), 2);
EXPECT_NEAR(0.4, round(result.first * 10) / 10, result.second);
// The place's level does not exceed 2 until the input transition is finally disabled
result = modelChecker.satisfies(Formula(std::make_shared<Until>(
Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 2)),
Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 2)),
Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 0))
)),
maxTime
)), 4);
EXPECT_NEAR(0.4, round(result.first * 10) / 10, result.second);
// The place's level does not exceed 2 until the input transition is finally disabled
result = modelChecker.satisfies(Formula(std::make_shared<Until>(
Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 2)),
Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 2)),
Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 0))
)),
maxTime
)), 6);
EXPECT_NEAR(0.5, round(result.first * 10) / 10, result.second);
// The place is actively being emptied by two pumps below level 2
result = modelChecker.satisfies(Formula(std::make_shared<Until>(
Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 0)), // input disabled
Formula(std::make_shared<DiscreteAtomicProperty>("pout1", 1)) // no output disabled
)),
Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 2)),
maxTime
)), 6);
EXPECT_NEAR(0.6, round(result.first * 10) / 10, result.second);
// The place is actively being emptied by two pumps below level 2
result = modelChecker.satisfies(Formula(std::make_shared<Until>(
Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 0)), // input disabled
Formula(std::make_shared<DiscreteAtomicProperty>("pout1", 1)) // no output disabled
)),
Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 2)),
maxTime
)), 7);
EXPECT_NEAR(0.7, round(result.first * 10) / 10, result.second);
// The place is actively being emptied by two pumps below level 2
result = modelChecker.satisfies(Formula(std::make_shared<Until>(
Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("pin1", 0)), // input disabled
Formula(std::make_shared<DiscreteAtomicProperty>("pout1", 1)) // no output disabled
)),
Formula(std::make_shared<ContinuousAtomicProperty>("pc1", 2)),
maxTime
)), 8);
EXPECT_NEAR(0.8, round(result.first * 10) / 10, result.second);
}
TEST(RegionModelChecker, VanishingMarking) {
const double maxTime = 20;
// TG: uniform distribution over [0, 10]
auto hpn = ReadHybridPetrinet{}.readHybridPetrinet("immediate.xml");
auto modelChecker = RegionModelChecker(*hpn, maxTime);
auto plt = ParseHybridPetrinet{}.parseHybridPetrinet(hpn, maxTime);
// Place p1 initially contains one token
auto result = modelChecker.satisfies(Formula(std::make_shared<DiscreteAtomicProperty>("p1", 1)), 1);
EXPECT_NEAR(0.9, round(result.first*10)/10, result.second);
// After the firing of td at t=5, the immediate transition ti has concession, so a token resides in p2 for zero time
result = modelChecker.satisfies(Formula(std::make_shared<DiscreteAtomicProperty>("p2", 1)), 5);
EXPECT_NEAR(0.0, round(result.first * 10) / 10, result.second);
// The token should immediately move to p2 after firing of td and ti
result = modelChecker.satisfies(Formula(std::make_shared<DiscreteAtomicProperty>("p3", 1)), 5);
EXPECT_NEAR(0.5, round(result.first * 10) / 10, result.second);
// No vanishing marking should be eventually reached
result = modelChecker.satisfies(Formula(std::make_shared<Until>(
Formula(std::make_shared<DiscreteAtomicProperty>("p1", 1)),
Formula(std::make_shared<DiscreteAtomicProperty>("p2", 1)),
maxTime
)), 1);
EXPECT_NEAR(0.0, round(result.first * 10) / 10, result.second);
// Do not consider a vanishing marking at all, but all child locations
result = modelChecker.satisfies(Formula(std::make_shared<Until>(
Formula(std::make_shared<DiscreteAtomicProperty>("p1", 1)),
Formula(std::make_shared<DiscreteAtomicProperty>("p3", 1)),
maxTime
)), 1);
EXPECT_NEAR(0.5, round(result.first * 10) / 10, result.second);
}
TEST(RegionModelChecker, ChecktimeMeetsAnDeterministicEvent) {
const double maxTime = 20;
// TG: uniform distribution over [0, 10]
auto hpn = ReadHybridPetrinet{}.readHybridPetrinet("immediate.xml");
auto modelChecker = RegionModelChecker(*hpn, maxTime);
auto plt = ParseHybridPetrinet{}.parseHybridPetrinet(hpn, maxTime);
// Ensure that only the latest possible location is used when the checktime meets the border of regions
auto result = modelChecker.satisfies(Formula(std::make_shared<DiscreteAtomicProperty>("p4", 0)), 5);
EXPECT_NEAR(0.5, round(result.first * 10) / 10, result.second);
}
TEST(RegionModelChecker, DeterministicTransitionConflict) {
const double maxTime = 20;
auto hpn = ReadHybridPetrinet{}.readHybridPetrinet("deterministic_same_time.xml");
auto modelChecker = RegionModelChecker(*hpn, maxTime);
auto plt = ParseHybridPetrinet{}.parseHybridPetrinet(hpn, maxTime);
// Two conflicting deterministic transitions fire at the exact same time.
// We want to check that no vanishing marking is considered.
// There is no marking m_p1=0 and m_p2=1 that is eventually reached, this is vanishing
auto result = modelChecker.satisfies(Formula(std::make_shared<Until>(
Formula(std::make_shared<True>()),
Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("p1", 0)),
Formula(std::make_shared<DiscreteAtomicProperty>("p2", 1))
)),
maxTime
)), 1);
EXPECT_NEAR(0.0, round(result.first * 10) / 10, result.second);
// There is no marking m_p1=1 and m_p2=0 that is eventually reached, this is vanishing
result = modelChecker.satisfies(Formula(std::make_shared<Until>(
Formula(std::make_shared<True>()),
Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("p1", 1)),
Formula(std::make_shared<DiscreteAtomicProperty>("p2", 0))
)),
maxTime
)), 1);
EXPECT_NEAR(0.0, round(result.first * 10) / 10, result.second);
// There is a marking m_p1=0 and m_p2=0 reached eventually
result = modelChecker.satisfies(Formula(std::make_shared<Until>(
Formula(std::make_shared<True>()),
Formula(std::make_shared<Conjunction>(
Formula(std::make_shared<DiscreteAtomicProperty>("p1", 0)),
Formula(std::make_shared<DiscreteAtomicProperty>("p2", 0))
)),
maxTime
)), 1);
EXPECT_NEAR(1.0, round(result.first * 10) / 10, result.second);
}
TEST(RegionModelChecker, ChecktimeMeetsTwoDeterministicEvents) {
const double maxTime = 20;
// TG: uniform distribution over [0, 10]
auto hpn = ReadHybridPetrinet{}.readHybridPetrinet("grid_independent.xml");
auto modelChecker = RegionModelChecker(*hpn, maxTime);
auto plt = ParseHybridPetrinet{}.parseHybridPetrinet(hpn, maxTime);
// There was the problem that two conflicting determinstic transitions created two independent regions
// and the Probability calculator did not incorporated the accumulated probability
auto result = modelChecker.satisfies(Formula(std::make_shared<DiscreteAtomicProperty>("grid_failed", 1)), 5);
EXPECT_NEAR(1.0, round(result.first * 10) / 10, result.second);
// Check that the relative time (since enabling) is used for general transitions
result = modelChecker.satisfies(Formula(std::make_shared<DiscreteAtomicProperty>("grid_failed", 1)), 7);
EXPECT_NEAR(0.8, round(result.first * 10) / 10, result.second);
result = modelChecker.satisfies(Formula(std::make_shared<DiscreteAtomicProperty>("grid_failed", 1)), 18);
EXPECT_NEAR(0.0, round(result.first * 10) / 10, result.second);
}
TEST(RegionModelChecker, ChecktimeMeetsOneDeterministicEventWithTwoGT) {
const double maxTime = 40;
// Use a well chosen probablity distribution. Here folded normal for all gts.
auto hpn = ReadHybridPetrinet{}.readHybridPetrinet("grid_independent_2gt.xml");
auto modelChecker = RegionModelChecker(*hpn, maxTime);
auto plt = ParseHybridPetrinet{}.parseHybridPetrinet(hpn, maxTime);
PLTWriter{}.writePLT(plt, maxTime);
// Adding more general transitions that are independent from the property to check
// resulted in a too small proability.
auto result = modelChecker.satisfies(Formula(std::make_shared<DiscreteAtomicProperty>("grid_failed", 1)), 18);
EXPECT_NEAR(1.0, round(result.first * 10) / 10, result.second);
}
|
90620f74ee78c32301caf68b44a7511e7b1f378f
|
f1b43dddc88b6f04aa44119a902bbc2b6610a68b
|
/Year3/LLP/RayTraceApplication/RayTraceApplication/_Configuration/PropertyMetadata.h
|
8e0530c21bfcc1790966f513da2afa62411682a7
|
[] |
no_license
|
GRMaverick/University
|
fbf453348e50f111c68f68230768ccda5e1725fc
|
7f213df8f5a1c81b5b20f30587d347dac3ac1a41
|
refs/heads/master
| 2023-03-28T13:50:56.705583
| 2021-03-31T20:47:11
| 2021-03-31T20:47:11
| 353,469,640
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 387
|
h
|
PropertyMetadata.h
|
#pragma once
template<typename Class, typename T>
struct PropertyImpl
{
constexpr PropertyImpl(T Class::*aMember, const char* aName)
: member{ aMember }, name{ aName }
{
}
using Type = T;
T Class::*member;
const char* name;
};
template<typename Class, typename T>
constexpr auto property(T Class::*member, const char* name)
{
return PropertyImpl<Class, T>{member, name};
}
|
28e290727d47c402eb7cf1504e60d245c24b7733
|
7dddfe758643603d83e5eeec78dfe1d5b8f38cef
|
/tdt/tdt/controllable_camera.cc
|
3d5c79b8cf714b01525efdca6c690195eef30441
|
[] |
no_license
|
steplee/lidarRender
|
a3f4ea742b080c4192e4a1e60dc799f1ba57221a
|
62addfb43a7603b5e6adf40421460135b81486dd
|
refs/heads/main
| 2023-08-02T11:58:42.012449
| 2021-09-30T22:49:27
| 2021-09-30T22:49:27
| 359,317,075
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,190
|
cc
|
controllable_camera.cc
|
#include "controllable_camera.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <iostream>
ControllabeCamera::ControllabeCamera(const CamSpec& cs)
: Camera(cs)
{
}
void ControllabeCamera::setPos(const double t[3]) {
this->t[0] = t[0];
this->t[1] = t[1];
this->t[2] = t[2];
}
void ControllabeCamera::setRot(const double R_[9]) {
Eigen::Map<const Eigen::Matrix<double,3,3,Eigen::RowMajor>> R(R_);
Eigen::Quaterniond qq { R };
q[0] = qq.w();
q[1] = qq.x();
q[2] = qq.y();
q[3] = qq.z();
}
void ControllabeCamera::getPos(double t[3]) {
t[0] = this->t[0];
t[1] = this->t[1];
t[2] = this->t[2];
}
void ControllabeCamera::getRot(double R[9]) {
Eigen::Quaterniond qq { q[0], q[1], q[2], q[3] };
Eigen::Matrix<double,3,3,Eigen::RowMajor> R_ = qq.toRotationMatrix();
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
R[i*3+j] = R_(i,j);
}
void ControllabeCamera::step(double dt) {
Eigen::Quaterniond qq { q[0], q[1], q[2], q[3] };
double aspeed = .3;
double dy = curY - lastY, dx = curX - lastX;
if (not leftMouseDown) dy = dx = 0;
if (lastY == -1 or dy > 100 or dy < -100 or dx > 100 or dx < -100) dy = dx = 0;
Eigen::Quaterniond dq = Eigen::Quaterniond {
(Eigen::AngleAxisd(dt*aspeed*dy, Eigen::Vector3d::UnitX()) *
Eigen::AngleAxisd(dt*aspeed*dx, Eigen::Vector3d::UnitY())) };
Eigen::Quaterniond qq2 = dq * qq;
Eigen::Matrix<double,3,3,Eigen::RowMajor> R = qq2.toRotationMatrix();
q[0] = qq2.w(); q[1] = qq2.x(); q[2] = qq2.y(); q[3] = qq2.z();
Eigen::Map<Eigen::Vector3d> t_(t);
Eigen::Map<Eigen::Vector3d> vel_(vel);
double speed = 25;
Eigen::Vector3d accRaw {
(keyDown['a'-'a'] ? 1 : keyDown['d'-'a'] ? -1 : 0) * speed,
0,
(keyDown['w'-'a'] ? 1 : keyDown['s'-'a'] ? -1 : 0) * speed };
Eigen::Vector3d acc = R.transpose() * accRaw;
//acc += -(vel_.array()*vel_.cwiseAbs().array()).matrix();
acc += -vel_;
vel_ += acc * dt;
t_ += vel_ * dt + acc * dt * .5;
Eigen::Map<Eigen::Matrix<double,4,4,Eigen::RowMajor>> V(view);
V.topLeftCorner<3,3>() = R;
V.topRightCorner<3,1>() = -R * t_;
//std::cout << " - view:\n" << V << "\n";
Eigen::Map<Eigen::Matrix<double,4,4,Eigen::RowMajor>> P(proj);
//std::cout << " - proj:\n" << P << "\n";
lastX = curX; lastY = curY;
}
void ControllabeCamera::keyboardFunc(int key, int scancode, int action, int mods) {
int c = key - GLFW_KEY_A;
if (action == GLFW_PRESS) {
if (c >= 0 and c < 26) keyDown[c] = true;
if (key == GLFW_KEY_SPACE) spaceDown = true;
if (key == GLFW_KEY_ESCAPE) escDown = true;
} else if (action == GLFW_RELEASE) {
if (c >= 0 and c < 26) keyDown[c] = false;
if (key == GLFW_KEY_SPACE) spaceDown = false;
if (key == GLFW_KEY_ESCAPE) escDown = false;
}
shiftDown = mods & GLFW_MOD_SHIFT;
ctrlDown = mods & GLFW_MOD_CONTROL;
}
void ControllabeCamera::clickFunc(int button, int action, int mods) {
if (button == GLFW_MOUSE_BUTTON_LEFT) leftMouseDown = action == GLFW_PRESS;
if (button == GLFW_MOUSE_BUTTON_RIGHT) rightMouseDown = action == GLFW_PRESS;
}
void ControllabeCamera::motionFunc(double xpos, double ypos) {
lastX = curX, lastY = curY;
curY = ypos, curX = xpos;
}
|
fd88aa144769cf1a01a5231410597e173720ad8a
|
50f74e9e0749cfb43b2db7c97ae4e580c87a301f
|
/include/redux/logging/logitem.hpp
|
79e70f578394ab95c7b865a9bffd610ec6684779
|
[] |
no_license
|
ISP-SST/redux
|
298e264b161004d61af0a36d90bd13968d5486cf
|
2bd80ec796d4dd7d7120e0dd26d84fe252b86eaa
|
refs/heads/master
| 2023-05-27T11:07:57.088498
| 2023-05-23T11:25:41
| 2023-05-23T11:26:02
| 45,384,045
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,145
|
hpp
|
logitem.hpp
|
#ifndef REDUX_LOGGING_LOGITEM_HPP
#define REDUX_LOGGING_LOGITEM_HPP
#include "logentry.hpp"
namespace redux {
namespace logging {
class Logger;
struct LogItem {
inline void setLogger( Logger* lg ) { logger = lg; }
inline LogItem& operator<<(LogItem &(*f)(LogItem &)) {
return f(*this);
}
inline LogItem& operator<<(const LogMask& m) {
entry.setMask(m);
return *this;
}
template <typename T>
inline LogItem& operator<<(const T &v) {
entry << v;
return *this;
}
// forward iostream manipulators (i.e. endl)
inline LogItem& operator<<(std::ostream &(*f)(std::ostream &)) {
entry << f;
return *this;
}
// forward ios manipulators
inline LogItem &operator<<(std::ios &(*f)(std::ios &)) {
entry << f;
return *this;
}
// forward ios_base manipulators
inline LogItem &operator<<(std::ios_base &(*f)(std::ios_base &)) {
entry << f;
return *this;
}
// apply LogEntry manipulators
inline LogItem& operator<<(LogEntry &(*f)(LogEntry &)) {
f(entry);
return *this;
}
void endEntry(void);
uint64_t size(void) const;
uint64_t pack(char*) const;
uint64_t unpack(const char*, bool);
Logger* logger;
LogEntry entry;
std::string context;
};
// mark the end of the log entry and trigger publishing.
inline LogItem& ende( LogItem &i ) {
i.endEntry();
return i;
}
typedef std::shared_ptr<LogItem> LogItemPtr;
} // log
} // redux
#endif // REDUX_LOGGING_LOGITEM_HPP
|
b76005d517ca07f3cae505c6ae5248f806160ec3
|
950b506e3f8fd978f076a5b9a3a950f6f4d5607b
|
/cf/398-div2/D.cpp
|
0ada8d492ba112d3119c889dbfc6e43d40761f21
|
[] |
no_license
|
Mityai/contests
|
2e130ebb8d4280b82e7e017037fc983063228931
|
5b406b2a94cc487b0c71cb10386d1b89afd1e143
|
refs/heads/master
| 2021-01-09T06:09:17.441079
| 2019-01-19T12:47:20
| 2019-01-19T12:47:20
| 80,909,953
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,921
|
cpp
|
D.cpp
|
#include <bits/stdc++.h>
#define fi first
#define se second
using namespace std;
using ll = long long;
const int N = 1e7;
vector<int> g[N + 1];
int have[N + 1];
int nxt[N + 1];
int over[N + 1];
int main() {
#if __APPLE__
freopen("D.in", "r", stdin);
freopen("D.out", "w", stdout);
#endif
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < n; ++i) {
int x;
scanf("%d", &x);
++have[x];
}
int carry = 0;
for (int t = N, nx = N + 1; t >= 0; --t) {
carry += max(0, have[t] - k);
have[t] = min(have[t], k);
nxt[t] = nx;
if (have[t] < k) {
over[t] = min(k - have[t], carry);
have[t] += over[t];
carry -= over[t];
if (over[t] > 0) {
nx = t;
}
}
}
if (carry > 0) {
puts("-1");
return 0;
}
vector<pair<int, int>> tobuy(m);
for (int i = 0; i < m; ++i) {
scanf("%d", &tobuy[i].fi);
tobuy[i].se = i;
}
sort(tobuy.begin(), tobuy.end(),
[](pair<int, int>& p1, pair<int, int>& p2) {
return p1.fi < p2.fi;
});
vector<int> ans;
for (int t = 0, j = 0; t <= N; ++t) {
while (j < m && tobuy[j].fi < t) ++j;
int added = 0;
for (int i = 0; i < k - have[t] && j < m; ++i, ++j) {
ans.push_back(tobuy[j].se);
++added;
}
have[t] += added;
if (have[t] < k) {
int can = k - have[t];
int x = nxt[t];
while (x != N + 1 && can > 0) {
int cur = min(can, over[x]);
over[x] -= cur;
have[x] -= cur;
can -= cur;
x = nxt[x];
}
}
}
printf("%d\n", int(ans.size()));
for (int x : ans) {
printf("%d ", x + 1);
}
puts("");
}
|
d54db6ecb2b4e730ac8f61ea7d1c847639534c0a
|
08b8cf38e1936e8cec27f84af0d3727321cec9c4
|
/data/crawl/git/hunk_335.cpp
|
c02e016bb0713582eb1983f26706e3be34cce66f
|
[] |
no_license
|
ccdxc/logSurvey
|
eaf28e9c2d6307140b17986d5c05106d1fd8e943
|
6b80226e1667c1e0760ab39160893ee19b0e9fb1
|
refs/heads/master
| 2022-01-07T21:31:55.446839
| 2018-04-21T14:12:43
| 2018-04-21T14:12:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,987
|
cpp
|
hunk_335.cpp
|
} while (lo < hi);
return -lo-1;
}
-
-/*
- * Conventional binary search loop looks like this:
- *
- * unsigned lo, hi;
- * do {
- * unsigned mi = (lo + hi) / 2;
- * int cmp = "entry pointed at by mi" minus "target";
- * if (!cmp)
- * return (mi is the wanted one)
- * if (cmp > 0)
- * hi = mi; "mi is larger than target"
- * else
- * lo = mi+1; "mi is smaller than target"
- * } while (lo < hi);
- *
- * The invariants are:
- *
- * - When entering the loop, lo points at a slot that is never
- * above the target (it could be at the target), hi points at a
- * slot that is guaranteed to be above the target (it can never
- * be at the target).
- *
- * - We find a point 'mi' between lo and hi (mi could be the same
- * as lo, but never can be as same as hi), and check if it hits
- * the target. There are three cases:
- *
- * - if it is a hit, we are happy.
- *
- * - if it is strictly higher than the target, we set it to hi,
- * and repeat the search.
- *
- * - if it is strictly lower than the target, we update lo to
- * one slot after it, because we allow lo to be at the target.
- *
- * If the loop exits, there is no matching entry.
- *
- * When choosing 'mi', we do not have to take the "middle" but
- * anywhere in between lo and hi, as long as lo <= mi < hi is
- * satisfied. When we somehow know that the distance between the
- * target and lo is much shorter than the target and hi, we could
- * pick mi that is much closer to lo than the midway.
- *
- * Now, we can take advantage of the fact that SHA-1 is a good hash
- * function, and as long as there are enough entries in the table, we
- * can expect uniform distribution. An entry that begins with for
- * example "deadbeef..." is much likely to appear much later than in
- * the midway of the table. It can reasonably be expected to be near
- * 87% (222/256) from the top of the table.
- *
- * However, we do not want to pick "mi" too precisely. If the entry at
- * the 87% in the above example turns out to be higher than the target
- * we are looking for, we would end up narrowing the search space down
- * only by 13%, instead of 50% we would get if we did a simple binary
- * search. So we would want to hedge our bets by being less aggressive.
- *
- * The table at "table" holds at least "nr" entries of "elem_size"
- * bytes each. Each entry has the SHA-1 key at "key_offset". The
- * table is sorted by the SHA-1 key of the entries. The caller wants
- * to find the entry with "key", and knows that the entry at "lo" is
- * not higher than the entry it is looking for, and that the entry at
- * "hi" is higher than the entry it is looking for.
- */
-int sha1_entry_pos(const void *table,
- size_t elem_size,
- size_t key_offset,
- unsigned lo, unsigned hi, unsigned nr,
- const unsigned char *key)
-{
- const unsigned char *base = table;
- const unsigned char *hi_key, *lo_key;
- unsigned ofs_0;
- static int debug_lookup = -1;
-
- if (debug_lookup < 0)
- debug_lookup = !!getenv("GIT_DEBUG_LOOKUP");
-
- if (!nr || lo >= hi)
- return -1;
-
- if (nr == hi)
- hi_key = NULL;
- else
- hi_key = base + elem_size * hi + key_offset;
- lo_key = base + elem_size * lo + key_offset;
-
- ofs_0 = 0;
- do {
- int cmp;
- unsigned ofs, mi, range;
- unsigned lov, hiv, kyv;
- const unsigned char *mi_key;
-
- range = hi - lo;
- if (hi_key) {
- for (ofs = ofs_0; ofs < 20; ofs++)
- if (lo_key[ofs] != hi_key[ofs])
- break;
- ofs_0 = ofs;
- /*
- * byte 0 thru (ofs-1) are the same between
- * lo and hi; ofs is the first byte that is
- * different.
- *
- * If ofs==20, then no bytes are different,
- * meaning we have entries with duplicate
- * keys. We know that we are in a solid run
- * of this entry (because the entries are
- * sorted, and our lo and hi are the same,
- * there can be nothing but this single key
- * in between). So we can stop the search.
- * Either one of these entries is it (and
- * we do not care which), or we do not have
- * it.
- *
- * Furthermore, we know that one of our
- * endpoints must be the edge of the run of
- * duplicates. For example, given this
- * sequence:
- *
- * idx 0 1 2 3 4 5
- * key A C C C C D
- *
- * If we are searching for "B", we might
- * hit the duplicate run at lo=1, hi=3
- * (e.g., by first mi=3, then mi=0). But we
- * can never have lo > 1, because B < C.
- * That is, if our key is less than the
- * run, we know that "lo" is the edge, but
- * we can say nothing of "hi". Similarly,
- * if our key is greater than the run, we
- * know that "hi" is the edge, but we can
- * say nothing of "lo".
- *
- * Therefore if we do not find it, we also
- * know where it would go if it did exist:
- * just on the far side of the edge that we
- * know about.
- */
- if (ofs == 20) {
- mi = lo;
- mi_key = base + elem_size * mi + key_offset;
- cmp = memcmp(mi_key, key, 20);
- if (!cmp)
- return mi;
- if (cmp < 0)
- return -1 - hi;
- else
- return -1 - lo;
- }
-
- hiv = hi_key[ofs_0];
- if (ofs_0 < 19)
- hiv = (hiv << 8) | hi_key[ofs_0+1];
- } else {
- hiv = 256;
- if (ofs_0 < 19)
- hiv <<= 8;
- }
- lov = lo_key[ofs_0];
- kyv = key[ofs_0];
- if (ofs_0 < 19) {
- lov = (lov << 8) | lo_key[ofs_0+1];
- kyv = (kyv << 8) | key[ofs_0+1];
- }
- assert(lov < hiv);
-
- if (kyv < lov)
- return -1 - lo;
- if (hiv < kyv)
- return -1 - hi;
-
- /*
- * Even if we know the target is much closer to 'hi'
- * than 'lo', if we pick too precisely and overshoot
- * (e.g. when we know 'mi' is closer to 'hi' than to
- * 'lo', pick 'mi' that is higher than the target), we
- * end up narrowing the search space by a smaller
- * amount (i.e. the distance between 'mi' and 'hi')
- * than what we would have (i.e. about half of 'lo'
- * and 'hi'). Hedge our bets to pick 'mi' less
- * aggressively, i.e. make 'mi' a bit closer to the
- * middle than we would otherwise pick.
- */
- kyv = (kyv * 6 + lov + hiv) / 8;
- if (lov < hiv - 1) {
- if (kyv == lov)
- kyv++;
- else if (kyv == hiv)
- kyv--;
- }
- mi = (range - 1) * (kyv - lov) / (hiv - lov) + lo;
-
- if (debug_lookup) {
- printf("lo %u hi %u rg %u mi %u ", lo, hi, range, mi);
- printf("ofs %u lov %x, hiv %x, kyv %x\n",
- ofs_0, lov, hiv, kyv);
- }
- if (!(lo <= mi && mi < hi))
- die("assertion failure lo %u mi %u hi %u %s",
- lo, mi, hi, sha1_to_hex(key));
-
- mi_key = base + elem_size * mi + key_offset;
- cmp = memcmp(mi_key + ofs_0, key + ofs_0, 20 - ofs_0);
- if (!cmp)
- return mi;
- if (cmp > 0) {
- hi = mi;
- hi_key = mi_key;
- } else {
- lo = mi + 1;
- lo_key = mi_key + elem_size;
- }
- } while (lo < hi);
- return -lo-1;
-}
|
bbe99bc92a9c8343dc56d8c7291e2e122d10629e
|
9ed1564e46c1d6f7bfb2138e328d3c6d0cb4931c
|
/source/widget/megalcdnumber.h
|
ae8c4b0f277eb58facfd48a11dd26c09b95d72d6
|
[] |
no_license
|
ww4u/mct-t4
|
c66a399fd2f4d281d1aa1cb6db1aded7edf781f1
|
b4ff50ce2947e7d69972d500633aec991cd13c57
|
refs/heads/master
| 2022-12-14T22:36:39.047386
| 2019-08-05T04:32:15
| 2019-08-05T04:32:15
| 296,253,721
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 375
|
h
|
megalcdnumber.h
|
#ifndef MEGALCD_H
#define MEGALCD_H
#include <QLCDNumber>
class MegaLcdnumber : public QLCDNumber
{
Q_OBJECT
public:
explicit MegaLcdnumber(QWidget *parent = 0);
~MegaLcdnumber();
public:
void display( float v );
void display( double v );
void display( int n );
void display( const QString &v );
};
#endif // MEGALCD_H
|
beabc881982b547b5307a3ab773d7d974780a3ec
|
1061216c2c33c1ed4ffb33e6211565575957e48f
|
/cpp-tizen/src/RealTimeEventsManager.cpp
|
c1d60e69ee07c9f4e8543ba76470db25a806af2d
|
[] |
no_license
|
MSurfer20/test2
|
be9532f54839e8f58b60a8e4587348c2810ecdb9
|
13b35d72f33302fa532aea189e8f532272f1f799
|
refs/heads/main
| 2023-07-03T04:19:57.548080
| 2021-08-11T19:16:42
| 2021-08-11T19:16:42
| 393,920,506
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 23,013
|
cpp
|
RealTimeEventsManager.cpp
|
#include <glib-object.h>
#include <json-glib/json-glib.h>
#include "RealTimeEventsManager.h"
#include "NetClient.h"
#include "Helpers.h"
#include "Error.h"
#include "RequestInfo.h"
using namespace std;
using namespace Tizen::ArtikCloud;
RealTimeEventsManager::RealTimeEventsManager()
{
}
RealTimeEventsManager::~RealTimeEventsManager()
{
}
static gboolean __RealTimeEventsManagerresponseHandler(gpointer data)
{
RequestInfo *request = static_cast<RequestInfo*>(data);
g_thread_join(request->thread);
// invoke the callback function
bool retval = request->processor(*(request->p_chunk), *(request->code), request->errormsg, request->userData, request->handler);
delete request;
return FALSE;
}
static gpointer __RealTimeEventsManagerthreadFunc(gpointer data)
{
RequestInfo *request = static_cast<RequestInfo*>(data);
// handle the request
NetClient::easycurl(request->host, request->path, request->method, request->queryParams,
request->mBody, request->headerList, request->p_chunk, request->code, request->errormsg);
request->thread = g_thread_self();
g_idle_add(__RealTimeEventsManagerresponseHandler, static_cast<gpointer>(request));
return NULL;
}
static bool deleteQueueProcessor(MemoryStruct_s p_chunk, long code, char* errormsg, void* userData,
void(* voidHandler)())
{
void(* handler)(JsonSuccess, Error, void* )
= reinterpret_cast<void(*)(JsonSuccess, Error, void* )> (voidHandler);
JsonNode* pJson;
char * data = p_chunk.memory;
JsonSuccess out;
if (code >= 200 && code < 300) {
Error error(code, string("No Error"));
if (isprimitive("JsonSuccess")) {
pJson = json_from_string(data, NULL);
jsonToValue(&out, pJson, "JsonSuccess", "JsonSuccess");
json_node_free(pJson);
if ("JsonSuccess" == "std::string") {
string* val = (std::string*)(&out);
if (val->empty() && p_chunk.size>4) {
*val = string(p_chunk.memory, p_chunk.size);
}
}
} else {
out.fromJson(data);
char *jsonStr = out.toJson();
printf("\n%s\n", jsonStr);
g_free(static_cast<gpointer>(jsonStr));
out.fromJson(data);
char *jsonStr = out.toJson();
printf("\n%s\n", jsonStr);
g_free(static_cast<gpointer>(jsonStr));
}
handler(out, error, userData);
return true;
//TODO: handle case where json parsing has an error
} else {
Error error;
if (errormsg != NULL) {
error = Error(code, string(errormsg));
} else if (p_chunk.memory != NULL) {
error = Error(code, string(p_chunk.memory));
} else {
error = Error(code, string("Unknown Error"));
}
handler(out, error, userData);
return false;
}
}
static bool deleteQueueHelper(char * accessToken,
std::string queueId,
void(* handler)(JsonSuccess, Error, void* )
, void* userData, bool isAsync)
{
//TODO: maybe delete headerList after its used to free up space?
struct curl_slist *headerList = NULL;
string accessHeader = "Authorization: Bearer ";
accessHeader.append(accessToken);
headerList = curl_slist_append(headerList, accessHeader.c_str());
headerList = curl_slist_append(headerList, "Content-Type: application/json");
map <string, string> queryParams;
string itemAtq;
itemAtq = stringify(&queueId, "std::string");
queryParams.insert(pair<string, string>("queue_id", itemAtq));
string mBody = "";
JsonNode* node;
JsonArray* json_array;
string url("/events");
int pos;
//TODO: free memory of errormsg, memorystruct
MemoryStruct_s* p_chunk = new MemoryStruct_s();
long code;
char* errormsg = NULL;
string myhttpmethod("DELETE");
if(strcmp("PUT", "DELETE") == 0){
if(strcmp("", mBody.c_str()) == 0){
mBody.append("{}");
}
}
if(!isAsync){
NetClient::easycurl(RealTimeEventsManager::getBasePath(), url, myhttpmethod, queryParams,
mBody, headerList, p_chunk, &code, errormsg);
bool retval = deleteQueueProcessor(*p_chunk, code, errormsg, userData,reinterpret_cast<void(*)()>(handler));
curl_slist_free_all(headerList);
if (p_chunk) {
if(p_chunk->memory) {
free(p_chunk->memory);
}
delete (p_chunk);
}
if (errormsg) {
free(errormsg);
}
return retval;
} else{
GThread *thread = NULL;
RequestInfo *requestInfo = NULL;
requestInfo = new(nothrow) RequestInfo (RealTimeEventsManager::getBasePath(), url, myhttpmethod, queryParams,
mBody, headerList, p_chunk, &code, errormsg, userData, reinterpret_cast<void(*)()>(handler), deleteQueueProcessor);;
if(requestInfo == NULL)
return false;
thread = g_thread_new(NULL, __RealTimeEventsManagerthreadFunc, static_cast<gpointer>(requestInfo));
return true;
}
}
bool RealTimeEventsManager::deleteQueueAsync(char * accessToken,
std::string queueId,
void(* handler)(JsonSuccess, Error, void* )
, void* userData)
{
return deleteQueueHelper(accessToken,
queueId,
handler, userData, true);
}
bool RealTimeEventsManager::deleteQueueSync(char * accessToken,
std::string queueId,
void(* handler)(JsonSuccess, Error, void* )
, void* userData)
{
return deleteQueueHelper(accessToken,
queueId,
handler, userData, false);
}
static bool getEventsProcessor(MemoryStruct_s p_chunk, long code, char* errormsg, void* userData,
void(* voidHandler)())
{
void(* handler)(JsonSuccessBase, Error, void* )
= reinterpret_cast<void(*)(JsonSuccessBase, Error, void* )> (voidHandler);
JsonNode* pJson;
char * data = p_chunk.memory;
JsonSuccessBase out;
if (code >= 200 && code < 300) {
Error error(code, string("No Error"));
if (isprimitive("JsonSuccessBase")) {
pJson = json_from_string(data, NULL);
jsonToValue(&out, pJson, "JsonSuccessBase", "JsonSuccessBase");
json_node_free(pJson);
if ("JsonSuccessBase" == "std::string") {
string* val = (std::string*)(&out);
if (val->empty() && p_chunk.size>4) {
*val = string(p_chunk.memory, p_chunk.size);
}
}
} else {
out.fromJson(data);
char *jsonStr = out.toJson();
printf("\n%s\n", jsonStr);
g_free(static_cast<gpointer>(jsonStr));
out.fromJson(data);
char *jsonStr = out.toJson();
printf("\n%s\n", jsonStr);
g_free(static_cast<gpointer>(jsonStr));
}
handler(out, error, userData);
return true;
//TODO: handle case where json parsing has an error
} else {
Error error;
if (errormsg != NULL) {
error = Error(code, string(errormsg));
} else if (p_chunk.memory != NULL) {
error = Error(code, string(p_chunk.memory));
} else {
error = Error(code, string("Unknown Error"));
}
handler(out, error, userData);
return false;
}
}
static bool getEventsHelper(char * accessToken,
std::string queueId, int lastEventId, bool dontBlock,
void(* handler)(JsonSuccessBase, Error, void* )
, void* userData, bool isAsync)
{
//TODO: maybe delete headerList after its used to free up space?
struct curl_slist *headerList = NULL;
string accessHeader = "Authorization: Bearer ";
accessHeader.append(accessToken);
headerList = curl_slist_append(headerList, accessHeader.c_str());
headerList = curl_slist_append(headerList, "Content-Type: application/json");
map <string, string> queryParams;
string itemAtq;
itemAtq = stringify(&queueId, "std::string");
queryParams.insert(pair<string, string>("queue_id", itemAtq));
itemAtq = stringify(&lastEventId, "int");
queryParams.insert(pair<string, string>("last_event_id", itemAtq));
if( itemAtq.empty()==true){
queryParams.erase("last_event_id");
}
itemAtq = stringify(&dontBlock, "bool");
queryParams.insert(pair<string, string>("dont_block", itemAtq));
if( itemAtq.empty()==true){
queryParams.erase("dont_block");
}
string mBody = "";
JsonNode* node;
JsonArray* json_array;
string url("/events");
int pos;
//TODO: free memory of errormsg, memorystruct
MemoryStruct_s* p_chunk = new MemoryStruct_s();
long code;
char* errormsg = NULL;
string myhttpmethod("GET");
if(strcmp("PUT", "GET") == 0){
if(strcmp("", mBody.c_str()) == 0){
mBody.append("{}");
}
}
if(!isAsync){
NetClient::easycurl(RealTimeEventsManager::getBasePath(), url, myhttpmethod, queryParams,
mBody, headerList, p_chunk, &code, errormsg);
bool retval = getEventsProcessor(*p_chunk, code, errormsg, userData,reinterpret_cast<void(*)()>(handler));
curl_slist_free_all(headerList);
if (p_chunk) {
if(p_chunk->memory) {
free(p_chunk->memory);
}
delete (p_chunk);
}
if (errormsg) {
free(errormsg);
}
return retval;
} else{
GThread *thread = NULL;
RequestInfo *requestInfo = NULL;
requestInfo = new(nothrow) RequestInfo (RealTimeEventsManager::getBasePath(), url, myhttpmethod, queryParams,
mBody, headerList, p_chunk, &code, errormsg, userData, reinterpret_cast<void(*)()>(handler), getEventsProcessor);;
if(requestInfo == NULL)
return false;
thread = g_thread_new(NULL, __RealTimeEventsManagerthreadFunc, static_cast<gpointer>(requestInfo));
return true;
}
}
bool RealTimeEventsManager::getEventsAsync(char * accessToken,
std::string queueId, int lastEventId, bool dontBlock,
void(* handler)(JsonSuccessBase, Error, void* )
, void* userData)
{
return getEventsHelper(accessToken,
queueId, lastEventId, dontBlock,
handler, userData, true);
}
bool RealTimeEventsManager::getEventsSync(char * accessToken,
std::string queueId, int lastEventId, bool dontBlock,
void(* handler)(JsonSuccessBase, Error, void* )
, void* userData)
{
return getEventsHelper(accessToken,
queueId, lastEventId, dontBlock,
handler, userData, false);
}
static bool realTimePostProcessor(MemoryStruct_s p_chunk, long code, char* errormsg, void* userData,
void(* voidHandler)())
{
void(* handler)(Error, void* ) = reinterpret_cast<void(*)(Error, void* )> (voidHandler);
JsonNode* pJson;
char * data = p_chunk.memory;
if (code >= 200 && code < 300) {
Error error(code, string("No Error"));
handler(error, userData);
return true;
} else {
Error error;
if (errormsg != NULL) {
error = Error(code, string(errormsg));
} else if (p_chunk.memory != NULL) {
error = Error(code, string(p_chunk.memory));
} else {
error = Error(code, string("Unknown Error"));
}
handler(error, userData);
return false;
}
}
static bool realTimePostHelper(char * accessToken,
std::list<std::string> eventTypes, std::list<std::list> narrow, bool allPublicStreams,
void(* handler)(Error, void* ) , void* userData, bool isAsync)
{
//TODO: maybe delete headerList after its used to free up space?
struct curl_slist *headerList = NULL;
string accessHeader = "Authorization: Bearer ";
accessHeader.append(accessToken);
headerList = curl_slist_append(headerList, accessHeader.c_str());
headerList = curl_slist_append(headerList, "Content-Type: application/json");
map <string, string> queryParams;
string itemAtq;
for (std::list
<std::string>::iterator queryIter = eventTypes.begin(); queryIter != eventTypes.end(); ++queryIter) {
string itemAt = stringify(&(*queryIter), "std::string");
if( itemAt.empty()){
continue;
}
queryParams.insert(pair<string, string>("eventTypes", itemAt));
}
for (std::list
<std::list>::iterator queryIter = narrow.begin(); queryIter != narrow.end(); ++queryIter) {
string itemAt = stringify(&(*queryIter), "std::list");
if( itemAt.empty()){
continue;
}
queryParams.insert(pair<string, string>("narrow", itemAt));
}
itemAtq = stringify(&allPublicStreams, "bool");
queryParams.insert(pair<string, string>("all_public_streams", itemAtq));
if( itemAtq.empty()==true){
queryParams.erase("all_public_streams");
}
string mBody = "";
JsonNode* node;
JsonArray* json_array;
string url("/real-time");
int pos;
//TODO: free memory of errormsg, memorystruct
MemoryStruct_s* p_chunk = new MemoryStruct_s();
long code;
char* errormsg = NULL;
string myhttpmethod("POST");
if(strcmp("PUT", "POST") == 0){
if(strcmp("", mBody.c_str()) == 0){
mBody.append("{}");
}
}
if(!isAsync){
NetClient::easycurl(RealTimeEventsManager::getBasePath(), url, myhttpmethod, queryParams,
mBody, headerList, p_chunk, &code, errormsg);
bool retval = realTimePostProcessor(*p_chunk, code, errormsg, userData,reinterpret_cast<void(*)()>(handler));
curl_slist_free_all(headerList);
if (p_chunk) {
if(p_chunk->memory) {
free(p_chunk->memory);
}
delete (p_chunk);
}
if (errormsg) {
free(errormsg);
}
return retval;
} else{
GThread *thread = NULL;
RequestInfo *requestInfo = NULL;
requestInfo = new(nothrow) RequestInfo (RealTimeEventsManager::getBasePath(), url, myhttpmethod, queryParams,
mBody, headerList, p_chunk, &code, errormsg, userData, reinterpret_cast<void(*)()>(handler), realTimePostProcessor);;
if(requestInfo == NULL)
return false;
thread = g_thread_new(NULL, __RealTimeEventsManagerthreadFunc, static_cast<gpointer>(requestInfo));
return true;
}
}
bool RealTimeEventsManager::realTimePostAsync(char * accessToken,
std::list<std::string> eventTypes, std::list<std::list> narrow, bool allPublicStreams,
void(* handler)(Error, void* ) , void* userData)
{
return realTimePostHelper(accessToken,
eventTypes, narrow, allPublicStreams,
handler, userData, true);
}
bool RealTimeEventsManager::realTimePostSync(char * accessToken,
std::list<std::string> eventTypes, std::list<std::list> narrow, bool allPublicStreams,
void(* handler)(Error, void* ) , void* userData)
{
return realTimePostHelper(accessToken,
eventTypes, narrow, allPublicStreams,
handler, userData, false);
}
static bool registerQueueProcessor(MemoryStruct_s p_chunk, long code, char* errormsg, void* userData,
void(* voidHandler)())
{
void(* handler)(JsonSuccessBase, Error, void* )
= reinterpret_cast<void(*)(JsonSuccessBase, Error, void* )> (voidHandler);
JsonNode* pJson;
char * data = p_chunk.memory;
JsonSuccessBase out;
if (code >= 200 && code < 300) {
Error error(code, string("No Error"));
if (isprimitive("JsonSuccessBase")) {
pJson = json_from_string(data, NULL);
jsonToValue(&out, pJson, "JsonSuccessBase", "JsonSuccessBase");
json_node_free(pJson);
if ("JsonSuccessBase" == "std::string") {
string* val = (std::string*)(&out);
if (val->empty() && p_chunk.size>4) {
*val = string(p_chunk.memory, p_chunk.size);
}
}
} else {
out.fromJson(data);
char *jsonStr = out.toJson();
printf("\n%s\n", jsonStr);
g_free(static_cast<gpointer>(jsonStr));
}
handler(out, error, userData);
return true;
//TODO: handle case where json parsing has an error
} else {
Error error;
if (errormsg != NULL) {
error = Error(code, string(errormsg));
} else if (p_chunk.memory != NULL) {
error = Error(code, string(p_chunk.memory));
} else {
error = Error(code, string("Unknown Error"));
}
handler(out, error, userData);
return false;
}
}
static bool registerQueueHelper(char * accessToken,
bool applyMarkdown, bool clientGravatar, bool slimPresence, std::list<std::string> eventTypes, bool allPublicStreams, bool includeSubscribers, std::string clientCapabilities, std::list<std::string> fetchEventTypes, std::list<std::list> narrow,
void(* handler)(JsonSuccessBase, Error, void* )
, void* userData, bool isAsync)
{
//TODO: maybe delete headerList after its used to free up space?
struct curl_slist *headerList = NULL;
string accessHeader = "Authorization: Bearer ";
accessHeader.append(accessToken);
headerList = curl_slist_append(headerList, accessHeader.c_str());
headerList = curl_slist_append(headerList, "Content-Type: application/json");
map <string, string> queryParams;
string itemAtq;
itemAtq = stringify(&applyMarkdown, "bool");
queryParams.insert(pair<string, string>("apply_markdown", itemAtq));
if( itemAtq.empty()==true){
queryParams.erase("apply_markdown");
}
itemAtq = stringify(&clientGravatar, "bool");
queryParams.insert(pair<string, string>("client_gravatar", itemAtq));
if( itemAtq.empty()==true){
queryParams.erase("client_gravatar");
}
itemAtq = stringify(&slimPresence, "bool");
queryParams.insert(pair<string, string>("slim_presence", itemAtq));
if( itemAtq.empty()==true){
queryParams.erase("slim_presence");
}
for (std::list
<std::string>::iterator queryIter = eventTypes.begin(); queryIter != eventTypes.end(); ++queryIter) {
string itemAt = stringify(&(*queryIter), "std::string");
if( itemAt.empty()){
continue;
}
queryParams.insert(pair<string, string>("eventTypes", itemAt));
}
itemAtq = stringify(&allPublicStreams, "bool");
queryParams.insert(pair<string, string>("all_public_streams", itemAtq));
if( itemAtq.empty()==true){
queryParams.erase("all_public_streams");
}
itemAtq = stringify(&includeSubscribers, "bool");
queryParams.insert(pair<string, string>("include_subscribers", itemAtq));
if( itemAtq.empty()==true){
queryParams.erase("include_subscribers");
}
itemAtq = stringify(&clientCapabilities, "std::string");
queryParams.insert(pair<string, string>("client_capabilities", itemAtq));
if( itemAtq.empty()==true){
queryParams.erase("client_capabilities");
}
for (std::list
<std::string>::iterator queryIter = fetchEventTypes.begin(); queryIter != fetchEventTypes.end(); ++queryIter) {
string itemAt = stringify(&(*queryIter), "std::string");
if( itemAt.empty()){
continue;
}
queryParams.insert(pair<string, string>("fetchEventTypes", itemAt));
}
for (std::list
<std::list>::iterator queryIter = narrow.begin(); queryIter != narrow.end(); ++queryIter) {
string itemAt = stringify(&(*queryIter), "std::list");
if( itemAt.empty()){
continue;
}
queryParams.insert(pair<string, string>("narrow", itemAt));
}
string mBody = "";
JsonNode* node;
JsonArray* json_array;
string url("/register");
int pos;
//TODO: free memory of errormsg, memorystruct
MemoryStruct_s* p_chunk = new MemoryStruct_s();
long code;
char* errormsg = NULL;
string myhttpmethod("POST");
if(strcmp("PUT", "POST") == 0){
if(strcmp("", mBody.c_str()) == 0){
mBody.append("{}");
}
}
if(!isAsync){
NetClient::easycurl(RealTimeEventsManager::getBasePath(), url, myhttpmethod, queryParams,
mBody, headerList, p_chunk, &code, errormsg);
bool retval = registerQueueProcessor(*p_chunk, code, errormsg, userData,reinterpret_cast<void(*)()>(handler));
curl_slist_free_all(headerList);
if (p_chunk) {
if(p_chunk->memory) {
free(p_chunk->memory);
}
delete (p_chunk);
}
if (errormsg) {
free(errormsg);
}
return retval;
} else{
GThread *thread = NULL;
RequestInfo *requestInfo = NULL;
requestInfo = new(nothrow) RequestInfo (RealTimeEventsManager::getBasePath(), url, myhttpmethod, queryParams,
mBody, headerList, p_chunk, &code, errormsg, userData, reinterpret_cast<void(*)()>(handler), registerQueueProcessor);;
if(requestInfo == NULL)
return false;
thread = g_thread_new(NULL, __RealTimeEventsManagerthreadFunc, static_cast<gpointer>(requestInfo));
return true;
}
}
bool RealTimeEventsManager::registerQueueAsync(char * accessToken,
bool applyMarkdown, bool clientGravatar, bool slimPresence, std::list<std::string> eventTypes, bool allPublicStreams, bool includeSubscribers, std::string clientCapabilities, std::list<std::string> fetchEventTypes, std::list<std::list> narrow,
void(* handler)(JsonSuccessBase, Error, void* )
, void* userData)
{
return registerQueueHelper(accessToken,
applyMarkdown, clientGravatar, slimPresence, eventTypes, allPublicStreams, includeSubscribers, clientCapabilities, fetchEventTypes, narrow,
handler, userData, true);
}
bool RealTimeEventsManager::registerQueueSync(char * accessToken,
bool applyMarkdown, bool clientGravatar, bool slimPresence, std::list<std::string> eventTypes, bool allPublicStreams, bool includeSubscribers, std::string clientCapabilities, std::list<std::string> fetchEventTypes, std::list<std::list> narrow,
void(* handler)(JsonSuccessBase, Error, void* )
, void* userData)
{
return registerQueueHelper(accessToken,
applyMarkdown, clientGravatar, slimPresence, eventTypes, allPublicStreams, includeSubscribers, clientCapabilities, fetchEventTypes, narrow,
handler, userData, false);
}
static bool restErrorHandlingProcessor(MemoryStruct_s p_chunk, long code, char* errormsg, void* userData,
void(* voidHandler)())
{
void(* handler)(Error, void* ) = reinterpret_cast<void(*)(Error, void* )> (voidHandler);
JsonNode* pJson;
char * data = p_chunk.memory;
if (code >= 200 && code < 300) {
Error error(code, string("No Error"));
handler(error, userData);
return true;
} else {
Error error;
if (errormsg != NULL) {
error = Error(code, string(errormsg));
} else if (p_chunk.memory != NULL) {
error = Error(code, string(p_chunk.memory));
} else {
error = Error(code, string("Unknown Error"));
}
handler(error, userData);
return false;
}
}
static bool restErrorHandlingHelper(char * accessToken,
void(* handler)(Error, void* ) , void* userData, bool isAsync)
{
//TODO: maybe delete headerList after its used to free up space?
struct curl_slist *headerList = NULL;
string accessHeader = "Authorization: Bearer ";
accessHeader.append(accessToken);
headerList = curl_slist_append(headerList, accessHeader.c_str());
headerList = curl_slist_append(headerList, "Content-Type: application/json");
map <string, string> queryParams;
string itemAtq;
string mBody = "";
JsonNode* node;
JsonArray* json_array;
string url("/rest-error-handling");
int pos;
//TODO: free memory of errormsg, memorystruct
MemoryStruct_s* p_chunk = new MemoryStruct_s();
long code;
char* errormsg = NULL;
string myhttpmethod("POST");
if(strcmp("PUT", "POST") == 0){
if(strcmp("", mBody.c_str()) == 0){
mBody.append("{}");
}
}
if(!isAsync){
NetClient::easycurl(RealTimeEventsManager::getBasePath(), url, myhttpmethod, queryParams,
mBody, headerList, p_chunk, &code, errormsg);
bool retval = restErrorHandlingProcessor(*p_chunk, code, errormsg, userData,reinterpret_cast<void(*)()>(handler));
curl_slist_free_all(headerList);
if (p_chunk) {
if(p_chunk->memory) {
free(p_chunk->memory);
}
delete (p_chunk);
}
if (errormsg) {
free(errormsg);
}
return retval;
} else{
GThread *thread = NULL;
RequestInfo *requestInfo = NULL;
requestInfo = new(nothrow) RequestInfo (RealTimeEventsManager::getBasePath(), url, myhttpmethod, queryParams,
mBody, headerList, p_chunk, &code, errormsg, userData, reinterpret_cast<void(*)()>(handler), restErrorHandlingProcessor);;
if(requestInfo == NULL)
return false;
thread = g_thread_new(NULL, __RealTimeEventsManagerthreadFunc, static_cast<gpointer>(requestInfo));
return true;
}
}
bool RealTimeEventsManager::restErrorHandlingAsync(char * accessToken,
void(* handler)(Error, void* ) , void* userData)
{
return restErrorHandlingHelper(accessToken,
handler, userData, true);
}
bool RealTimeEventsManager::restErrorHandlingSync(char * accessToken,
void(* handler)(Error, void* ) , void* userData)
{
return restErrorHandlingHelper(accessToken,
handler, userData, false);
}
|
dc09d01f38f45da69d1e53669c7ffd2f852adbbf
|
567d8fff1e71de5a23ddfc20b5288965adc8a547
|
/cplus_training/77.cpp
|
4ad65b40977c7715d9c62ee5eb68db7dc5143003
|
[] |
no_license
|
zhengjunrui/C-training
|
cff87f398b845573b32c2f6dd25081b5f015a678
|
18a99e21e38cdced02b66a60c59aaf32106ceed2
|
refs/heads/master
| 2021-05-06T23:45:28.865462
| 2018-01-07T02:49:10
| 2018-01-07T02:49:10
| 112,983,834
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 247
|
cpp
|
77.cpp
|
#include<stdlib.h>
#include<iostream>
using namespace std;
int main()
{
const char *s[]={"q","a","b","c","d"};
const char **q;
for(int k=0;k<5;k++)
{
q = &s[k];
cout<<*q<<"\n";
}
cout<<endl;
return 0;
}
|
e132fe1e08f646b1ce33e9f7918ed932ef38a5b0
|
1c027949aa9c9b255c994ccdef9cffb34a6746c2
|
/heap.cpp
|
8cd0680286e74f63f46294b97a0d85a815d7d852
|
[] |
no_license
|
overmind2/sanya-cpp
|
dee7e81a7d061c2497e42eb6ad4114a5d7fd657d
|
7ba15f18d103f3fdcfed95faad0bebb8b415414d
|
refs/heads/master
| 2016-09-06T01:15:30.747847
| 2011-11-09T04:38:15
| 2011-11-09T04:38:15
| 2,727,418
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,627
|
cpp
|
heap.cpp
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <utility>
#include "heap.hpp"
#include "objectmodel.hpp"
#include "inlines.hpp"
namespace sanya {
Heap *Heap::default_s = NULL;
Heap::Heap(size_t size)
: size_(size),
usage_(0),
from_space_(new char[size]),
copy_usage_(0),
to_space_(new char[size]) {
// Not quite sure why valgrind says error....
memset(from_space_, 0, size);
memset(to_space_, 0, size_);
}
Heap::~Heap() {
delete[] from_space_;
from_space_ = NULL;
delete[] to_space_;
to_space_ = NULL;
size_ = 0;
usage_ = 0;
}
void Heap::TriggerCollection() {
Handle *dummy = RootSet::Get().head_;
Handle *it;
// Iterate through the root set, do mark-and-copy, and update
// the pointer fields in the root sets.
for (it = dummy->next_root_; it != dummy; it = it->next_root_) {
it->raw_ = MarkAndCopy(it->raw_);
}
// Optional: call destructors for objects.
printf(":heap-collect %ld => %ld\n", usage_, copy_usage_);
// Flip over and clean up
std::swap(usage_, copy_usage_);
copy_usage_ = 0;
std::swap(from_space_, to_space_);
std::fill(to_space_, to_space_ + size_, 0);
}
// Private implementation of a dummy head.
class DummyObjectHead : public Handle {
public:
DummyObjectHead() {
next_root_ = this;
prev_root_ = this;
}
};
static DummyObjectHead dummy_head_s = DummyObjectHead();
RootSet *RootSet::default_s = NULL;
RootSet::RootSet()
: head_(&dummy_head_s) { }
RootSet::~RootSet() {
}
} // namespace sanya
// vim: set ts=4 sw=4 sts=4:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.