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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b45e04ba75e3fc7921e45d96bf2a57e2c3fb4240
|
9cb14eaff82ba9cf75c6c99e34c9446ee9d7c17b
|
/uva/sales.cpp
|
386bf33c7771e14c1c32d740597b705b5bee954e
|
[] |
no_license
|
rafa95359/programacionCOmpetitiva
|
fe7008e85a41e958517a0c336bdb5da9c8a5df83
|
d471229758e9c4f3cac7459845e04c7056e2a1e0
|
refs/heads/master
| 2022-02-19T06:43:37.794325
| 2019-09-02T15:09:35
| 2019-09-02T15:09:35
| 183,834,924
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 384
|
cpp
|
sales.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ll t;
cin>>t;
for(ll i=0;i<t;i++){
ll a;cin>>a;
vector<ll> arrA;
for(ll i=0;i<a;i++){
ll aux;
cin>>aux;
arrA.push_back(aux);
}
ll ans=0;
for(ll i=1;i<a;i++){
for(ll j=0;j<i;j++){
if(arrA[j]<=arrA[i]) ans++;
}
}
cout<<ans<<endl;
}
return 0;
}
|
1105d51e8376d5230faf0d3b2ee260072c7cff17
|
60205812b617b29713fe22dcb6084c4daed9da18
|
/01-Question_after_WangDao/Chapter_02/2.2/T11_00-WangDao_Original.cpp
|
7819d86348f0bfad1717a7160a69da8ca6d7dee9
|
[
"MIT"
] |
permissive
|
liruida/kaoyan-data-structure
|
bc04d6306736027cb5fc4090a2796aca7abbbaa4
|
d0a469bf0e9e7040de21eca38dc19961aa7e9a53
|
refs/heads/master
| 2023-04-02T19:57:49.252343
| 2021-01-03T07:20:11
| 2021-01-03T07:20:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,196
|
cpp
|
T11_00-WangDao_Original.cpp
|
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct {
ElemType *data;
int length;
} SqList;
void outPutList(SqList L) {
for (int i = 0; i < L.length; i++)
cout << L.data[i] << " ";
cout << endl;
}
SqList initList(int arr[], int length) {
SqList L;
L.length = length;
L.data = (ElemType *)malloc(sizeof(ElemType) * L.length);
for (int i = 0; i < length; i++)
L.data[i] = arr[i];
return L;
}
// 根据王道书上的算法进行了代码可读性优化
int getMid(SqList A, SqList B) {
int low1 = 0, high1 = A.length - 1,
low2 = 0, high2 = B.length - 1;
while (low1 != high1 || low2 != high2) {
int mid1 = (low1 + high1) / 2;
int mid2 = (low2 + high2) / 2;
if (A.data[mid1] == B.data[mid2])
return A.data[mid1];
if (A.data[mid1] < B.data[mid2]) {
low1 = ((low1 + high1) % 2 == 0) ? mid1 : mid1 + 1;
high2 = mid2;
} else {
low2 = ((low2 + high2) % 2 == 0) ? mid2 : mid2 + 1;
high1 = mid1;
}
}
return A.data[low1] < B.data[low2] ? A.data[low1] : B.data[low2];
}
void test(int arr1[], int length1, int arr2[], int length2) {
SqList A = initList(arr1, length1);
SqList B = initList(arr2, length2);
cout << getMid(A, B) << endl;
}
int main() {
ElemType A[] = {1, 3, 5, 7, 9};
ElemType B[] = {2, 4, 6, 8, 10};
int length1 = sizeof(A) / sizeof(int);
int length2 = sizeof(B) / sizeof(int);
test(A, length1, B, length2);
return 0;
}
// 输出结果:
// 5
// 下面的全部都有错误
// //-----------------------------------------------------------------------------
// int middle(int A[], int B[], int n) {
// int low1 = 0, high1 = n - 1, mid1,
// low2 = 0, high2 = n - 1, mid2;
// while (low1 != high1 || low2 != high2) {
// mid1 = (low1 + high1) / 2;
// mid2 = (low2 + high2) / 2;
// if (A[mid1] == B[mid2])
// return A[mid1];
// if (A[mid1] < B[mid2]) {
// low1 = ((low1 + high1) % 2 == 0) ? mid1 : mid1 + 1;
// high2 = mid2;
// } else {
// low2 = ((low2 + high2) % 2 == 0) ? mid2 : mid2 + 1;
// high1 = mid1;
// }
// }
// return A[low1] < B[low2] ? A[low1] : B[low2];
// }
// // 时间复杂度:O(log_2(n))
// // 空间复杂度:O(1)
// // ---------------------------------------------------------------------------------
// int m_Search(int A[], int B[], int n) {
// int start1 = 0, end1 = n - 1, middle1,
// start2 = 0, end2 = n - 1, middle2;
// //分别表示序列A和B的首位数、末位数和中位数
// while (start1 != end1 || start2 != end2) {
// middle1 = (start1 + end1) / 2;
// middle2 = (start2 + end2) / 2;
// if (A[middle1] == B[middle2]) {
// return A[middle1]; // 满足条件(1)
// }
// if (A[middle1] < B[middle2]) { // 满足条件(2)
// // if ((start1 + end1) % 2 == 0) { // 若元素个数为奇数
// // start1 = middle1; // 舍弃A中间点以前的部分且保留中间点
// // } else { //元素个数为偶数
// // start1 = middle1 + 1; //舍弃A中间点及中间点以前的部分
// // }
// start1 = ((start1 + end1) % 2 == 0) ? middle1 : middle1 + 1;
// end2 = middle2; //舍弃B中间点以后部分且保留中间点
// } else { // 满足条件(3)
// // if((start2 + end2) % 2 == 0) { //若元素个数为奇数
// // start2 = middle2; // 舍弃B中间点以前的部分且保留中间点
// // } else {
// // start2 = middle2 + 1; // 舍弃B中间点及中间点以前的的部分
// // }
// start2 = ((start2 + end2) % 2 == 0) ? middle2 : middle2 + 1;
// end1 = middle1; // 舍弃A中间点以后的部分且保留中间点
// }
// }
// return A[start1] < B[start2] ? A[start1] : B[start2];
// }
// // 时间复杂度:O(log_2(n))
// // 空间复杂度:O(1)
|
281a44e71f1dafac2553b34148b23bea69ab084c
|
3970d59a547fe82174b96e3afd7951bfa5884cf4
|
/lab1/server.cc
|
13cf0e31bda215a0dbfd0b0f93eb170bc313d7cc
|
[] |
no_license
|
magical/cs478
|
4d929c418bbf0adbbd385a4fe2704107e4557276
|
64675fd3e1d81ab90ddc560d30412ef06b01f447
|
refs/heads/master
| 2020-03-18T02:45:52.688091
| 2018-05-21T06:20:14
| 2018-05-21T06:20:14
| 134,206,209
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,980
|
cc
|
server.cc
|
#include <iostream>
#include <string>
#include <unistd.h>
#include "zmq.hpp"
extern "C" {
#include "miracl.h"
}
#include "puzzles.hpp"
using std::string;
zmq::message_t empty;
std::string tostring(uint64_t t) {
std::string s(8, '0');
s[0] = (char)(t & 0xff);
s[1] = (char)((t>>8) & 0xff);
s[2] = (char)((t>>16) & 0xff);
s[3] = (char)((t>>24) & 0xff);
s[4] = (char)((t>>32) & 0xff);
s[5] = (char)((t>>40) & 0xff);
s[6] = (char)((t>>48) & 0xff);
s[7] = (char)((t>>56) & 0xff);
return s;
}
Puzzle genpuzzle(string secret, time_t t, string msg, int strength) {
Puzzle puz;
// generate puzzle
string output(32, '0');
sha256 sh;
shs256_init(&sh);
shs256_process_string(&sh, secret);
shs256_process_string(&sh, tostring(t));
shs256_process_string(&sh, msg);
shs256_hash(&sh, &output[0]);
puz.puzzle = output;
// generate goal
puz.goal = hash(output);
// clear low bits
setbits(puz.puzzle, 0, strength);
puz.t = t;
puz.bits = strength;
return puz;
}
bool valid(string secret, time_t t, string msg, string puzzle) {
string output(32, '0');
sha256 sh;
shs256_init(&sh);
shs256_process_string(&sh, secret);
shs256_process_string(&sh, tostring(t));
shs256_process_string(&sh, msg);
shs256_hash(&sh, &output[0]);
shs256_init(&sh);
shs256_process_string(&sh, output);
shs256_hash(&sh, &output[0]);
string puzhash = hash(puzzle);
return output == puzhash;
}
string ztostring(zmq::message_t &zmsg) {
string s(zmsg.size(), '\0');
memmove(&s[0], zmsg.data(), zmsg.size());
return s;
}
int main(int argc, char** argv) {
int strength = 16;
string secret = "server secret";
int opt;
while ((opt = getopt(argc, argv, "n:")) != -1) {
if (opt == 'n') {
strength = atoi(optarg);
}
}
zmq::context_t context;
zmq::socket_t socket(context, zmq::socket_type::rep);
socket.bind("tcp://127.0.0.1:7000");
for (;;) {
zmq::message_t req;
socket.recv(&req);
// read message
auto s = std::string(reinterpret_cast<char*>(req.data()), req.size());
//std::cout << s << "\n";
// does it contain a response to a puzzle?
// if so, check
// otherwise, generate a new puzzle
if (s.at(0) == 2) {
// 2 | solution | goal | t | nbits | message
Puzzle puz = parse(s);
if (!puz.err.empty()) {
// invalid message size
goto error;
}
string message = s.substr(MESSAGE_LENGTH);
if (valid(secret, puz.t, message, puz.puzzle)) {
std::cout << message << "\n";
} else {
std::cout << "invalid\n";
}
socket.send(empty);
} else if (s.at(0) == 0) {
// 0 | message
// generate puzzle
time_t t = time(NULL);
string message = s.substr(1);
Puzzle puz = genpuzzle(secret, t, message, strength);
// 1 | puzzle | goal | t | nbits
zmq::message_t resp(MESSAGE_LENGTH);
reinterpret_cast<char*>(resp.data())[0] = 1;
encode(puz, resp.data());
socket.send(resp);
} else {
goto error;
}
continue;
error:
std::cerr << "error\n";
socket.send(empty);
}
return 0;
}
|
1cd7dc78ec7a7cdc5d4938fcc181fd9ad8245a20
|
5e16bdc8da61393ac4548aa8ffd6bdbfdb466495
|
/chapter02/p54.cpp
|
4b6d3737852fc55d1b4c29d3ea54f355597dd31e
|
[] |
no_license
|
TolicWang/C-Plus-Plus-Primer-Edition-5
|
38610bd03dfb7800cc965c5d8f325552f7d50e60
|
b897381d407f7278431397c54a080b39fdc95f9c
|
refs/heads/master
| 2021-01-19T09:54:50.836805
| 2017-06-13T10:29:00
| 2017-06-13T10:29:00
| 87,797,677
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 413
|
cpp
|
p54.cpp
|
/*************************************************************************
> File Name: p54.cpp
> Author: Tolic
> Mail: mr_king1994@163.com
> Created Time: Sun 02 Apr 2017 10:04:23 AM CST
************************************************************************/
#include<iostream>
using namespace std;
int main()
{
const int &r1 = 43;
const int &r4 = r1 * 9;
cout<<r4<<endl;
return 0;
}
|
9be01c97c61e85dac87a63835b794a52fd1703e5
|
318f4c88ea77251660e7dbee9182ca138d7b95d9
|
/Cplusplus/rotateArray.cpp
|
74aa23a73f468781b0c3c73523588ca7d58abcbf
|
[] |
no_license
|
Sahil12S/LeetCode
|
b1548aec56c7eb30139b0f2975329c6ed9034379
|
5a9916827e969cd4adbc394779e1bb3ba576f6e2
|
refs/heads/master
| 2021-06-02T07:39:00.503814
| 2020-09-23T03:21:53
| 2020-09-23T03:21:53
| 145,740,842
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 701
|
cpp
|
rotateArray.cpp
|
// Given an array, rotate the array to the right by k steps, where k is non-negative.
#include <iostream>
#include <vector>
using namespace std;
void rotate(vector<int>& nums, int k);
int main(int argc, char const *argv[])
{
vector<int> nums{1,2,3,4,5,6,7,8,9,0};
rotate(nums, 4);
for (int n : nums) {
cout << " " << n;
}
cout << endl;
return 0;
}
void rotate(vector<int>& nums, int k) {
int size = nums.size();
int swap_size = size;
for (; k %= swap_size; swap_size -= k) {
for (int i = 0; i < k; ++i) {
int index = size - swap_size;
swap( nums[size - swap_size + i], nums[size - k + i] );
}
}
}
|
3d82286d19186b96661a6cfd86050f5c9563c31c
|
c48067c6986bdcfc2787b834e40bde88e9a520ad
|
/utility/utilities.h
|
d64e3055820cb00659f23a271fd94a5e3712257f
|
[] |
no_license
|
leoking01/PlatForm
|
c6fa1140143e9cb2e853695e469ade69e4c47a1d
|
5c493c5ea90f8cce50cccb36fe929f94819eae87
|
refs/heads/main
| 2023-06-06T02:12:35.196369
| 2021-07-02T01:02:32
| 2021-07-02T01:02:32
| 382,192,707
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 748
|
h
|
utilities.h
|
//
// Created by alex on 2021/7/1.
//
#ifndef VISIONCOMPAREBENCH_UTILITIES_H
#define VISIONCOMPAREBENCH_UTILITIES_H
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <strstream>
#include <string>
#include <list>
#include <set>
#include <map>
#include <vector>
#include <algorithm>
#include <memory>
#include <thread>
#include <chrono>
#include <mutex>
#include <string.h>
#include <sstream>
class utilities {
};
std::vector<std::string> split_std_string(const std::string &str, const std::string &delim);
bool IsContainsStr(std::string str, std::string contains_str);
std::vector<std::string> split_std_string(const std::string &s, std::vector<std::string> &res, char delim);
#endif //VISIONCOMPAREBENCH_UTILITIES_H
|
e673a00471d6a4530689766bcf15f3265d58b8a5
|
7f62f204ffde7fed9c1cb69e2bd44de9203f14c8
|
/DboClient/Tool/NtlWE/SLPropDlg.h
|
6e1556f680674871acd572bbd4442c2afc2b7e69
|
[] |
no_license
|
4l3dx/DBOGLOBAL
|
9853c49f19882d3de10b5ca849ba53b44ab81a0c
|
c5828b24e99c649ae6a2953471ae57a653395ca2
|
refs/heads/master
| 2022-05-28T08:57:10.293378
| 2020-05-01T00:41:08
| 2020-05-01T00:41:08
| 259,094,679
| 3
| 3
| null | 2020-04-29T17:06:22
| 2020-04-26T17:43:08
| null |
UTF-8
|
C++
| false
| false
| 955
|
h
|
SLPropDlg.h
|
#pragma once
#include "colourpicker.h"
#include "afxwin.h"
#include "NtlWorldSLManger.h"
class CSLPropDlg : public CDialog
{
DECLARE_DYNAMIC(CSLPropDlg)
public:
CSLPropDlg(CWnd* pParent = NULL); // standard constructor
virtual ~CSLPropDlg();
enum { IDD = IDD_ATTR_SL };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
CString m_StrSoftness;
CString m_StrSLClrR;
CString m_StrSLClrG;
CString m_StrSLClrB;
CString m_StrBrightnessMin;
CString m_StrBrightnessMax;
CColourPicker m_SLClrPickeer;
CComboBox m_SLDirCombo;
CButton m_ApplySlopeLighting;
COLORREF m_ClrSL;
public:
virtual BOOL DestroyWindow();
virtual BOOL OnInitDialog();
virtual BOOL PreTranslateMessage(MSG* pMsg);
void SetData(sNTL_WORLD_SL& NtlWorldSL, RwBool IsMultipleSelected = FALSE);
void SetColor(int r, int g, int b);
RwBool GetSLData(RwV3d& Pos, sNTL_WORLD_SL& NtlWorldSL);
};
|
a81be1fa64529a27256919cca7e68eecdb66f554
|
c7c48790f1988bd22a4e6dfa3743788c1697f077
|
/parser/parser_expr.hpp
|
738a7cce0c4fe72ddbc83a756568e8d25d9c5327
|
[] |
no_license
|
NotMichaelChen/CS6413
|
9d6d77fdd5d4047f3d08a4cf2d7de5b8fa0271e6
|
04ce66b7fd5620f85b06c53c71ecfe70869340f3
|
refs/heads/master
| 2020-03-14T09:10:45.961820
| 2018-05-05T05:04:44
| 2018-05-05T05:04:44
| 131,540,007
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 575
|
hpp
|
parser_expr.hpp
|
//Michael Chen - mzc223 - CS6413 - Spring 2018 - Boris Aronov
#ifndef PARSER_EXPR_HPP
#define PARSER_EXPR_HPP
#include <string>
struct ExprResult
{
bool isint;
//Represents which memory location the result of the computation is in. Negative if literal
int resultloc;
//Only access the one indicated by isint
int intliteral;
float floatliteral;
};
void formatExpr(std::string& command, ExprResult& arg);
ExprResult expr();
ExprResult expr1();
ExprResult term();
ExprResult factor();
ExprResult functioncall();
void boolexpr(int endlabel);
#endif
|
333940bdb5d4e6042eef5d8877739fc92b1fca07
|
864a03b8cb1debb3a4fefc284d8406c6e4306db8
|
/classNormal.cpp
|
47fb059801b862cbd6a61601254d52d302938b3a
|
[] |
no_license
|
dimkael/VRMLConverterToDirectX
|
cecb8366a586b11b1d23922be4bc0eba96264e99
|
f37cf7506e2e24b1543dfd44a7e31bec86298fa3
|
refs/heads/master
| 2023-04-01T14:07:10.840860
| 2021-04-10T22:22:39
| 2021-04-10T22:22:39
| 356,703,821
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 177
|
cpp
|
classNormal.cpp
|
#include "classNormal.h"
Normal::Normal() : def("") {}
Normal::Normal(string _def) : def(_def) {}
void Normal::writeX(ofstream& file) {}
Normal::~Normal() {
del(vector);
}
|
9ae5a25414ab22f9e9eccbf261b03e7e651ac4a3
|
117ffa29d63005010f2658d8e65461a7944528ab
|
/src/memory.cpp
|
422f93a7c5f59ac9615402e3d30d11fc665f7649
|
[] |
no_license
|
cwlroda/MIPS-Simulator
|
7407c6c992481d772a8586582f61ae81f062d233
|
e16fd5b5b46c716a523299d095d2527485636c53
|
refs/heads/master
| 2020-12-04T19:00:25.338880
| 2020-02-03T04:06:24
| 2020-02-03T04:06:24
| 231,875,354
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,555
|
cpp
|
memory.cpp
|
#include "include/memory.hpp"
#include <iostream>
#include <cstdlib>
void RAM::loadtoMemory(unsigned char binstr){
unsigned int addr = ADDR_INSTR_OFFSET + offset;
try{
if(addr < ADDR_INSTR_OFFSET || addr >= (ADDR_INSTR_OFFSET + ADDR_INSTR_LENGTH)){
throw "Accessing out of bounds memory!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-11);
}
memory[offset] = binstr;
offset++;
}
unsigned int RAM::pullfromMemory(unsigned int& ProgCount){
unsigned int data;
if((ProgCount-1) == (ADDR_INSTR_OFFSET + offset)){
ProgCount = 0;
return 1;
}
try{
if(ProgCount < ADDR_INSTR_OFFSET || ProgCount > (ADDR_INSTR_OFFSET + offset + 4)){
throw "Accessing out of bounds memory!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-11);
}
unsigned int addr = ProgCount - ADDR_INSTR_OFFSET;
try{
if(ProgCount%4 == 0){
data = (((unsigned int)memory[addr] << 8) + (unsigned int)memory[addr+1]) << 8;
data = (data + (unsigned int)memory[addr+2]) << 8;
data = data + (unsigned int)memory[addr+3];
}
else{
throw "Invalid address!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-11);
}
return data;
}
unsigned int RAM::get_addr(){
return (ADDR_INSTR_OFFSET + offset);
}
void RAM::loadtoDataMem(unsigned int addr, unsigned int data, int num){
try{
if(addr < ADDR_DATA_OFFSET || addr >= (ADDR_DATA_OFFSET + ADDR_DATA_LENGTH)){
throw "Accessing out of bounds memory!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-11);
}
unsigned int lsb = data << 24 >> 24;
unsigned int xlsb = data << 16 >> 24;
unsigned int xmsb = data << 8 >> 24;
unsigned int msb = data >> 24;
unsigned int index = addr - ADDR_DATA_OFFSET;
if(num == 0){
datamem[index] = lsb;
}
else if(num == 1){
try{
if(addr%2 == 0){
datamem[index] = xlsb;
datamem[index+1] = lsb;
}
else{
throw "Invalid address!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-11);
}
}
else if(num == 2){
try{
if(addr%4 == 0){
datamem[index] = msb;
datamem[index+1] = xmsb;
datamem[index+2] = xlsb;
datamem[index+3] = lsb;
}
else{
throw "Invalid address!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-11);
}
}
}
unsigned int RAM::getfromDataMem(unsigned int addr, int num){
unsigned int data;
try{
if((addr < ADDR_DATA_OFFSET) || (addr >= (ADDR_DATA_OFFSET + ADDR_DATA_LENGTH))){
if((addr < ADDR_INSTR_OFFSET) || (addr >= (ADDR_INSTR_OFFSET + ADDR_INSTR_LENGTH))){
throw "Accessing out of bounds memory!";
}
}
} catch(const char* msg){
cerr << msg << endl;
exit(-11);
}
if((addr & 0x10000000) > 0){
unsigned int index = addr - ADDR_INSTR_OFFSET;
if(num == 0){
data = memory[index];
}
else if(num == 1){
try{
if(addr%2 == 0){
data = (memory[index] << 8) + memory[index+1];
}
else{
throw "Invalid address!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-11);
}
}
else if(num == 2){
try{
if(addr%4 == 0){
data = ((memory[index] << 8) + memory[index+1]) << 8;
data = (data + memory[index+2]) << 8;
data = data + memory[index+3];
}
else{
throw "Invalid address!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-11);
}
}
}
else if((addr & 0x30000000) > 0){
unsigned int index = addr - ADDR_DATA_OFFSET;
if(num == 0){
data = datamem[index];
}
else if(num == 1){
try{
if(addr%2 == 0){
data = (datamem[index] << 8) + datamem[index+1];
}
else{
throw "Invalid address!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-11);
}
}
else if(num == 2){
try{
if(addr%4 == 0){
data = ((datamem[index] << 8) + datamem[index+1]) << 8;
data = (data + datamem[index+2]) << 8;
data = data + datamem[index+3];
}
else{
throw "Invalid address!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-11);
}
}
}
return data;
}
int RAM::getc(int num){
if(num == 0){
int x;
try{
x = getchar();
if(cin.fail()){
throw "I/O error!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-21);
}
if(x == -1){
return -1;
}
else{
return 0;
}
}
else if(num == 1){
int x;
try{
x = getchar();
if(cin.fail()){
throw "I/O error!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-21);
}
return x;
}
}
void RAM::putc(int num, char ch){
if(num == 0){
char ch = 0;
try{
putchar(ch);
if(cout.fail()){
throw "I/O error!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-21);
}
}
else if(num == 1){
try{
putchar(ch);
if(cout.fail()){
throw "I/O error!";
}
} catch(const char* msg){
cerr << msg << endl;
exit(-21);
}
}
}
|
2b815f57e25c08125112de5650ce76781482324c
|
dc2f458cdf8fecd409e96394f6dd50af970d0ab4
|
/util/YR_ThreadPool.cpp
|
be830a64a181952da589c1b82a212b02a8582cff
|
[] |
no_license
|
Typedefintbool/youren
|
be2a0d301c03f1134beb9440ee529df41f36c01b
|
e9cefb275ad45f4f02cc48729ae610087f70028d
|
refs/heads/master
| 2022-02-24T17:51:11.546574
| 2019-10-15T11:28:30
| 2019-10-15T11:28:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,783
|
cpp
|
YR_ThreadPool.cpp
|
#include "YR_ThreadPool.h"
#include "YR_Common.h"
namespace youren {
YR_ThreadPool::KeyInitialize YR_ThreadPool::g_key_initialize;
pthread_key_t YR_ThreadPool::g_key;
YR_ThreadPool::YR_ThreadPool()
:_bAllDone(true)
{
}
YR_ThreadPool::~YR_ThreadPool()
{
stop();
clear();
}
void YR_ThreadPool::init(size_t num)
{
stop();
Lock sync(*this);
clear();
for(size_t i = 0; i<num; i++)
{
_jobthread.push_back(new ThreadWorker(this));
}
}
void YR_ThreadPool::stop()
{
Lock sync(*this);
auto it = _jobthread.begin();
while(it != _jobthread.end())
{
if((*it)->isAlive())
{
(*it)->terminate();
(*it)->getThreadControl().join(); //线程回收
}
++it;
}
}
void YR_ThreadPool::start()
{
Lock sync(*this);
auto it = _jobthread.begin();
while(it != _jobthread.end())
{
(*it)->start();
++it;
}
_bAllDone = false;
}
void YR_ThreadPool::setThreadData(YR_ThreadPool::ThreadData *p)
{
//释放原来数据
YR_ThreadPool::ThreadData *pOld = getThreadData();
if(pOld != NULL && pOld != p)
delete pOld;
int ret = pthread_setspecific(g_key, (void*)p);
if(ret != 0)
{
throw YR_ThreadPool_Exception("[YR_ThreadPool::setThreadData] pthread_setspecific error", ret);
}
}
void YR_ThreadPool::setThreadData(pthread_key_t pkey, ThreadData *p)
{
YR_ThreadPool::ThreadData *pOld = getThreadData(pkey);
if(pOld != NULL && pOld != p)
delete pOld;
int ret = pthread_setspecific(pkey, (void*)p);
if(ret != 0)
{
throw YR_ThreadPool_Exception("[YR_ThreadPool::setThreadData] pthread_setspecific error", ret);
}
}
YR_ThreadPool::ThreadData* YR_ThreadPool::getThreadData()
{
return (ThreadData*)pthread_getspecific(g_key);
}
YR_ThreadPool::ThreadData* YR_ThreadPool::getThreadData(pthread_key_t pkey)
{
return (ThreadData*)pthread_getspecific(pkey);
}
void YR_ThreadPool::destructor(void *p)
{
ThreadData* ttd = (ThreadData*)p;
delete ttd;
}
void YR_ThreadPool::clear()
{
auto it = _jobthread.begin();
while(it != _jobthread.end())
{
delete(*it);
++it;
}
_jobthread.clear();
_jobqueue.clear();
}
std::function<void()> YR_ThreadPool::get(ThreadWorker* ptw)
{
std::function<void()> res;
if(!_jobqueue.pop_front(res, 1000))
{
return NULL;
}
{
Lock sync(_tmutex);
_busthread.insert(ptw);
}
return res;
}
std::function<void()> YR_ThreadPool::get()
{
std::function<void()> res;
if(!_startqueue.pop_front(res))
{
return NULL;
}
return res;
}
void YR_ThreadPool::exit()
{
YR_ThreadPool::ThreadData *p = getThreadData();
if(p)
{
delete p;
int ret = pthread_setspecific(g_key, NULL);
if(ret != 0)
{
throw YR_ThreadPool_Exception("[YR_ThreadPool::exit] pthread_setspecific error", ret);
}
}
_jobqueue.clear();
}
void YR_ThreadPool::notifyT()
{
_jobqueue.notifyT();
}
bool YR_ThreadPool::finish()
{
return _startqueue.empty() && _jobqueue.empty() && _busthread.empty() && _bAllDone;
}
void YR_ThreadPool::idle(ThreadWorker* ptw)
{
Lock sync(_tmutex);
_busthread.erase(ptw);
if(_busthread.empty())
{
_bAllDone = true;
_tmutex.notifyAll();
}
}
/////////////////////////////////////////////////////////////////////////////////////////
void YR_ThreadPool::ThreadWorker::run()
{
//获取启动任务
//调用初始化部分
auto pst = _tpool->get();
if(pst)
{
try{
pst();
}
catch(...)
{
}
}
//调用处理部分
while(!_bTerminate)
{
auto pfw = _tpool->get(this);
if(pfw)
{
try
{
pfw();
}
catch(...)
{
}
_tpool->idle(this);
}
}
_tpool->exit();
}
void YR_ThreadPool::ThreadWorker::terminate()
{
_bTerminate = true;
_tpool->notifyT();
}
bool YR_ThreadPool::waitForAllDone(int millsecond)
{
Lock sync(_tmutex);
start1:
//任务队列和繁忙线程都是空的
if (finish())
{
return true;
}
//永远等待
if(millsecond < 0)
{
_tmutex.timeWait(1000);
goto start1;
}
int64_t iNow= YR_Common::nowToms();
int m = millsecond;
start2:
bool b = _tmutex.timeWait(millsecond);
//完成处理了
if(finish())
{
return true;
}
if(!b)
{
return false;
}
millsecond = max((int64_t)0, m - (YR_Common::nowToms() - iNow));
goto start2;
return false;
}
}
|
3fc7d35c042de93114b3b5435d8f2538d501e624
|
eab73a7acf3194b5d9f095aade9ca83ba2e9c5cb
|
/src/Pegasus/Common/tests/StatisticalData/StatisticalData.cpp
|
66e1999d62c77077b3430446ae3a94e578fca885
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
edwardt/Pegasus-2.5
|
f1af8e7c546d1ae50bbcbd0b5af752b111b5d895
|
4a0b9a1b37e2eae5c8105fdea631582dc2333f9a
|
refs/heads/master
| 2022-03-17T17:34:46.748653
| 2013-07-23T13:21:50
| 2013-07-23T13:21:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,498
|
cpp
|
StatisticalData.cpp
|
//%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN
// ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED
// "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//==============================================================================
//
// Author: Willis White (whiwill@us.ibm.com)
//
// Modified By:
//
//
//
//%/////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <cassert>
#include <Pegasus/Common/StatisticalData.h>
PEGASUS_USING_STD;
PEGASUS_USING_PEGASUS;
int main(int argc, char** argv)
{
StatisticalData* sd = StatisticalData::current();
StatisticalData* curr = StatisticalData::current();
//cur = StatisticalData::current();
//check to make sure current() returns a pointer to the existing StatisticalData
// object
assert(sd->length == curr->length);
assert(sd->requestSize == curr->requestSize);
assert(sd->copyGSD == curr->copyGSD);
assert(sd->numCalls[5] == curr->numCalls[5]);
assert(sd->requestSize[6] == curr->requestSize[6]);
// *****************************************
// check the addToValue() method
// Changes sd.numCalls[5] from 0 to 10
sd->addToValue(10,5,StatisticalData::PEGASUS_STATDATA_SERVER);
// Changes sd.requestSize[6] form 0 to 10
sd->addToValue(10,6,StatisticalData::PEGASUS_STATDATA_BYTES_READ);
//assert(sd->numCalls[5] == 0);
//assert(sd->requestSize[6] == 10);
//**********************************************
// check the setCopyGSD method
sd->setCopyGSD(1);
assert(sd->copyGSD == 1);
//****************************************************
// make sure the cur the sd objects are still the same
assert(sd->length == curr->length);
assert(sd->requestSize == curr->requestSize);
assert(sd->copyGSD == curr->copyGSD);
assert(sd->numCalls[5] == curr->numCalls[5]);
assert(sd->requestSize[6] == curr->requestSize[6]);
//**************************
cout << argv[0] << " +++++ passed all tests" << endl;
return 0;
}
|
96b750cc2b5cabd72fd1c3b73a503073b32fb65d
|
1619d31e3f7db1661bfa13560fa51bed75e6de5f
|
/Snake-And-Ladders/models/Ladder.h
|
a8059aeefac42104cbc6d3ac2f63e1eca4db5292
|
[
"MIT"
] |
permissive
|
abdul699/Machine_Coding
|
7603e115fd38331d4d40442ba0c160f57df8972a
|
7e71397aa25a77d7d96c4117eda8b473af341d4a
|
refs/heads/main
| 2023-03-06T07:08:10.790465
| 2021-02-18T18:23:47
| 2021-02-18T18:23:47
| 339,701,578
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 253
|
h
|
Ladder.h
|
#pragma once
#include<iostream>
using namespace std;
class Ladder {
int start, end;
public:
Ladder(int start, int end);
int getStart();
int getEnd();
void setStart(int start);
void setEnd(int end);
};
|
ef8e99db292896bf1102b4c44e244551686e1cf5
|
d979e3b9f5fd2b1324af677eb3068dfb676267f3
|
/src/LightSwitch/Configuration.h
|
a65098fb4990a07f78505463378d343917f850e0
|
[
"MIT"
] |
permissive
|
krconv/iot-devices
|
42d17323555efabb244059082a124e6c6aafef5b
|
8bdd2f0cfbdc7d4f8489264870e5a4e745c1151d
|
refs/heads/main
| 2023-03-03T17:24:22.934496
| 2021-02-16T12:24:48
| 2021-02-16T12:24:48
| 335,498,743
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,052
|
h
|
Configuration.h
|
#pragma once
#include <Arduino.h>
#include <string>
#include "../Common/Configuration.h"
#include "../Common/Types.h"
#include "../Setup.h"
namespace LightSwitch
{
namespace Configuration
{
inline static pin_t getButtonPin()
{
return PIN_BUTTON;
}
constexpr inline static voltage_t getButtonVoltageNotPressed()
{
return VOLTAGE_BUTTON_NOT_PRESSED;
}
constexpr inline static voltage_t getButtonVoltagePressed()
{
return VOLTAGE_BUTTON_PRESSED;
}
inline static pin_t getRelayPin()
{
return PIN_RELAY;
}
constexpr inline static voltage_t getRelayVoltageOn()
{
return VOLTAGE_RELAY_ON;
}
constexpr inline static voltage_t getRelayVoltageOff()
{
return VOLTAGE_RELAY_OFF;
}
inline static pin_t getWhiteStatusLedPin()
{
return PIN_WHITE_STATUS_LED;
}
inline static pin_t getRedStatusLedPin()
{
return PIN_RED_STATUS_LED;
}
constexpr inline static analog_voltage_t getStatusLedVoltageOn()
{
return VOLTAGE_STATUS_LED_ON;
}
constexpr inline static analog_voltage_t getStatusLedVoltageDim()
{
return VOLTAGE_STATUS_LED_DIM;
}
constexpr inline static analog_voltage_t getStatusLedVoltageOff()
{
return VOLTAGE_STATUS_LED_OFF;
}
inline static std::string getMqttTopicButtonSetState()
{
return MQTT_DOMAIN "/" BUTTON_NAME "/state/set";
}
inline static std::string getMqttTopicButtonState()
{
return MQTT_DOMAIN "/" BUTTON_NAME "/state";
}
inline static std::string getMqttTopicSwitchSetState()
{
return MQTT_DOMAIN "/" SWITCH_NAME "/state/set";
}
inline static std::string getMqttTopicSwitchState()
{
return MQTT_DOMAIN "/" SWITCH_NAME "/state";
}
inline static std::string getMqttPayloadOn()
{
return "on";
}
inline static std::string getMqttPayloadOff()
{
return "off";
}
} // namespace Configuration
} // namespace LightSwitch
|
8208523caa696da3ffb1155783d932c5d2228f14
|
6fd7d4463602194d1dd69dec887fcf2891937a2a
|
/RenderKit/cappedcylindertriplebondgeometry.cpp
|
96362cfa0bccc2d1e9847b59939f484e915e5593
|
[
"MIT"
] |
permissive
|
gnvramanarao/iRASPA-QT
|
1039cfea17357a5c27ec21b32bbbc2fdd5dcdfc8
|
d63adefa8e66daf4dfaf4c5899cdaa2477b756d1
|
refs/heads/master
| 2022-12-01T20:21:29.741523
| 2020-08-09T15:21:06
| 2020-08-09T15:21:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,622
|
cpp
|
cappedcylindertriplebondgeometry.cpp
|
#include "cappedcylindertriplebondgeometry.h"
#include "cappedcylindersinglebondgeometry.h"
#include <algorithm>
#include <float4.h>
CappedCylinderTripleBondGeometry::CappedCylinderTripleBondGeometry(double r, int s)
{
_slices = s;
_numberOfVertexes = 3*(4 * _slices + 2);
_numberOfIndices = 3*(12 * _slices);
_vertexes = std::vector<RKVertex>();
_indices = std::vector<short>();
CappedCylinderSingleBondGeometry singleBondGeometry = CappedCylinderSingleBondGeometry(r,s);
std::transform(singleBondGeometry.vertices().begin(), singleBondGeometry.vertices().end(), std::back_inserter(_vertexes), [](RKVertex i) {return RKVertex(i.position + float4(-1.0,0.0,-0.5*sqrt(3.0),0.0), i.normal, i.st);});
std::transform(singleBondGeometry.vertices().begin(), singleBondGeometry.vertices().end(), std::back_inserter(_vertexes), [](RKVertex i) {return RKVertex(i.position + float4(1.0,0.0,-0.5*sqrt(3.0),0.0), i.normal, i.st);});
std::transform(singleBondGeometry.vertices().begin(), singleBondGeometry.vertices().end(), std::back_inserter(_vertexes), [](RKVertex i) {return RKVertex(i.position + float4(0.0,0.0,0.5*sqrt(3.0),0.0), i.normal, i.st);});
std::copy(singleBondGeometry.indices().begin(), singleBondGeometry.indices().end(), std::back_inserter(_indices));
std::transform(singleBondGeometry.indices().begin(), singleBondGeometry.indices().end(), std::back_inserter(_indices), [=](uint16_t i) {return i + 4 * _slices + 2;});
std::transform(singleBondGeometry.indices().begin(), singleBondGeometry.indices().end(), std::back_inserter(_indices), [=](uint16_t i) {return i + 8 * _slices + 4;});
}
|
587e4d44667c15eb39691a2d9a1a81dd0f243fca
|
549270020f6c8724e2ef1b12e38d11b025579f8d
|
/recipes/audiofile/all/test_package/test_package.cpp
|
6943fcec35d57205766dd1a9466bddad6182dc4e
|
[
"MIT"
] |
permissive
|
conan-io/conan-center-index
|
1bcec065ccd65aa38b1fed93fbd94d9d5fe6bc43
|
3b17e69bb4e5601a850b6e006e44775e690bac33
|
refs/heads/master
| 2023-08-31T11:34:45.403978
| 2023-08-31T11:13:23
| 2023-08-31T11:13:23
| 204,671,232
| 844
| 1,820
|
MIT
| 2023-09-14T21:22:42
| 2019-08-27T09:43:58
|
Python
|
UTF-8
|
C++
| false
| false
| 276
|
cpp
|
test_package.cpp
|
#include <AudioFile.h>
#include <iostream>
int main(int argc, char **argv) {
if (argc < 2) {
std::cerr << "Need at least one argument" << std::endl;
return 1;
}
AudioFile<double> audioFile;
audioFile.load(argv[1]);
audioFile.printSummary();
return 0;
}
|
2024313dc8053a45ca77752271f0bee818b079a8
|
91c85b8f40ae85c07ea33edbafe8d79b766cf112
|
/Assignment 3/Assignment 3/BaseEventData.h
|
a9ca3f6f524f5ea61b66b199363eefd20f4453f7
|
[] |
no_license
|
JeffreySmalley/EngineDesign-Jeff-Rob
|
f14f7c2690f7511cc391d4995cdc66ac98aee0bf
|
00b147270bb597f2408830434d660f2ba9cbbc9c
|
refs/heads/master
| 2021-05-28T01:44:50.131285
| 2014-12-16T04:46:49
| 2014-12-16T04:46:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 309
|
h
|
BaseEventData.h
|
#include "IEventData.h"
class BaseEventData : public IEventData
{
private:
const float m_timeStamp;
public:
explicit BaseEventData(const float timeStamp = 0.0f) : m_timeStamp(timeStamp){}
virtual ~BaseEventData();
// Returns the type of event
virtual const EventType& VGetEventType(void) const = 0;
};
|
311c5befae4f18341c06cd51267c04559743d99a
|
7ad71b57a48ccfdb82bdad59953006ad9a410af2
|
/ConjPrior.h
|
b9bbd46a186c0f2fff5fad97664b3420fb2972a6
|
[] |
no_license
|
scherman/algo2-tp3-pokemon_go
|
f2277af768a6b00153e22b5d141e770be02a9097
|
9f288f80f659329cf70d096181880a4881005ba5
|
refs/heads/master
| 2020-07-27T11:13:29.998879
| 2016-12-04T00:44:58
| 2016-12-04T00:44:58
| 73,429,910
| 0
| 2
| null | 2016-11-19T20:34:36
| 2016-11-10T23:35:02
|
C++
|
WINDOWS-1250
|
C++
| false
| false
| 6,231
|
h
|
ConjPrior.h
|
#ifndef CONJPRIOR_H
#define CONJPRIOR_H
#include <iostream>
#include "aed2.h"
using namespace std;
using namespace aed2;
class ConjPrior
{
private:
struct nodo;
public:
//clase exportada
struct elem{
Nat campo1 ;
Nat campo2;
elem( Nat a,Nat b) : campo1( a), campo2(b ){};
bool operator == ( elem h){
return campo1 == h.campo1 && campo2 == h.campo2;
}
};
//forward declarations
class Iterador;
class const_Iterador;
//class elem;
//struct nodo;
//class const_Iterador;
// Generadores
ConjPrior();
~ConjPrior();
ConjPrior(const ConjPrior& otro); //este crea una copia del conjunto y no genera aliasing?
ConjPrior& operator=(const ConjPrior& otro);//este crea copia y genera aliasing? ambos hacen lo mismo?
Iterador Agregar(Nat cantPokesAtrap, Nat jugador);
// Observadores
bool Pertenece(Nat a, Nat b) const;
Nat Cardinal() const;
Nat Minimo() const ;
Iterador CrearIt();
const_Iterador CrearIt() const;
//const_Iterador CrearIt() const;
//esta funcion la agregamos aca, porque nos conviene acceder a
//la representación. Sino, no haria falta.
bool operator == (const ConjPrior& otro) const;
/************************************
* Iterador de Conjunto, modificable *
************************************/
class Iterador
{
public:
Iterador();
Iterador(const typename ConjPrior::Iterador& otra);
Iterador& operator = (const typename ConjPrior::Iterador& otra);
bool operator == (const typename ConjPrior::Iterador& otro) const;
bool HaySiguienteElem() const;
elem SiguienteElem() const;
void AvanzarElem();
void EliminarSiguienteElem();
private:
typename Lista< typename ConjPrior:: nodo*>::Iterador nodos;
typename ConjPrior::nodo** prim;
//funcion modificada *************************************
Iterador( ConjPrior * c )
: nodos(c->nodosDeArbol.CrearIt()),prim(&c->primero ){}
friend class ConjPrior::const_Iterador;
friend typename ConjPrior::Iterador ConjPrior::CrearIt();
//invoca Iterador sobre primero y nodosDeArbol
};
class const_Iterador
{
public:
const_Iterador();
const_Iterador(const typename ConjPrior::const_Iterador& otra);
const_Iterador(const typename ConjPrior::Iterador& otra);
const_Iterador& operator = (const typename ConjPrior::const_Iterador& otra);
bool operator == (const typename ConjPrior::const_Iterador& otro) const;
bool HaySiguienteElem() const;
elem SiguienteElem() const;
void AvanzarElem();
private:
typename Lista< typename ConjPrior:: nodo*>::const_Iterador nodos;
typename ConjPrior::nodo* const* prim;
//funcion modificada *************************************
const_Iterador( const ConjPrior * c )
: nodos(c->nodosDeArbol.CrearIt()),prim( &c->primero ){}
friend typename ConjPrior::const_Iterador ConjPrior::CrearIt() const;
//invoca Iterador sobre primero y nodosDeArbol
};
private:
struct nodo
{
Nat clave;
Nat significado;
Nat ran;
nodo * izq;
nodo * der;
nodo * padre;
nodo(Nat c,Nat s,Nat r,nodo * i,nodo * d, nodo * p) {
clave = c;
significado = s;
ran = r;
izq = i;
der = d;
padre = p;
};
bool operator == ( const nodo& h){
return clave == h.clave && significado == h.significado && ran == h.ran; // &&
}
};
nodo * primero;
Lista<nodo *> nodosDeArbol;
//operaciones auxiliares
static nodo * fusionar(nodo * p,nodo * q){
if (p == NULL)
return q;
else{
if (q == NULL)
return p;
else
return fusionarAux(p,q);
}
}
static nodo * fusionarAux(nodo * p, nodo *q){
if (p->clave >= q->clave){
p->padre = q;
if (q->der == NULL)
q->der = p;
else
q->der = fusionarAux(p,q->der); //modificado - original: fusionarAux(q->der,p)
if ((q->izq != NULL && (q->izq->ran < q->der->ran))|| q->izq == NULL ){
nodo * aux = q->izq;
q->izq = q->der;
q->der = aux;
}
if (q->der != NULL )
q->ran = q->der->ran + 1;
else
q->ran = 1;
return q;
} else {
q->padre = p;
if (p->der == NULL)
p->der = q;
else
p->der = fusionarAux(q,p->der); //modificado - original: fusionarAux(p->der,q)
if ((p->izq != NULL && (p->izq->ran < p->der->ran))|| p->izq == NULL ){
nodo * aux = p->izq;
p->izq = p->der;
p->der = aux;
}
if (p->der != NULL )
p->ran = p->der->ran + 1;
else
p->ran = 1;
return p;
}
}
//probablemente nodo * p deba cambiarse por nodo ** p
static void eliminarMin(nodo * /*&*/*p,typename Lista< typename ConjPrior:: nodo*>::Iterador& itL ,nodo ** cabeza){
nodo * izqAux = (*p)->izq;
nodo * derAux = (*p)->der;
nodo * padreAux = (*p)->padre;
nodo * copiaOriginal = *p;
if (padreAux != NULL){
if (padreAux->izq == *p){
*p = fusionar(izqAux,derAux) ;
padreAux->izq = *p;
if (*p != NULL)
(*p)->padre = padreAux;
}else{
*p = fusionar(izqAux,derAux) ;
padreAux->der = *p;
if (*p != NULL)
(*p)->padre = padreAux;
}
}else{
*p = fusionar(izqAux,derAux);
*cabeza = *p ;
if (*p != NULL)
(*p)->padre = NULL;
}
itL.EliminarSiguiente();
delete copiaOriginal;
}
};
//algoritmos *******************************************************************************************+
#endif
|
3a56cb36bb8d40263f631114541682d884f9073c
|
66a7c9a3eafca6f956edc23e02b0b210385d2475
|
/mls-mpm88_3d/MarchingCubes.h
|
6884c8af53300bdb8275d868e0fd4c3ca7a99646
|
[] |
no_license
|
juniorcarvalho07/mls
|
1d474ee2b9ca42ff46b2e2cad77374e935c3aea0
|
c4db6d456404d9cf31cdd2252136af1fa4316ce6
|
refs/heads/master
| 2020-07-14T20:35:10.228466
| 2019-10-17T15:14:42
| 2019-10-17T15:14:42
| 205,395,608
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 41,966
|
h
|
MarchingCubes.h
|
/**
* @file MarchingCubes.h
* @author Thomas Lewiner <thomas.lewiner@polytechnique.org>
* @author Math Dept, PUC-Rio
* @version 0.2
* @date 12/08/2002
*
* @brief MarchingCubes Algorithm
*/
//________________________________________________
#ifndef _MARCHINGCUBES_H_
#define _MARCHINGCUBES_H_
#define ALLOC_SIZE 65536
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
//#include <time.h>
#include <vector>
#include <memory.h>
#include <iostream>
#include <float.h>
#include "ply.h"
#include "LookUpTable.h"
#include "vector.hh"
//#if !defined(WIN32) || defined(__CYGWIN__)
//#pragma interface
//#endif // WIN32
//_____________________________________________________________________________
// types
/** unsigned char alias */
typedef unsigned char uchar ;
/** signed char alias */
typedef signed char schar ;
/** isovalue alias */
typedef float real ;
//-----------------------------------------------------------------------------
// Vertex structure
/** \struct Vertex "MarchingCubes.h" MarchingCubes
* Position and normal of a vertex
* \brief vertex structure
* \param x X coordinate
* \param y Y coordinate
* \param z Z coordinate
* \param nx X component of the normal
* \param ny Y component of the normal
* \param nz Z component of the normal
*/
typedef struct
{
real x, y, z ; /**< Vertex coordinates */
real nx, ny, nz ; /**< Vertex normal */
} Vertex ;
//-----------------------------------------------------------------------------
// Triangle structure
/** \struct Triangle "MarchingCubes.h" MarchingCubes
* Indices of the oriented triange vertices
* \brief triangle structure
* \param v1 First vertex index
* \param v2 Second vertex index
* \param v3 Third vertex index
*/
typedef struct
{
int v1,v2,v3 ; /**< Triangle vertices */
} Triangle ;
//_____________________________________________________________________________
//_____________________________________________________________________________
/** Marching Cubes algorithm wrapper */
/** \class MarchingCubes
* \brief Marching Cubes algorithm.
*/
class MarchingCubesL
//-----------------------------------------------------------------------------
{
// Constructors
public :
/**
* Main and default constructor
* \brief constructor
* \param size_x width of the grid
* \param size_y depth of the grid
* \param size_z height of the grid
*/
MarchingCubesL ( const int size_x = -1, const int size_y = -1, const int size_z = -1 ):
_originalMC(false),
_ext_data (false),
_size_x (size_x),
_size_y (size_y),
_size_z (size_z),
_data ((real *)NULL),
_x_verts (( int *)NULL),
_y_verts (( int *)NULL),
_z_verts (( int *)NULL),
_nverts (0),
_ntrigs (0),
_Nverts (0),
_Ntrigs (0),
_vertices (( Vertex *)NULL),
_triangles ((Triangle*)NULL){}
/** Destructor */
~MarchingCubesL() {clean_all() ;}
void CopyPolyhedron(std::vector<std::vector<unsigned int> > &triangles,std::vector <Vector> &MCMeshPoints,std::vector<Vector> *nrms)
{
int i;
unsigned int nnrms = _nverts;
nrms->resize(nnrms);
for(unsigned int i = 0; i < nnrms; i++){
nrms->at(i).x = 0;
nrms->at(i).y = 0;
nrms->at(i).z = 0;
}
//MCMeshPoints.erase(MCMeshPoints.begin(),MCMeshPoints.end());
MCMeshPoints.resize(_nverts);
for ( i = 0; i < _nverts; i++ )
{
//Vector v(_vertices[i].x,_vertices[i].y,_vertices[i].z);
nrms->at(i).x = _vertices[i].nx;
nrms->at(i).y = _vertices[i].ny;
nrms->at(i).z = _vertices[i].nz;
MCMeshPoints.at(i).x=_vertices[i].x;
MCMeshPoints.at(i).y=_vertices[i].y;
MCMeshPoints.at(i).z=_vertices[i].z;
}
for ( i = _ntrigs-1; i >=0 ; i-- )
{
std::vector<unsigned int> tri;tri.resize(3);
tri[0] = _triangles[i].v1;
tri[1] = _triangles[i].v2;
tri[2] = _triangles[i].v3;
triangles.push_back(tri);
}
}
//-----------------------------------------------------------------------------
// Accessors
public :
/** accesses the number of vertices of the generated mesh */
inline const int nverts() const { return _nverts ; }
/** accesses the number of triangles of the generated mesh */
inline const int ntrigs() const { return _ntrigs ; }
/** accesses a specific vertex of the generated mesh */
inline Vertex * vert( const int i ) const { if( i < 0 || i >= _nverts ) return ( Vertex *)NULL ; return _vertices + i ; }
/** accesses a specific triangle of the generated mesh */
inline Triangle * trig( const int i ) const { if( i < 0 || i >= _ntrigs ) return (Triangle*)NULL ; return _triangles + i ; }
/** accesses the vertex buffer of the generated mesh */
inline Vertex *vertices () { return _vertices ; }
/** accesses the triangle buffer of the generated mesh */
inline Triangle *triangles() { return _triangles ; }
/** accesses the width of the grid */
inline const int size_x() const { return _size_x ; }
/** accesses the depth of the grid */
inline const int size_y() const { return _size_y ; }
/** accesses the height of the grid */
inline const int size_z() const { return _size_z ; }
/**
* changes the size of the grid
* \param size_x width of the grid
* \param size_y depth of the grid
* \param size_z height of the grid
*/
inline void set_resolution( const int size_x, const int size_y, const int size_z, const real cellsizex,const real cellsizey,const real cellsizez,const real bx,const real by,const real bz )
{ _size_x = size_x ; _size_y = size_y ; _size_z = size_z ;
_cellsizex = cellsizex ; _cellsizey = cellsizey ; _cellsizez = cellsizez;
_bx = bx ; _by = by ; _bz = bz ;
}
/**
* selects wether the algorithm will use the enhanced topologically controlled lookup table or the original MarchingCubes
* \param originalMC true for the original Marching Cubes
*/
inline void set_method ( const bool originalMC = false ) { _originalMC = originalMC ; }
/**
* selects to use data from another class
* \param data is the pointer to the external data, allocated as a size_x*size_y*size_z vector running in x first
*/
inline void set_ext_data ( real *data )
{ if( !_ext_data ) delete [] _data ; _ext_data = data != NULL ; if( _ext_data ) _data = data ; }
/**
* selects to allocate data
*/
inline void set_int_data () { _ext_data = false ; _data = NULL ; }
// Data access
/**
* accesses a specific cube of the grid
* \param i abscisse of the cube
* \param j ordinate of the cube
* \param k height of the cube
*/
inline const real get_data ( const int i, const int j, const int k ) const { return _data[ i + j*_size_x + k*_size_x*_size_y] ; }
/**
* sets a specific cube of the grid
* \param val new value for the cube
* \param i abscisse of the cube
* \param j ordinate of the cube
* \param k height of the cube
*/
inline void set_data ( const real val, const int i, const int j, const int k ) { _data[ i + j*_size_x + k*_size_x*_size_y] = val ; }
// Data initialization
/** inits temporary structures (must set sizes before call) : the grid and the vertex index per cube */
void init_temps ()
{
if( !_ext_data )
_data = new real [_size_x * _size_y * _size_z] ;
_x_verts = new int [_size_x * _size_y * _size_z] ;
_y_verts = new int [_size_x * _size_y * _size_z] ;
_z_verts = new int [_size_x * _size_y * _size_z] ;
memset( _x_verts, -1, _size_x * _size_y * _size_z * sizeof( int ) ) ;
memset( _y_verts, -1, _size_x * _size_y * _size_z * sizeof( int ) ) ;
memset( _z_verts, -1, _size_x * _size_y * _size_z * sizeof( int ) ) ;
}
/** inits all structures (must set sizes before call) : the temporary structures and the mesh buffers */
void init_all ()
{
init_temps() ;
_nverts = _ntrigs = 0 ;
_Nverts = _Ntrigs = ALLOC_SIZE ;
_vertices = new Vertex [_Nverts] ;
_triangles = new Triangle[_Ntrigs] ;
}
/** clears temporary structures : the grid and the main */
inline void clean_temps()
{
if( !_ext_data )
delete [] _data;
delete [] _x_verts;
delete [] _y_verts;
delete [] _z_verts;
if( !_ext_data )
_data = (real*)NULL ;
_x_verts = (int*)NULL ;
_y_verts = (int*)NULL ;
_z_verts = (int*)NULL ;
}
/** clears all structures : the temporary structures and the mesh buffers */
inline void clean_all ()
{
clean_temps() ;
delete [] _vertices ;
delete [] _triangles ;
_vertices = (Vertex *)NULL ;
_triangles = (Triangle *)NULL ;
_nverts = _ntrigs = 0 ;
_Nverts = _Ntrigs = 0 ;
_size_x = _size_y = _size_z = -1 ;
}
//-----------------------------------------------------------------------------
// Exportation
public :
/**
* PLY exportation of the generated mesh
* \param fn name of the PLY file to create
* \param bin if true, the PLY will be written in binary mode
*/
//_____________________________________________________________________________
/**
* PLY importation of a mesh
* \param fn name of the PLY file to read from
*/
void readPLY( const char *fn ) ;
/**
* VRML / Open Inventor exportation of the generated mesh
* \param fn name of the IV file to create
*/
void writeIV ( const char *fn ) ;
/**
* ISO exportation of the input grid
* \param fn name of the ISO file to create
*/
void writeISO( const char *fn ) ;
//-----------------------------------------------------------------------------
// Algorithm
public :
/**
* Main algorithm : must be called after init_all
* \param iso isovalue
*/
inline void run( real iso = (float)0.0 )
{
// clock_t time = clock() ;
compute_intersection_points( iso ) ;
for( _k = 0 ; _k < _size_z-1 ; _k++ )
for( _j = 0 ; _j < _size_y-1 ; _j++ )
for( _i = 0 ; _i < _size_x-1 ; _i++ )
{
_lut_entry = 0 ;
for( int p = 0 ; p < 8 ; ++p )
{
_cube[p] = get_data( _i+((p^(p>>1))&1), _j+((p>>1)&1), _k+((p>>2)&1) ) - iso ;
if( fabs( _cube[p] ) < FLT_EPSILON ) _cube[p] = FLT_EPSILON ;
if( _cube[p] > 0 ) _lut_entry += 1 << p ;
}
process_cube( ) ;
}
//printf("Marching Cubes ran in %lf secs.\n", (double)(clock() - time)/CLOCKS_PER_SEC) ;
}
protected :
/** tesselates one cube */
inline void process_cube ()
{
if( _originalMC )
{
char nt = 0 ;
while( casesClassic[_lut_entry][3*nt] != -1 ) nt++ ;
add_triangle( casesClassic[_lut_entry], nt ) ;
return ;
}
int v12 = -1 ;
_case = cases[_lut_entry][0] ;
_config = cases[_lut_entry][1] ;
_subconfig = 0 ;
switch( _case )
{
case 0 :
break ;
case 1 :
add_triangle( tiling1[_config], 1 ) ;
break ;
case 2 :
add_triangle( tiling2[_config], 2 ) ;
break ;
case 3 :
if( test_face( test3[_config]) )
add_triangle( tiling3_2[_config], 4 ) ; // 3.2
else
add_triangle( tiling3_1[_config], 2 ) ; // 3.1
break ;
case 4 :
if( test_interior( test4[_config]) )
add_triangle( tiling4_1[_config], 2 ) ; // 4.1.1
else
add_triangle( tiling4_2[_config], 6 ) ; // 4.1.2
break ;
case 5 :
add_triangle( tiling5[_config], 3 ) ;
break ;
case 6 :
if( test_face( test6[_config][0]) )
add_triangle( tiling6_2[_config], 5 ) ; // 6.2
else
{
if( test_interior( test6[_config][1]) )
add_triangle( tiling6_1_1[_config], 3 ) ; // 6.1.1
else
{
v12 = add_c_vertex() ;
add_triangle( tiling6_1_2[_config], 9 , v12) ; // 6.1.2
}
}
break ;
case 7 :
if( test_face( test7[_config][0] ) ) _subconfig += 1 ;
if( test_face( test7[_config][1] ) ) _subconfig += 2 ;
if( test_face( test7[_config][2] ) ) _subconfig += 4 ;
switch( _subconfig )
{
case 0 :
add_triangle( tiling7_1[_config], 3 ) ; break ;
case 1 :
add_triangle( tiling7_2[_config][0], 5 ) ; break ;
case 2 :
add_triangle( tiling7_2[_config][1], 5 ) ; break ;
case 3 :
v12 = add_c_vertex() ;
add_triangle( tiling7_3[_config][0], 9, v12 ) ; break ;
case 4 :
add_triangle( tiling7_2[_config][2], 5 ) ; break ;
case 5 :
v12 = add_c_vertex() ;
add_triangle( tiling7_3[_config][1], 9, v12 ) ; break ;
case 6 :
v12 = add_c_vertex() ;
add_triangle( tiling7_3[_config][2], 9, v12 ) ; break ;
case 7 :
if( test_interior( test7[_config][3]) )
add_triangle( tiling7_4_2[_config], 9 ) ;
else
add_triangle( tiling7_4_1[_config], 5 ) ;
break ;
};
break ;
case 8 :
add_triangle( tiling8[_config], 2 ) ;
break ;
case 9 :
add_triangle( tiling9[_config], 4 ) ;
break ;
case 10 :
if( test_face( test10[_config][0]) )
{
if( test_face( test10[_config][1]) )
add_triangle( tiling10_1_1_[_config], 4 ) ; // 10.1.1
else
{
v12 = add_c_vertex() ;
add_triangle( tiling10_2[_config], 8, v12 ) ; // 10.2
}
}
else
{
if( test_face( test10[_config][1]) )
{
v12 = add_c_vertex() ;
add_triangle( tiling10_2_[_config], 8, v12 ) ; // 10.2
}
else
{
if( test_interior( test10[_config][2]) )
add_triangle( tiling10_1_1[_config], 4 ) ; // 10.1.1
else
add_triangle( tiling10_1_2[_config], 8 ) ; // 10.1.2
}
}
break ;
case 11 :
add_triangle( tiling11[_config], 4 ) ;
break ;
case 12 :
if( test_face( test12[_config][0]) )
{
if( test_face( test12[_config][1]) )
add_triangle( tiling12_1_1_[_config], 4 ) ; // 12.1.1
else
{
v12 = add_c_vertex() ;
add_triangle( tiling12_2[_config], 8, v12 ) ; // 12.2
}
}
else
{
if( test_face( test12[_config][1]) )
{
v12 = add_c_vertex() ;
add_triangle( tiling12_2_[_config], 8, v12 ) ; // 12.2
}
else
{
if( test_interior( test12[_config][2]) )
add_triangle( tiling12_1_1[_config], 4 ) ; // 12.1.1
else
add_triangle( tiling12_1_2[_config], 8 ) ; // 12.1.2
}
}
break ;
case 13 :
if( test_face( test13[_config][0] ) ) _subconfig += 1 ;
if( test_face( test13[_config][1] ) ) _subconfig += 2 ;
if( test_face( test13[_config][2] ) ) _subconfig += 4 ;
if( test_face( test13[_config][3] ) ) _subconfig += 8 ;
if( test_face( test13[_config][4] ) ) _subconfig += 16 ;
if( test_face( test13[_config][5] ) ) _subconfig += 32 ;
switch( subconfig13[_subconfig] )
{
case 0 :/* 13.1 */
add_triangle( tiling13_1[_config], 4 ) ; break ;
case 1 :/* 13.2 */
add_triangle( tiling13_2[_config][0], 6 ) ; break ;
case 2 :/* 13.2 */
add_triangle( tiling13_2[_config][1], 6 ) ; break ;
case 3 :/* 13.2 */
add_triangle( tiling13_2[_config][2], 6 ) ; break ;
case 4 :/* 13.2 */
add_triangle( tiling13_2[_config][3], 6 ) ; break ;
case 5 :/* 13.2 */
add_triangle( tiling13_2[_config][4], 6 ) ; break ;
case 6 :/* 13.2 */
add_triangle( tiling13_2[_config][5], 6 ) ; break ;
case 7 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][0], 10, v12 ) ; break ;
case 8 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][1], 10, v12 ) ; break ;
case 9 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][2], 10, v12 ) ; break ;
case 10 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][3], 10, v12 ) ; break ;
case 11 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][4], 10, v12 ) ; break ;
case 12 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][5], 10, v12 ) ; break ;
case 13 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][6], 10, v12 ) ; break ;
case 14 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][7], 10, v12 ) ; break ;
case 15 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][8], 10, v12 ) ; break ;
case 16 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][9], 10, v12 ) ; break ;
case 17 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][10], 10, v12 ) ; break ;
case 18 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][11], 10, v12 ) ; break ;
case 19 :/* 13.4 */
v12 = add_c_vertex() ;
add_triangle( tiling13_4[_config][0], 12, v12 ) ; break ;
case 20 :/* 13.4 */
v12 = add_c_vertex() ;
add_triangle( tiling13_4[_config][1], 12, v12 ) ; break ;
case 21 :/* 13.4 */
v12 = add_c_vertex() ;
add_triangle( tiling13_4[_config][2], 12, v12 ) ; break ;
case 22 :/* 13.4 */
v12 = add_c_vertex() ;
add_triangle( tiling13_4[_config][3], 12, v12 ) ; break ;
case 23 :/* 13.5 */
_subconfig = 0 ;
if( test_interior( test13[_config][6] ) )
add_triangle( tiling13_5_1[_config][0], 6 ) ;
else
add_triangle( tiling13_5_2[_config][0], 10 ) ;
break ;
case 24 :/* 13.5 */
_subconfig = 1 ;
if( test_interior( test13[_config][6] ) )
add_triangle( tiling13_5_1[_config][1], 6 ) ;
else
add_triangle( tiling13_5_2[_config][1], 10 ) ;
break ;
case 25 :/* 13.5 */
_subconfig = 2 ;
if( test_interior( test13[_config][6] ) )
add_triangle( tiling13_5_1[_config][2], 6 ) ;
else
add_triangle( tiling13_5_2[_config][2], 10 ) ;
break ;
case 26 :/* 13.5 */
_subconfig = 3 ;
if( test_interior( test13[_config][6] ) )
add_triangle( tiling13_5_1[_config][3], 6 ) ;
else
add_triangle( tiling13_5_2[_config][3], 10 ) ;
break ;
case 27 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][0], 10, v12 ) ; break ;
case 28 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][1], 10, v12 ) ; break ;
case 29 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][2], 10, v12 ) ; break ;
case 30 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][3], 10, v12 ) ; break ;
case 31 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][4], 10, v12 ) ; break ;
case 32 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][5], 10, v12 ) ; break ;
case 33 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][6], 10, v12 ) ; break ;
case 34 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][7], 10, v12 ) ; break ;
case 35 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][8], 10, v12 ) ; break ;
case 36 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][9], 10, v12 ) ; break ;
case 37 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][10], 10, v12 ) ; break ;
case 38 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][11], 10, v12 ) ; break ;
case 39 :/* 13.2 */
add_triangle( tiling13_2_[_config][0], 6 ) ; break ;
case 40 :/* 13.2 */
add_triangle( tiling13_2_[_config][1], 6 ) ; break ;
case 41 :/* 13.2 */
add_triangle( tiling13_2_[_config][2], 6 ) ; break ;
case 42 :/* 13.2 */
add_triangle( tiling13_2_[_config][3], 6 ) ; break ;
case 43 :/* 13.2 */
add_triangle( tiling13_2_[_config][4], 6 ) ; break ;
case 44 :/* 13.2 */
add_triangle( tiling13_2_[_config][5], 6 ) ; break ;
case 45 :/* 13.1 */
add_triangle( tiling13_1_[_config], 4 ) ; break ;
default :
printf("Marching Cubes: Impossible case 13?\n" ) ; print_cube() ;
}
break ;
case 14 :
add_triangle( tiling14[_config], 4 ) ;
break ;
};
}
/** tests if the components of the tesselation of the cube should be connected by the interior of an ambiguous face */
inline bool test_face ( schar face )
{
real A,B,C,D ;
switch( face )
{
case -1 : case 1 : A = _cube[0] ; B = _cube[4] ; C = _cube[5] ; D = _cube[1] ; break ;
case -2 : case 2 : A = _cube[1] ; B = _cube[5] ; C = _cube[6] ; D = _cube[2] ; break ;
case -3 : case 3 : A = _cube[2] ; B = _cube[6] ; C = _cube[7] ; D = _cube[3] ; break ;
case -4 : case 4 : A = _cube[3] ; B = _cube[7] ; C = _cube[4] ; D = _cube[0] ; break ;
case -5 : case 5 : A = _cube[0] ; B = _cube[3] ; C = _cube[2] ; D = _cube[1] ; break ;
case -6 : case 6 : A = _cube[4] ; B = _cube[7] ; C = _cube[6] ; D = _cube[5] ; break ;
default : printf( "Invalid face code %d\n", face ) ; print_cube() ; A = B = C = D = 0 ;
};
if( fabs( A*C - B*D ) < FLT_EPSILON )
return face >= 0 ;
return face * A * ( A*C - B*D ) >= 0 ; // face and A invert signs
}
/** tests if the components of the tesselation of the cube should be connected through the interior of the cube */
inline bool test_interior( schar s )
{
real t, At=0, Bt=0, Ct=0, Dt=0, a, b ;
char test = 0 ;
char edge = -1 ; // reference edge of the triangulation
switch( _case )
{
case 4 :
case 10 :
a = ( _cube[4] - _cube[0] ) * ( _cube[6] - _cube[2] ) - ( _cube[7] - _cube[3] ) * ( _cube[5] - _cube[1] ) ;
b = _cube[2] * ( _cube[4] - _cube[0] ) + _cube[0] * ( _cube[6] - _cube[2] )
- _cube[1] * ( _cube[7] - _cube[3] ) - _cube[3] * ( _cube[5] - _cube[1] ) ;
t = - b / (2*a) ;
if( t<0 || t>1 ) return s>0 ;
At = _cube[0] + ( _cube[4] - _cube[0] ) * t ;
Bt = _cube[3] + ( _cube[7] - _cube[3] ) * t ;
Ct = _cube[2] + ( _cube[6] - _cube[2] ) * t ;
Dt = _cube[1] + ( _cube[5] - _cube[1] ) * t ;
break ;
case 6 :
case 7 :
case 12 :
case 13 :
switch( _case )
{
case 6 : edge = test6 [_config][2] ; break ;
case 7 : edge = test7 [_config][4] ; break ;
case 12 : edge = test12[_config][3] ; break ;
case 13 : edge = tiling13_5_1[_config][_subconfig][0] ; break ;
}
switch( edge )
{
case 0 :
t = _cube[0] / ( _cube[0] - _cube[1] ) ;
At = 0 ;
Bt = _cube[3] + ( _cube[2] - _cube[3] ) * t ;
Ct = _cube[7] + ( _cube[6] - _cube[7] ) * t ;
Dt = _cube[4] + ( _cube[5] - _cube[4] ) * t ;
break ;
case 1 :
t = _cube[1] / ( _cube[1] - _cube[2] ) ;
At = 0 ;
Bt = _cube[0] + ( _cube[3] - _cube[0] ) * t ;
Ct = _cube[4] + ( _cube[7] - _cube[4] ) * t ;
Dt = _cube[5] + ( _cube[6] - _cube[5] ) * t ;
break ;
case 2 :
t = _cube[2] / ( _cube[2] - _cube[3] ) ;
At = 0 ;
Bt = _cube[1] + ( _cube[0] - _cube[1] ) * t ;
Ct = _cube[5] + ( _cube[4] - _cube[5] ) * t ;
Dt = _cube[6] + ( _cube[7] - _cube[6] ) * t ;
break ;
case 3 :
t = _cube[3] / ( _cube[3] - _cube[0] ) ;
At = 0 ;
Bt = _cube[2] + ( _cube[1] - _cube[2] ) * t ;
Ct = _cube[6] + ( _cube[5] - _cube[6] ) * t ;
Dt = _cube[7] + ( _cube[4] - _cube[7] ) * t ;
break ;
case 4 :
t = _cube[4] / ( _cube[4] - _cube[5] ) ;
At = 0 ;
Bt = _cube[7] + ( _cube[6] - _cube[7] ) * t ;
Ct = _cube[3] + ( _cube[2] - _cube[3] ) * t ;
Dt = _cube[0] + ( _cube[1] - _cube[0] ) * t ;
break ;
case 5 :
t = _cube[5] / ( _cube[5] - _cube[6] ) ;
At = 0 ;
Bt = _cube[4] + ( _cube[7] - _cube[4] ) * t ;
Ct = _cube[0] + ( _cube[3] - _cube[0] ) * t ;
Dt = _cube[1] + ( _cube[2] - _cube[1] ) * t ;
break ;
case 6 :
t = _cube[6] / ( _cube[6] - _cube[7] ) ;
At = 0 ;
Bt = _cube[5] + ( _cube[4] - _cube[5] ) * t ;
Ct = _cube[1] + ( _cube[0] - _cube[1] ) * t ;
Dt = _cube[2] + ( _cube[3] - _cube[2] ) * t ;
break ;
case 7 :
t = _cube[7] / ( _cube[7] - _cube[4] ) ;
At = 0 ;
Bt = _cube[6] + ( _cube[5] - _cube[6] ) * t ;
Ct = _cube[2] + ( _cube[1] - _cube[2] ) * t ;
Dt = _cube[3] + ( _cube[0] - _cube[3] ) * t ;
break ;
case 8 :
t = _cube[0] / ( _cube[0] - _cube[4] ) ;
At = 0 ;
Bt = _cube[3] + ( _cube[7] - _cube[3] ) * t ;
Ct = _cube[2] + ( _cube[6] - _cube[2] ) * t ;
Dt = _cube[1] + ( _cube[5] - _cube[1] ) * t ;
break ;
case 9 :
t = _cube[1] / ( _cube[1] - _cube[5] ) ;
At = 0 ;
Bt = _cube[0] + ( _cube[4] - _cube[0] ) * t ;
Ct = _cube[3] + ( _cube[7] - _cube[3] ) * t ;
Dt = _cube[2] + ( _cube[6] - _cube[2] ) * t ;
break ;
case 10 :
t = _cube[2] / ( _cube[2] - _cube[6] ) ;
At = 0 ;
Bt = _cube[1] + ( _cube[5] - _cube[1] ) * t ;
Ct = _cube[0] + ( _cube[4] - _cube[0] ) * t ;
Dt = _cube[3] + ( _cube[7] - _cube[3] ) * t ;
break ;
case 11 :
t = _cube[3] / ( _cube[3] - _cube[7] ) ;
At = 0 ;
Bt = _cube[2] + ( _cube[6] - _cube[2] ) * t ;
Ct = _cube[1] + ( _cube[5] - _cube[1] ) * t ;
Dt = _cube[0] + ( _cube[4] - _cube[0] ) * t ;
break ;
default : printf( "Invalid edge %d\n", edge ) ; print_cube() ; break ;
}
break ;
default : printf( "Invalid ambiguous case %d\n", _case ) ; print_cube() ; break ;
}
if( At >= 0 ) test ++ ;
if( Bt >= 0 ) test += 2 ;
if( Ct >= 0 ) test += 4 ;
if( Dt >= 0 ) test += 8 ;
switch( test )
{
case 0 : return s>0 ;
case 1 : return s>0 ;
case 2 : return s>0 ;
case 3 : return s>0 ;
case 4 : return s>0 ;
case 5 : if( At * Ct - Bt * Dt < FLT_EPSILON ) return s>0 ; break ;
case 6 : return s>0 ;
case 7 : return s<0 ;
case 8 : return s>0 ;
case 9 : return s>0 ;
case 10 : if( At * Ct - Bt * Dt >= FLT_EPSILON ) return s>0 ; break ;
case 11 : return s<0 ;
case 12 : return s>0 ;
case 13 : return s<0 ;
case 14 : return s<0 ;
case 15 : return s<0 ;
}
return s<0 ;
}
//-----------------------------------------------------------------------------
// Operations
protected :
/**
* computes almost all the vertices of the mesh by interpolation along the cubes edges
* \param iso isovalue
*/
inline void compute_intersection_points( real iso )
//-----------------------------------------------------------------------------
{
for( _k = 0 ; _k < _size_z ; _k++ )
for( _j = 0 ; _j < _size_y ; _j++ )
for( _i = 0 ; _i < _size_x ; _i++ )
{
_cube[0] = get_data( _i, _j, _k ) - iso ;
if( _i < _size_x - 1 ) _cube[1] = get_data(_i+1, _j , _k ) - iso ;
else _cube[1] = _cube[0] ;
if( _j < _size_y - 1 ) _cube[3] = get_data( _i ,_j+1, _k ) - iso ;
else _cube[3] = _cube[0] ;
if( _k < _size_z - 1 ) _cube[4] = get_data( _i , _j ,_k+1) - iso ;
else _cube[4] = _cube[0] ;
if( fabs( _cube[0] ) < FLT_EPSILON ) _cube[0] = FLT_EPSILON ;
if( fabs( _cube[1] ) < FLT_EPSILON ) _cube[1] = FLT_EPSILON ;
if( fabs( _cube[3] ) < FLT_EPSILON ) _cube[3] = FLT_EPSILON ;
if( fabs( _cube[4] ) < FLT_EPSILON ) _cube[4] = FLT_EPSILON ;
if( _cube[0] < 0 )
{
if( _cube[1] > 0 ) set_x_vert( add_x_vertex( ), _i,_j,_k ) ;
if( _cube[3] > 0 ) set_y_vert( add_y_vertex( ), _i,_j,_k ) ;
if( _cube[4] > 0 ) set_z_vert( add_z_vertex( ), _i,_j,_k ) ;
}
else
{
if( _cube[1] < 0 ) set_x_vert( add_x_vertex( ), _i,_j,_k ) ;
if( _cube[3] < 0 ) set_y_vert( add_y_vertex( ), _i,_j,_k ) ;
if( _cube[4] < 0 ) set_z_vert( add_z_vertex( ), _i,_j,_k ) ;
}
}
}
/**
* routine to add a triangle to the mesh
* \param trig the code for the triangle as a sequence of edges index
* \param n the number of triangles to produce
* \param v12 the index of the interior vertex to use, if necessary
*/
inline void add_triangle ( const char* trig, char n, int v12 = -1 )
{
int tv[3] ;
for( int t = 0 ; t < 3*n ; t++ )
{
switch( trig[t] )
{
case 0 : tv[ t % 3 ] = get_x_vert( _i , _j , _k ) ; break ;
case 1 : tv[ t % 3 ] = get_y_vert(_i+1, _j , _k ) ; break ;
case 2 : tv[ t % 3 ] = get_x_vert( _i ,_j+1, _k ) ; break ;
case 3 : tv[ t % 3 ] = get_y_vert( _i , _j , _k ) ; break ;
case 4 : tv[ t % 3 ] = get_x_vert( _i , _j ,_k+1) ; break ;
case 5 : tv[ t % 3 ] = get_y_vert(_i+1, _j ,_k+1) ; break ;
case 6 : tv[ t % 3 ] = get_x_vert( _i ,_j+1,_k+1) ; break ;
case 7 : tv[ t % 3 ] = get_y_vert( _i , _j ,_k+1) ; break ;
case 8 : tv[ t % 3 ] = get_z_vert( _i , _j , _k ) ; break ;
case 9 : tv[ t % 3 ] = get_z_vert(_i+1, _j , _k ) ; break ;
case 10 : tv[ t % 3 ] = get_z_vert(_i+1,_j+1, _k ) ; break ;
case 11 : tv[ t % 3 ] = get_z_vert( _i ,_j+1, _k ) ; break ;
case 12 : tv[ t % 3 ] = v12 ; break ;
default : break ;
}
if( tv[t%3] == -1 )
{
printf("Marching Cubes: invalid triangle %d\n", _ntrigs+1) ;
print_cube() ;
}
if( t%3 == 2 )
{
if( _ntrigs >= _Ntrigs )
{
Triangle *temp = _triangles ;
_triangles = new Triangle[ 2*_Ntrigs ] ;
memcpy( _triangles, temp, _Ntrigs*sizeof(Triangle) ) ;
delete[] temp ;
//printf("%d allocated triangles\n", _Ntrigs) ;
_Ntrigs *= 2 ;
}
Triangle *T = _triangles + _ntrigs++ ;
T->v1 = tv[0] ;
T->v2 = tv[1] ;
T->v3 = tv[2] ;
}
}
}
/** tests and eventually doubles the vertex buffer capacity for a new vertex insertion */
inline void test_vertex_addition()
{
if( _nverts >= _Nverts )
{
Vertex *temp = _vertices ;
_vertices = new Vertex[ _Nverts*2 ] ;
memcpy( _vertices, temp, _Nverts*sizeof(Vertex) ) ;
delete[] temp ;
//printf("%d allocated vertices\n", _Nverts) ;
_Nverts *= 2 ;
}
}
/** adds a vertex on the current horizontal edge */
inline int add_x_vertex()
{
test_vertex_addition() ;
Vertex *vert = _vertices + _nverts++ ;
real u = ( _cube[0] ) / ( _cube[0] - _cube[1] ) ;
vert->x = (real)_bx+(_i+u)*_cellsizex;
vert->y = (real)_by+ _j*_cellsizey ;
vert->z = (real)_bz+ _k*_cellsizez ;
vert->nx = (1-u)*get_x_grad(_i,_j,_k) + u*get_x_grad(_i+1,_j,_k) ;
vert->ny = (1-u)*get_y_grad(_i,_j,_k) + u*get_y_grad(_i+1,_j,_k) ;
vert->nz = (1-u)*get_z_grad(_i,_j,_k) + u*get_z_grad(_i+1,_j,_k) ;
u = (real) sqrt( vert->nx * vert->nx + vert->ny * vert->ny +vert->nz * vert->nz ) ;
if( u > 0 )
{
vert->nx /= u ;
vert->ny /= u ;
vert->nz /= u ;
}
return _nverts-1 ;
}
/** adds a vertex on the current longitudinal edge */
inline int add_y_vertex()
{
test_vertex_addition() ;
Vertex *vert = _vertices + _nverts++ ;
real u = ( _cube[0] ) / ( _cube[0] - _cube[3] ) ;
vert->x = (real)_bx +_i*_cellsizex;
vert->y = (real)_by+(_j+u)*_cellsizey;
vert->z = (real)_bz+ _k*_cellsizez;
vert->nx = (1-u)*get_x_grad(_i,_j,_k) + u*get_x_grad(_i,_j+1,_k) ;
vert->ny = (1-u)*get_y_grad(_i,_j,_k) + u*get_y_grad(_i,_j+1,_k) ;
vert->nz = (1-u)*get_z_grad(_i,_j,_k) + u*get_z_grad(_i,_j+1,_k) ;
u = (real) sqrt( vert->nx * vert->nx + vert->ny * vert->ny +vert->nz * vert->nz ) ;
if( u > 0 )
{
vert->nx /= u ;
vert->ny /= u ;
vert->nz /= u ;
}
return _nverts-1 ;
}
/** adds a vertex on the current vertical edge */
inline int add_z_vertex()
{
test_vertex_addition() ;
Vertex *vert = _vertices + _nverts++ ;
real u = ( _cube[0] ) / ( _cube[0] - _cube[4] ) ;
vert->x = (real) _bx +_i*_cellsizex; ;
vert->y = (real) _by+ _j*_cellsizey; ;
vert->z = (real)_bz+(_k+u)*_cellsizez;
vert->nx = (1-u)*get_x_grad(_i,_j,_k) + u*get_x_grad(_i,_j,_k+1) ;
vert->ny = (1-u)*get_y_grad(_i,_j,_k) + u*get_y_grad(_i,_j,_k+1) ;
vert->nz = (1-u)*get_z_grad(_i,_j,_k) + u*get_z_grad(_i,_j,_k+1) ;
u = (real) sqrt( vert->nx * vert->nx + vert->ny * vert->ny +vert->nz * vert->nz ) ;
if( u > 0 )
{
vert->nx /= u ;
vert->ny /= u ;
vert->nz /= u ;
}
return _nverts-1 ;
}
/** adds a vertex inside the current cube */
inline int add_c_vertex()
{
test_vertex_addition() ;
Vertex *vert = _vertices + _nverts++ ;
real u = 0 ;
int vid ;
vert->x = vert->y = vert->z = vert->nx = vert->ny = vert->nz = 0 ;
// Computes the average of the intersection points of the cube
vid = get_x_vert( _i , _j , _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_y_vert(_i+1, _j , _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_x_vert( _i ,_j+1, _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_y_vert( _i , _j , _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_x_vert( _i , _j ,_k+1) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_y_vert(_i+1, _j ,_k+1) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_x_vert( _i ,_j+1,_k+1) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_y_vert( _i , _j ,_k+1) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_z_vert( _i , _j , _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_z_vert(_i+1, _j , _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_z_vert(_i+1,_j+1, _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_z_vert( _i ,_j+1, _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vert->x /= u ;
vert->y /= u ;
vert->z /= u ;
u = (real) sqrt( vert->nx * vert->nx + vert->ny * vert->ny +vert->nz * vert->nz ) ;
if( u > 0 )
{
vert->nx /= u ;
vert->ny /= u ;
vert->nz /= u ;
}
return _nverts-1 ;
}
/**
* interpolates the horizontal gradient of the implicit function at the lower vertex of the specified cube
* \param i abscisse of the cube
* \param j ordinate of the cube
* \param k height of the cube
*/
inline real get_x_grad( const int i, const int j, const int k )
{
if( i > 0 )
{
if ( i < _size_x - 1 )
return ( get_data( i+1, j, k ) - get_data( i-1, j, k ) ) / 2 ;
else
return get_data( i, j, k ) - get_data( i-1, j, k ) ;
}
else
return get_data( i+1, j, k ) - get_data( i, j, k ) ;
}
/**
* interpolates the longitudinal gradient of the implicit function at the lower vertex of the specified cube
* \param i abscisse of the cube
* \param j ordinate of the cube
* \param k height of the cube
*/
inline real get_y_grad( const int i, const int j, const int k )
{
if( j > 0 )
{
if ( j < _size_y - 1 )
return ( get_data( i, j+1, k ) - get_data( i, j-1, k ) ) / 2 ;
else
return get_data( i, j, k ) - get_data( i, j-1, k ) ;
}
else
return get_data( i, j+1, k ) - get_data( i, j, k ) ;
}
/**
* interpolates the vertical gradient of the implicit function at the lower vertex of the specified cube
* \param i abscisse of the cube
* \param j ordinate of the cube
* \param k height of the cube
*/
inline real get_z_grad( const int i, const int j, const int k )
{
if( k > 0 )
{
if ( k < _size_z - 1 )
return ( get_data( i, j, k+1 ) - get_data( i, j, k-1 ) ) / 2 ;
else
return get_data( i, j, k ) - get_data( i, j, k-1 ) ;
}
else
return get_data( i, j, k+1 ) - get_data( i, j, k ) ;
}
/**
* accesses the pre-computed vertex index on the lower horizontal edge of a specific cube
* \param i abscisse of the cube
* \param j ordinate of the cube
* \param k height of the cube
*/
inline int get_x_vert( const int i, const int j, const int k ) const { return _x_verts[ i + j*_size_x + k*_size_x*_size_y] ; }
/**
* accesses the pre-computed vertex index on the lower longitudinal edge of a specific cube
* \param i abscisse of the cube
* \param j ordinate of the cube
* \param k height of the cube
*/
inline int get_y_vert( const int i, const int j, const int k ) const { return _y_verts[ i + j*_size_x + k*_size_x*_size_y] ; }
/**
* accesses the pre-computed vertex index on the lower vertical edge of a specific cube
* \param i abscisse of the cube
* \param j ordinate of the cube
* \param k height of the cube
*/
inline int get_z_vert( const int i, const int j, const int k ) const { return _z_verts[ i + j*_size_x + k*_size_x*_size_y] ; }
/**
* sets the pre-computed vertex index on the lower horizontal edge of a specific cube
* \param val the index of the new vertex
* \param i abscisse of the cube
* \param j ordinate of the cube
* \param k height of the cube
*/
inline void set_x_vert( const int val, const int i, const int j, const int k ) { _x_verts[ i + j*_size_x + k*_size_x*_size_y] = val ; }
/**
* sets the pre-computed vertex index on the lower longitudinal edge of a specific cube
* \param val the index of the new vertex
* \param i abscisse of the cube
* \param j ordinate of the cube
* \param k height of the cube
*/
inline void set_y_vert( const int val, const int i, const int j, const int k ) { _y_verts[ i + j*_size_x + k*_size_x*_size_y] = val ; }
/**
* sets the pre-computed vertex index on the lower vertical edge of a specific cube
* \param val the index of the new vertex
* \param i abscisse of the cube
* \param j ordinate of the cube
* \param k height of the cube
*/
inline void set_z_vert( const int val, const int i, const int j, const int k ) { _z_verts[ i + j*_size_x + k*_size_x*_size_y] = val ; }
/** prints cube for debug */
inline void print_cube() { printf( "\t%f %f %f %f %f %f %f %f\n", _cube[0], _cube[1], _cube[2], _cube[3], _cube[4], _cube[5], _cube[6], _cube[7]) ; }
//-----------------------------------------------------------------------------
// Elements
protected :
bool _originalMC ; /**< selects wether the algorithm will use the enhanced topologically controlled lookup table or the original MarchingCubes */
bool _ext_data ; /**< selects wether to allocate data or use data from another class */
int _size_x ; /**< width of the grid */
int _size_y ; /**< depth of the grid */
int _size_z ; /**< height of the grid */
real *_data ; /**< implicit function values sampled on the grid */
real _cellsizex;
real _cellsizey;
real _cellsizez; /* size of eache cell*/
real _bx;
real _by;
real _bz; /* begin of the grid*/
real _ex;
real _ey;
real _ez; /* end of the grid*/
int *_x_verts ; /**< pre-computed vertex indices on the lower horizontal edge of each cube */
int *_y_verts ; /**< pre-computed vertex indices on the lower longitudinal edge of each cube */
int *_z_verts ; /**< pre-computed vertex indices on the lower vertical edge of each cube */
int _nverts ; /**< number of allocated vertices in the vertex buffer */
int _ntrigs ; /**< number of allocated triangles in the triangle buffer */
int _Nverts ; /**< size of the vertex buffer */
int _Ntrigs ; /**< size of the triangle buffer */
Vertex *_vertices ; /**< vertex buffer */
Triangle *_triangles ; /**< triangle buffer */
int _i ; /**< abscisse of the active cube */
int _j ; /**< height of the active cube */
int _k ; /**< ordinate of the active cube */
real _cube[8] ; /**< values of the implicit function on the active cube */
uchar _lut_entry ; /**< cube sign representation in [0..255] */
uchar _case ; /**< case of the active cube in [0..15] */
uchar _config ; /**< configuration of the active cube */
uchar _subconfig ; /**< subconfiguration of the active cube */
};
//_____________________________________________________________________________
#endif // _MARCHINGCUBES_H_
|
9eb0cb2a74f874213850b67bc3f15cacdfb70a9a
|
25f69259c6190a6ca57942dbdb95e333c8b32da0
|
/sandbox/hello.cpp
|
8210c5c7a5559a09de11e6472f38bed9659e4d5b
|
[] |
no_license
|
raymonraymon/code
|
649ec81640433b957e07be8f5884752fe5a87d18
|
51a4b0f8f135847bdd4db83aa9d501f185fe871d
|
refs/heads/master
| 2021-01-17T14:02:31.255136
| 2017-07-04T10:29:37
| 2017-07-04T10:29:37
| 61,924,859
| 0
| 0
| null | 2017-07-04T10:29:37
| 2016-06-25T03:19:31
|
C++
|
UTF-8
|
C++
| false
| false
| 358
|
cpp
|
hello.cpp
|
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
printf("Hello world!\n"); // 教科书的写法
puts("Hello world!\n"); // 我最喜欢的
puts("Hello" " " "world!"); // 拼接字符串
cout << "Hello world!" << endl; // C++风格的教科书写法
return 0;
}
|
101fce979ff705d98243a8b2b56245adb0d36000
|
1be60aa8bec3ced9a169be6c87f6812cb8443a7a
|
/2015/d15.cpp
|
2cd755972861925724af71611e4ddfbaaf845a59
|
[] |
no_license
|
tamaskenez/advent-of-code
|
4f863c29ee2bb12c927f0d90b9987b198c30aed1
|
6c1315f94c13b67d41c141256519841d59c67480
|
refs/heads/master
| 2022-09-08T18:15:03.742902
| 2022-09-04T09:20:30
| 2022-09-04T09:20:30
| 231,270,108
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,426
|
cpp
|
d15.cpp
|
#include "common.h"
using i64 = int64_t;
using VI64 = vector<i64>;
const vector<VI64> caps = {VI64{3, 0, 0, -3, 2}, VI64{-3, 3, 0, 0, 9}, VI64{-1, 0, 4, 0, 1},
VI64{0, 0, -2, 2, 8}};
const VS ingrs = {"Sugar", "Sprinkles", "Candy", "Chocolate"};
VI64 operator*(i64 x, const VI64& l)
{
VI64 result = l;
for (auto& i : result) {
i *= x;
}
return result;
}
VI64 operator+(const VI64& x, const VI64& y)
{
auto N = ~x;
assert(~x == ~y);
VI64 result(N);
FOR (i, 0, < N) {
result[i] = x[i] + y[i];
}
return result;
}
int main()
{
FOR (partn, 0, <= 1) {
RunningStat<i64> best;
FOR (i, 0, <= 100) {
FOR (j, 0, <= 100 - i) {
FOR (k, 0, <= 100 - i - j) {
auto l = 100 - i - j - k;
auto vs = i * caps[0] + j * caps[1] + k * caps[2] + l * caps[3];
auto total =
max(0LL, vs[0]) * max(0LL, vs[1]) * max(0LL, vs[2]) * max(0LL, vs[3]);
if (partn == 1) {
if (vs[4] != 500) {
continue;
}
}
best.add(total);
}
}
}
printf("part%d %s\n", partn + 1, to_string(*best.upper).c_str());
}
// print_result("part2", ...);
return 0;
}
// 1256
|
8289e7bb6f1e7a97607750edf4c1b76b838de9fb
|
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
|
/generated/src/aws-cpp-sdk-iotsitewise/include/aws/iotsitewise/model/TumblingWindow.h
|
5a6387f54a452bf2b764a8e1209f2c69204ec020
|
[
"Apache-2.0",
"MIT",
"JSON"
] |
permissive
|
aws/aws-sdk-cpp
|
aff116ddf9ca2b41e45c47dba1c2b7754935c585
|
9a7606a6c98e13c759032c2e920c7c64a6a35264
|
refs/heads/main
| 2023-08-25T11:16:55.982089
| 2023-08-24T18:14:53
| 2023-08-24T18:14:53
| 35,440,404
| 1,681
| 1,133
|
Apache-2.0
| 2023-09-12T15:59:33
| 2015-05-11T17:57:32
| null |
UTF-8
|
C++
| false
| false
| 26,227
|
h
|
TumblingWindow.h
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/iotsitewise/IoTSiteWise_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace IoTSiteWise
{
namespace Model
{
/**
* <p>Contains a tumbling window, which is a repeating fixed-sized,
* non-overlapping, and contiguous time window. You can use this window in metrics
* to aggregate data from properties and other assets.</p> <p>You can use
* <code>m</code>, <code>h</code>, <code>d</code>, and <code>w</code> when you
* specify an interval or offset. Note that <code>m</code> represents minutes,
* <code>h</code> represents hours, <code>d</code> represents days, and
* <code>w</code> represents weeks. You can also use <code>s</code> to represent
* seconds in <code>offset</code>.</p> <p>The <code>interval</code> and
* <code>offset</code> parameters support the <a
* href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601 format</a>. For example,
* <code>PT5S</code> represents 5 seconds, <code>PT5M</code> represents 5 minutes,
* and <code>PT5H</code> represents 5 hours.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/iotsitewise-2019-12-02/TumblingWindow">AWS
* API Reference</a></p>
*/
class TumblingWindow
{
public:
AWS_IOTSITEWISE_API TumblingWindow();
AWS_IOTSITEWISE_API TumblingWindow(Aws::Utils::Json::JsonView jsonValue);
AWS_IOTSITEWISE_API TumblingWindow& operator=(Aws::Utils::Json::JsonView jsonValue);
AWS_IOTSITEWISE_API Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The time interval for the tumbling window. The interval time must be between
* 1 minute and 1 week.</p> <p>IoT SiteWise computes the <code>1w</code> interval
* the end of Sunday at midnight each week (UTC), the <code>1d</code> interval at
* the end of each day at midnight (UTC), the <code>1h</code> interval at the end
* of each hour, and so on. </p> <p>When IoT SiteWise aggregates data points for
* metric computations, the start of each interval is exclusive and the end of each
* interval is inclusive. IoT SiteWise places the computed data point at the end of
* the interval.</p>
*/
inline const Aws::String& GetInterval() const{ return m_interval; }
/**
* <p>The time interval for the tumbling window. The interval time must be between
* 1 minute and 1 week.</p> <p>IoT SiteWise computes the <code>1w</code> interval
* the end of Sunday at midnight each week (UTC), the <code>1d</code> interval at
* the end of each day at midnight (UTC), the <code>1h</code> interval at the end
* of each hour, and so on. </p> <p>When IoT SiteWise aggregates data points for
* metric computations, the start of each interval is exclusive and the end of each
* interval is inclusive. IoT SiteWise places the computed data point at the end of
* the interval.</p>
*/
inline bool IntervalHasBeenSet() const { return m_intervalHasBeenSet; }
/**
* <p>The time interval for the tumbling window. The interval time must be between
* 1 minute and 1 week.</p> <p>IoT SiteWise computes the <code>1w</code> interval
* the end of Sunday at midnight each week (UTC), the <code>1d</code> interval at
* the end of each day at midnight (UTC), the <code>1h</code> interval at the end
* of each hour, and so on. </p> <p>When IoT SiteWise aggregates data points for
* metric computations, the start of each interval is exclusive and the end of each
* interval is inclusive. IoT SiteWise places the computed data point at the end of
* the interval.</p>
*/
inline void SetInterval(const Aws::String& value) { m_intervalHasBeenSet = true; m_interval = value; }
/**
* <p>The time interval for the tumbling window. The interval time must be between
* 1 minute and 1 week.</p> <p>IoT SiteWise computes the <code>1w</code> interval
* the end of Sunday at midnight each week (UTC), the <code>1d</code> interval at
* the end of each day at midnight (UTC), the <code>1h</code> interval at the end
* of each hour, and so on. </p> <p>When IoT SiteWise aggregates data points for
* metric computations, the start of each interval is exclusive and the end of each
* interval is inclusive. IoT SiteWise places the computed data point at the end of
* the interval.</p>
*/
inline void SetInterval(Aws::String&& value) { m_intervalHasBeenSet = true; m_interval = std::move(value); }
/**
* <p>The time interval for the tumbling window. The interval time must be between
* 1 minute and 1 week.</p> <p>IoT SiteWise computes the <code>1w</code> interval
* the end of Sunday at midnight each week (UTC), the <code>1d</code> interval at
* the end of each day at midnight (UTC), the <code>1h</code> interval at the end
* of each hour, and so on. </p> <p>When IoT SiteWise aggregates data points for
* metric computations, the start of each interval is exclusive and the end of each
* interval is inclusive. IoT SiteWise places the computed data point at the end of
* the interval.</p>
*/
inline void SetInterval(const char* value) { m_intervalHasBeenSet = true; m_interval.assign(value); }
/**
* <p>The time interval for the tumbling window. The interval time must be between
* 1 minute and 1 week.</p> <p>IoT SiteWise computes the <code>1w</code> interval
* the end of Sunday at midnight each week (UTC), the <code>1d</code> interval at
* the end of each day at midnight (UTC), the <code>1h</code> interval at the end
* of each hour, and so on. </p> <p>When IoT SiteWise aggregates data points for
* metric computations, the start of each interval is exclusive and the end of each
* interval is inclusive. IoT SiteWise places the computed data point at the end of
* the interval.</p>
*/
inline TumblingWindow& WithInterval(const Aws::String& value) { SetInterval(value); return *this;}
/**
* <p>The time interval for the tumbling window. The interval time must be between
* 1 minute and 1 week.</p> <p>IoT SiteWise computes the <code>1w</code> interval
* the end of Sunday at midnight each week (UTC), the <code>1d</code> interval at
* the end of each day at midnight (UTC), the <code>1h</code> interval at the end
* of each hour, and so on. </p> <p>When IoT SiteWise aggregates data points for
* metric computations, the start of each interval is exclusive and the end of each
* interval is inclusive. IoT SiteWise places the computed data point at the end of
* the interval.</p>
*/
inline TumblingWindow& WithInterval(Aws::String&& value) { SetInterval(std::move(value)); return *this;}
/**
* <p>The time interval for the tumbling window. The interval time must be between
* 1 minute and 1 week.</p> <p>IoT SiteWise computes the <code>1w</code> interval
* the end of Sunday at midnight each week (UTC), the <code>1d</code> interval at
* the end of each day at midnight (UTC), the <code>1h</code> interval at the end
* of each hour, and so on. </p> <p>When IoT SiteWise aggregates data points for
* metric computations, the start of each interval is exclusive and the end of each
* interval is inclusive. IoT SiteWise places the computed data point at the end of
* the interval.</p>
*/
inline TumblingWindow& WithInterval(const char* value) { SetInterval(value); return *this;}
/**
* <p>The offset for the tumbling window. The <code>offset</code> parameter accepts
* the following:</p> <ul> <li> <p>The offset time.</p> <p>For example, if you
* specify <code>18h</code> for <code>offset</code> and <code>1d</code> for
* <code>interval</code>, IoT SiteWise aggregates data in one of the following
* ways:</p> <ul> <li> <p>If you create the metric before or at 6 PM (UTC), you get
* the first aggregation result at 6 PM (UTC) on the day when you create the
* metric.</p> </li> <li> <p>If you create the metric after 6 PM (UTC), you get the
* first aggregation result at 6 PM (UTC) the next day.</p> </li> </ul> </li> <li>
* <p>The ISO 8601 format.</p> <p>For example, if you specify <code>PT18H</code>
* for <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT
* SiteWise aggregates data in one of the following ways:</p> <ul> <li> <p>If you
* create the metric before or at 6 PM (UTC), you get the first aggregation result
* at 6 PM (UTC) on the day when you create the metric.</p> </li> <li> <p>If you
* create the metric after 6 PM (UTC), you get the first aggregation result at 6 PM
* (UTC) the next day.</p> </li> </ul> </li> <li> <p>The 24-hour clock.</p> <p>For
* example, if you specify <code>00:03:00</code> for <code>offset</code>,
* <code>5m</code> for <code>interval</code>, and you create the metric at 2 PM
* (UTC), you get the first aggregation result at 2:03 PM (UTC). You get the second
* aggregation result at 2:08 PM (UTC). </p> </li> <li> <p>The offset time
* zone.</p> <p>For example, if you specify <code>2021-07-23T18:00-08</code> for
* <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT SiteWise
* aggregates data in one of the following ways:</p> <ul> <li> <p>If you create the
* metric before or at 6 PM (PST), you get the first aggregation result at 6 PM
* (PST) on the day when you create the metric.</p> </li> <li> <p>If you create the
* metric after 6 PM (PST), you get the first aggregation result at 6 PM (PST) the
* next day.</p> </li> </ul> </li> </ul>
*/
inline const Aws::String& GetOffset() const{ return m_offset; }
/**
* <p>The offset for the tumbling window. The <code>offset</code> parameter accepts
* the following:</p> <ul> <li> <p>The offset time.</p> <p>For example, if you
* specify <code>18h</code> for <code>offset</code> and <code>1d</code> for
* <code>interval</code>, IoT SiteWise aggregates data in one of the following
* ways:</p> <ul> <li> <p>If you create the metric before or at 6 PM (UTC), you get
* the first aggregation result at 6 PM (UTC) on the day when you create the
* metric.</p> </li> <li> <p>If you create the metric after 6 PM (UTC), you get the
* first aggregation result at 6 PM (UTC) the next day.</p> </li> </ul> </li> <li>
* <p>The ISO 8601 format.</p> <p>For example, if you specify <code>PT18H</code>
* for <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT
* SiteWise aggregates data in one of the following ways:</p> <ul> <li> <p>If you
* create the metric before or at 6 PM (UTC), you get the first aggregation result
* at 6 PM (UTC) on the day when you create the metric.</p> </li> <li> <p>If you
* create the metric after 6 PM (UTC), you get the first aggregation result at 6 PM
* (UTC) the next day.</p> </li> </ul> </li> <li> <p>The 24-hour clock.</p> <p>For
* example, if you specify <code>00:03:00</code> for <code>offset</code>,
* <code>5m</code> for <code>interval</code>, and you create the metric at 2 PM
* (UTC), you get the first aggregation result at 2:03 PM (UTC). You get the second
* aggregation result at 2:08 PM (UTC). </p> </li> <li> <p>The offset time
* zone.</p> <p>For example, if you specify <code>2021-07-23T18:00-08</code> for
* <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT SiteWise
* aggregates data in one of the following ways:</p> <ul> <li> <p>If you create the
* metric before or at 6 PM (PST), you get the first aggregation result at 6 PM
* (PST) on the day when you create the metric.</p> </li> <li> <p>If you create the
* metric after 6 PM (PST), you get the first aggregation result at 6 PM (PST) the
* next day.</p> </li> </ul> </li> </ul>
*/
inline bool OffsetHasBeenSet() const { return m_offsetHasBeenSet; }
/**
* <p>The offset for the tumbling window. The <code>offset</code> parameter accepts
* the following:</p> <ul> <li> <p>The offset time.</p> <p>For example, if you
* specify <code>18h</code> for <code>offset</code> and <code>1d</code> for
* <code>interval</code>, IoT SiteWise aggregates data in one of the following
* ways:</p> <ul> <li> <p>If you create the metric before or at 6 PM (UTC), you get
* the first aggregation result at 6 PM (UTC) on the day when you create the
* metric.</p> </li> <li> <p>If you create the metric after 6 PM (UTC), you get the
* first aggregation result at 6 PM (UTC) the next day.</p> </li> </ul> </li> <li>
* <p>The ISO 8601 format.</p> <p>For example, if you specify <code>PT18H</code>
* for <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT
* SiteWise aggregates data in one of the following ways:</p> <ul> <li> <p>If you
* create the metric before or at 6 PM (UTC), you get the first aggregation result
* at 6 PM (UTC) on the day when you create the metric.</p> </li> <li> <p>If you
* create the metric after 6 PM (UTC), you get the first aggregation result at 6 PM
* (UTC) the next day.</p> </li> </ul> </li> <li> <p>The 24-hour clock.</p> <p>For
* example, if you specify <code>00:03:00</code> for <code>offset</code>,
* <code>5m</code> for <code>interval</code>, and you create the metric at 2 PM
* (UTC), you get the first aggregation result at 2:03 PM (UTC). You get the second
* aggregation result at 2:08 PM (UTC). </p> </li> <li> <p>The offset time
* zone.</p> <p>For example, if you specify <code>2021-07-23T18:00-08</code> for
* <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT SiteWise
* aggregates data in one of the following ways:</p> <ul> <li> <p>If you create the
* metric before or at 6 PM (PST), you get the first aggregation result at 6 PM
* (PST) on the day when you create the metric.</p> </li> <li> <p>If you create the
* metric after 6 PM (PST), you get the first aggregation result at 6 PM (PST) the
* next day.</p> </li> </ul> </li> </ul>
*/
inline void SetOffset(const Aws::String& value) { m_offsetHasBeenSet = true; m_offset = value; }
/**
* <p>The offset for the tumbling window. The <code>offset</code> parameter accepts
* the following:</p> <ul> <li> <p>The offset time.</p> <p>For example, if you
* specify <code>18h</code> for <code>offset</code> and <code>1d</code> for
* <code>interval</code>, IoT SiteWise aggregates data in one of the following
* ways:</p> <ul> <li> <p>If you create the metric before or at 6 PM (UTC), you get
* the first aggregation result at 6 PM (UTC) on the day when you create the
* metric.</p> </li> <li> <p>If you create the metric after 6 PM (UTC), you get the
* first aggregation result at 6 PM (UTC) the next day.</p> </li> </ul> </li> <li>
* <p>The ISO 8601 format.</p> <p>For example, if you specify <code>PT18H</code>
* for <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT
* SiteWise aggregates data in one of the following ways:</p> <ul> <li> <p>If you
* create the metric before or at 6 PM (UTC), you get the first aggregation result
* at 6 PM (UTC) on the day when you create the metric.</p> </li> <li> <p>If you
* create the metric after 6 PM (UTC), you get the first aggregation result at 6 PM
* (UTC) the next day.</p> </li> </ul> </li> <li> <p>The 24-hour clock.</p> <p>For
* example, if you specify <code>00:03:00</code> for <code>offset</code>,
* <code>5m</code> for <code>interval</code>, and you create the metric at 2 PM
* (UTC), you get the first aggregation result at 2:03 PM (UTC). You get the second
* aggregation result at 2:08 PM (UTC). </p> </li> <li> <p>The offset time
* zone.</p> <p>For example, if you specify <code>2021-07-23T18:00-08</code> for
* <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT SiteWise
* aggregates data in one of the following ways:</p> <ul> <li> <p>If you create the
* metric before or at 6 PM (PST), you get the first aggregation result at 6 PM
* (PST) on the day when you create the metric.</p> </li> <li> <p>If you create the
* metric after 6 PM (PST), you get the first aggregation result at 6 PM (PST) the
* next day.</p> </li> </ul> </li> </ul>
*/
inline void SetOffset(Aws::String&& value) { m_offsetHasBeenSet = true; m_offset = std::move(value); }
/**
* <p>The offset for the tumbling window. The <code>offset</code> parameter accepts
* the following:</p> <ul> <li> <p>The offset time.</p> <p>For example, if you
* specify <code>18h</code> for <code>offset</code> and <code>1d</code> for
* <code>interval</code>, IoT SiteWise aggregates data in one of the following
* ways:</p> <ul> <li> <p>If you create the metric before or at 6 PM (UTC), you get
* the first aggregation result at 6 PM (UTC) on the day when you create the
* metric.</p> </li> <li> <p>If you create the metric after 6 PM (UTC), you get the
* first aggregation result at 6 PM (UTC) the next day.</p> </li> </ul> </li> <li>
* <p>The ISO 8601 format.</p> <p>For example, if you specify <code>PT18H</code>
* for <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT
* SiteWise aggregates data in one of the following ways:</p> <ul> <li> <p>If you
* create the metric before or at 6 PM (UTC), you get the first aggregation result
* at 6 PM (UTC) on the day when you create the metric.</p> </li> <li> <p>If you
* create the metric after 6 PM (UTC), you get the first aggregation result at 6 PM
* (UTC) the next day.</p> </li> </ul> </li> <li> <p>The 24-hour clock.</p> <p>For
* example, if you specify <code>00:03:00</code> for <code>offset</code>,
* <code>5m</code> for <code>interval</code>, and you create the metric at 2 PM
* (UTC), you get the first aggregation result at 2:03 PM (UTC). You get the second
* aggregation result at 2:08 PM (UTC). </p> </li> <li> <p>The offset time
* zone.</p> <p>For example, if you specify <code>2021-07-23T18:00-08</code> for
* <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT SiteWise
* aggregates data in one of the following ways:</p> <ul> <li> <p>If you create the
* metric before or at 6 PM (PST), you get the first aggregation result at 6 PM
* (PST) on the day when you create the metric.</p> </li> <li> <p>If you create the
* metric after 6 PM (PST), you get the first aggregation result at 6 PM (PST) the
* next day.</p> </li> </ul> </li> </ul>
*/
inline void SetOffset(const char* value) { m_offsetHasBeenSet = true; m_offset.assign(value); }
/**
* <p>The offset for the tumbling window. The <code>offset</code> parameter accepts
* the following:</p> <ul> <li> <p>The offset time.</p> <p>For example, if you
* specify <code>18h</code> for <code>offset</code> and <code>1d</code> for
* <code>interval</code>, IoT SiteWise aggregates data in one of the following
* ways:</p> <ul> <li> <p>If you create the metric before or at 6 PM (UTC), you get
* the first aggregation result at 6 PM (UTC) on the day when you create the
* metric.</p> </li> <li> <p>If you create the metric after 6 PM (UTC), you get the
* first aggregation result at 6 PM (UTC) the next day.</p> </li> </ul> </li> <li>
* <p>The ISO 8601 format.</p> <p>For example, if you specify <code>PT18H</code>
* for <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT
* SiteWise aggregates data in one of the following ways:</p> <ul> <li> <p>If you
* create the metric before or at 6 PM (UTC), you get the first aggregation result
* at 6 PM (UTC) on the day when you create the metric.</p> </li> <li> <p>If you
* create the metric after 6 PM (UTC), you get the first aggregation result at 6 PM
* (UTC) the next day.</p> </li> </ul> </li> <li> <p>The 24-hour clock.</p> <p>For
* example, if you specify <code>00:03:00</code> for <code>offset</code>,
* <code>5m</code> for <code>interval</code>, and you create the metric at 2 PM
* (UTC), you get the first aggregation result at 2:03 PM (UTC). You get the second
* aggregation result at 2:08 PM (UTC). </p> </li> <li> <p>The offset time
* zone.</p> <p>For example, if you specify <code>2021-07-23T18:00-08</code> for
* <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT SiteWise
* aggregates data in one of the following ways:</p> <ul> <li> <p>If you create the
* metric before or at 6 PM (PST), you get the first aggregation result at 6 PM
* (PST) on the day when you create the metric.</p> </li> <li> <p>If you create the
* metric after 6 PM (PST), you get the first aggregation result at 6 PM (PST) the
* next day.</p> </li> </ul> </li> </ul>
*/
inline TumblingWindow& WithOffset(const Aws::String& value) { SetOffset(value); return *this;}
/**
* <p>The offset for the tumbling window. The <code>offset</code> parameter accepts
* the following:</p> <ul> <li> <p>The offset time.</p> <p>For example, if you
* specify <code>18h</code> for <code>offset</code> and <code>1d</code> for
* <code>interval</code>, IoT SiteWise aggregates data in one of the following
* ways:</p> <ul> <li> <p>If you create the metric before or at 6 PM (UTC), you get
* the first aggregation result at 6 PM (UTC) on the day when you create the
* metric.</p> </li> <li> <p>If you create the metric after 6 PM (UTC), you get the
* first aggregation result at 6 PM (UTC) the next day.</p> </li> </ul> </li> <li>
* <p>The ISO 8601 format.</p> <p>For example, if you specify <code>PT18H</code>
* for <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT
* SiteWise aggregates data in one of the following ways:</p> <ul> <li> <p>If you
* create the metric before or at 6 PM (UTC), you get the first aggregation result
* at 6 PM (UTC) on the day when you create the metric.</p> </li> <li> <p>If you
* create the metric after 6 PM (UTC), you get the first aggregation result at 6 PM
* (UTC) the next day.</p> </li> </ul> </li> <li> <p>The 24-hour clock.</p> <p>For
* example, if you specify <code>00:03:00</code> for <code>offset</code>,
* <code>5m</code> for <code>interval</code>, and you create the metric at 2 PM
* (UTC), you get the first aggregation result at 2:03 PM (UTC). You get the second
* aggregation result at 2:08 PM (UTC). </p> </li> <li> <p>The offset time
* zone.</p> <p>For example, if you specify <code>2021-07-23T18:00-08</code> for
* <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT SiteWise
* aggregates data in one of the following ways:</p> <ul> <li> <p>If you create the
* metric before or at 6 PM (PST), you get the first aggregation result at 6 PM
* (PST) on the day when you create the metric.</p> </li> <li> <p>If you create the
* metric after 6 PM (PST), you get the first aggregation result at 6 PM (PST) the
* next day.</p> </li> </ul> </li> </ul>
*/
inline TumblingWindow& WithOffset(Aws::String&& value) { SetOffset(std::move(value)); return *this;}
/**
* <p>The offset for the tumbling window. The <code>offset</code> parameter accepts
* the following:</p> <ul> <li> <p>The offset time.</p> <p>For example, if you
* specify <code>18h</code> for <code>offset</code> and <code>1d</code> for
* <code>interval</code>, IoT SiteWise aggregates data in one of the following
* ways:</p> <ul> <li> <p>If you create the metric before or at 6 PM (UTC), you get
* the first aggregation result at 6 PM (UTC) on the day when you create the
* metric.</p> </li> <li> <p>If you create the metric after 6 PM (UTC), you get the
* first aggregation result at 6 PM (UTC) the next day.</p> </li> </ul> </li> <li>
* <p>The ISO 8601 format.</p> <p>For example, if you specify <code>PT18H</code>
* for <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT
* SiteWise aggregates data in one of the following ways:</p> <ul> <li> <p>If you
* create the metric before or at 6 PM (UTC), you get the first aggregation result
* at 6 PM (UTC) on the day when you create the metric.</p> </li> <li> <p>If you
* create the metric after 6 PM (UTC), you get the first aggregation result at 6 PM
* (UTC) the next day.</p> </li> </ul> </li> <li> <p>The 24-hour clock.</p> <p>For
* example, if you specify <code>00:03:00</code> for <code>offset</code>,
* <code>5m</code> for <code>interval</code>, and you create the metric at 2 PM
* (UTC), you get the first aggregation result at 2:03 PM (UTC). You get the second
* aggregation result at 2:08 PM (UTC). </p> </li> <li> <p>The offset time
* zone.</p> <p>For example, if you specify <code>2021-07-23T18:00-08</code> for
* <code>offset</code> and <code>1d</code> for <code>interval</code>, IoT SiteWise
* aggregates data in one of the following ways:</p> <ul> <li> <p>If you create the
* metric before or at 6 PM (PST), you get the first aggregation result at 6 PM
* (PST) on the day when you create the metric.</p> </li> <li> <p>If you create the
* metric after 6 PM (PST), you get the first aggregation result at 6 PM (PST) the
* next day.</p> </li> </ul> </li> </ul>
*/
inline TumblingWindow& WithOffset(const char* value) { SetOffset(value); return *this;}
private:
Aws::String m_interval;
bool m_intervalHasBeenSet = false;
Aws::String m_offset;
bool m_offsetHasBeenSet = false;
};
} // namespace Model
} // namespace IoTSiteWise
} // namespace Aws
|
d903c9f053626a0160c7fd36626b272c7b71af7c
|
01d4359173c703e217370f3c063e13d002110fa1
|
/BFS.h
|
b695c5aeca82f61a5d5898d9769111871e7c65d4
|
[] |
no_license
|
amitkoz/Milestone-2
|
c704cf799d1564c567639181269bbacbf5847bc0
|
c02132f3907a7f4a40924569923021019d2ec264
|
refs/heads/master
| 2022-04-03T07:44:46.227302
| 2020-01-26T16:33:00
| 2020-01-26T16:33:00
| 235,830,361
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 271
|
h
|
BFS.h
|
#ifndef EX4_BFS_H
#define EX4_BFS_H
#include "Searcher.h"
#include "MatrixSearchable.h"
#include <bits/stdc++.h>
using namespace std;
class BFS: public Searcher {
public:
vector<this_state *> search(Searchable<this_state> *searchable) override;
};
#endif //EX4_BFS_H
|
64096c79ed2ba8e2607fbb8894088c19e3388698
|
f65ec23ed0dd258c04808d52e19ee45e7d695d73
|
/알고리즘/7193.cpp
|
e552cc0241666bc47de8e3516736d4f049b62ae1
|
[] |
no_license
|
mznx13579/CODESTUDY
|
04df5e6d1364b334bb848477cce63662ba27b644
|
7ba8bab4e923896c4379cb5da541148906204988
|
refs/heads/master
| 2021-07-25T17:53:15.694048
| 2020-09-05T08:31:51
| 2020-09-05T08:31:51
| 184,990,915
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 981
|
cpp
|
7193.cpp
|
#include<iostream>
using namespace std;
int iy[9];
int ky[9];
bool checkArr[9];
int win;
void permutation(int idx, int ky_score, int iy_score){
if(idx==9){
if(ky_score>iy_score) {
win++;
return;
}
return;
}
for(int i=0; i<9; i++){
if(checkArr[i]==false){
checkArr[i]=true;
if(ky[idx]>iy[i]) permutation(idx+1, ky_score+(ky[idx]+iy[i]), iy_score);
else permutation(idx+1, ky_score, iy_score+(ky[idx]+iy[i]));
checkArr[i]=false;
}
}
}
int main(){
int T;
cin>>T;
for(int t=1; t<=T; t++){
cout<<'#'<<t<<' ';
win=0;
int card[19]={0};
for(int i=0; i<9; i++){
cin>>ky[i];
card[ky[i]]=1;
}
int k=0;
for(int i=1; i<=18; i++){
if(card[i]==0) {iy[k++]=i;}
}
permutation(0,0,0);
cout<<win<<' '<<362880-win<<'\n';
}
return 0;
}
|
31f4db85f70823576899dedc134dca71f3451267
|
a923165a84ee40771f8d1bde425290432a73a4d2
|
/Tests/TestWindows/Main.cpp
|
82f59e18b5a279974fe9410676282155e2bc1e90
|
[] |
no_license
|
SimoHayha/Engine
|
5ba108cdae4d5303f3e740a5823f112d82ff759c
|
2660a6fcef7e9a808e8d313712df035d3762f5bf
|
refs/heads/master
| 2020-12-30T09:51:37.824399
| 2018-10-02T20:08:28
| 2018-10-02T20:08:28
| 150,993,046
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 264
|
cpp
|
Main.cpp
|
#include <iostream>
#include <Engine/Engine.hpp>
using namespace Ngine;
int main(int ac, char** av)
{
auto ngine = std::make_unique<Engine>();
int32_t exitCode = ngine->Run();
std::cout << "Press enter to continue...";
std::cin.get();
return exitCode;
}
|
5b91577bfab4f48b477a6db5b7e13d74c2332566
|
752ddaca71f6729c7ea8d852e77e789591b8315b
|
/AdvancedLevel/1058.cpp
|
9c34ae162c02e09b161a05e60974312f397c0248
|
[] |
no_license
|
Edith-vis/PAT
|
79b5f7aca10693a432525704b90f912999e4d4ad
|
4ebb8eb01c6e5d6829c854a809f1989ced7b4d02
|
refs/heads/master
| 2022-02-09T06:34:14.138081
| 2019-07-31T09:10:46
| 2019-07-31T09:10:46
| 172,714,092
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 380
|
cpp
|
1058.cpp
|
#include <iostream>
using namespace std;
int main() {
freopen("D:/in.txt", "r", stdin);
long long int a, b, c, d, e, f;
scanf("%lld.%lld.%lld %lld.%lld.%lld", &a, &b, &c, &d, &e, &f);
long long int num = (a+d)*17*29 + (b+e)*29 + (c+f);
long long int g = num / (17*29);
num = num % (17*29);
printf("%lld.%lld.%lld", g, num/29, num%29);
return 0;
}
|
1a16f92e81006b180581b01e886a47ebec41f936
|
9a955648aa0bedb9f1103abaf302979b5b61e87c
|
/basic/tree/binomial_tree.cpp
|
9f794dac06849852480a6437ff3c529033de866c
|
[
"Apache-2.0"
] |
permissive
|
sanjosh/smallprogs
|
363641b0d41d95550b977d6dead3ed74f1fd62be
|
8acf7a357080b9154b55565be7c7667db0d4049b
|
refs/heads/master
| 2021-12-23T21:54:48.619529
| 2021-11-01T07:25:33
| 2021-11-01T07:25:33
| 25,510,383
| 7
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 359
|
cpp
|
binomial_tree.cpp
|
/*
http://stackoverflow.com/questions/13849381/disjoint-sets-data-structures-and-binomial-trees?rq=1
TODO
Has subtrees of order 1, 2, 4, 8 - with a root - hence binomial tree of order k has 2^k nodes and (k/d) nodes at depth d
to merge 2 binomial trees of order k, attach one as leftchild of root of other
http://en.wikipedia.org/wiki/Binomial_heap
*/
|
882063acd20f93cd5911911e14fb1dd0bbdc3838
|
57b0279f10421e713ed1a07fbd6a65ea71bbfd0f
|
/src/Simulator/glSimulation.cpp
|
77ec1f23e6668b1009594757364aad1cb4d1c011
|
[] |
no_license
|
mikoval/GraphicsProject
|
97d37c25103c25f140138b022c188866c3cff304
|
6a28f0fc4f16c9670c9ed057ca790681b007d77c
|
refs/heads/master
| 2021-07-16T21:55:18.544692
| 2020-06-30T01:53:47
| 2020-06-30T01:53:47
| 180,271,839
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,358
|
cpp
|
glSimulation.cpp
|
#include <Simulator/glSimulation.h>
#include <Core/glContextUtil.h>
#include <Controls/Controls.h>
#include <Core/SceneLoader.h>
#include <Core/Base.h>
#include <Cameras/OrbitalCamera.h>
#include <Controls/CameraInputManager.h>
#include <Utils/FBOUtils.h>
#include <TexturePrograms/glTextureDisplayProgram.h>
#include <TexturePrograms/glTextureBlurProgram.h>
const double maxFPS = 60.0;
const double maxPeriod = 1.0 / maxFPS;
static FBO fbo;
static FBO fbo2;
glTextureDisplayProgram *textureDisplayer;
glTextureBlurProgram *textureBlurrer;
static inline void SwapBuffers(FBO a, FBO b){
FBO tmp = a;
a = b;
b = tmp;
}
glSimulation::glSimulation() {
InitGLContext();
initMaterials();
glClearColor(0.0, 0.0, 0.0, 1.0);
}
void glSimulation::simulate() {
// Enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
fbo = GenerateFBO(WIDTH, HEIGHT);
fbo2 = GenerateFBO(WIDTH, HEIGHT);
textureDisplayer = new glTextureDisplayProgram();
textureBlurrer = new glTextureBlurProgram();
cout << "error: " << glGetError() << endl;
double lastTime = 0.0;
int framecount = 0;
double startTime = glfwGetTime();
while (glRunning())
{
double time = glfwGetTime();
deltaTime = time - lastTime;
if(time-startTime > 5 ){
cout << "FPS: " << framecount << endl;
startTime = time;
framecount = 0;
}
if( deltaTime >= maxPeriod ) {
framecount++;
lastTime = time;
inputManager->processInput();
draw();
Display();
Poll();
}
}
}
void glSimulation::updateShadows(){
glCullFace(GL_FRONT);
for(int i = 0; i < directionalLights.size(); i++){
directionalLights[i]->updateShadows();
for(int i = 0; i < objects.size(); i++){
objects[i]->drawShadow();
}
}
glCullFace(GL_BACK);
}
void glSimulation::drawImage(){
updateShadows();
glViewport(0, 0, WIDTH, HEIGHT);
glBindFramebuffer(GL_FRAMEBUFFER, fbo.fbo);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderer.setProj(camera->projection());
renderer.setView(camera->view());
for(int i = 0; i < objects.size(); i++){
objects[i]->draw();
}
for(int i = 0; i < pointLights.size(); i++){
pointLights[i]->draw();
}
}
void glSimulation::postProcess(){
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
textureBlurrer->setTexture(&fbo.texture);
textureBlurrer->draw();
SwapBuffers(fbo, fbo2);
}
void glSimulation::display(){
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
textureDisplayer->setTexture(&fbo.texture);
textureDisplayer->draw();
}
void glSimulation::draw(){
drawImage();
postProcess();
display();
}
void glSimulation::setInputManager(InputManager *im) {
inputManager = im;
BindControls(inputManager);
}
void glSimulation::loadScene(string scene){
glLoadScene(scene, this);
CameraInputManager *im = new CameraInputManager(camera);
setInputManager(im);
}
void glSimulation::addLight(DirectionalLight *light) {
directionalLights.push_back(light);
}
void glSimulation::addLight(PointLight *light) {
pointLights.push_back(light);
}
void glSimulation::addObject(glObject *obj) {
objects.push_back(obj);
}
void glSimulation::setCamera(Camera *cam) {
camera = cam;
}
|
02ba3f50b2a0d65de93436ec94214fc27e47836d
|
e9b34a1896d28125035d945f3ac33ce6ef37ed21
|
/Jeopardy/Jeopardy.ino
|
a78f2730fb06ec00ce49886ace1270bda31087d6
|
[] |
no_license
|
sxlijin/Stuy-Jeopardy
|
418d522dbad1dc406f60df6e40f51fa5552ca9ff
|
f39faa9cc9411b025a8ba18277130e4f3f60c00b
|
refs/heads/master
| 2021-01-17T10:38:10.073396
| 2014-06-07T02:54:12
| 2014-06-07T02:54:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,378
|
ino
|
Jeopardy.ino
|
/**
* Stuyvesant Jeopardy System
* @author FRC694
*
* This system is a replica of Jeopardy and works as follows:
* - There are 4 "contestants": 1 parent, 1 teacher, 1 alumnus, 1 team of students
* - The team of students consists of 4 students
* - The moderator asks a question.
* - The contestants buzz to answer the question
* - The buzzer sounds to indicate that the answering period has begun
* - The contestant has 5 seconds to answer the question
* - If the constestant answers correctly, the moderator presses his button, after which any contestant may buzz to answer again.
* - If the contestant answers falsely (or doesn't answer), everyone must wait until his questioning period is up, at which point the buzzer sounds twice and anyone else may answer.
* - If any student answers falsely, the entire team of students is seen as having answered falsely.
* - A contestant has 5 seconds to answer a question after buzzing and being selected to answer.
*/
unsigned int contest_pin[] = {A0,A1,A2,A3,A4,A5,2}; // input lines for buttons; the first 6 (0-5) are analog ins; the last one is a digital
unsigned int moderator_pin = 3; // input line for moderator button (digital input)
unsigned int contest_light[] = {6,7,8,9,10,11,12}; // output lines for lights
// unsigned int moderator_light = 3; // why is this here????
unsigned int claxon_pin = 4; // GPIO pin on the speaker
int i; // iterator
boolean correct_answer = false;
boolean hasAnswered[] = {false, false, false, false};
void setup() {
Serial.begin(9600);
for (i = 0; i < 7; i++) {
pinMode(contest_pin[i], INPUT); // allocate and configure contestant input lines
pinMode(contest_light[i], OUTPUT); // allocate and configure contestant output lines
}
pinMode(moderator_pin, INPUT); // allocate and configure moderator input
//pinMode(moderator_light, OUTPUT);
pinMode(claxon_pin, OUTPUT); // allocate and configure speaker line
i = 0; // initialize iterator
}
void loop() {
Serial.print("loop conditions: ");
Serial.print(isPressed(i)); Serial.print(", ");
Serial.println( (getAnsweredState(i) == false) );
if (isPressed(i) && (getAnsweredState(i) == false)) {
Serial.println("Someone who's still allowed to answer has buzzed in!")
Serial.print("Index (i) is: ");
Serial.println(i);
Serial.print("isPressed returns the following for i: ");
Serial.println(isPressed(i));
Serial.print("not getAnsweredState (i.e. are they allowed to answer?) says: ");
Serial.println(!getAnsweredState(i));
// if contestant who *can* answer questions...
long int start = millis();
lightSet(i, HIGH); //Enable the corresponding light
signalStart(claxon_pin); //Sound the claxon!
correct_answer = false; //Contestant can only get it right if mod says he got it right!
while (millis() - start < 5000) { // 5 seconds for contestant to answer AND
if (isPressed(moderator_pin)) { // for moderator to confirm the answer
correct_answer = true;
break;
}
}
signalEnd(claxon_pin); // signal that the waiting period is over or question has been answered
lightSet(i, LOW); //light off
if (correct_answer)
resetAnswerStates(); // The question's over - everyone can answer again for the next question
else
setAnswerState(i, true); // Prevent contestant [group] from answering this question again.
}
Serial.print("mod pin is ");
Serial.println(isPressed(moderator_pin));
if (isPressed(moderator_pin) && (hasAnswered[] == {true, true, true, true})) {
resetAnswerStates(); // If everyone gets locked out, mod presses his button to reset the system.
}
i = (i + 1) % 7; //Cycles through all 7 contestants.
}
boolean getAnsweredState(int contestant) {
if (contestant > 2)
return hasAnswered[3]; //Students altogether only get one chance at answering
else
return hasAnswered[contestant]; //Everyone else has an individual chance
}
void setAnswerState(int contestant, boolean set) {
if (contestant > 2)
hasAnswered[3] = set; //Students altogether only get one chance at answering
else
hasAnswered[contestant] = set; //Everyone else has an individual chance
}
boolean isPressed(unsigned int i) {
// All the switches are pulled up
if (digitalRead(contest_pin[i])) //-- meaning that it is HIGH by
return false; // So in its default state (unpressed), digitalRead returns HIGH, i.e. TRUE
else
return true; //whereas in its active state (pressed), digitalRead returns LOW, i.e. FALSE
}
void resetAnswerStates() {
hasAnswered[] = {false, false, false, false};
}
void lightSet(unsigned int i, boolean state) {
digitalWrite(contest_light[7 - i - 1], state);
}
void signalStart(unsigned int speaker_line) {
int frequency = 150;
int duration = 200;
tone(speaker_line, frequency);
delay(duration);
noTone(speaker_line);
}
void signalEnd(unsigned int speaker_line) {
//pulses the speaker twice in quick succession
int frequency = 300; // in Hz
int duration = 75; //in msec
tone(speaker_line, frequency);
delay(duration);
noTone(speaker_line);
delay(50);
tone(speaker_line, frequency);
delay(duration);
noTone(speaker_line);
}
|
c0a386650c9f3ae133f6a5852b5a857bd259cc10
|
cc88f042da9e65aad45d9b09cf43de4f8c255849
|
/src/Titulacion.h
|
09c14929834004e5e5f80e34e037b6ba51c1d3b6
|
[] |
no_license
|
frojomar/edi2015-16
|
20370c21cb3cb1fba5414c4cb87879531a1ab327
|
104d19034fcf6845a4506aaddeb1f0e5d144ddb9
|
refs/heads/master
| 2020-03-29T23:40:24.116938
| 2018-09-26T20:08:53
| 2018-09-26T20:08:53
| 150,483,297
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,023
|
h
|
Titulacion.h
|
/*
* Titulacion.h
*
* Created on: 07/03/2016
* Author: FRANCISCO JAVIER ROJO MARTÍN DNI:76042262-F
*/
#ifndef TITULACION_H_
#define TITULACION_H_
#include <cstring>
#include <iostream>
#include "ListaEstudiantes.h"
#include "ColeccionEstudiantes.h"
using namespace std;
class Titulacion {
private:
int codigo;
string nombre;
float nota_corte;
int plazas;
ListaEstudiantes *admitidos;
ListaEstudiantes *espera;
GestorEstudiantes *arbAdm;
GestorEstudiantes *arbEsp;
public:
//***********************************
////*******CONSTRUCTORES.
//***********************************
/*
* PRE: instancia creada,
* POST:inicializa los atributos de la instancia con los valores por defecto
* COMPLEJIDAD O(1)
*/
Titulacion();
/*
* PRE: instancia creada,
* POST:inicializa los atributos de la instancia con los valores de codigo, nombre y plazas indicados por los parametros de entrada
* COMPLEJIDAD O(1)
*/
Titulacion(int _codigo, string _nombre, int _plazas);
/*
* PRE: instancia creada,
* POST:inicializa los atributos de la instancia con los valores de la titulacion t, haciendo una copia del valor de sus atributos
* COMPLEJIDAD O(1)
*/
Titulacion(const Titulacion &t);
//***********************************
////*******METODOS SELECTORES (GET).
//***********************************
/*
* PRE: instancia creada e inicializada
* POST: devuelve el valor almacenado en el atributo Codigo
* COMPLEJIDAD O(1)
*/
int getCodigo()const;
/*
* PRE: instancia creada e inicializada
* POST: devuelve el valor almacenado en el atributo Nota_corte
* COMPLEJIDAD O(1)
*/
float getNota_corte()const;
/*
* PRE: instancia creada e inicializada
* POST: devuelve el valor almacenado en el atributo Nombre
* COMPLEJIDAD O(1)
*/
string getNombre()const;
/*
* PRE: instancia creada e inicializada
* POST: cambia el valor de la nota de corte a nota
* COMPLEJIDAD O(1)
*/
void setNota_Corte(float nota);
//***********************************
////*******OTROS METODOS.
//***********************************
/*
* PRE: instancia creada e inicializada
* POST: nos devuelve si estan las plazas llenas o no de esta titulacion, es decir, si el numero de plazas es igual al de estudiantes admitidos
* COMPLEJIDAD O(1)
*/
bool plazasLlenas();
/*
* PRE: instancia creada e inicializada
* POST: cambia el valor de 'notaCorte' al de la nota del ultimo estudiante admitido
* COMPLEJIDAD O(1)
*/
void actualizarNotaCorte();
/*
* PRE: instancia creada e inicializada, e inicializado
* POST: nos dice si la nota del estudiante dado es mayor que la de corte (si puede entrar en admitidos, por tanto)
* COMPLEJIDAD O(1)
*/
bool cumpleNota(Estudiante *e);
/*
* PRE: instancia creada e inicializada, e inicializado
* POST: inserta al estudiante en la lista de Espera, indicando que no esta admitido ademas
* COMPLEJIDAD O(1)
*/
void insertarEspera(Estudiante *e);
/*
* PRE: instancia creada e inicializada, e inicializado
* POST: inserta al estudiante en la lista de Admitidos, indicando que esta admitido ademas
* COMPLEJIDAD O(1)
*/
void insertarAdmitido(Estudiante *e);
/*
* PRE: instancia creada e inicializada
* POST: nos debuelve el estudiante sobrante, es decir, al de menor nota de la lista de Admitidos
* COMPLEJIDAD O(1)
*/
void obtenerSobrante(Estudiante *&e);
/*
* PRE: instancia creada e inicializada, preincscripcion llevada a cabo, matricula no llevada a cabo
* POST: nos devuelve al estudiante cuyo dni coincide con el dado si bool==true y nos indica si esta admitido en esta titulacion o no
* COMPLEJIDAD O(1)
*/
bool buscarEstudiante(string dni, Estudiante *&e, bool &admitido);
////////////////////////////////////////////////////////////
/*
* PRE: instancia creada e inicializada, preinscripcion llevada a cabo
* POST: copia los estudiantes admitidos al Arbol de Estudiantes admitidos, la lista de admitidos queda vacia
* COMPLEJIDAD O(n)
*/
void Admitidos_a_Arbol();
/*
* PRE: instancia creada e inicializada, preinscripcion llevada a cabo
* POST: copia los estudiantes en espera al Arbol de Estudiantes en espera, la lista de en espera queda vacia
* COMPLEJIDAD O(n)
*/
void Espera_a_Arbol();
/*
* PRE: instancia creada e inicializada, preinscripcion llevada a cabo, matricula llevada a cabo
* POST: nos devuelve todos los estudiantes de la titulacion con apellido que empiece por el apellido dado
* COMPLEJIDAD O(1)
*/
void busquedaxraiz(string apellido);
////////////////////////////////////////////////////////////
/*
* PRE: instancia creada e inicializada
* POST:muestra la info de la titulacion por pantalla (el valor de cada uno de sus atributos, asi como los estudiantes admitidos y en espera)
* COMPLEJIDAD O(1)
*/
void mostrar();
//***********************************
////*******METODOS PARA FASE 03.
//***********************************
/*
* PRE: instancia creada e inicializada, preinscripcion llevada a cabo, matricula llevada a cabo
* POST: imprime la info de la titulacion al fichero vinculado al fsal pasado como parametro
* COMPLEJIDAD O(1)
*/
void InfoAFichero(ofstream &fsal);
/*
* PRE: instancia creada e inicializada, preinscripcion llevada a cabo, matricula llevada a cabo
* POST: nos devuelve bool=true si lo ha encontrado y 'e' es un estudiante valido
* COMPLEJIDAD O(1)
*/
bool buscarAdmitidos(string apellido, string apellido2, string nombre, string dni, Estudiante *&e);
/*
* PRE: instancia creada e inicializada, preinscripcion llevada a cabo, matricula llevada a cabo
* POST: saca de el arbol de espera al estudiante con mayor nota y lo inserta en el de admitidos
* COMPLEJIDAD O(1)
*/
void admitirEstMayorNota();
/*
* PRE: instancia creada e inicializada, preinscripcion llevada a cabo, matricula llevada a cabo
* POST: elimina del arbol de admitidos el puntero al estudiante 'e'
* COMPLEJIDAD O(1)
*/
void eliminarDeAdmitidos(Estudiante *&e);
/*
* PRE: instancia creada e inicializada, preinscripcion llevada a cabo, matricula llevada a cabo
* POST: elimina de el arbol de espera el puntero al estudiante 'e'
* COMPLEJIDAD O(1)
*/
void eliminarDeEspera(Estudiante *&e);
/*
* PRE: instancia creada e inicializada, preinscripcion llevada a cabo, matricula llevada a cabo
* POST: nos muestra la info de la titulacion con los estudiantes admitidos ordenados alfabeticamente
* COMPLEJIDAD O(1)
*/
void mostrar2();
/*
* PRE: instancia creada e inicializada, preinscripcion llevada a cabo, matricula llevada a cabo
* POST: nos devuelve el estudiante raiz de el arbol de admitidos
* COMPLEJIDAD O(1)
*/
bool EstAleatorioAdm(Estudiante *&e);
/*
* PRE: instancia creada e inicializada, preinscripcion llevada a cabo, matricula llevada a cabo
* POST: nos devuelve el estudiante raiz de el arbol de espera
* COMPLEJIDAD O(1)
*/
bool EstAleatorioEsp(Estudiante *&e);
/*
* PRE: instancia creada e inicializada
* POST: elimina la instancia
* COMPLEJIDAD O(1)
*/
~Titulacion();
};
#endif /* TITULACION_H_ */
|
ca17ddbc4098548f4bf0155b1d73e128f5471dc3
|
b39e187e9d47d9fd3470d6f25fdd3a92eb25f11b
|
/source/design/MatrixConverter.cpp
|
08ec50ae39a1576ea492a74b258e8011310ead15
|
[
"MIT"
] |
permissive
|
SlimDX/slimdx
|
b0e22cb26b5da34ad3dd522ced54768b71b3e929
|
284f3ab1ddadc17b4091bfa7c7b9faed8bf0ded8
|
refs/heads/master
| 2022-09-02T19:14:14.879176
| 2022-08-31T03:04:57
| 2022-08-31T03:04:57
| 32,283,841
| 93
| 49
|
MIT
| 2022-08-31T03:04:58
| 2015-03-15T21:01:40
|
C++
|
UTF-8
|
C++
| false
| false
| 6,729
|
cpp
|
MatrixConverter.cpp
|
#include "stdafx.h"
/*
* Copyright (c) 2007-2012 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "../InternalHelpers.h"
#include "../math/Matrix.h"
#include "MatrixConverter.h"
#include "FieldPropertyDescriptor.h"
using namespace System;
using namespace System::Collections;
using namespace System::Drawing;
using namespace System::ComponentModel;
using namespace System::ComponentModel::Design::Serialization;
using namespace System::Globalization;
using namespace System::Reflection;
namespace SlimDX
{
namespace Design
{
MatrixConverter::MatrixConverter()
{
Type^ type = Matrix::typeid;
array<PropertyDescriptor^>^ propArray =
{
gcnew FieldPropertyDescriptor(type->GetField("M11")),
gcnew FieldPropertyDescriptor(type->GetField("M12")),
gcnew FieldPropertyDescriptor(type->GetField("M13")),
gcnew FieldPropertyDescriptor(type->GetField("M14")),
gcnew FieldPropertyDescriptor(type->GetField("M21")),
gcnew FieldPropertyDescriptor(type->GetField("M22")),
gcnew FieldPropertyDescriptor(type->GetField("M23")),
gcnew FieldPropertyDescriptor(type->GetField("M24")),
gcnew FieldPropertyDescriptor(type->GetField("M31")),
gcnew FieldPropertyDescriptor(type->GetField("M32")),
gcnew FieldPropertyDescriptor(type->GetField("M33")),
gcnew FieldPropertyDescriptor(type->GetField("M34")),
gcnew FieldPropertyDescriptor(type->GetField("M41")),
gcnew FieldPropertyDescriptor(type->GetField("M42")),
gcnew FieldPropertyDescriptor(type->GetField("M43")),
gcnew FieldPropertyDescriptor(type->GetField("M44")),
};
m_Properties = gcnew PropertyDescriptorCollection(propArray);
}
bool MatrixConverter::CanConvertTo(ITypeDescriptorContext^ context, Type^ destinationType)
{
if( destinationType == String::typeid )
return true;
else
return ExpandableObjectConverter::CanConvertTo(context, destinationType);
}
bool MatrixConverter::CanConvertFrom(ITypeDescriptorContext^ context, Type^ sourceType)
{
if( sourceType == String::typeid )
return true;
else
return ExpandableObjectConverter::CanConvertFrom(context, sourceType);
}
Object^ MatrixConverter::ConvertTo(ITypeDescriptorContext^ context, CultureInfo^ culture, Object^ value, Type^ destinationType)
{
if( destinationType == nullptr )
throw gcnew ArgumentNullException( "destinationType" );
if( culture == nullptr )
culture = CultureInfo::CurrentCulture;
Matrix^ matrix = dynamic_cast<Matrix^>( value );
if( destinationType == String::typeid && matrix != nullptr )
{
String^ separator = culture->TextInfo->ListSeparator + " ";
TypeConverter^ converter = TypeDescriptor::GetConverter(float::typeid);
array<String^>^ stringArray = gcnew array<String^>( 16 );
for( int i = 0; i < 4; i++ )
{
for( int j = 0; j < 4; j++ )
stringArray[i * 4 + j] = converter->ConvertToString( context, culture, matrix[i, j] );
}
return String::Join( separator, stringArray );
}
return ExpandableObjectConverter::ConvertTo(context, culture, value, destinationType);
}
Object^ MatrixConverter::ConvertFrom(ITypeDescriptorContext^ context, CultureInfo^ culture, Object^ value)
{
if( culture == nullptr )
culture = CultureInfo::CurrentCulture;
String^ string = dynamic_cast<String^>( value );
if( string != nullptr )
{
string = string->Trim();
TypeConverter^ converter = TypeDescriptor::GetConverter(float::typeid);
array<String^>^ stringArray = string->Split( culture->TextInfo->ListSeparator[0] );
if( stringArray->Length != 16 )
throw gcnew ArgumentException("Invalid matrix format.");
Matrix matrix;
for( int i = 0; i < 4; i++ )
{
for( int j = 0; j < 4; j++ )
matrix[i, j] = safe_cast<float>( converter->ConvertFromString( context, culture, stringArray[i * 4 + j] ) );
}
return matrix;
}
return ExpandableObjectConverter::ConvertFrom(context, culture, value);
}
bool MatrixConverter::GetCreateInstanceSupported(ITypeDescriptorContext^ context)
{
SLIMDX_UNREFERENCED_PARAMETER(context);
return true;
}
Object^ MatrixConverter::CreateInstance(ITypeDescriptorContext^ context, IDictionary^ propertyValues)
{
SLIMDX_UNREFERENCED_PARAMETER(context);
if( propertyValues == nullptr )
throw gcnew ArgumentNullException( "propertyValues" );
Matrix matrix;
matrix.M11 = safe_cast<float>( propertyValues["M11"] );
matrix.M12 = safe_cast<float>( propertyValues["M12"] );
matrix.M13 = safe_cast<float>( propertyValues["M13"] );
matrix.M14 = safe_cast<float>( propertyValues["M14"] );
matrix.M21 = safe_cast<float>( propertyValues["M21"] );
matrix.M22 = safe_cast<float>( propertyValues["M22"] );
matrix.M23 = safe_cast<float>( propertyValues["M23"] );
matrix.M24 = safe_cast<float>( propertyValues["M24"] );
matrix.M31 = safe_cast<float>( propertyValues["M31"] );
matrix.M32 = safe_cast<float>( propertyValues["M32"] );
matrix.M33 = safe_cast<float>( propertyValues["M33"] );
matrix.M34 = safe_cast<float>( propertyValues["M34"] );
matrix.M41 = safe_cast<float>( propertyValues["M41"] );
matrix.M42 = safe_cast<float>( propertyValues["M42"] );
matrix.M43 = safe_cast<float>( propertyValues["M43"] );
matrix.M44 = safe_cast<float>( propertyValues["M44"] );
return matrix;
}
bool MatrixConverter::GetPropertiesSupported(ITypeDescriptorContext^)
{
return true;
}
PropertyDescriptorCollection^ MatrixConverter::GetProperties(ITypeDescriptorContext^, Object^, array<Attribute^>^)
{
return m_Properties;
}
}
}
|
f37a35a1ea648c63bba4fba61446779606a08aa5
|
bfcddd7d51dbffbaa97d43c8f9521f90a66bd9a5
|
/Exercise-Function-2.cpp deivina.cpp
|
6ba6ea552a113816a0964de7bbcb7ff370b25e6a
|
[] |
no_license
|
DDWC1603/lab-exercise-chapter-5-deyvenaVisu
|
31514b6442d08f9ec31fb08391d43af4f8ea8f56
|
4dc930039578d8addf1e4801792596b8c0e0cae8
|
refs/heads/master
| 2021-05-12T03:24:37.278326
| 2018-01-16T02:59:43
| 2018-01-16T02:59:43
| 117,615,644
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 280
|
cpp
|
Exercise-Function-2.cpp deivina.cpp
|
//this is an unfinish program
//finish up this program
#include <iostream>
using namespace std;
int sum(int x,int y);
int main ()
{
int result, sum;
char x, y;
x=4;
y=5;
cout<<"x=4"<<endl;
cout<<"y=5"<<endl;
result= x+y;
cout<<"The result is:"<<result<<endl;
}
|
d45634deae0bf2e2d4d07d2a7e766853d65971bd
|
130fc6ecaf5f9e57ea64b08b5b6c287ce432dc1f
|
/Unreal 4/CppCourse/Source/CppCourse/CppCourseGameModeBase.cpp
|
8ab2e9723c0dd5a182c74b3ed576787d26e2a9c7
|
[] |
no_license
|
Xuzon/PortFolio
|
d1dc98f352e6d0459d7739c0a866c6f1a701542d
|
c2f1674bc15930ce0d45143e4d935e3e631fe9c2
|
refs/heads/master
| 2021-01-17T15:05:08.179998
| 2020-05-13T17:26:19
| 2020-05-13T17:26:19
| 53,209,189
| 5
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 221
|
cpp
|
CppCourseGameModeBase.cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "CppCourseGameModeBase.h"
ACppCourseGameModeBase::ACppCourseGameModeBase()
{
DefaultPawnClass = ACppAdventurer::StaticClass();
}
|
bfa5354c946c1ee1fb9b6461d895badcdeb43eaa
|
f01435961bc41fbb8877d775619f38d057f49ee9
|
/src/ncnn_ultraface.cpp
|
ef2c041384b308a52ea298f2f7d9808e8884b27a
|
[] |
no_license
|
nilseuropa/ros_ncnn
|
3a904d339add5fba31b4ac914e7d4d2ff1544130
|
a7e08d3804ae582f0e6bf726a83d5e4c37d87c56
|
refs/heads/master
| 2023-03-22T07:47:29.167285
| 2021-03-14T16:12:25
| 2021-03-14T16:12:25
| 270,976,229
| 63
| 19
| null | 2020-06-11T11:56:20
| 2020-06-09T10:49:17
|
C++
|
UTF-8
|
C++
| false
| false
| 6,504
|
cpp
|
ncnn_ultraface.cpp
|
#include "ros_ncnn/ncnn_utils.h"
#include "ros_ncnn/ncnn_ultraface.h"
#include <iostream>
#define clip(x, y) (x < 0 ? 0 : (x > y ? y : x))
void ncnnUltraFace::init(int input_width, int input_length, float score_threshold_, float iou_threshold_) {
score_threshold = score_threshold_;
iou_threshold = iou_threshold_;
in_w = input_width;
in_h = input_length;
w_h_list = {in_w, in_h};
for (auto size : w_h_list) {
std::vector<float> fm_item;
for (float stride : strides) {
fm_item.push_back(ceil(size / stride));
}
featuremap_size.push_back(fm_item);
}
for (auto size : w_h_list) {
shrinkage_size.push_back(strides);
}
/* generate prior anchors */
for (int index = 0; index < num_featuremap; index++) {
float scale_w = in_w / shrinkage_size[0][index];
float scale_h = in_h / shrinkage_size[1][index];
for (int j = 0; j < featuremap_size[1][index]; j++) {
for (int i = 0; i < featuremap_size[0][index]; i++) {
float x_center = (i + 0.5) / scale_w;
float y_center = (j + 0.5) / scale_h;
for (float k : min_boxes[index]) {
float w = k / in_w;
float h = k / in_h;
priors.push_back({clip(x_center, 1), clip(y_center, 1), clip(w, 1), clip(h, 1)});
}
}
}
}
num_anchors = priors.size();
}
int ncnnUltraFace::detect(const cv::Mat& bgr, std::vector<FaceInfo> &face_list, uint8_t n_threads) {
image_w = bgr.cols;
image_h = bgr.rows;
ncnn::Mat in = ncnn::Mat::from_pixels(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, image_w, image_h);
ncnn::Mat ncnn_img;
ncnn::resize_bilinear(in, ncnn_img, in_w, in_h);
ncnn_img.substract_mean_normalize(mean_vals, norm_vals);
std::vector<FaceInfo> bbox_collection;
ncnn::Extractor ex = neuralnet.create_extractor();
ex.set_num_threads(n_threads);
ex.input("input", ncnn_img);
ncnn::Mat scores;
ncnn::Mat boxes;
ex.extract("scores", scores);
ex.extract("boxes", boxes);
generateBBox(bbox_collection, scores, boxes, score_threshold, num_anchors);
nms(bbox_collection, face_list);
return 0;
}
void ncnnUltraFace::generateBBox(std::vector<FaceInfo> &bbox_collection, ncnn::Mat scores, ncnn::Mat boxes, float score_threshold, int num_anchors) {
for (int i = 0; i < num_anchors; i++) {
if (scores.channel(0)[i * 2 + 1] > score_threshold) {
FaceInfo rects;
float x_center = boxes.channel(0)[i * 4] * center_variance * priors[i][2] + priors[i][0];
float y_center = boxes.channel(0)[i * 4 + 1] * center_variance * priors[i][3] + priors[i][1];
float w = exp(boxes.channel(0)[i * 4 + 2] * size_variance) * priors[i][2];
float h = exp(boxes.channel(0)[i * 4 + 3] * size_variance) * priors[i][3];
rects.x1 = clip(x_center - w / 2.0, 1) * image_w;
rects.y1 = clip(y_center - h / 2.0, 1) * image_h;
rects.x2 = clip(x_center + w / 2.0, 1) * image_w;
rects.y2 = clip(y_center + h / 2.0, 1) * image_h;
rects.score = clip(scores.channel(0)[i * 2 + 1], 1);
bbox_collection.push_back(rects);
}
}
}
void ncnnUltraFace::draw(const cv::Mat& bgr, const std::vector<FaceInfo>& face_info, double dT){
cv::Mat image = bgr.clone();
for (long unsigned int i = 0; i < face_info.size(); i++) {
auto face = face_info[i];
cv::Point pt1(face.x1, face.y1);
cv::Point pt2(face.x2, face.y2);
cv::rectangle(image, pt1, pt2, cv::Scalar(0, 0, 255), 2);
}
cv::putText(image, std::to_string(1/dT)+" Hz", cv::Point(20, 20), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 255, 255));
cv::imshow("ULTRAFACE", image);
cv::waitKey(1);
}
void ncnnUltraFace::nms(std::vector<FaceInfo> &input, std::vector<FaceInfo> &output, int type) {
std::sort(input.begin(), input.end(), [](const FaceInfo &a, const FaceInfo &b) { return a.score > b.score; });
int box_num = input.size();
std::vector<int> merged(box_num, 0);
for (int i = 0; i < box_num; i++) {
if (merged[i])
continue;
std::vector<FaceInfo> buf;
buf.push_back(input[i]);
merged[i] = 1;
float h0 = input[i].y2 - input[i].y1 + 1;
float w0 = input[i].x2 - input[i].x1 + 1;
float area0 = h0 * w0;
for (int j = i + 1; j < box_num; j++) {
if (merged[j])
continue;
float inner_x0 = input[i].x1 > input[j].x1 ? input[i].x1 : input[j].x1;
float inner_y0 = input[i].y1 > input[j].y1 ? input[i].y1 : input[j].y1;
float inner_x1 = input[i].x2 < input[j].x2 ? input[i].x2 : input[j].x2;
float inner_y1 = input[i].y2 < input[j].y2 ? input[i].y2 : input[j].y2;
float inner_h = inner_y1 - inner_y0 + 1;
float inner_w = inner_x1 - inner_x0 + 1;
if (inner_h <= 0 || inner_w <= 0)
continue;
float inner_area = inner_h * inner_w;
float h1 = input[j].y2 - input[j].y1 + 1;
float w1 = input[j].x2 - input[j].x1 + 1;
float area1 = h1 * w1;
float score;
score = inner_area / (area0 + area1 - inner_area);
if (score > iou_threshold) {
merged[j] = 1;
buf.push_back(input[j]);
}
}
switch (type) {
case hard_nms: {
output.push_back(buf[0]);
break;
}
case blending_nms: {
float total = 0;
for (int i = 0; i < buf.size(); i++) {
total += exp(buf[i].score);
}
FaceInfo rects;
memset(&rects, 0, sizeof(rects));
for (int i = 0; i < buf.size(); i++) {
float rate = exp(buf[i].score) / total;
rects.x1 += buf[i].x1 * rate;
rects.y1 += buf[i].y1 * rate;
rects.x2 += buf[i].x2 * rate;
rects.y2 += buf[i].y2 * rate;
rects.score += buf[i].score * rate;
}
output.push_back(rects);
break;
}
default: {
printf("wrong type of nms.");
exit(-1);
}
}
}
}
|
c5092ef68ce766ce8124ae7559b6ae664b92ad0e
|
a851ee43f6acc20b8058f74abb7eb7afa094f553
|
/AHW13_QT_Chats/Server/srvclient.h
|
cf1e06cfa398e7275894743a5dbc1b1d3b30f96d
|
[] |
no_license
|
Kapurin/CPP_code_adv
|
e91ecdc7cbb300c1c6b1271cccc7e702dfb9f494
|
195a1c0577bd0b356a9f76b435dd7bb588984854
|
refs/heads/master
| 2022-11-16T20:42:41.896721
| 2020-06-14T15:43:55
| 2020-06-14T15:43:55
| 253,762,570
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 399
|
h
|
srvclient.h
|
#ifndef SRVCLIENT_H
#define SRVCLIENT_H
#include <QTcpSocket>
#include <QTcpServer>
class Srvclient : public QObject
{
Q_OBJECT
public:
Srvclient(QTcpSocket *client, uint16_t m_numclient);
~Srvclient();
private:
QTcpSocket *m_client = nullptr;
uint16_t m_numclient = 0;
public slots:
void slotReadClient();
void slotClientDisconnected();
};
#endif // SRVCLIENT_H
|
0964b0b6c80db306f8ec11eb207412995c69df61
|
da86d9f9cf875db42fd912e3366cfe9e0aa392c6
|
/2020/solutions/D/VDB-Haskovo/password.cpp
|
dd61b4f65e209f4c829547bb4c16d1b0bf04a5d9
|
[] |
no_license
|
Alaxe/noi2-ranking
|
0c98ea9af9fc3bd22798cab523f38fd75ed97634
|
bb671bacd369b0924a1bfa313acb259f97947d05
|
refs/heads/master
| 2021-01-22T23:33:43.481107
| 2020-02-15T17:33:25
| 2020-02-15T17:33:25
| 85,631,202
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 755
|
cpp
|
password.cpp
|
#include <bits/stdc++.h>
#define endl "\n"
using namespace std;
char s[5005];
char l[26];
struct povtoreniq
{
int Beg, End;
};
povtoreniq p[1000];
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> s;
for(int i=0; i<26; i++)
l[i]='a'+i;
int n = strlen(s), j=0;
for(int i=0; i<n; i++)
{
p[j].Beg=i;
while(s[i]==s[i+1]) i++;
if(i-p[j].Beg+1<3) continue;
p[j].End=i+1;
j++;
}
int r=0;
for(int i=0; i<j; i++)
{
for(int k=p[i].Beg+2; k<p[i].End; k+=3)
{
if(s[k]==l[r]) r++;
if(r>25) r=0;
s[k]=l[r++];
}
}
cout << s << endl;
return 0;
}
|
9c8f48200f484b0e5f652933121a6bec39b2c882
|
0577a46d8d28e1fd8636893bbdd2b18270bb8eb8
|
/chromium/components/autofill_assistant/browser/base_browsertest.cc
|
e31dc32c4a08f8007a713380e0bfe740c6636a6b
|
[
"BSD-3-Clause"
] |
permissive
|
ric2b/Vivaldi-browser
|
388a328b4cb838a4c3822357a5529642f86316a5
|
87244f4ee50062e59667bf8b9ca4d5291b6818d7
|
refs/heads/master
| 2022-12-21T04:44:13.804535
| 2022-12-17T16:30:35
| 2022-12-17T16:30:35
| 86,637,416
| 166
| 41
|
BSD-3-Clause
| 2021-03-31T18:49:30
| 2017-03-29T23:09:05
| null |
UTF-8
|
C++
| false
| false
| 2,111
|
cc
|
base_browsertest.cc
|
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/autofill_assistant/browser/base_browsertest.h"
#include "content/public/test/content_browser_test_utils.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/switches.h"
namespace autofill_assistant {
// Flag to enable site per process to enforce OOPIFs.
const char* kSitePerProcess = "site-per-process";
BaseBrowserTest::BaseBrowserTest() = default;
BaseBrowserTest::~BaseBrowserTest() = default;
void BaseBrowserTest::SetUpCommandLine(base::CommandLine* command_line) {
command_line->AppendSwitch(kSitePerProcess);
// Necessary to avoid flakiness or failure due to input arriving
// before the first compositor commit.
command_line->AppendSwitch(blink::switches::kAllowPreCommitInput);
}
void BaseBrowserTest::SetUpOnMainThread() {
ContentBrowserTest::SetUpOnMainThread();
// Start a mock server for hosting an OOPIF.
http_server_iframe_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTP);
http_server_iframe_->ServeFilesFromSourceDirectory(
"components/test/data/autofill_assistant/html_iframe");
// We must assign a known port since we reference http_server_iframe_ from the
// html hosted in http_server_.
ASSERT_TRUE(http_server_iframe_->Start(51217));
// Start the main server hosting the test page.
http_server_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTP);
http_server_->ServeFilesFromSourceDirectory(
"components/test/data/autofill_assistant/html");
ASSERT_TRUE(http_server_->Start());
ASSERT_TRUE(NavigateToURL(shell(), http_server_->GetURL(kTargetWebsitePath)));
}
void BaseBrowserTest::TearDown() {
ASSERT_TRUE(http_server_->ShutdownAndWaitUntilComplete());
ASSERT_TRUE(http_server_iframe_->ShutdownAndWaitUntilComplete());
ContentBrowserTest::TearDown();
}
} // namespace autofill_assistant
|
bd51743708b306b633ad0b6ddfbaf5b89cd97889
|
895e5d3600f5c5a06d2cd23fc840de57223b4925
|
/include/eosio/mysql_plugin/mysql_plugin.hpp
|
e4179cf7b991886633fff1f015a863b4da20cccf
|
[] |
no_license
|
a610138467/mysql_plugin
|
18e11c707f765a29bbc9bb7dda3a6ff0d21d82f4
|
8133132257b7b91b4c857fb9abbf12c57a88ed9f
|
refs/heads/master
| 2020-05-18T00:32:23.475027
| 2019-04-29T12:21:01
| 2019-04-29T12:21:01
| 184,065,792
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,008
|
hpp
|
mysql_plugin.hpp
|
#pragma once
#include <mysql.h>
#include <fc/io/json.hpp>
#include <appbase/application.hpp>
#include <eosio/chain_plugin/chain_plugin.hpp>
namespace eosio {
using namespace eosio::chain;
using namespace appbase;
class mysql_plugin : public appbase::plugin<mysql_plugin> {
public:
APPBASE_PLUGIN_REQUIRES((chain_plugin))
void set_program_options(options_description&, options_description& cfg) override;
void plugin_initialize(const variables_map& options);
void plugin_startup();
void plugin_shutdown();
private:
bool enable;
boost::signals2::connection on_accepted_block_connection;
boost::signals2::connection on_irreversible_block_connection;
boost::signals2::connection on_applied_transaction_connection;
boost::signals2::connection on_accepted_transaction_connection;
MYSQL* mysql_connection;
private:
void analyse_action (action_trace& trace);
void add_amount (string account, double amount);
};
}
|
fa720cb2184d0af80a98419cb7d6116b2113ae86
|
c7e14e1579d62ce3d1f60fe91e5c9426081b4b78
|
/MathExpPlotter/Expression.cpp
|
f4829e066b144b29b4ef7e77a7caf47e1de34aa1
|
[
"MIT"
] |
permissive
|
JoshOY/math-expression-plotter
|
3444d56b09e2931abbe010c401a325e2b4aaf18f
|
fddcfc1dead16f21db0fb731fc12ca3c7aac1cba
|
refs/heads/master
| 2021-01-10T16:37:25.754098
| 2015-11-19T13:57:30
| 2015-11-19T13:57:30
| 44,462,189
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,112
|
cpp
|
Expression.cpp
|
#include "Expression.h"
Expression::Expression()
{
this->exp_str = "";
this->exp_id = -1;
this->exp_color = 0x000000;
this->rangeStart = 0;
this->rangeEnd = 0;
this->enabled = true;
}
Expression::Expression(
string _init_exp_str,
int _init_exp_id,
COLORREF _exp_color,
double _rangeStart,
double _rangeEnd
)
{
this->exp_str = _init_exp_str;
this->exp_id = _init_exp_id;
this->exp_color = _exp_color;
this->rangeStart = _rangeStart;
this->rangeEnd = _rangeEnd;
this->enabled = true;
}
std::string MBFromW(LPCWSTR pwsz, UINT cp)
{
int cch = WideCharToMultiByte(cp, 0, pwsz, -1, 0, 0, NULL, NULL);
char* psz = new char[cch];
WideCharToMultiByte(cp, 0, pwsz, -1, psz, cch, NULL, NULL);
std::string st(psz);
delete[] psz;
return st;
}
bool Expression::operator==(const Expression & rVal) const
{
if (this->exp_id == rVal.exp_id) {
return true;
}
else {
return false;
}
}
bool Expression::operator<(const Expression & rVal) const
{
if (this->exp_id < rVal.exp_id) {
return true;
}
else {
return false;
}
}
|
b00f98cc2e5118e58ab2c4cc3367fda2da42bbf4
|
8cb34ab7f2cc06667885e67290dde71c9e885a49
|
/include/angie/bitfield.hpp
|
c7c9b4d78f4ee289b93cd8b2842ecfe6a2df6bb8
|
[] |
no_license
|
fabio-polimeni/angie
|
c805126e725aedddd8f8386c9a0a896e175410bc
|
ac91763a2cd8548fc6404f8c096660aa7a26e1b1
|
refs/heads/master
| 2021-01-01T05:49:10.319843
| 2013-04-02T22:47:15
| 2013-04-02T22:47:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,231
|
hpp
|
bitfield.hpp
|
#ifndef ANGIE_BITFIELD_HPP
#define ANGIE_BITFIELD_HPP
///////////////////////////////////////////////////////////////////////////////
/// Copyright (c) 2013 Fabio Polimeni
///////////////////////////////////////////////////////////////////////////////
/// Created : 2013-02-09
/// Updated :
/// Licence : This source is under MIT License
/// File : bitfield.hpp
///////////////////////////////////////////////////////////////////////////////
/// Description:
///
/// A class that allows to use a C++11 enum class definition as flag type.
/// E.g.
/// enum class Input { In = 0, Out = 1 };
/// Bitfield<Input> in_out = Input.In | Input.Out;
///////////////////////////////////////////////////////////////////////////////
#include <bitset>
#include <type_traits>
#include <angie/config.hpp>
#include <angie/types.hpp>
namespace angie
{
template < typename T >
class bitfield
{
public:
typedef T enum_t;
typedef typename std::underlying_type<T>::type underlying_t;
typedef std::bitset<sizeof(underlying_t)*8> bitset_t;
private:
static_assert(sizeof(underlying_t) <= sizeof(unsigned long long),
"The enum T can't be bigger than long long (at least 64 bits) bits!");
bitset_t m_Bitset;
bitfield( const bitset_t& bs ) : m_Bitset(bs) { }
public:
bitfield( void ) : m_Bitset(static_cast<underlying_t>(0)) { }
bitfield( T value ) : m_Bitset(1<<static_cast<underlying_t>(value)) { }
//Bitfield( const Bitfield& bf ) : m_Bitset(bf.m_Bitset) { }
//Bitfield( Bitfield&& bf ) : m_Bitset(std::move(bf.m_Bitset)) { }
bitset_t& Bitset( void ) { return m_Bitset; }
const bitset_t& Bitset( void ) const { return m_Bitset; }
void set( T value ) { m_Bitset.set(1<<static_cast<underlying_t>(value)); }
void reset( T value ) { m_Bitset.reset(1<<static_cast<underlying_t>(value)); }
void flip( T value ) { m_Bitset.flip(1<<static_cast<underlying_t>(value)); }
void set( void ) { m_Bitset.set(); }
void reset( void ) { m_Bitset.reset(); }
void flip( void ) { m_Bitset.flip(); }
bool all( void ) const { return m_Bitset.all(); }
bool any( void ) const { return m_Bitset.any(); }
bool none( void ) const { return m_Bitset.none(); }
bool all( const bitfield& other ) const { return (*this & other) == other; }
bool any( const bitfield& other ) const { return (*this & other).any(); }
bool has( T value ) const { return m_Bitset.test(static_cast<size_t>(value)); }
bool operator==( const bitfield& rhs ) const { return m_Bitset == rhs.m_Bitset; }
bitfield& operator&=( const bitfield& other ) { m_Bitset &= other.m_Bitset; return *this; }
bitfield& operator|=( const bitfield& other ) { m_Bitset |= other.m_Bitset; return *this; }
bitfield& operator^=( const bitfield& other ) { m_Bitset ^= other.m_Bitset; return *this; }
bitfield operator~() const { return ~m_Bitset; }
bitfield operator<<( size_t pos ) const { return m_Bitset << pos; }
bitfield& operator<<=( size_t pos ) { m_Bitset << pos; return *this; }
bitfield operator>>( size_t pos ) const { return m_Bitset >> pos; }
bitfield& operator>>=( size_t pos ) { m_Bitset >>= pos; return *this; }
};
template< typename T > inline
bitfield<T> operator&(const bitfield<T>& left, const bitfield<T>& right) noexcept
{
bitfield<T> ans(left);
return (ans &= right);
}
template< typename T > inline
bitfield<T> operator&(T left, T right) noexcept
{
bitfield<T> ans(left);
return (ans &= right);
}
template< typename T > inline
bitfield<T> operator&(T left, const bitfield<T>& right) noexcept
{
bitfield<T> ans(left);
return (ans &= right);
}
template< typename T > inline
bitfield<T> operator&(const bitfield<T>& left, T right) noexcept
{
bitfield<T> ans(left);
return (ans &= right);
}
template< typename T > inline
bitfield<T> operator|(const bitfield<T>& left, const bitfield<T>& right) noexcept
{
bitfield<T> ans(left);
return (ans |= right);
}
template< typename T > inline
bitfield<T> operator|(T left, T right) noexcept
{
bitfield<T> ans(left);
return (ans |= right);
}
template< typename T > inline
bitfield<T> operator|(T left, const bitfield<T>& right) noexcept
{
bitfield<T> ans(left);
return (ans |= right);
}
template< typename T > inline
bitfield<T> operator|(const bitfield<T>& left, T right) noexcept
{
bitfield<T> ans(left);
return (ans |= right);
}
template< typename T > inline
bitfield<T> operator^(const bitfield<T>& left, const bitfield<T>& right) noexcept
{
bitfield<T> ans(left);
return (ans ^= right);
}
template< typename T > inline
bitfield<T> operator^(T left, T right) noexcept
{
bitfield<T> ans(left);
return (ans ^= right);
}
template< typename T > inline
bitfield<T> operator^(T left, const bitfield<T>& right) noexcept
{
bitfield<T> ans(left);
return (ans ^= right);
}
template< typename T > inline
bitfield<T> operator^(const bitfield<T>& left, T right) noexcept
{
bitfield<T> ans(left);
return (ans ^= right);
}
template< typename T > inline
bitfield<T> operator~(T mask) noexcept
{
bitfield<T> ans(mask);
return ~ans;
}
}
#endif // ANGIE_BITFIELD_HPP
|
28501a9df6b83b4a528c83a8f8226406dbed04c9
|
2549f2e7d73eca116a03c53f50fb08564ca3be08
|
/src/InputManager.cpp
|
9d0cf86d124a2ceafe32007754c922a62274d97d
|
[
"MIT"
] |
permissive
|
Eduardojvr/NeonEdgeGame
|
a4a7f6f24830d6d2ce022635d31b0c22fdb5aeba
|
1305853005052765e50d8f5351c23f8ec4ee786d
|
refs/heads/master
| 2021-01-22T18:02:30.532792
| 2017-07-16T03:47:16
| 2017-07-16T03:47:16
| 100,743,895
| 0
| 0
| null | 2017-08-18T19:28:48
| 2017-08-18T19:28:48
| null |
UTF-8
|
C++
| false
| false
| 2,778
|
cpp
|
InputManager.cpp
|
#include "InputManager.h"
InputManager* InputManager::instance = nullptr;
InputManager::InputManager():
mouseX(0),
mouseY(0),
updateCounter(0),
quitRequested(false),
mouseState{false},
mouseUpdate{0},
translationTable{SDLK_SPACE,SDLK_e,SDLK_q,SDLK_a,SDLK_d,SDLK_s,SDLK_w,SDLK_s,SDLK_z,SDLK_j,SDLK_k,SDLK_l}
{
}
InputManager::~InputManager() {
}
void InputManager::Update() {
SDL_Event event;
SDL_GetMouseState(&mouseX, &mouseY);
if(updateCounter < 100)
updateCounter++;
else
updateCounter = 0;
while(SDL_PollEvent(&event)) {
if(event.key.repeat != 1) {
if(event.type == SDL_QUIT)
quitRequested = true;
if(event.type == SDL_MOUSEBUTTONDOWN) {
mouseState[event.button.button] = true;
mouseUpdate[event.button.button] = updateCounter;
}
if(event.type == SDL_MOUSEBUTTONUP) {
mouseState[event.button.button] = false;
mouseUpdate[event.button.button] = updateCounter;
}
if(event.type == SDL_KEYDOWN) {
keyState[event.key.keysym.sym] = true;
keyUpdate[event.key.keysym.sym] = updateCounter;
lastKey = event.key.keysym.sym;
}
if(event.type == SDL_KEYUP) {
keyState[event.key.keysym.sym] = false;
keyUpdate[event.key.keysym.sym] = updateCounter;
}
}
}
}
int InputManager::TranslateKey(int key)
{
return translationTable[key];
}
bool InputManager::KeyPress(int key,bool translate) {
if(translate)
key = TranslateKey(key);
return (keyUpdate[key] == updateCounter) ? (keyState[key]) : false;
}
bool InputManager::KeyRelease(int key,bool translate) {
if(translate)
key = TranslateKey(key);
return (keyUpdate[key] == updateCounter) ? (!keyState[key]) : false;
}
bool InputManager::IsKeyDown(int key,bool translate) {
if(translate)
key = TranslateKey(key);
return keyState[key];
}
bool InputManager::MousePress(int button) {
return (mouseUpdate[button] == updateCounter) ? (mouseState[button]) : false;
}
bool InputManager::MouseRelease(int button) {
return (mouseUpdate[button] == updateCounter) ? (!mouseState[button]) : false;
}
bool InputManager::IsMouseDown(int button) {
return mouseState[button];
}
void InputManager::SetTranslationKey(int src, int dest)
{
translationTable[src]=dest;
}
int InputManager::GetMouseX() {
return mouseX;
}
int InputManager::GetMouseY() {
return mouseY;
}
int InputManager::GetTranslationKey(int key)
{
return translationTable[key];
}
int InputManager::GetLastKey()
{
int temp = lastKey;
lastKey = -1;
return temp;
}
bool InputManager::QuitRequested() {
return quitRequested;
}
InputManager& InputManager::GetInstance() {
if(instance == nullptr)
instance = new InputManager();
return *instance;
}
|
7033fcf604af21cb4f63f6667c993d57c98c8685
|
fed9f14edb87cd975ac946e01e063df492a9929a
|
/src/abc/039/abc39d.cpp
|
2ce96f63d51d5b3fa91233bb19faf9c2a42a2a0a
|
[] |
no_license
|
n-inja/kyoupro
|
ba91dd582488b2a8c7222242801cf3115ed7fd10
|
44c5a888984764b98e105780ca57d522a47d832d
|
refs/heads/master
| 2021-01-01T06:52:59.655419
| 2020-10-17T13:28:35
| 2020-10-17T13:28:35
| 97,537,227
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,335
|
cpp
|
abc39d.cpp
|
#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
#include<vector>
#include<map>
#include<math.h>
#include<algorithm>
#include<iomanip>
#include<set>
#include<utility>
using namespace std;
int hx[8] = {0, 0, 1, -1, -1, -1, 1, 1};
int hy[8] = {1, -1, 0, 0, -1, 1, 1, -1};
int main() {
int h, w;
cin >> h >> w;
vector<string> mp(h), ans(h), ch(h);
for(int i = 0; i < h; i++) {
cin >> mp[i];
for(int j = 0; j < w; j++) {
ans[i].push_back('#');
ch[i].push_back('.');
}
}
for(int i = 0; i < h; i++) for(int j = 0; j < w; j++) {
if(mp[i][j] == '.') {
ans[i][j] = '.';
for(int k = 0; k < 8; k++) {
int x = j + hx[k];
int y = i + hy[k];
if(x < 0 || x >= w || y < 0 || y >= h) continue;
ans[y][x] = '.';
}
}
}
for(int i = 0; i < h; i++) for(int j = 0; j < w; j++) {
if(ans[i][j] == '#') {
ch[i][j] = '#';
for(int k = 0; k < 8; k++) {
int x = j + hx[k];
int y = i + hy[k];
if(x < 0 || x >= w || y < 0 || y >= h) continue;
ch[y][x] = '#';
}
}
}
for(int i = 0; i < h; i++) {
if(mp[i] != ch[i]) {
cout << "impossible" << endl;
return 0;
}
}
cout << "possible" << endl;
for(int i = 0; i < h; i++) cout << ans[i] << endl;
return 0;
}
|
53372341ed8bc3d145e1ffdda183e87fc4e46a70
|
419e55c56c5ed91f82657ae451db4dc5ae3dfcce
|
/practice/SeniorHigh1/semester1/November2021/20211115testFSYo/f.cpp
|
f34f2710d209b7d7bad74239703962cffc63bee7
|
[] |
no_license
|
AlexWei061/cpp
|
6e267bea4f163f77245fd2b66863b34edb7e64aa
|
f5f124b0c37b81036932e79290fb5cebcc7f1a5b
|
refs/heads/master
| 2022-07-15T06:17:46.061007
| 2022-07-09T06:55:26
| 2022-07-09T06:55:26
| 216,490,498
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 991
|
cpp
|
f.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define in read()
#define MAXN 2020
#define endl '\n'
inline int read(){
int x = 0; char c = getchar();
while(c < '0' or c > '9') c = getchar();
while('0' <= c and c <= '9'){
x = x * 10 + c - '0'; c = getchar();
}
return x;
}
int n = 0;
int a[MAXN] = { 0 };
int b[MAXN] = { 0 };
unordered_map<int , int> s;
int cnt = 0;
int ans[MAXN] = { 0 };
bool comp(int x, int y){
return x < y;
}
void check(int x){
unordered_map <int, int> c;
for(int i = 1; i <= n; i++) c[b[i]]++;
for(int i = 1; i <= n; i++){
if(!c[a[i] ^ x]) return;
c[a[i] ^ x]--;
}
ans[++cnt] = x;
}
int main(){
n = in;
for(int i = 1; i <= n; i++) a[i] = in;
for(int i = 1; i <= n; i++) b[i] = in;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
s[a[i] ^ b[j]]++;
for(auto x : s)
if(x.second >= n) check(x.first);
sort(ans+1, ans+cnt+1, comp);
cout << cnt << endl;
for(int i = 1; i <= cnt; i++)
cout << ans[i] << ' ';
puts("");
return 0;
}
|
a7048f4ba43efb698b10255dc6387c7b4df9efc2
|
f7c673d103a0a7261246dbdde75490f8eed918ab
|
/source/Client/old/source/scene/TestGameScene.cpp
|
5d0e81df81b454dc7d9d711221f261e9b3482f54
|
[] |
no_license
|
phisn/PixelJumper2
|
2c69faf83c09136b81befd7a930c19ea0ab521f6
|
842878cb3e44113cc2753abe889de62921242266
|
refs/heads/master
| 2022-11-14T04:44:00.690120
| 2020-07-06T09:38:38
| 2020-07-06T09:38:38
| 277,490,158
| 0
| 0
| null | 2020-07-06T09:38:42
| 2020-07-06T08:48:52
|
C++
|
UTF-8
|
C++
| false
| false
| 27
|
cpp
|
TestGameScene.cpp
|
#include "TestGameScene.h"
|
bd3208fd3192956315df5444846d891d231815ef
|
a124718be979c91107ea3f7de6bdcfb01a2c9022
|
/WorkoutSystem/PidjomNohy.cpp
|
53651ac6012d201b02ca8386f5b1ed241f05258a
|
[
"MIT"
] |
permissive
|
TarasShSh/WorkoutSystemApp
|
0cb528c6392a003c3ae2458dcff527cf93d18570
|
f92f0ff4a8b4a283ab101217ae1c25def1947666
|
refs/heads/main
| 2023-05-06T23:45:36.255503
| 2021-06-05T14:13:28
| 2021-06-05T14:13:28
| 371,174,701
| 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 1,721
|
cpp
|
PidjomNohy.cpp
|
#include "PidjomNohy.h"
void PidjomNohy::DoExercise() { // робимо вправу
SetName("підйом ноги"); // <- Вписати назву вправи
cout << " Ви робите вправу " << name << endl;
int key;
cout << " [1] — Як виконувати вправу" << endl;
cout << " [2] — Завершити виконання вправи" << endl;
cout << " [0] — Вийти з програми" << endl;
do {
cout << " Введіть ваше значення:"; cin >> key;
} while (key != 1 && key != 2 && key != 0);
cout << endl << endl;
switch (key) {
case 1:
ShowInfo(); // показуємо інф. про вправу і повертаємось до цього меню
DoExercise();
case 2:
break; // припиняємо виконання цієї вправи
case 0:
exit(0); // виходимо з програми
}
}
void PidjomNohy::ShowInfo() { // виводимо про вправу
cout << " Вправа зміцнює та тонізує стегна" << endl << endl;
cout << " Виконання: " << endl;
cout << " • ляжте на правий бік" << endl;
cout << " • повільно підійміть ліву ногу настільки високо, наскільки зможете" <<
endl;
cout << " • затримайтеся на вершечку, потім опустіть ногу та початкову позицію"
<< endl;
cout << " • впевніться, що таз зафіксований і не 'гуляє', а корпус напружений"
<< endl << endl;
cout << " • повторіть вправу 15 раз на правий бік, 15 на лівий" << endl;
}
|
29dbc9a9b22bc643de43b79d737816b7516fddf8
|
efc84d2b16ffd64e605a7dcf741953b08d7aaee3
|
/mainwindow.cpp
|
dcf9f30071a0e979a528dd43135790babe18c925
|
[] |
no_license
|
infoforcefeed/shitspace
|
d106f0e8b503d7cb86737a539e253bd87f85a9a8
|
4d4a671d12dc3417af56e61949b2376236fae32c
|
refs/heads/master
| 2016-09-06T07:56:57.216980
| 2014-09-21T20:08:11
| 2014-09-21T20:08:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,926
|
cpp
|
mainwindow.cpp
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/Xatom.h>
#include <cstdlib>
#include <unistd.h>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
int i;
thumbnails[20] = {0};
ui->setupUi(this);
QApplication::setQuitOnLastWindowClosed(true);
setWindowFlags(Qt::Popup);
setStyleSheet("background-color: black; color: white;");
layout = new QGridLayout;
setCentralWidget(new QWidget);
centralWidget()->setLayout(layout);
long unsigned workspaces = getWorkspaceCount();
setWorkspace(0);
for (i = 0; i < workspaces; i++) {
setWorkspace(i);
setThumbnail(i);
}
setWorkspace(0);
this->setWindowFlags(Qt::WindowStaysOnTopHint | Qt::Popup);
XClientMessageEvent xev;
Display *display = XOpenDisplay(0);
xev.type = ClientMessage;
xev.window = this->winId();
xev.send_event = True;
xev.display = display;
xev.message_type = XInternAtom(display, "_NET_WM_DESKTOP", True);
xev.format = 32;
xev.data.l[0] = -1;
XSendEvent(display, RootWindow(display, 0), False,
(SubstructureNotifyMask | SubstructureRedirectMask),
(XEvent *) & xev);
adjustSize();
move(QApplication::desktop()->screen()->rect().center() - rect().center());
}
MainWindow::~MainWindow()
{
delete ui;
}
long unsigned MainWindow::getWorkspaceCount()
{
Display *display;
Atom actual_type;
int actual_format;
long unsigned nitems;
long unsigned bytes;
long unsigned *data;
int status;
long unsigned count;
display = XOpenDisplay(0);
if (!display) {
printf("can't open display");
exit(1);
}
status = XGetWindowProperty(
display,
RootWindow(display, 0),
XInternAtom(display, "_NET_NUMBER_OF_DESKTOPS", True), //replace this with your property
0,
(~0L),
False,
AnyPropertyType,
&actual_type,
&actual_format,
&nitems,
&bytes,
(unsigned char**)&data);
if (status != Success) {
fprintf(stderr, "status = %d\n", status);
exit(1);
}
count = *data;
return count;
}
int MainWindow::getWorkspace()
{
Display *display;
Atom actual_type;
int actual_format;
long unsigned nitems;
long unsigned bytes;
unsigned char *data;
int status;
long unsigned count;
display = XOpenDisplay(0);
if (!display) {
printf("can't open display");
exit(1);
}
status = XGetWindowProperty(
display,
RootWindow(display, 0),
XInternAtom(display, "_NET_CURRENT_DESKTOP", True), //replace this with your property
0,
32,
False,
XA_CARDINAL,
&actual_type,
&actual_format,
&nitems,
&bytes,
&data
);
if (status != Success) {
fprintf(stderr, "status = %d\n", status);
exit(1);
}
int r = std::atoi( reinterpret_cast<char( & )[sizeof(data)]>( data ) );
XCloseDisplay(display);
return r;
}
void MainWindow::setWorkspace(int i) {
Display *display = XOpenDisplay(0);
if (!display) {
printf("can't open display");
exit(1);
}
XClientMessageEvent xev;
xev.type = ClientMessage;
xev.window = RootWindow(display, 0);
xev.send_event = True;
xev.display = display;
xev.message_type = XInternAtom(display, "_NET_CURRENT_DESKTOP", True);
xev.format = 32;
xev.data.l[0] = i;
XSendEvent(
display,
RootWindow(display, 0),
False,
(SubstructureNotifyMask | SubstructureRedirectMask),
(XEvent *) &xev
);
XFlush(display);
while (True) {
int workspace = getWorkspace();
if(workspace == i) {
break;
}
usleep(5);
}
XCloseDisplay(display);
}
void MainWindow::setThumbnail(int i) {
QLabel *screenshotLabel;
if (thumbnails[i] == NULL) {
screenshotLabel = new QLabel;
screenshotLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
screenshotLabel->setAlignment(Qt::AlignCenter);
screenshotLabel->setMinimumSize(240, 160);
layout->addWidget(screenshotLabel, i / 3, i % 3);
thumbnails[i] = screenshotLabel;
}
else {
screenshotLabel = thumbnails[i];
}
QScreen *srn = QApplication::screens().at(0);
QPixmap workspacePixmap = srn->grabWindow(QApplication::desktop()->winId());
screenshotLabel->setPixmap(
workspacePixmap.scaled(
screenshotLabel->size(),
Qt::KeepAspectRatio,
Qt::SmoothTransformation
)
);
}
|
38da9238a0d543d479a0922d4bbd5bfc4cdb2010
|
5ddd70f4a4799dcbc39148415dbfad09d3a10fef
|
/d3d12app/d3d12app/Render/Wireframe.cpp
|
84415f9212a85d70a0ad83fc55220a12850f40f8
|
[] |
no_license
|
zhumake1993/d3d12app
|
706fe718bac930c4b03a8e5a9abd91cb4943869a
|
64db6773017ade7311ae835d307f5ded11fb944b
|
refs/heads/master
| 2022-01-20T04:48:51.897430
| 2019-07-05T11:27:19
| 2019-07-05T11:27:19
| 192,184,449
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 3,764
|
cpp
|
Wireframe.cpp
|
#include "Wireframe.h"
Wireframe::Wireframe()
{
BuildRootSignature();
BuildShader();
BuildPSO();
}
void Wireframe::Draw(const CD3DX12_CPU_DESCRIPTOR_HANDLE& rtv, const D3D12_CPU_DESCRIPTOR_HANDLE& dsv)
{
//设置视口和剪裁矩形。每次重置指令列表后都要设置视口和剪裁矩形
gCommandList->RSSetViewports(1, &gScreenViewport);
gCommandList->RSSetScissorRects(1, &gScissorRect);
//清空后背缓冲和深度模板缓冲
gCommandList->ClearRenderTargetView(rtv, DirectX::Colors::Black, 0, nullptr);
gCommandList->ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr);
//设置渲染目标
gCommandList->OMSetRenderTargets(1, &rtv, true, &dsv);
// 设置根签名
gCommandList->SetGraphicsRootSignature(mRootSignature.Get());
// 绑定常量缓冲
auto passCB = gPassCB->GetCurrResource()->Resource();
gCommandList->SetGraphicsRootConstantBufferView(1, passCB->GetGPUVirtualAddress());
// 绑定所有材质。对于结构化缓冲,我们可以绕过堆,使用根描述符
auto matBuffer = gMaterialManager->CurrResource();
gCommandList->SetGraphicsRootShaderResourceView(2, matBuffer->GetGPUVirtualAddress());
// 绑定描述符堆
ID3D12DescriptorHeap* descriptorHeaps[] = { gTextureManager->GetSrvDescriptorHeapPtr() };
gCommandList->SetDescriptorHeaps(_countof(descriptorHeaps), descriptorHeaps);
// 绑定所有的纹理
gCommandList->SetGraphicsRootDescriptorTable(3, gTextureManager->GetGpuSrvTex());
// 绑定天空球立方体贴图
gCommandList->SetGraphicsRootDescriptorTable(4, gTextureManager->GetGpuSrvCube());
gCommandList->SetPipelineState(gPSOs["Wireframe"].Get());
gInstanceManager->Draw((int)RenderLayer::Opaque);
gInstanceManager->Draw((int)RenderLayer::OpaqueDynamicReflectors);
gInstanceManager->Draw((int)RenderLayer::AlphaTested);
gInstanceManager->Draw((int)RenderLayer::Transparent);
}
void Wireframe::BuildRootSignature()
{
mRootSignature = gRootSignatures["main"];
}
void Wireframe::BuildShader()
{
gShaders["WireframeVS"] = d3dUtil::CompileShader(L"Shaders\\Wireframe.hlsl", nullptr, "VS", "vs_5_1");
gShaders["WireframePS"] = d3dUtil::CompileShader(L"Shaders\\Wireframe.hlsl", nullptr, "PS", "ps_5_1");
}
void Wireframe::BuildPSO()
{
D3D12_GRAPHICS_PIPELINE_STATE_DESC opaqueWireframePsoDesc;
ZeroMemory(&opaqueWireframePsoDesc, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
opaqueWireframePsoDesc.InputLayout = { gInputLayout.data(), (UINT)gInputLayout.size() };
opaqueWireframePsoDesc.pRootSignature = mRootSignature.Get();
opaqueWireframePsoDesc.VS =
{
reinterpret_cast<BYTE*>(gShaders["WireframeVS"]->GetBufferPointer()),
gShaders["WireframeVS"]->GetBufferSize()
};
opaqueWireframePsoDesc.PS =
{
reinterpret_cast<BYTE*>(gShaders["WireframePS"]->GetBufferPointer()),
gShaders["WireframePS"]->GetBufferSize()
};
opaqueWireframePsoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
opaqueWireframePsoDesc.RasterizerState.FillMode = D3D12_FILL_MODE_WIREFRAME;
opaqueWireframePsoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
opaqueWireframePsoDesc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT);
opaqueWireframePsoDesc.SampleMask = UINT_MAX;
opaqueWireframePsoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
opaqueWireframePsoDesc.NumRenderTargets = 1;
opaqueWireframePsoDesc.RTVFormats[0] = gBackBufferFormat;
opaqueWireframePsoDesc.SampleDesc.Count = g4xMsaaState ? 4 : 1;
opaqueWireframePsoDesc.SampleDesc.Quality = g4xMsaaState ? (g4xMsaaQuality - 1) : 0;
opaqueWireframePsoDesc.DSVFormat = gDepthStencilFormat;
ThrowIfFailed(gD3D12Device->CreateGraphicsPipelineState(&opaqueWireframePsoDesc, IID_PPV_ARGS(&gPSOs["Wireframe"])));
}
|
6906a304c0b809bfc220d272b018f89aad4b5057
|
bd9739abf849efecd3ed0ffa7c2238f56d927e9e
|
/maverick/convoy-sidemission/remoteExec.cpp
|
8ffd0db7935d36fa2086cc9d32ae359a0fd79339
|
[] |
no_license
|
kubalife/kuba_life
|
a105cf71bf1788d03e7cefa777a4fc7615a4aecd
|
bd17f36babc4150083ba28237acac832d3c82f70
|
refs/heads/master
| 2021-01-12T15:13:26.689526
| 2016-11-09T21:13:05
| 2016-11-09T21:13:17
| 69,878,844
| 7
| 7
| null | 2019-06-15T13:26:50
| 2016-10-03T14:30:16
|
SQF
|
UTF-8
|
C++
| false
| false
| 68
|
cpp
|
remoteExec.cpp
|
class mav_convoy_fnc_addTriggerHandlers {
allowedTargets = 1;
};
|
77f9afd619ff698f7e847cab94a94f41ee5f9bbf
|
5702c0a20b6bbf0babd1f8b915d67318f9746284
|
/Servo.h
|
299c182b853bbfe1123013e2d9fc487c7bc2db42
|
[
"BSD-3-Clause"
] |
permissive
|
AnmanTechnology/mbed-RCServo
|
fe70400ae37001e573e9ea0e7d5bfa05bdd5d582
|
732cf4b79f513069008fa18c941baa9b1620aa54
|
refs/heads/master
| 2020-09-30T03:17:43.878593
| 2019-12-10T18:36:51
| 2019-12-10T18:36:51
| 227,189,769
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,922
|
h
|
Servo.h
|
/**
* @author Liews Wuttipat
* @date 13 Nov 2019
*
* @section LICENSE
*
* Copyright (c) 2018 Anman Technology Co.,Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @section DESCRIPTION
*
* R/C Servo Library
*/
#ifndef _SERVO_H_
#define _SERVO_H_
#include "mbed.h"
/** Servo control class, based on a PwmOut
*
* Example:
* @code
* // Continously sweep the servo
* #include "mbed.h"
* #incldee "Servo.h"
*
* Servo servo(PA_2);
*
* int main() {
* while(true) {
* for(int i=0; i<100; i++) {
* servo.writePercent(i/100.0);
* wait_ms(10);
* }
* for(int i=100; i>0; i++) {
* servo.writePercent(i/100.0);
* wait_ms(10);
* }
* }
* }
* @endcode
* @code
* // Drive servo 3 steps
* #include "mbed.h"
* #incldee "Servo.h"
*
* Servo servo(PA_2);
*
* int main() {
* while(true) {
* servo.writePosition(0);
* wait_ms(1000);
* servo.writePosition(90);
* wait_ms(1000);
* servo.writePosition(180);
* wait_ms(1000);
* servo.writePosition(90);
* wait_ms(1000);
* }
* }
* @endcode
*/
class Servo
{
public:
/** Create a servo object connected to the specified PwmOut pin
*
* @param pin PwmOut pin to connect to
* @param period Period of servo in millisecs
*/
Servo(PinName pin, int period = 20);
/** Set the servo offset to center
*
* @param offset Pulsewidth to Center position in microseconds
*/
void setOffset(int offset = 0);
/** Set the servo range of position
*
* @param range_min Position range min in degrees
* @param range_max Position range max in degrees
*/
void setRange(float range_min = 0, float range_max = 180);
/** Set the servo limit low and limit high
*
* @param limit_min Pulsewidth limit min in microseconds
* @param limit_max Pulsewidth limit max in microseconds
*/
void setPulseLimit(int limit_min = 1000, int limit_max = 2000);
/** Set the servo Pulsewidth
*
* @param pulse Pulsewidth in microseconds
*/
void writePulse(int pulse);
/** Set the servo position, normalised to it's full range
*
* @param percent A normalised number 0.0-1.0 to represent the full range.
*/
void writePercent(float percent);
/** Set the servo position
*
* @param degrees Servo position in degrees
*/
void writePosition(float degrees);
/** Read the servo motors current position
*
* @param returns A normalised number 0.0-1.0 representing the full range.
*/
float read();
private:
PwmOut _pwm;
int _pulse_limit_min, _pulse_limit_max, _pulse_span;
int _pulse;
int _pulse_offset;
float _range_min, _range_max, _range_span;
};
#endif
|
3deb52e51e3b0c103a60c93b1087bea1505601c8
|
177be7fbc768c9776e5f1e3b4d2104405c163236
|
/controller/src/main_stringBuilder.h
|
d3bc004341daa310c81ea02de71129a8df0e69db
|
[] |
no_license
|
JostMat/projektpraktikum
|
1f60d6814ebbf028730cee4f73b96194ba927e6e
|
691c2f5e8b1c3d1f4b42d5e9bd412347dd7c49c9
|
refs/heads/master
| 2021-01-13T13:05:47.001653
| 2017-01-07T22:34:04
| 2017-01-07T22:34:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,615
|
h
|
main_stringBuilder.h
|
#ifndef MAIN_STRINGBUILDER_H
#define MAIN_STRINGBUILDER_H
#include <Arduino.h>
#include <newdel.h> //fügt new und delete hinzu, wird für "mthread" benötigt
#include <mthread.h>
#include "StoreD.h" //StoreD wird vom StringBuilder verwaltet und aufgerufen
#include "main_valveCtrl.h" //Objekte zum Speichern der Objektpointer
#include "main_mfcCtrl.h"
#include "main_boschCom.h"
#include "ownlibs/serialCommunication.h"
namespace communication {
class Main_StringBuilder : public Thread {
public:
//Defaultconstructor
Main_StringBuilder();
//Destructor
~Main_StringBuilder();
//setze das Intervall, in welchem die Hauptschleife ausgefuert wird.
//Zeit ist gleich der des Sensors
void setIntervall(int intervall);
//aktiviere Klasse von LabCom aus, setzt die erste Intervallzeit
void start(unsigned long time);
//Uebergebe Objektpointer
void setMainValveObjectPointer(control::Main_ValveCtrl *main_valveCtrl);
void setMainMfcObjectPointer(control::Main_MfcCtrl *main_mfcCtrl);
void setMainBoschObjectPointer(communication::Main_BoschCom *main_boschCom);
protected:
//Die Loop wird kontinuierlich aufgerufen und vollstaendig ausgefuehrt
bool loop();
private:
bool ready;
unsigned long lastTime;
int intervall;
storage::StoreD *storeD; //Hier wird das StoreD-Objekt gespeichert
control::Main_ValveCtrl *main_valveCtrl;
control::Main_MfcCtrl *main_mfcCtrl;
communication::Main_BoschCom *main_boschCom;
};
}
#endif
|
b10dc08ea6f520b6588e13fa1e3021d3d05c1226
|
cb88da4001d6dbf6ea1a99940aea8f704f84f06c
|
/a_PY.cpp
|
5b75de61966ba0d92ea708ebdfb17112b1c246c3
|
[] |
no_license
|
ayshih/GRASP
|
562ca9f8b661e5fc0cb4f5d13a7c501235662fd3
|
5eaecf60805ec58a06742f18d8de375a96ca7605
|
refs/heads/master
| 2021-01-21T17:06:42.985412
| 2016-02-03T05:37:18
| 2016-02-03T05:37:18
| 19,009,056
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,342
|
cpp
|
a_PY.cpp
|
/* =============================================================================================
analysis_PY_int_2: code returns error for negative values of the xp or yp. using analysis_PY_int.h
analysis_PY_int: first integrated version of the analysis code (a7) into the control program
========================================================================================== */
#include "a_PY.h"
// Standard libs
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <sys/time.h>
#include <fstream>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>
using namespace std;
/* =============================================================================================
initialize the image structure
========================================================================================== */
bool init_im(info& im){
for(int i=0;i<3;i++){
//im.there[i]=false; //true = its there
//im.wsun[i]=false; //true = its a whole sun
im.xp[i]=0; //pixel coordinates
im.yp[i]=0;
im.xs[i]=0; //solar coordinates
im.ys[i]=0;
im.thresh[i]=0;
im.ngt[i]=0; //npixels gt thresh --> need to add to mask_centroid
}
//im.theta=0; //orientation of relative roll
//im.w=0;
return true;
}
// __________________________________________________________________________________________end
/* =============================================================================================
initialize the parameters and load a parameter table
========================================================================================== */
bool init_params(params& val, int w_in, int n_in){
val.width=w_in;
val.nel=n_in;
val.a_timer=false;
//change these to load from parameter table
val.Rs= 100;
//val.ns = 3; //number of suns to find, finds the brightest --> dimmest
val.ns = 1;
val.min = 50; //min number of pixels for a sun to "be there"
val.reject = 100;
val.th[0] = .6;
val.th[1] = .4;
val.th[2] = .2;
//val.box = 80; //for dimsun
val.box = 350; //for tstim & tstim2
//val.box = 210; //for 960x1290_bw
/*val.ix = 1; //full image
val.iy = 1;
val.comp =1;*/
/*val.ix = 14; //for timetests
val.iy = 14;
val.comp = 4; */
val.ix = 20; //limits of test image
val.iy = 20;
val.comp = 50;
//val.drawline=true;
val.drawline = false;
return true;
}
// __________________________________________________________________________________________end
/* =============================================================================================
The main function to call for analysis of the PY images
follows the code outline in a7.cpp
========================================================================================== */
bool analyzePY(info& im, params val, valarray<unsigned char> imarr){
//find solar centers
Find_3_mask(imarr, val, im);
//find fiducials
//coordinate transform to match-up with sun sensor
return true;
}
// __________________________________________________________________________________________end
/* =============================================================================================
Method 1: use centroiding to find all 3 suns
From a single image containing 3 suns at different intensities,
This program finds each of their xy locations using the mask_centoid function
This is probably more robust, but slower than Method 2
========================================================================================== */
bool Find_3_mask(valarray<unsigned char> imarr, params& val, info& im){
//get thresholds
timeval t;
if(val.a_timer)
timetest(1,t,0);
find_thresh(imarr, im.thresh, val);
if(val.a_timer){
cout<<"find_thresh ";
timetest(2,t,0);
}
//operate on images
for(int i=0; i<val.ns; i++){
//threshold and mask
if(val.a_timer)
timetest(1,t,0);
valarray<unsigned short> mask(val.nel);
//mask entire imarr
for (int p = 0; p < val.nel; p++){
mask[p] = ((imarr[p] >= im.thresh[i] ) ? 1 : 0);
}
//mask only the rows we use in centroiding - possibly didn't implement correctly. ran 10x slower
/* int height = val.nel/val.width;
for(int n=0; n<height;n+=val.ic){
for (int p = n*val.width; p < (n+1)*val.width; p++){
mask[p] = ((imarr[p] >= im.thresh[i] ) ? 255 : 0);
}
}
for(int m=0; m<val.width;m+=val.ic){
for (int p = m; p < (m+1)*height; p++){ //this rewrites where we've already compared with x
mask[p] = ((imarr[p] >= im.thresh[i] ) ? 255 : 0);
}
} */
if(val.a_timer){
cout<<"d_mask ";
timetest(2,t,0);
}
//centroid the mask
centroid(mask, val, im.xp[i], im.yp[i], im.there[i]);
~mask;
//crop and black out the current sun from the mask
if(im.there[i] == true){
const char* fnc= "!dimsun_crop.fits"; //right now this calls all of them the same name, need to dynamically assign
crop(imarr, fnc, im.xp[i], im.yp[i], val); //crops and blacks out sun > thresh
}
}
//other function options to add in
//drawline(imarr, val.nel, width, x, y); //draws a line at centroid location
//const char* fn= "!dimsun1_imarr1.fits";
//savefits(imarr, fn, val.nel, width); //good diagnostic to check if the suns are blacked out
return true;
}
// __________________________________________________________________________________________end
/* =============================================================================================
Find Thresholds
========================================================================================== */
bool find_thresh(valarray<unsigned char> imarr, unsigned char thresh[], params val){
//for a single sun should be .25*max, since we have 3 suns, thresh must be >2nd brightest sun
//sort
//cout<<"Sorting times: ";
/*timetest(1,t,0);
sort(&imarr[0], &imarr[val.nel-1]); //sorts the values of the image array in ascending order
cout<<"imarr ";
timetest(2,t,0);
//timetest(2); */
//sort comppressed array
valarray<unsigned char> cim(imarr[slice(0, (val.nel/val.comp), val.comp)]);
sort(&cim[0], &cim[(val.nel/val.comp)-1]);
/*thresh[0]=th1*(int)imarr[val.nel-reject];
thresh[1]=th2*(int)imarr[val.nel-reject];
thresh[2]=th3*(int)imarr[val.nel-reject];*/
//use the compressed thresh
thresh[0]=val.th[0]*(int)cim[(val.nel/val.comp)-val.reject];
thresh[1]=val.th[1]*(int)cim[(val.nel/val.comp)-val.reject];
thresh[2]=val.th[2]*(int)cim[(val.nel/val.comp)-val.reject];
//check thresholds are similar
/* cout<<"th = "<<th1*(int)imarr[val.nel-reject]<<" , "<<th2*(int)imarr[val.nel-reject]<<" , "<<th3*(int)imarr[val.nel-reject]<<endl;
//cout<<"c_th = "<<th1*(int)cim[(val.nel/2)-reject]<<" , "<<th2*(int)cim[(val.nel/2)-reject]<<" , "<<th3*(int)cim[(val.nel/2)-reject]<<endl;
cout<<"c_th = "<<th1*(int)cim[(val.nel/4)-reject]<<" , "<<th2*(int)cim[(val.nel/4)-reject]<<" , "<<th3*(int)cim[(val.nel/4)-reject]<<endl;
*/
return true;
}
// __________________________________________________________________________________________end
/* =============================================================================================
Time Testing different methods
don't need this and timer from v1_dvx. But until I make and include those files here, I just have two of them
========================================================================================== */
void timetest(int x, timeval& t1, int i){
//get time
timeval highrestime;
char filename[17];
time_t rawtime;
struct tm * timeinfo;
gettimeofday(&highrestime, NULL);
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime (filename, 17, "%Y%m%d_%H%M%S_", timeinfo);
float sec;
float us;
//tests
switch (x){
case 0 : {
cout<<"Time: "<<filename << highrestime.tv_usec<<"\n";
break;
}
case 1 : {
t1 = highrestime;
break;
}
case 2 : {
sec = highrestime.tv_sec - t1.tv_sec;
if (sec == 0) {
us = highrestime.tv_usec - t1.tv_usec;
} else {
us = (1000000 - t1.tv_usec) + highrestime.tv_usec;
us = us + ((sec - 1) * 1000);
}
cout<<"dt = "<< (us/1000)<<" ms"<<endl;
break;
}
default: {
break;
}
}
}
//_____________________________________________________________________________________________
/* =============================================================================================
Mask image and get rough centroid
========================================================================================== */
void centroid(valarray<unsigned short>& mask, params val, float& xloc, float& yloc, bool& there){
int height = val.nel/val.width;
unsigned long sumy = 0;
unsigned long sumx = 0;
unsigned long weighted_sumx =0; //unsigned long ok so long as sun diameter = 330 and the mask is 0 & 1 only
unsigned long weighted_sumy =0;
timeval t;
if(val.a_timer)
timetest(1,t,0);
//strips along y
for(int m=0; m<val.width;m+=val.iy){
valarray<unsigned short> stripx(mask[slice(m, height, val.width)]);
weighted_sumx += stripx.sum()*m;
sumx += stripx.sum();
//~stripx;
}
//strips along x
for(int n=0; n<height;n+=val.ix){
valarray<unsigned short> stripy(mask[slice(n*val.width, val.width, 1)]);
weighted_sumy += stripy.sum()*n;
sumy += stripy.sum();
//~stripy;
}
//strips along y
/* for(int m=0; m<val.width;m+=val.iy){
valarray<unsigned short> stripx(mask[slice(m, height, val.width)]);
weighted_sumx += stripx.sum()*m;
sumx += stripx.sum();
//~stripx;
} */
if(val.a_timer){
cout<<"summing ";
timetest(2,t,0);
}
~mask;
/* cout<<"wx: "<<weighted_sumx<<endl;
cout<<"wy: "<<weighted_sumy<<endl;
cout<<"sumx: "<<sumx<<endl;
cout<<"sumy: "<<sumy<<endl;
cout<<"nx: "<<nx<<endl;
cout<<"ny: "<<ny<<endl; */
xloc = (float)weighted_sumx/sumx;
yloc = (float)weighted_sumy/sumy;
//is the sun there?
if((sumy/1) > val.min)
there = true;
}
// __________________________________________________________________________________________end
/* =============================================================================================
Crop the image & black-out the cropped image in imarr
========================================================================================== */
bool crop(valarray<unsigned char>& imarr, const char* fn, float x, float y, params val){
//This code assumes x & y are the approximate center coordinates of the box
int bx = x - val.box/2;
int by = y - val.box/2;
//adjust for cropped area extending outside of the image area
if(bx<0) bx=0;
if(bx > (val.width - val.box)) bx = (val.width - val.box);
if(by<0) by=0;
if(by > (val.nel/val.width - val.box)) by = ((val.nel/val.width) - val.box);
//cout<<"bx, by: "<<bx<<" , "<<by<<endl;
//for blacking out & saving
slice slicex;
valarray<unsigned char> cropped(255, val.box*val.box); //initally set to white so we see problem
//size_t size = sizeof(unsigned short); //change this if we change int -> char
size_t size = sizeof(unsigned char);
valarray<unsigned char> sliced(val.box);
for(int ny=0; ny<val.box;ny++){
slicex = slice (((by+ny)*val.width+bx),val.box,1);
//save cropped data
if(val.savecrop){
sliced = imarr[slicex];
memcpy(&cropped[ny*val.box], &sliced[0] , val.box*size );
~sliced;
}
//black out region that is cropped
imarr[slicex]=0;
}
if(val.savecrop){
//savefits(cropped, fn, box*box, box); //saved cropped images //need saveim available here
}
return true;
}
// __________________________________________________________________________________________end
/* =============================================================================================
Analysis results
========================================================================================== */
void diagnostics(params val, info im){
//diagnostics
cout<<"width: "<<val.width<<endl;
cout<<"nel: "<<val.nel<<endl;
//cout<<"image struct:\n";
cout<<"xp: "<<im.xp[0]<<" ,"<<im.xp[1]<<" , "<<im.xp[2]<<endl;
cout<<"yp: "<<im.yp[0]<<" ,"<<im.yp[1]<<" , "<<im.yp[2]<<endl;
cout<<"thresh: "<<(int)im.thresh[0]<<" ,"<<(int)im.thresh[1]<<" , "<<(int)im.thresh[2]<<endl;
cout<<"there: "<<im.there[0]<<" ,"<<im.there[1]<<" , "<<im.there[2]<<endl;
//cout<<"wsun: "<<im.wsun[0]<<" ,"<<im.wsun[1]<<" , "<<im.wsun[2]<<endl;
//cout<<"theta: "<<im.theta<<endl;
cout<<"\n\n";
}
// __________________________________________________________________________________________end
/* =============================================================================================
Draw line in image where the xy location is
========================================================================================== */
void drawline(valarray<unsigned char>& imarr, params val, info im){
slice slicex;
slice slicey;
for(int i =0; i<val.ns;i++){
slicex = slice (im.yp[i]*val.width,val.width,1);
slicey = slice (im.xp[i], val.nel/val.width, val.width);
imarr[slicex] = 255;
imarr[slicey] = 255;
}
}
// __________________________________________________________________________________________end
|
b5858eb5bf726aefba943a69958547da7d637cf6
|
9406dcf1f1ccdd67bb34cb9a0030618a50d505b0
|
/source/gw/renderer/rectangle_3d_renderer.hpp
|
8ec01eec70623d76cb9d858f4d462e6ff8ea32d5
|
[] |
no_license
|
code1009/gw
|
51f8ec43a23dc9da03c3846d34937553a1c6e116
|
e72d9afbf3cb23ff1cac70156913229d12854c49
|
refs/heads/master
| 2021-07-19T01:06:58.429198
| 2020-06-19T09:33:11
| 2020-06-19T09:33:11
| 176,871,720
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,758
|
hpp
|
rectangle_3d_renderer.hpp
|
#ifndef INCLUDED__CX__GW__RENDERER__RECTANGLE_3D_RENDERER__HPP
#define INCLUDED__CX__GW__RENDERER__RECTANGLE_3D_RENDERER__HPP
/////////////////////////////////////////////////////////////////////////////
//
// File: rectangle_3d_renderer.hpp
//
// Created by code1009.
// Created on Dec-17th, 2014.
//
/////////////////////////////////////////////////////////////////////////////
//===========================================================================
/////////////////////////////////////////////////////////////////////////////
//===========================================================================
namespace gw
{
/////////////////////////////////////////////////////////////////////////////
//
// Class: rectangle_3d_renderer
//
/////////////////////////////////////////////////////////////////////////////
//===========================================================================
class rectangle_3d_renderer : public renderer
{
private:
rectangle_t _rectangle;
color_t _fill_color;
cx::float_t _3d_width;
color_t _3d_light_color;
color_t _3d_shadow_color;
cx::bool_t _3d_pressed;
public:
rectangle_3d_renderer();
virtual ~rectangle_3d_renderer();
// renderer 가상함수
public:
virtual void render (graphic_t g);
public:
void set_rectangle (rectangle_t v);
void set_fill_color (color_t v);
void set_3d_width (cx::float_t v);
void set_3d_light_color (color_t v);
void set_3d_shadow_color (color_t v);
void set_3d_color_by_fill_color (void);
void set_3d_pressed (cx::bool_t v);
};
/////////////////////////////////////////////////////////////////////////////
//===========================================================================
}
#endif
|
a33e3db68a7a72315bcc5c5a130da0663933a256
|
19bdd1ecf1833d17915752a0d9d66780246412a3
|
/src/corelib/mimetypes/qmimetype.cpp
|
55c7de0c8772e39e6ee617670cce7561364f780f
|
[
"GPL-3.0-only",
"Qt-GPL-exception-1.0",
"LicenseRef-scancode-commercial-license",
"LGPL-3.0-only",
"GPL-2.0-only",
"BSD-3-Clause",
"MIT",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"LGPL-2.1-only",
"GFDL-1.3-only",
"LicenseRef-scancode-qt-commercial-1.1",
"LicenseRef-scancode-kfqf-accepted-gpl",
"LGPL-2.1-or-later",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
Unity-Technologies/qtbase
|
04964cd1a0a21f4435e476f6299b266d6acb655a
|
eca43e4a5ef7ce9016e6b8dd4d78f43d7fea6511
|
refs/heads/qtbuild.5.13.2
| 2023-07-18T17:20:15.969921
| 2021-02-12T13:25:37
| 2021-02-22T11:35:03
| 170,777,336
| 7
| 7
|
BSD-3-Clause
| 2023-04-30T11:12:08
| 2019-02-15T00:25:30
|
C++
|
UTF-8
|
C++
| false
| false
| 17,392
|
cpp
|
qmimetype.cpp
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2015 Klaralvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author David Faure <david.faure@kdab.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmimetype.h"
#include "qmimetype_p.h"
#include "qmimedatabase_p.h"
#include "qmimeprovider_p.h"
#include "qmimeglobpattern_p.h"
#include <QtCore/QDebug>
#include <QtCore/QLocale>
#include <QtCore/QHashFunctions>
#include <memory>
QT_BEGIN_NAMESPACE
QMimeTypePrivate::QMimeTypePrivate()
: loaded(false), fromCache(false)
{}
QMimeTypePrivate::QMimeTypePrivate(const QMimeType &other)
: loaded(other.d->loaded),
name(other.d->name),
localeComments(other.d->localeComments),
genericIconName(other.d->genericIconName),
iconName(other.d->iconName),
globPatterns(other.d->globPatterns)
{}
void QMimeTypePrivate::clear()
{
name.clear();
localeComments.clear();
genericIconName.clear();
iconName.clear();
globPatterns.clear();
}
void QMimeTypePrivate::addGlobPattern(const QString &pattern)
{
globPatterns.append(pattern);
}
/*!
\class QMimeType
\inmodule QtCore
\ingroup shared
\brief The QMimeType class describes types of file or data, represented by a MIME type string.
\since 5.0
For instance a file named "readme.txt" has the MIME type "text/plain".
The MIME type can be determined from the file name, or from the file
contents, or from both. MIME type determination can also be done on
buffers of data not coming from files.
Determining the MIME type of a file can be useful to make sure your
application supports it. It is also useful in file-manager-like applications
or widgets, in order to display an appropriate \l {QMimeType::iconName}{icon} for the file, or even
the descriptive \l {QMimeType::comment()}{comment} in detailed views.
To check if a file has the expected MIME type, you should use inherits()
rather than a simple string comparison based on the name(). This is because
MIME types can inherit from each other: for instance a C source file is
a specific type of plain text file, so text/x-csrc inherits text/plain.
\sa QMimeDatabase, {MIME Type Browser Example}
*/
/*!
\fn QMimeType &QMimeType::operator=(QMimeType &&other)
Move-assigns \a other to this QMimeType instance.
\since 5.2
*/
/*!
\fn QMimeType::QMimeType();
Constructs this QMimeType object initialized with default property values that indicate an invalid MIME type.
*/
QMimeType::QMimeType() :
d(new QMimeTypePrivate())
{
}
/*!
\fn QMimeType::QMimeType(const QMimeType &other);
Constructs this QMimeType object as a copy of \a other.
*/
QMimeType::QMimeType(const QMimeType &other) :
d(other.d)
{
}
/*!
\fn QMimeType &QMimeType::operator=(const QMimeType &other);
Assigns the data of \a other to this QMimeType object, and returns a reference to this object.
*/
QMimeType &QMimeType::operator=(const QMimeType &other)
{
if (d != other.d)
d = other.d;
return *this;
}
/*!
\fn QMimeType::QMimeType(const QMimeTypePrivate &dd);
Assigns the data of the QMimeTypePrivate \a dd to this QMimeType object, and returns a reference to this object.
\internal
*/
QMimeType::QMimeType(const QMimeTypePrivate &dd) :
d(new QMimeTypePrivate(dd))
{
}
/*!
\fn void QMimeType::swap(QMimeType &other);
Swaps QMimeType \a other with this QMimeType object.
This operation is very fast and never fails.
The swap() method helps with the implementation of assignment
operators in an exception-safe way. For more information consult
\l {http://en.wikibooks.org/wiki/More_C++_Idioms/Copy-and-swap}
{More C++ Idioms - Copy-and-swap}.
*/
/*!
\fn QMimeType::~QMimeType();
Destroys the QMimeType object, and releases the d pointer.
*/
QMimeType::~QMimeType()
{
}
/*!
\fn bool QMimeType::operator==(const QMimeType &other) const;
Returns \c true if \a other equals this QMimeType object, otherwise returns \c false.
The name is the unique identifier for a mimetype, so two mimetypes with
the same name, are equal.
*/
bool QMimeType::operator==(const QMimeType &other) const
{
return d == other.d || d->name == other.d->name;
}
/*!
\since 5.6
\relates QMimeType
Returns the hash value for \a key, using
\a seed to seed the calculation.
*/
uint qHash(const QMimeType &key, uint seed) Q_DECL_NOTHROW
{
return qHash(key.d->name, seed);
}
/*!
\fn bool QMimeType::operator!=(const QMimeType &other) const;
Returns \c true if \a other does not equal this QMimeType object, otherwise returns \c false.
*/
/*!
\property QMimeType::valid
\brief \c true if the QMimeType object contains valid data, \c false otherwise
A valid MIME type has a non-empty name().
The invalid MIME type is the default-constructed QMimeType.
While this property was introduced in 5.10, the
corresponding accessor method has always been there.
*/
bool QMimeType::isValid() const
{
return !d->name.isEmpty();
}
/*!
\property QMimeType::isDefault
\brief \c true if this MIME type is the default MIME type which
applies to all files: application/octet-stream.
While this property was introduced in 5.10, the
corresponding accessor method has always been there.
*/
bool QMimeType::isDefault() const
{
return d->name == QMimeDatabasePrivate::instance()->defaultMimeType();
}
/*!
\property QMimeType::name
\brief the name of the MIME type
While this property was introduced in 5.10, the
corresponding accessor method has always been there.
*/
QString QMimeType::name() const
{
return d->name;
}
/*!
\property QMimeType::comment
\brief the description of the MIME type to be displayed on user interfaces
The default language (QLocale().name()) is used to select the appropriate translation.
While this property was introduced in 5.10, the
corresponding accessor method has always been there.
*/
QString QMimeType::comment() const
{
QMimeDatabasePrivate::instance()->loadMimeTypePrivate(*d);
QStringList languageList;
languageList << QLocale().name();
languageList << QLocale().uiLanguages();
languageList << QLatin1String("default"); // use the default locale if possible.
for (const QString &language : qAsConst(languageList)) {
const QString lang = language == QLatin1String("C") ? QLatin1String("en_US") : language;
const QString comm = d->localeComments.value(lang);
if (!comm.isEmpty())
return comm;
const int pos = lang.indexOf(QLatin1Char('_'));
if (pos != -1) {
// "pt_BR" not found? try just "pt"
const QString shortLang = lang.left(pos);
const QString commShort = d->localeComments.value(shortLang);
if (!commShort.isEmpty())
return commShort;
}
}
// Use the mimetype name as fallback
return d->name;
}
/*!
\property QMimeType::genericIconName
\brief the file name of a generic icon that represents the MIME type
This should be used if the icon returned by iconName() cannot be found on
the system. It is used for categories of similar types (like spreadsheets
or archives) that can use a common icon.
The freedesktop.org Icon Naming Specification lists a set of such icon names.
The icon name can be given to QIcon::fromTheme() in order to load the icon.
While this property was introduced in 5.10, the
corresponding accessor method has always been there.
*/
QString QMimeType::genericIconName() const
{
QMimeDatabasePrivate::instance()->loadGenericIcon(*d);
if (d->genericIconName.isEmpty()) {
// From the spec:
// If the generic icon name is empty (not specified by the mimetype definition)
// then the mimetype is used to generate the generic icon by using the top-level
// media type (e.g. "video" in "video/ogg") and appending "-x-generic"
// (i.e. "video-x-generic" in the previous example).
const QString group = name();
QStringRef groupRef(&group);
const int slashindex = groupRef.indexOf(QLatin1Char('/'));
if (slashindex != -1)
groupRef = groupRef.left(slashindex);
return groupRef + QLatin1String("-x-generic");
}
return d->genericIconName;
}
/*!
\property QMimeType::iconName
\brief the file name of an icon image that represents the MIME type
The icon name can be given to QIcon::fromTheme() in order to load the icon.
While this property was introduced in 5.10, the
corresponding accessor method has always been there.
*/
QString QMimeType::iconName() const
{
QMimeDatabasePrivate::instance()->loadIcon(*d);
if (d->iconName.isEmpty()) {
// Make default icon name from the mimetype name
d->iconName = name();
const int slashindex = d->iconName.indexOf(QLatin1Char('/'));
if (slashindex != -1)
d->iconName[slashindex] = QLatin1Char('-');
}
return d->iconName;
}
/*!
\property QMimeType::globPatterns
\brief the list of glob matching patterns
While this property was introduced in 5.10, the
corresponding accessor method has always been there.
*/
QStringList QMimeType::globPatterns() const
{
QMimeDatabasePrivate::instance()->loadMimeTypePrivate(*d);
return d->globPatterns;
}
/*!
\property QMimeType::parentMimeTypes
\brief the names of parent MIME types
A type is a subclass of another type if any instance of the first type is
also an instance of the second. For example, all image/svg+xml files are also
text/xml, text/plain and application/octet-stream files. Subclassing is about
the format, rather than the category of the data (for example, there is no
'generic spreadsheet' class that all spreadsheets inherit from).
Conversely, the parent mimetype of image/svg+xml is text/xml.
A mimetype can have multiple parents. For instance application/x-perl
has two parents: application/x-executable and text/plain. This makes
it possible to both execute perl scripts, and to open them in text editors.
While this property was introduced in 5.10, the
corresponding accessor method has always been there.
*/
QStringList QMimeType::parentMimeTypes() const
{
return QMimeDatabasePrivate::instance()->mimeParents(d->name);
}
static void collectParentMimeTypes(const QString &mime, QStringList &allParents)
{
const QStringList parents = QMimeDatabasePrivate::instance()->mimeParents(mime);
for (const QString &parent : parents) {
// I would use QSet, but since order matters I better not
if (!allParents.contains(parent))
allParents.append(parent);
}
// We want a breadth-first search, so that the least-specific parent (octet-stream) is last
// This means iterating twice, unfortunately.
for (const QString &parent : parents)
collectParentMimeTypes(parent, allParents);
}
/*!
\property QMimeType::allAncestors
\brief the names of direct and indirect parent MIME types
Return all the parent mimetypes of this mimetype, direct and indirect.
This includes the parent(s) of its parent(s), etc.
For instance, for image/svg+xml the list would be:
application/xml, text/plain, application/octet-stream.
Note that application/octet-stream is the ultimate parent for all types
of files (but not directories).
While this property was introduced in 5.10, the
corresponding accessor method has always been there.
*/
QStringList QMimeType::allAncestors() const
{
QStringList allParents;
collectParentMimeTypes(d->name, allParents);
return allParents;
}
/*!
\property QMimeType::aliases
\brief the list of aliases of this mimetype
For instance, for text/csv, the returned list would be:
text/x-csv, text/x-comma-separated-values.
Note that all QMimeType instances refer to proper mimetypes,
never to aliases directly.
The order of the aliases in the list is undefined.
While this property was introduced in 5.10, the
corresponding accessor method has always been there.
*/
QStringList QMimeType::aliases() const
{
return QMimeDatabasePrivate::instance()->listAliases(d->name);
}
/*!
\property QMimeType::suffixes
\brief the known suffixes for the MIME type
No leading dot is included, so for instance this would return "jpg", "jpeg" for image/jpeg.
While this property was introduced in 5.10, the
corresponding accessor method has always been there.
*/
QStringList QMimeType::suffixes() const
{
QMimeDatabasePrivate::instance()->loadMimeTypePrivate(*d);
QStringList result;
for (const QString &pattern : qAsConst(d->globPatterns)) {
// Not a simple suffix if it looks like: README or *. or *.* or *.JP*G or *.JP?
if (pattern.startsWith(QLatin1String("*.")) &&
pattern.length() > 2 &&
pattern.indexOf(QLatin1Char('*'), 2) < 0 && pattern.indexOf(QLatin1Char('?'), 2) < 0) {
const QString suffix = pattern.mid(2);
result.append(suffix);
}
}
return result;
}
/*!
\property QMimeType::preferredSuffix
\brief the preferred suffix for the MIME type
No leading dot is included, so for instance this would return "pdf" for application/pdf.
The return value can be empty, for mime types which do not have any suffixes associated.
While this property was introduced in 5.10, the
corresponding accessor method has always been there.
*/
QString QMimeType::preferredSuffix() const
{
if (isDefault()) // workaround for unwanted *.bin suffix for octet-stream, https://bugs.freedesktop.org/show_bug.cgi?id=101667, fixed upstream in 1.10
return QString();
const QStringList suffixList = suffixes();
return suffixList.isEmpty() ? QString() : suffixList.at(0);
}
/*!
\property QMimeType::filterString
\brief a filter string usable for a file dialog
While this property was introduced in 5.10, the
corresponding accessor method has always been there.
*/
QString QMimeType::filterString() const
{
QMimeDatabasePrivate::instance()->loadMimeTypePrivate(*d);
QString filter;
if (!d->globPatterns.empty()) {
filter += comment() + QLatin1String(" (");
for (int i = 0; i < d->globPatterns.size(); ++i) {
if (i != 0)
filter += QLatin1Char(' ');
filter += d->globPatterns.at(i);
}
filter += QLatin1Char(')');
}
return filter;
}
/*!
\fn bool QMimeType::inherits(const QString &mimeTypeName) const;
Returns \c true if this mimetype is \a mimeTypeName,
or inherits \a mimeTypeName (see parentMimeTypes()),
or \a mimeTypeName is an alias for this mimetype.
This method has been made invokable from QML since 5.10.
*/
bool QMimeType::inherits(const QString &mimeTypeName) const
{
if (d->name == mimeTypeName)
return true;
return QMimeDatabasePrivate::instance()->mimeInherits(d->name, mimeTypeName);
}
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, const QMimeType &mime)
{
QDebugStateSaver saver(debug);
if (!mime.isValid()) {
debug.nospace() << "QMimeType(invalid)";
} else {
debug.nospace() << "QMimeType(" << mime.name() << ")";
}
return debug;
}
#endif
QT_END_NAMESPACE
|
9c0d91eefd7ff298ca8e71f4325178eb0d4b15bd
|
0184e96e37298e01d7270afa64035ef26888dc22
|
/src/math/ltiUniformContinuousDistribution.cpp
|
e562f88ce65b5500cdd383ccd53e1457bb3c2c49
|
[] |
no_license
|
edwinV21/LTI-LIB2
|
8f938915cc9918f55618ac7e3213862dba2ecce1
|
458cb35eedc1c0d1758416b78c112ff226116ede
|
refs/heads/master
| 2021-01-16T21:07:49.394303
| 2017-12-04T23:51:27
| 2017-12-04T23:51:27
| 100,211,418
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,125
|
cpp
|
ltiUniformContinuousDistribution.cpp
|
/*
* Copyright (C) 2007
* Pablo Alvarado
*
* This file is part of the LTI-Computer Vision Library (LTI-Lib)
*
* The LTI-Lib is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* The LTI-Lib 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 the LTI-Lib; see the file LICENSE. If
* not, write to the Free Software Foundation, Inc., 59 Temple Place -
* Suite 330, Boston, MA 02111-1307, USA.
*/
/**
* \file ltiUniformContinuousDistribution.cpp
* Generate uniformly distributed random integers in a given interval.
* \author Pablo Alvarado
* \date 25.09.2007
*
* revisions ..: $Id: ltiUniformContinuousDistribution.cpp,v 1.1 2007-09-26 21:21:52 alvarado Exp $
*/
#include "ltiUniformContinuousDistribution.h"
#include "ltiFactory.h"
namespace lti {
// WARNING: this has to be in exactly one line: do not break it, or
// the scripts for automatic reference detection won't work.
_LTI_REGISTER_IN_FACTORY(univariateContinuousDistribution,uniformContinuousDistribution)
// --------------------------------------------------
// uniformContinuousDistribution::parameters
// --------------------------------------------------
// default constructor
uniformContinuousDistribution::parameters::parameters()
: univariateContinuousDistribution::parameters() {
min = 0.0;
max = 1.0;
}
// copy constructor
uniformContinuousDistribution::
parameters::parameters(const parameters& other)
: univariateContinuousDistribution::parameters() {
copy(other);
}
// destructor
uniformContinuousDistribution::parameters::~parameters() {
}
// copy member
uniformContinuousDistribution::parameters&
uniformContinuousDistribution::parameters::copy(const parameters& other) {
univariateContinuousDistribution::parameters::copy(other);
min = other.min;
max = other.max;
return *this;
}
// alias for copy method
uniformContinuousDistribution::parameters&
uniformContinuousDistribution::parameters::
operator=(const parameters& other) {
return copy(other);
}
// class name
const std::string& uniformContinuousDistribution::parameters::name() const {
_LTI_RETURN_CLASS_NAME
}
// clone method
uniformContinuousDistribution::parameters*
uniformContinuousDistribution::parameters::clone() const {
return new parameters(*this);
}
// new instance
uniformContinuousDistribution::parameters*
uniformContinuousDistribution::parameters::newInstance() const {
return new parameters();
}
/*
* Write the parameters in the given ioHandler
* @param handler the ioHandler to be used
* @param complete if true (the default) the enclosing begin/end will
* be also written, otherwise only the data block will be written.
* @return true if write was successful
*/
bool uniformContinuousDistribution::parameters::write(ioHandler& handler,
const bool complete) const {
bool b = true;
if (complete) {
b = handler.writeBegin();
}
if (b) {
lti::write(handler,"min",min);
lti::write(handler,"max",max);
}
b = b &&
univariateContinuousDistribution::parameters::write(handler,false);
if (complete) {
b = b && handler.writeEnd();
}
return b;
}
/*
* Read the parameters from the given ioHandler
* @param handler the ioHandler to be used
* @param complete if true (the default) the enclosing begin/end will
* be also read, otherwise only the data block will be read.
* @return true if read was successful
*/
bool uniformContinuousDistribution::parameters::read(ioHandler& handler,
const bool complete) {
bool b = true;
if (complete) {
b = handler.readBegin();
}
if (b) {
lti::read(handler,"min",min);
lti::read(handler,"max",max);
}
b = b && univariateContinuousDistribution::parameters::read(handler,false);
if (complete) {
b = b && handler.readEnd();
}
return b;
}
// --------------------------------------------------
// uniformContinuousDistribution
// --------------------------------------------------
// default constructor
uniformContinuousDistribution::uniformContinuousDistribution()
: univariateContinuousDistribution(),
minimum_(0.0),maximum_(0.0),
fminimum_(0.0),fmaximum_(0.0) {
// create an instance of the parameters with the default values
parameters defaultParameters;
// set the default parameters
setParameters(defaultParameters);
}
// default constructor
uniformContinuousDistribution::
uniformContinuousDistribution(const double tmin,const double tmax)
: univariateContinuousDistribution(),
minimum_(0.0),maximum_(0.0),
fminimum_(0.0),fmaximum_(0.0) {
// create an instance of the parameters with the default values
parameters defaultParameters;
defaultParameters.min=tmin;
defaultParameters.max=tmax;
// set the default parameters
setParameters(defaultParameters);
}
// default constructor
uniformContinuousDistribution::
uniformContinuousDistribution(const parameters& par)
: univariateContinuousDistribution(),
minimum_(0.0),maximum_(0.0),
fminimum_(0.0),fmaximum_(0.0) {
// set the given parameters
setParameters(par);
}
// copy constructor
uniformContinuousDistribution::
uniformContinuousDistribution(const uniformContinuousDistribution& other)
: univariateContinuousDistribution(),
minimum_(0.0),maximum_(0.0),
fminimum_(0.0),fmaximum_(0.0) {
copy(other);
}
// destructor
uniformContinuousDistribution::~uniformContinuousDistribution() {
}
// copy member
uniformContinuousDistribution&
uniformContinuousDistribution::
copy(const uniformContinuousDistribution& other) {
univariateContinuousDistribution::copy(other);
return (*this);
}
// alias for copy member
uniformContinuousDistribution& uniformContinuousDistribution::
operator=(const uniformContinuousDistribution& other) {
return (copy(other));
}
// class name
const std::string& uniformContinuousDistribution::name() const {
_LTI_RETURN_CLASS_NAME
}
// clone member
uniformContinuousDistribution* uniformContinuousDistribution::clone() const {
return new uniformContinuousDistribution(*this);
}
// create a new instance
uniformContinuousDistribution*
uniformContinuousDistribution::newInstance() const {
return new uniformContinuousDistribution();
}
// return parameters
const uniformContinuousDistribution::parameters&
uniformContinuousDistribution::getParameters() const {
const parameters* par =
dynamic_cast<const parameters*>(&functor::getParameters());
if(isNull(par)) {
throw invalidParametersException(name());
}
return *par;
}
bool uniformContinuousDistribution::updateParameters() {
if (univariateContinuousDistribution::updateParameters()) {
const parameters& par = getParameters();
if (par.min > par.max) {
setStatusString("Parameter min has to be lower than max.");
return false;
}
minimum_ = par.min;
maximum_ = par.max;
fminimum_ = static_cast<float>(par.min);
fmaximum_ = static_cast<float>(par.max);
delta_ = (maximum_ - minimum_)*dnorm_;
fdelta_ = static_cast<float>(delta_);
return true;
}
return false;
}
// -------------------------------------------------------------------
// The apply() member functions
// -------------------------------------------------------------------
// On place apply for type int!
bool uniformContinuousDistribution::apply(double& rnd) {
rnd = static_cast<double>(generator_->draw() * delta_) + minimum_;
return true;
}
// On place apply for type int!
double uniformContinuousDistribution::draw() {
return static_cast<double>(generator_->draw() * delta_) + minimum_;
}
// On place apply for type int!
double uniformContinuousDistribution::rand() {
// this is maybe the fastest way, although maybe not so correct as
// we are giving a small higher probability to the lowest
// generator_->max() % delta_ values of the distribution. We are
// going to assume that the intervall is relatively small.
return static_cast<double>(generator_->draw() * delta_) + minimum_;
}
// On place apply for type int!
bool uniformContinuousDistribution::apply(float& rnd) {
rnd = static_cast<float>(generator_->draw() * fdelta_) + fminimum_;
return true;
}
// On place apply for type int!
float uniformContinuousDistribution::fdraw() {
return static_cast<float>(generator_->draw() * fdelta_) + fminimum_;
}
// On place apply for type int!
float uniformContinuousDistribution::frand() {
// this is maybe the fastest way, although maybe not so correct as
// we are giving a small higher probability to the lowest
// generator_->max() % delta_ values of the distribution. We are
// going to assume that the intervall is relatively small.
return static_cast<float>(generator_->draw() * fdelta_) + fminimum_;
}
/*
* Virtual method to obtain the maximum possible number
* (inclusive) to be returned by this distribution
*/
double uniformContinuousDistribution::max() {
return maximum_;
}
/*
* Virtual method to obtain the minimum possible number
* (inclusive) to be returned by this distribution.
*/
double uniformContinuousDistribution::min() {
return minimum_;
}
}
|
34f1bdffba43d589d5bef57882a0f94f0bf2dccd
|
9bdffba3a8b84aca95c7907aa8e47a085b0ada8e
|
/src/main/simulator/hypercube/RendezVousPacket.cpp
|
aa73646a5d5e9485128036e4bdd35adc1a431b7c
|
[] |
no_license
|
alejandromarcu/quenas
|
9a8ca96c7d27299f894e33897ca60b107acba4b0
|
f2aad975f011f29d81584de2a708057ae86d3ec6
|
refs/heads/master
| 2021-01-17T06:24:30.125651
| 2016-06-18T21:51:30
| 2016-06-18T21:51:30
| 61,453,712
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,351
|
cpp
|
RendezVousPacket.cpp
|
#include <vector>
#include <iterator>
#include "RendezVousPacket.h"
#include "common.h"
#include "HCPacket.h"
#include "HypercubeControlLayer.h"
#include "Message.h"
#include "Units.h"
#include "Event.h"
#include "StateMachines.h"
#include "HypercubeNode.h"
namespace simulator {
namespace hypercube {
using namespace std;
using namespace simulator::hypercube::dataUnit;
using namespace simulator::message;
using namespace simulator::event;
const byte RendezVousRegister::TYPE = 1;
const byte RendezVousDeregister::TYPE = 2;
const byte RendezVousAddressSolve::TYPE = 3;
const byte RendezVousAddressLookup::TYPE = 4;
const byte RendezVousLookupTable::TYPE = 5;
const byte RendezVousLookupTableReceived::TYPE = 6;
int16 RendezVousLookupTable::globalId = 0;
//-------------------------------------------------------------------------
//------------------------< TRendezVousPacket >----------------------------
//-------------------------------------------------------------------------
/**
* @brief Create a base Rendez Vous Packet.
*
* @param typeAndFlags type of packet and its flags.
*/
TRendezVousPacket::TRendezVousPacket(byte typeAndFlags) : typeAndFlags(typeAndFlags)
{
}
/**
* @brief Create a packet from raw data,.
*
* @param data raw data to process.
* @param an instance of a TRendezVousPacket subclass.
*/
TRendezVousPacket *TRendezVousPacket::create(const VB &data)
{
byte type = data[0] & 0x1F;
TRendezVousPacket *packet;
switch (type) {
case RendezVousRegister::TYPE : packet = new RendezVousRegister(data); break;
case RendezVousDeregister::TYPE : packet = new RendezVousDeregister(data); break;
case RendezVousAddressSolve::TYPE : packet = new RendezVousAddressSolve(data); break;
case RendezVousAddressLookup::TYPE : packet = new RendezVousAddressLookup(data); break;
case RendezVousLookupTable::TYPE : packet = new RendezVousLookupTable(data); break;
case RendezVousLookupTableReceived::TYPE : packet = new RendezVousLookupTableReceived(data); break;
default: throw invalid_argument("Invalid rendez vous packet type: " + type);
}
return packet;
}
/**
* @brief Helper method to read an hypercube address from raw data.
*
* @param it iterator where the address will be read.
* @return an hypercube address.
*/
HypercubeAddress TRendezVousPacket::readHypercubeAddress(ConstItVB &it) const
{
byte aux[256];
byte addrBitLength = readByte(it);
byte addrLength = (addrBitLength + 7) / 8;
copy (it, it + addrLength, aux);
HypercubeAddress addr(aux, addrBitLength);
it += addrLength;
return addr;
}
/**
* @brief Get the packet data as a vector<byte>
*
* @return the packet data as a vector<byte>
*/
VB TRendezVousPacket::getData() const
{
VB data;
dumpTo(back_inserter(data));
return data;
}
/**
* @brief Get the specified flag (from 0 to 2 inclusive).
*
* @param n the flag to retrieve, from 0 to 2 inclusive
* @return the n flag (n from 0 to 2 inclusive)
*/
bool TRendezVousPacket::getFlag(int n) const
{
return (typeAndFlags & (0x80 >> n)) != 0;
}
/**
* @brief Set the specified flag (from 0 to 2 inclusive).
*
* @param n flag to set (from 0 to 2 inclusive).
* @param value value for the flag.
*/
void TRendezVousPacket::setFlag(int n, bool value)
{
if (value) typeAndFlags |= 0x80 >> n;
else typeAndFlags &= 0xFF - (0x80 >> n);
}
/**
* @brief Get the type of packet.
*
* @return the type of packet.
*/
byte TRendezVousPacket::getType() const
{
return typeAndFlags & 0x1F;
}
//-------------------------------------------------------------------------
//------------------------< RendezVousRegister >---------------------------
//-------------------------------------------------------------------------
/**
* @brief Create a packet from raw data.
*
* @param data data to read.
*/
RendezVousRegister::RendezVousRegister(const VB &data) : TRendezVousPacket(TYPE), universalAddress("")
{
ConstItVB it = data.begin();
byte aux[256];
typeAndFlags = readByte(it);
primaryAddress = readHypercubeAddress(it);
universalAddress = UniversalAddress(readString(it));
}
/**
* @brief Create a RV packet.
*
* @param primaryAddress hypercube address of the node to register.
* @param universalAddress universal address of the node to register.
*/
RendezVousRegister::RendezVousRegister(const HypercubeAddress &primaryAddress, const UniversalAddress &universalAddress)
: TRendezVousPacket(TYPE), primaryAddress(primaryAddress), universalAddress(universalAddress)
{
}
/**
* @brief Get the primary address of the registering node.
*
* @return the primary address of the registering node.
*/
HypercubeAddress RendezVousRegister::getPrimaryAddress() const
{
return primaryAddress;
}
/**
* @brief Get the universal address of the registering node.
*
* @return the universal address of the registering node.
*/
UniversalAddress RendezVousRegister::getUniversalAddress () const
{
return universalAddress;
}
/**
* @brief Dump the RV packet as raw data to the iterator.
*
* @param it iterator where data is dumped.
*/
void RendezVousRegister::dumpTo(BackItVB it) const
{
dumpByteTo(typeAndFlags, it);
dumpByteTo(primaryAddress.getBitLength(), it);
primaryAddress.dumpTo(it);
dumpStringTo(universalAddress.toString(), it);
}
//-------------------------------------------------------------------------
//-----------------------< RendezVousDeregister >--------------------------
//-------------------------------------------------------------------------
/**
* @brief Create a packet from raw data.
*
* @param data data to read.
*/
RendezVousDeregister::RendezVousDeregister(const VB &data) : TRendezVousPacket(TYPE), universalAddress("")
{
ConstItVB it = data.begin();
byte aux[256];
typeAndFlags = readByte(it);
primaryAddress = readHypercubeAddress(it);
universalAddress = UniversalAddress(readString(it));
}
/**
* @brief Create a RV packet.
*
* @param primaryAddress hypercube address of the node to deregister.
* @param universalAddress universal address of the node to deregister.
*/
RendezVousDeregister::RendezVousDeregister(const HypercubeAddress &primaryAddress, const UniversalAddress &universalAddress)
: TRendezVousPacket(TYPE), primaryAddress(primaryAddress), universalAddress(universalAddress)
{
}
/**
* @brief Get the primary address of the deregistering node.
*
* @return the primary address of the deregistering node.
*/
HypercubeAddress RendezVousDeregister::getPrimaryAddress() const
{
return primaryAddress;
}
/**
* @brief Get the universal address of the deregistering node.
*
* @return the universal address of the deregistering node.
*/
UniversalAddress RendezVousDeregister::getUniversalAddress () const
{
return universalAddress;
}
/**
* @brief Dump the RV packet as raw data to the iterator.
*
* @param it iterator where data is dumped.
*/
void RendezVousDeregister::dumpTo(BackItVB it) const
{
dumpByteTo(typeAndFlags, it);
dumpByteTo(primaryAddress.getBitLength(), it);
primaryAddress.dumpTo(it);
dumpStringTo(universalAddress.toString(), it);
}
//-------------------------------------------------------------------------
//----------------------< RendezVousAddressSolve >------------------------
//-------------------------------------------------------------------------
/**
* @brief Create a packet from raw data.
*
* @param data data to read.
*/
RendezVousAddressSolve::RendezVousAddressSolve(const VB &data) : TRendezVousPacket(TYPE), universalAddress("")
{
ConstItVB it = data.begin();
byte aux[256];
typeAndFlags = readByte(it);
universalAddress = UniversalAddress(readString(it));
}
/**
* @brief Create a RendezVousAddressSolve packet.
*
* @param universalAddress universal address to solve
*/
RendezVousAddressSolve::RendezVousAddressSolve(const UniversalAddress &universalAddress)
: TRendezVousPacket(TYPE), universalAddress(universalAddress)
{
}
/**
* @brief Get the universal address to solve.
*
* @return the universal address to solve.
*/
UniversalAddress RendezVousAddressSolve::getUniversalAddress () const
{
return universalAddress;
}
/**
* @brief Dump the RV packet as raw data to the iterator.
*
* @param it iterator where data is dumped.
*/
void RendezVousAddressSolve::dumpTo(BackItVB it) const
{
dumpByteTo(typeAndFlags, it);
dumpStringTo(universalAddress.toString(), it);
}
//-------------------------------------------------------------------------
//---------------------< RendezVousAddressLookup >-------------------------
//-------------------------------------------------------------------------
/**
* @brief Create a packet from raw data.
*
* @param data data to read.
*/
RendezVousAddressLookup::RendezVousAddressLookup(const VB &data) : TRendezVousPacket(TYPE), universalAddress("")
{
ConstItVB it = data.begin();
byte aux[256];
typeAndFlags = readByte(it);
primaryAddress = readHypercubeAddress(it);
universalAddress = UniversalAddress(readString(it));
}
/**
* @brief Create a RendezVousAddressLookup packet.
*
* @param primaryAddress hypercube address of the looked up node.
* @param universalAddress universal address of the looked up node.
* @param solved whether the address could be solved or not.
*/
RendezVousAddressLookup::RendezVousAddressLookup(const HypercubeAddress &primaryAddress,
const UniversalAddress &universalAddress, bool solved)
: TRendezVousPacket(TYPE), primaryAddress(primaryAddress), universalAddress(universalAddress)
{
setFlag(0, solved);
}
/**
* @brief Get the solved primaryy address.
*
* @return the solved primary address.
*/
HypercubeAddress RendezVousAddressLookup::getPrimaryAddress() const
{
return primaryAddress;
}
/**
* @brief Get the universal address looked up.
*
* @return the universal address looked up.
*/
UniversalAddress RendezVousAddressLookup::getUniversalAddress () const
{
return universalAddress;
}
/**
* @brief Return whether the addres could be solved.
*
* @return whether the addres could be solved.
*/
bool RendezVousAddressLookup::isSolved() const
{
return getFlag(0);
}
/**
* @brief Dump the RV packet as raw data to the iterator.
*
* @param it iterator where data is dumped.
*/
void RendezVousAddressLookup::dumpTo(BackItVB it) const
{
dumpByteTo(typeAndFlags, it);
dumpByteTo(primaryAddress.getBitLength(), it);
primaryAddress.dumpTo(it);
dumpStringTo(universalAddress.toString(), it);
}
//-------------------------------------------------------------------------
//-----------------------< RendezVousLookupTable >-------------------------
//-------------------------------------------------------------------------
/**
* @brief Create a packet from raw data.
*
* @param data data to read.
*/
RendezVousLookupTable::RendezVousLookupTable(const VB &data) : TRendezVousPacket(TYPE)
{
ConstItVB it = data.begin();
byte aux[256];
typeAndFlags = readByte(it);
id = readInt16(it);
int n = readInt16(it);
byte addrBitLength = readByte(it);
byte addrLength = (addrBitLength + 7) / 8;
for (int i = 0; i < n; i++) {
UniversalAddress u(readString(it));
copy (it, it + addrLength, aux);
HypercubeAddress p(aux, addrBitLength);
it += addrLength;
table.push_back(make_pair(p, u));
}
}
/**
* @brief Create a RendezVousLookupTable packet.
* It automatically generates an id that will be used to acknowledge it.
* Data from the lookupo table should be added with add method.
*/
RendezVousLookupTable::RendezVousLookupTable() : id(globalId++), TRendezVousPacket(TYPE)
{
}
/**
* @brief get the table contained in this packet.
*
* @return the table contained in this packet.
*/
const RendezVousLookupTable::TTABLE &RendezVousLookupTable::getTable() const
{
return table;
}
/**
* @brief Dump the RV packet as raw data to the iterator.
*
* @param it iterator where data is dumped.
*/
void RendezVousLookupTable::dumpTo(BackItVB it) const
{
dumpByteTo(typeAndFlags, it);
dumpInt16To(id, it);
dumpInt16To(table.size(), it);
byte bitLength = 0;
if (table.size() > 0) bitLength = table[0].first.getBitLength();
dumpByteTo(bitLength, it);
for (int i = 0; i < table.size(); i++) {
dumpStringTo(table[i].second.toString(), it);
table[i].first.dumpTo(it);
}
}
/**
* @brief Add an entry to the table in the packet.
*
* @param primaryAddress primary address in the new entry.
* @param universalAddress universal address in the new entry.
*/
void RendezVousLookupTable::add(const HypercubeAddress &primaryAddress, const UniversalAddress &universalAddress)
{
table.push_back(make_pair(primaryAddress, universalAddress));
}
/**
* @brief Get the identifier for this packet, used to acknowledge it.
*
* @return the identifier for this packet, used to acknowledge it.
*/
int16 RendezVousLookupTable::getId() const
{
return id;
}
//-------------------------------------------------------------------------
//-------------------< RendezVousLookupTableReceived >---------------------
//-------------------------------------------------------------------------
/**
* @brief Create a packet from raw data.
*
* @param data data to read.
*/
RendezVousLookupTableReceived::RendezVousLookupTableReceived(const VB &data) : TRendezVousPacket(TYPE)
{
ConstItVB it = data.begin();
typeAndFlags = readByte(it);
id = readInt16(it);
}
/**
* @brief Create a RendezVousLookupTableReceived packet.
*
* @param id id that is being acknowledged.
*/
RendezVousLookupTableReceived::RendezVousLookupTableReceived(int16 id) : id(id), TRendezVousPacket(TYPE)
{
}
/**
* @brief Dump the RV packet as raw data to the iterator.
*
* @param it iterator where data is dumped.
*/
void RendezVousLookupTableReceived::dumpTo(BackItVB it) const
{
dumpByteTo(typeAndFlags, it);
dumpInt16To(id, it);
}
/**
* @brief Get the acknowledged id.
*
* @return the acknowledged id.
*/
int16 RendezVousLookupTableReceived::getId() const
{
return id;
}
}
}
|
bd500284c248af829e1b85740e57e895f6877c9a
|
ab538bfad711372b66cb90c9eef24ab00ac2386b
|
/gba/src/turnipemu/log.cpp
|
9fcccb812b60dc5250a172eb61b4caeab2e50574
|
[
"Apache-2.0"
] |
permissive
|
theturboturnip/turnipemu
|
7ff8feb827237ea10b239ea4fdfa2e9316a424bb
|
e35560eda30e4a63d5ea7413f3f80b8a845fbbfe
|
refs/heads/master
| 2020-03-21T13:59:14.816159
| 2018-09-14T18:55:50
| 2018-09-14T18:55:50
| 138,635,937
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,294
|
cpp
|
log.cpp
|
#include "turnipemu/log.h"
#include <cstdio>
#include <cstring>
constexpr int TAG_WIDTH = 4;
char lastTag[TAG_WIDTH] = "";
constexpr int FULL_TAG_WIDTH = TAG_WIDTH + 2 + 1; // Tag Width with braces and following space
int indentLevel = 0;
void LogLineVarargs(const char* tag, const char* format, va_list argptr){
for (int i = 0; i < indentLevel; i++){
fprintf(stdout, "\t");
}
if (strcmp(tag, lastTag) == 0){
for (int i = 0; i < FULL_TAG_WIDTH; i++){
fprintf(stdout, " ");
}
}else{
fprintf(stdout, "[%-*.*s] ", TAG_WIDTH, TAG_WIDTH, tag);
strncpy(lastTag, tag, TAG_WIDTH);
}
vfprintf(stdout, format, argptr);
}
void TurnipEmu::LogLine(const char* tag, const char* format, ...){
va_list argptr;
va_start(argptr, format);
LogLineVarargs(tag, format, argptr);
va_end(argptr);
fprintf(stdout, "\n");
}
void TurnipEmu::LogLineOverwrite(const char* tag, const char* format, ...){
if (strcmp(tag, lastTag) == 0) fprintf(stdout, "\r");
va_list argptr;
va_start(argptr, format);
LogLineVarargs(tag, format, argptr);
va_end(argptr);
}
void TurnipEmu::Indent(){
indentLevel++;
}
void TurnipEmu::Unindent(){
if (indentLevel > 0) indentLevel--;
else{
indentLevel = 0; // Just in case
LogLine("WARN", "Tried to unindent the log when it was already 0!");
}
}
|
171810d1813ced3ac128aafb268dc684ac5fbb48
|
573b7f2b79b6fb8b21b40985f7639bc003b60f7e
|
/SDK/mtlb_nsvt_reticle_classes.h
|
bee5fdd8c2ff52499389aec5c8042b3f7f661ac9
|
[] |
no_license
|
AlexzDK/SquadSDK2021
|
8d4c29486922fed3ba8451680d823a04a7b7fc44
|
cdce732ad4713b6d7f668f8b9c39e160035efb34
|
refs/heads/main
| 2023-02-21T02:52:15.634663
| 2021-01-23T23:28:57
| 2021-01-23T23:28:57
| 332,328,796
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,007
|
h
|
mtlb_nsvt_reticle_classes.h
|
#pragma once
// Name: Squad, Version: 13-01-2021
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
/*!!HELPER_DEF!!*/
/*!!DEFINE!!*/
namespace UFT
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass mtlb_nsvt_reticle.mtlb_nsvt_reticle_C
// 0x0040 (FullSize[0x02A0] - InheritedSize[0x0260])
class Umtlb_nsvt_reticle_C : public USQVehicleViewWidget
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0260(0x0008) (ZeroConstructor, Transient, DuplicateTransient)
class UImage* Cracked_Screen; // 0x0268(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash)
class UImage* Image_1; // 0x0270(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash)
class UImage* MainReticle; // 0x0278(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash)
class UCanvasPanel* Unzoomed; // 0x0280(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash)
class ABP_MTLB_turret_NSV_C* NSVTurretRef; // 0x0288(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class UMaterialInstanceDynamic* ReticleMat; // 0x0290(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class ASQVehicleSeat* TurretRef; // 0x0298(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass mtlb_nsvt_reticle.mtlb_nsvt_reticle_C");
return ptr;
}
void Construct();
void UpdateTurretHealth();
void Tick(const struct FGeometry& MyGeometry, float InDeltaTime);
void UpdateZoomLevelReticle();
void ExecuteUbergraph_mtlb_nsvt_reticle(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
e35b5211d2bc353e80561943af38f6bfe8b602cb
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_1673486_1/C++/RafaelBrandao/pass_problem.cpp
|
c20aa9ab9088d0a6ebd4753734006f99bc55fd43
|
[] |
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
| 1,299
|
cpp
|
pass_problem.cpp
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
int cn;
double e[100010], p[100010];
int n,A,B;
int main() {
int cases;
scanf("%d",&cases);
while (cases--) {
scanf("%d%d",&A,&B);
double allSu = 1.0;
for (int i=0; i < A; ++i) {
e[i] = 0.0;
scanf("%lf",&p[i]);
allSu *= p[i];
}
double res = 0.0, t;
double prob = 1.0, probBad, su = 1.0;
double cost, costBad;
cost = B-A + 1;
res = allSu * cost;
cost = B-A + 1 + B + 1;
res += (1.0-allSu) * cost;
//printf("all su: %.2lf\n",res);
cost = 1 + B + 1;
res = min(res, cost);
for (int i=0; i < A; ++i) {
// fail at this char, but all the previous correct
//printf("Mistake on %d (su = %.2lf):\n",i,1.0-su);
if (i==0) prob = 1.0;
else prob = (1.0 - p[i]) * su + allSu;
cost = (A-i) + (B-i) + 1;
//printf(" %.2lf * cost(%.2lf) = %.2lf\n", prob,cost,prob*cost);
if (i) {
probBad = 1.0 - prob;
costBad = (A-i) + (B-i) + 1 + B + 1;
t = prob*cost + probBad*costBad;
//printf(" %.2lf * costBad(%.2lf) = %.2lf\n", probBad,costBad,probBad*costBad);
} else {
t = prob*cost;
}
res = min(res, t);
//printf("exp: %.2lf\n", t);
su *= p[i];
}
printf("Case #%d: %.10lf\n",++cn,res);
}
return 0;
}
|
e6a260e28c22cd150b88229a2f53fdeb75bbf8b5
|
abbdcd4ae84da6109eb1209052e0668e581b5be2
|
/MonitorIntensityAdjustment.ino
|
9a387a4d9973c6dfa40224f48099ff5c8538ca58
|
[] |
no_license
|
mkrumin/varia
|
5284244ae37fc48be50ca239e28716396d8fe8a5
|
fa8bc5f26f50a05323fef45bec7f54298c4cc9d1
|
refs/heads/master
| 2023-03-16T00:35:48.691435
| 2023-03-10T18:41:10
| 2023-03-10T18:41:10
| 191,590,652
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,189
|
ino
|
MonitorIntensityAdjustment.ino
|
/*
A sketch for adjusting the intensity of three screens
Useful for setting the intensity to a certain lavel
and (more importantly) equalizing it across the three screens.
Michael Krumin, May 2021
- Reads an analog input pin (the value can be controlled by a potentiometer)
- Calculates the On/Off durations
- Runs through a single cycle of On/Off on all three screens
The circuit (repeat three times for three monitors with different AO and AI channels:
- Potentiometer connected to analog pin 0 (1, 2).
Center pin of the potentiometer goes to the analog pin.
side pins of the potentiometer go to +5V and ground
- Monitor backlight control/override connected to a digital output pin, ground to ground.
NOTE: not using PWM output to be able to control the frequency
*/
// These constants won't change. They're used to give names to the pins used:
const int analogInPinLeft = A0; // Analog input pin that the potentiometer is attached to
const int digitalOutPinLeft = 13; // Digital output pin that the monitor backlight LED is attached to
const int analogInPinCenter = A1; // Analog input pin that the potentiometer is attached to
const int digitalOutPinCenter = 12; // Digital output pin that the monitor backlight LED is attached to
const int analogInPinRight = A2; // Analog input pin that the potentiometer is attached to
const int digitalOutPinRight = 11; // Digital output pin that the monitor backlight LED is attached to
int freq = 200; // Target frequency of PWM
int sensorValueLeft = 0; // value read from the pot
long durLeft = 0; // duration of left monitor ON
int sensorValueCenter = 0; // value read from the pot
long durCenter = 0; // duration of center monitor ON
int sensorValueRight = 0; // value read from the pot
long durRight = 0; // duration of right monitor ON
long cycleDuration = 0;
int firstPin = 0;
int secondPin = 0;
int thirdPin = 0;
long durFirst = 0;
long durSecond = 0;
long durThird = 0;
long waitFirst = 0;
long waitSecond = 0;
long waitThird = 0;
long waitEnd = 0;
void setup() {
// setting up digital channels to output and set them to LOW
pinMode(digitalOutPinLeft, OUTPUT);
pinMode(digitalOutPinCenter, OUTPUT);
pinMode(digitalOutPinRight, OUTPUT);
digitalWrite(digitalOutPinLeft, LOW);
digitalWrite(digitalOutPinCenter, LOW);
digitalWrite(digitalOutPinRight, LOW);
}
void loop() {
// read the analog in values:
sensorValueLeft = analogRead(analogInPinLeft);
sensorValueCenter = analogRead(analogInPinCenter);
sensorValueRight = analogRead(analogInPinRight);
// map the values to durations:
cycleDuration = round(1e6/freq); // microseconds
durLeft = map(sensorValueLeft, 0, 1023, 0, cycleDuration);
durCenter = map(sensorValueCenter, 0, 1023, 0, cycleDuration);
durRight = map(sensorValueRight, 0, 1023, 0, cycleDuration);
// complicated way to figure out which pins to switch off when
if (durLeft < durCenter){
if (durLeft < durRight){
firstPin = digitalOutPinLeft;
durFirst = durLeft;
if (durRight < durCenter){
secondPin = digitalOutPinRight;
durSecond = durRight;
thirdPin = digitalOutPinCenter;
durThird = durCenter;
}
else{
secondPin = digitalOutPinCenter;
durSecond = durCenter;
thirdPin = digitalOutPinRight;
durThird = durRight;
}
}
else{
firstPin = digitalOutPinRight;
durFirst = durRight;
secondPin = digitalOutPinLeft;
durSecond = durLeft;
thirdPin = digitalOutPinCenter;
durThird = durCenter;
}
}
else{
if (durCenter < durRight){
firstPin = digitalOutPinCenter;
durFirst = durCenter;
if (durRight < durLeft){
secondPin = digitalOutPinRight;
durSecond = durRight;
thirdPin = digitalOutPinLeft;
durThird = durLeft;
}
else{
secondPin = digitalOutPinLeft;
durSecond = durLeft;
thirdPin = digitalOutPinRight;
durThird = durRight;
}
}
else{
firstPin = digitalOutPinRight;
durFirst = durRight;
secondPin = digitalOutPinCenter;
durSecond = durCenter;
thirdPin = digitalOutPinLeft;
durThird = durLeft;
}
}
// calculating waiting times (currently assuming operations take no time)
// (for higher frequencies need to take the digital operation and calculation durations into account)
waitFirst = durFirst;
waitSecond = durSecond - durFirst;
waitThird = durThird - durSecond;
waitEnd = cycleDuration - durThird;
// Flip the outputs up, wait required time and flip them down:
digitalWrite(firstPin, HIGH);
digitalWrite(secondPin, HIGH);
digitalWrite(thirdPin, HIGH);
delayMicroseconds(waitFirst);
digitalWrite(firstPin, LOW);
delayMicroseconds(waitSecond);
digitalWrite(secondPin, LOW);
delayMicroseconds(waitThird);
digitalWrite(thirdPin, LOW);
// wait before the next loop
delayMicroseconds(waitEnd);
}
|
45117fc4ff80f64f30fc78820afb3b78b4103203
|
8ddff22e52da764f54db4091efcfbdafaa63b64d
|
/4/class_test/main.cpp
|
f52c297db58db98f04f28dcc75aab1ca23afd1c4
|
[] |
no_license
|
weilaidb/cpp.eg
|
b6b6f2941a7887c56d76939f80ce85c8cfed4785
|
b8ec49ddbd70abd04d1b3512943911d1e988562b
|
refs/heads/master
| 2021-01-10T01:36:35.788706
| 2016-01-29T17:22:45
| 2016-01-29T17:22:45
| 47,979,460
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,400
|
cpp
|
main.cpp
|
#include <iostream>
#include <cmath> // or math.h
#include <cstring> // for the strlen() function
#include <string>
#define ARRAY_SIZE(A) sizeof(A)/sizeof(A[0])
using namespace std;
void cpplus11_add_new_features()
{
//可不在大括号内包含任何东西,这将所有元素都设置为零
float balances[100] {};
}
void arraysize()
{
char bird[11] = "Mr. Cheeps";
char fish[] = "Bubbles";
//用引起的字符串隐藏地包含结尾的空字符,因此不显示包括空字符。
//通过C++键盘输入,将字符串读入到char字符串数组会自动加上空字符
}
void instr1_reading_more_than_one_string()
{
//cin使用空白(空格、制表符和换行符)来确定字符串的结束位置,这意味着cin在获取
//字符数组输入时只读取一个单词,读取该单词后,cin将该字符串放到数组中,并自动在结尾添加空字符。
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin >> name;
cout << "Enter your favorite dessert:\n";
cin >> dessert;
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
}
//读取一行
void getline()
{
const int ArSize = 20;
char name[ArSize];
cout << "Enter your name,here:\n";
cin.getline(name,20);
cout << "your name is:" << name << endl;
}
void instr2_read_more_than_one_word_with_getline()
{
//cin使用空白(空格、制表符和换行符)来确定字符串的结束位置,这意味着cin在获取
//cin.getline读取的是一行的内容了,最多是size -1的字符的长度
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin.getline(name,ArSize);
cout << "Enter your favorite dessert:\n";
cin.getline(dessert, ArSize);
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
}
void get()
{
//面向行的输入
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
// cout << "cin.get() is:" << cin.get();
// cout << "cin.get() is:" << cin.get();
// cout << "cin.get() is:" << cin.get();
// cout << "cin.get() is:" << cin.get();
// cout << "cin.get() is:" << cin.get();
cout << "Enter your name:\n";
cin.get(name,ArSize); //first line
cin.get();//read newline
cout << "Enter your favorite dessert:\n";
cin.get(dessert, ArSize); //read second line
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
}
void get_get()
{
//面向行的输入
//拼接方式, getline().getline();
//cin.get(name1,ArSize).get();//concatenate member functions
//cin.get()读取一个字符
//cin.getline(name,size) 读取一行内容,包括换行符
//cin.get(name,size)读取一行内容,不包括换行符
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "Enter your name:\n";
cin.get(name,ArSize).get(); //first line
cout << "Enter your favorite dessert:\n";
cin.get(dessert, ArSize).get(); //read second line
cout << "I have some delicious " << dessert;
cout << " for you, " << name << ".\n";
}
void null_line_problem()
{
//当getline或get读取空行时,
//当get(0(不是getline())读取空行后将设置失效位(failbit)。意味着接下来的输入被阻断,可通过以下命令来恢复输入。
cin.clear();
}
void instr_following_number_input_with_line_input(void)
{
//cin读取年份时,将回车键生成的换行符留在了输入队列中。后面的getline()看到换行符后,将认为是一个空行,并将一个空字赋给address数组。
//解决之道是,在读取地址之前先读取并丢弃换行符。
cout << "What year was your house built?\n";
int year;
(cin >> year).get();
// cin.get(); //or cin.get(ch);
cout << "What is its street address?\n";
char address[80];
cin.getline(address,sizeof(address));
cout << "Year built: " << year << endl;
cout << "Address : " << address << endl;
cout << "Done!\n";
}
void string_init()
{
char first_date[] = {"Le Chapon Dodu"};
char second_date[] {"The Elegant Plate"};
// string third_date = {"The Bread Bowl"};
// string fourth_date {"Hank's Fine Eats"};
string third_date = "The Bread Bowl";
string fourth_date = "Hank's Fine Eats";
}
void string_test(void)
{
string str;
cout << "Enter a string test:\n";
getline(cin,str);
cout << "get string result:" << str;
}
void string_other_type()
{
//wchar_t L
//char16_t u
//char32_t U
wchar_t title[] = L"Chief Astrogator";
// char16_t name[] = u"Felonia Ripova";
// char32_t car[] = U"Humber Super Snipe";
//c++ 11新增
// cout << R"(Jim "King" Tutt uses "\n" instead of endl.)" << endl;
}
int main()
{
// cpplus11_add_new_features();
// instr1_reading_more_than_one_string();
// getline();
// instr2_read_more_than_one_word_with_getline();
// get();
// null_line_problem();
// instr_following_number_input_with_line_input();
string_init();
// string_test();
string_other_type();
// unsigned int counts[10] = {};
// for(int i = 0; i < ARRAY_SIZE(counts); i++)
// {
// cout << i << ",counts[" << i << "]:" << counts[i] << endl;
// }
/*
0,counts[0]:0
1,counts[1]:0
2,counts[2]:0
3,counts[3]:0
4,counts[4]:0
5,counts[5]:0
6,counts[6]:0
7,counts[7]:0
8,counts[8]:0
9,counts[9]:0
*/
// char p[20] = "1234456567";
// cout << "len of p:" << strlen(p) << endl;
// double area;
// cout << "Enter the floor area, in square feet, of your home: ";
// cin >> area;
// double side;
// side = sqrt(area);
// cout << "That's the equivalent of a square " << side
// << " feet to the side." << endl;
// cout << "How fascinating!" << endl;
// int carrots;
// cout << "How many carrots do you have?" << endl;
// cin >> carrots;
// cout << "Here are tow more.";
// carrots = carrots * 2;
// //the next line concatenates output
// cout << "Now you have " << carrots << " carrots." << endl;
// cout << "Hello World!" << endl;
// cerr << "Here happens some err!" << endl;
// clog << "Record some logs" << endl;
return 0;
}
|
8f3efe6b8939552473289f79571266b38e758103
|
b32dc9c68715276f36ec455b90a602348d39522a
|
/src/source/class/input/Input.cpp
|
75ef825760b2dc9694d007b6f576a92040f80955
|
[] |
no_license
|
wicanr2/GameTest
|
3287432f7cb60323e0a61489aa515f660dac7d44
|
2ca9ac9401c75305bc86750e16d6bc56400f8814
|
refs/heads/master
| 2021-01-15T08:31:55.280976
| 2015-12-14T09:07:17
| 2015-12-14T09:07:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 151
|
cpp
|
Input.cpp
|
#include "class/input/Input.h"
Input::Input() {
keyboard=new KeyBoard();
mouse=new Mouse();
}
Input::~Input() {
delete keyboard;
delete mouse;
}
|
c330bcfc1912ae5fdc00ba29ecca07e9b77f2747
|
9f320d46e7fafb59ea4ae4a18fbcc082fee01c4f
|
/projet/testIRPTOWMAjuste/main.cpp
|
148947cd01c40500a73e0dfa1eb38a68ac178519
|
[] |
no_license
|
Machine223/INF1900
|
6464fbac0b1467a9fe809b317dadac10558bef59
|
3f33478677e3b034706fe0f63ec640bf07ead0a1
|
refs/heads/master
| 2020-04-25T10:50:24.049091
| 2019-06-01T18:31:35
| 2019-06-01T18:31:35
| 172,723,733
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,806
|
cpp
|
main.cpp
|
#define F_CPU 8000000
#include <avr/io.h>
#include <util/delay.h>
//#include "IRPT.h"
#include "clock.h"
#include "can.h"
#include "Memoire_24.h"
#include "uart.h"
void setPort(){
DDRB = 0xff; // PORT B est en mode sortie
DDRD = 0xff;
}
void ajustementPWM (uint8_t val) {
// // mise à un des sorties OC1A et OC1B sur comparaison
// // réussie en mode PWM 8 bits, phase correcte // et valeur de TOP fixe à 0xFF (mode #1 de la table 17-6
// TCCR1A |= (1<<WGM10) | (1<<COM1A1) | (1<<COM1B1) ; //pour mettre le signal mode PWM 8 bits, phase correcte
// TCCR1B |= (1<<CS11) ; //diviser lhorloge par 256 pr avoir 60hz pr la frequence
// OCR1A = 0xff * ratio;
// OCR1B = 0xff * ratio;
// // division d'horloge par 8 - implique une frequence de PWM fixe
// TCCR1C = 0;
TCCR1A=0;//reset the register
TCCR1B=0;//reset the register
TCCR1A=0b01010011;// fast pwm mode(WGM10 and WGM11 are 1)
TCCR1B=0b00011001;// no prescaler and WGM12 and WGM13 are 1
OCR1A=val;//control value from the formula
}
int main ()
{
UART uart;
setPort();
uint8_t valeurNumerique =0 ; // Valeur utiliser pour l'intensite lumineux de la photorésistance
for (;;) //Boucle infinie qui repete l'instruction suivante
{
for (int j=0; j< 200; ++j)
{
if (j%2==0)
ajustementPWM(100);
else
ajustementPWM(50);
for (int i=0; i< 200; ++i)
if ((can().lecture(7)>>2) <3){
PORTB= 0x01;
uart.MemoryToUart('s');
}
else {
PORTB= 0x00;
uart.MemoryToUart(valeurNumerique);
uart.MemoryToUart('e');
}
}
}
return 0;
}
|
9b15a88a9b94babc66257d998f86f7b78a860525
|
0960ed88a83fe845649976100d3dab7e24e94204
|
/glsh/GLSH_Text.cpp
|
a819b88cb3e4fbdd6ce06e770fc034a69055ed96
|
[] |
no_license
|
mmoussa/TypingCity
|
513e9b1290b24f99a9caa14f0961ff156557a6aa
|
cb36e5d05c1c08b1684fefa6b6486b483b9874da
|
refs/heads/master
| 2020-05-10T00:18:23.369725
| 2019-04-15T16:35:08
| 2019-04-15T16:35:08
| 181,526,889
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,043
|
cpp
|
GLSH_Text.cpp
|
#include "GLSH_Text.h"
#include "GLSH_Image.h"
#include "GLSH_Mesh.h"
#include "tinyxml2.h"
#include <iostream>
#include <vector>
namespace glsh {
Font::Font()
: mTex(0)
, mHeight(0)
, mWidth(0)
{
}
Font::~Font()
{
Unload();
}
void Font::Unload()
{
if (IsLoaded()) {
glDeleteTextures(1, &mTex);
mTex = 0;
mChars = std::vector<TexRect>();
mHeight = 0;
mWidth = 0;
}
}
bool Font::IsLoaded() const
{
return mTex != 0;
}
bool Font::Load(const std::string& name)
{
Unload();
std::cout << "Loading font " << name << std::endl;
std::string textureFilename = name + ".tga";
std::string metricsFilename = name + ".xml";
using namespace tinyxml2;
XMLDocument doc;
if (doc.LoadFile(metricsFilename.c_str()) != XML_NO_ERROR) {
std::cerr << "*** Failed to load " << metricsFilename << std::endl;
return false;
}
Image img;
if (!img.LoadTarga(textureFilename)) {
std::cerr << "*** Failed to load " << textureFilename << std::endl;
return false;
}
TextureSpace texSpace(img.getWidth(), img.getHeight());
XMLElement* root = doc.FirstChildElement("fontMetrics");
//std::cout << (void*)root << std::endl;
mChars.resize(128); // basic ASCII chars only
int maxHeight = 0;
int maxWidth = 0;
XMLElement* ch = root->FirstChildElement("character");
for ( ; ch; ch = ch->NextSiblingElement("character")) {
const char* keystr = ch->Attribute("key");
//std::cout << "char " << keystr << std::endl;
int key = std::atoi(keystr);
if (key < 0 || key >= (int)mChars.size()) {
std::cerr << "character key out of range: " << key << std::endl;
continue;
}
const char* xstr = ch->FirstChildElement("x")->GetText();
const char* ystr = ch->FirstChildElement("y")->GetText();
const char* wstr = ch->FirstChildElement("width")->GetText();
const char* hstr = ch->FirstChildElement("height")->GetText();
//std::cout << xstr << std::endl;
int x = std::atoi(xstr);
int y = std::atoi(ystr);
int w = std::atoi(wstr);
int h = std::atoi(hstr);
if (h > maxHeight) {
maxHeight = h;
}
if (w > maxWidth) {
maxWidth = w;
}
texSpace.getTexRect(x, y, w, h, &mChars[key]);
}
mHeight = (float)maxHeight;
mWidth = (float)maxWidth;
// create the texture
mTex = CreateTexture2D(img, false);
if (!mTex) {
std::cerr << "*** Failed to create font texture" << std::endl;
return false;
}
// yay
return true;
}
Font* CreateFont(const std::string& name)
{
Font* font = new Font;
font->Load(name);
return font;
}
TextBatch::TextBatch()
: mFont(NULL)
, mWidth(0)
, mHeight(0)
{
}
void TextBatch::Clear()
{
mFont = NULL;
mWidth = 0;
mHeight = 0;
mVerts.clear();
}
void TextBatch::SetText(const Font* font, const std::string& text, bool fixedWidth)
{
Clear();
if (font && font->IsLoaded()) {
mFont = font;
float x = 0;
float y = 0;
float maxX = 0; // used to figure out width
float fontHeight = font->getHeight();
float fontWidth = font->getWidth();
// line spacing
float lineSpacing = 0;
//float lineSpacing = 0.1f * fontHeight;
float dy = fontHeight + lineSpacing;
for (char c : text) {
if (c == '\n') {
x = 0;
y -= dy;
} else if (font->hasChar(c)) {
const TexRect& cRect = font->getCharRect(c);
float xOffset;
if (fixedWidth) {
// center this character
xOffset = std::floor(0.5f * (fontWidth - cRect.w));
} else {
xOffset = 0;
}
float x1 = x + xOffset;
float x2 = x1 + cRect.w;
float y1 = y;
float y2 = y1 - cRect.h;
mVerts.push_back(VPT(x1, y1, 0, cRect.uLeft, cRect.vTop)); // top-left
mVerts.push_back(VPT(x1, y2, 0, cRect.uLeft, cRect.vBottom)); // bottom-left
mVerts.push_back(VPT(x2, y2, 0, cRect.uRight, cRect.vBottom)); // bottom-right
mVerts.push_back(VPT(x2, y2, 0, cRect.uRight, cRect.vBottom)); // bottom-right
mVerts.push_back(VPT(x2, y1, 0, cRect.uRight, cRect.vTop)); // top-right
mVerts.push_back(VPT(x1, y1, 0, cRect.uLeft, cRect.vTop)); // top-left
if (fixedWidth) {
x += fontWidth;
} else {
x += cRect.w;
}
if (x > maxX) {
maxX = x;
}
}
mWidth = maxX;
mHeight = -(y - fontHeight);
}
}
}
void TextBatch::SetText(const Font* font, const std::vector<std::string>& textLines)
{
Clear();
if (font && font->IsLoaded()) {
mFont = font;
float x = 0;
float y = 0;
float maxX = 0; // used to figure out width
// line spacing
float fontHeight = font->getHeight();
//float lineSpacing = 0.1f * fontHeight;
float lineSpacing = 0;
float dy = fontHeight + lineSpacing;
for (unsigned i = 0; i < textLines.size(); i++) {
if (i > 0) {
y -= dy;
}
const std::string& text = textLines[i];
for (char c : text) {
if (c == '\n') {
x = 0;
y -= dy;
} else if (font->hasChar(c)) {
const TexRect& cRect = font->getCharRect(c);
mVerts.push_back(VPT(x, y, 0, cRect.uLeft, cRect.vTop)); // top-left
mVerts.push_back(VPT(x, y - cRect.h, 0, cRect.uLeft, cRect.vBottom)); // bottom-left
mVerts.push_back(VPT(x + cRect.w, y - cRect.h, 0, cRect.uRight, cRect.vBottom)); // bottom-right
mVerts.push_back(VPT(x + cRect.w, y - cRect.h, 0, cRect.uRight, cRect.vBottom)); // bottom-right
mVerts.push_back(VPT(x + cRect.w, y, 0, cRect.uRight, cRect.vTop)); // top-right
mVerts.push_back(VPT(x, y, 0, cRect.uLeft, cRect.vTop)); // top-left
x += cRect.w;
if (x > maxX) {
maxX = x;
}
}
mWidth = maxX;
mHeight = -(y - fontHeight);
}
}
}
}
void TextBatch::DrawGeometry() const
{
::glsh::DrawGeometry(GL_TRIANGLES, mVerts);
// FUTURE: could implement a retained mode
}
} // end of namespace
|
287a4ac94d22e7d7fba653bab0cd5f4d7cee88fb
|
15f0514701a78e12750f68ba09d68095172493ee
|
/C++/538.cpp
|
0c8a186864061b08f95de42593bb1b444512477e
|
[
"MIT"
] |
permissive
|
strengthen/LeetCode
|
5e38c8c9d3e8f27109b9124ae17ef8a4139a1518
|
3ffa6dcbeb787a6128641402081a4ff70093bb61
|
refs/heads/master
| 2022-12-04T21:35:17.872212
| 2022-11-30T06:23:24
| 2022-11-30T06:23:24
| 155,958,163
| 936
| 365
|
MIT
| 2021-11-15T04:02:45
| 2018-11-03T06:47:38
| null |
UTF-8
|
C++
| false
| false
| 1,792
|
cpp
|
538.cpp
|
__________________________________________________________________________________________________
sample 36 ms submission
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
std::ios_base::sync_with_stdio(false);
TreeNode* initialRoot{root};
std::stack<TreeNode*> st;
int sum = 0;
while (!st.empty() || root != nullptr) {
if (root != nullptr) {
st.push(root);
root = root->right;
} else {
root = st.top();
st.pop();
root->val = (sum += root->val);
root = root->left;
}
}
return initialRoot;
}
};
__________________________________________________________________________________________________
sample 23656 kb submission
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
static const auto _____ = []()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
int sum=0;
addlarger(root,sum);
return root;
}
void addlarger(TreeNode* root, int& sum){
if(!root) return;
addlarger(root->right,sum);
root->val+=sum;
sum=root->val;
addlarger(root->left,sum);
}
};
__________________________________________________________________________________________________
|
5bea4c640421d5ebff774ceb43473e24682eaea7
|
e2d5aff660791992599a58e3e644fd655439f706
|
/merge_sort.cpp
|
68d5762ff41bf70decc07b8202225c26658410f1
|
[] |
no_license
|
TirtharajSen01/Competititve-Programming
|
05a2e2f8118c56ff7a23a7ea0f10a1e24b44c9a8
|
441fa97a3469835d7adc1beb60a36cdfcf994de5
|
refs/heads/master
| 2023-05-13T12:14:03.968736
| 2021-06-11T12:57:28
| 2021-06-11T12:57:28
| 356,622,353
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,100
|
cpp
|
merge_sort.cpp
|
#include<bits/stdc++.h>
using namespace std;
void merge(int [], int , int , int , int);
void merge_sort(int a[] , int l , int h)
{
if(l<h)
{
int mid = (l+h)/2;
cout<<"l="<<l<<"mid="<<mid<<"h="<<h<<endl;
merge_sort(a, l , mid);
cout<<"After first"<<endl;
cout<<"l="<<l<<"mid="<<mid<<"h="<<h<<endl;
merge_sort(a , mid+1 , h);
cout<<"After second"<<endl;
cout<<"l="<<l<<"mid="<<mid<<"h="<<h<<endl;
merge(a , l, mid , mid+1 , h);
cout<<"After merge"<<endl;
cout<<"l="<<l<<"mid="<<mid<<"h="<<h<<endl;
}
}
void merge(int a[] , int l1 , int h1, int l2 , int h2)
{
cout<<"In the merge function"<<endl;
}
int main()
{
int n;
cout<<"Enter number of elements";
cin>>n;
int arr[n];
for(int i = 0 ; i <n ;i++)
cin>>arr[i];
cout<<"inside the main programme is starting here"<<endl;
merge_sort(arr , 0 , n-1);
cout<<"after the sorting again in the main at last of the programme"<<endl;
for(int i = 0 ; i< n ; i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
|
68ff1c9974163f32c038283c46225b834356ae8b
|
7fff3b37f0f17ea17aaff4aed8165ce2aee02271
|
/HDU/2047/9381715_AC_0ms_1940kB.cpp
|
b26e9c56a2a570146225f40555948d8a0d71fba0
|
[] |
no_license
|
onlyless/ACM
|
d17fc92b2ff94cdcf73811e9cfa58a1d544dc9ed
|
c6e90e75f0a73a232e574cd7f0c82c40180eb9a7
|
refs/heads/master
| 2021-01-21T11:36:18.808454
| 2017-08-31T15:37:31
| 2017-08-31T15:37:31
| 96,624,657
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 265
|
cpp
|
9381715_AC_0ms_1940kB.cpp
|
#include<iostream>
#include<cmath>
using namespace std;
using LL = long long;
int main()
{
int n=0;
LL A[41];
A[1] = 3;
A[2] = 8;
for (int i = 3; i <= 40; ++i) {
A[i] = 2 * (A[i - 1] + A[i - 2]);
}
while (cin >> n) {
cout << A[n] << endl;
}
return 0;
}
|
17448a88e9fabaadbe308e4e9abfc4d806a65ab4
|
8a4c9287668ee62fdc34e41440311d630fed3d71
|
/src/Espace.h
|
8c5a3ac1efcd50fbc378dab242a6bd6b6bdbcd88
|
[] |
no_license
|
ZiedSoua/AsteroideGAME
|
e523b064b2e92844372faca6ced6ab983342855a
|
c6afa89beaa16c6d5bbe1ea213c2bddc2ef155f5
|
refs/heads/master
| 2022-08-02T05:04:02.129616
| 2020-05-27T17:02:57
| 2020-05-27T17:02:57
| 267,377,622
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 650
|
h
|
Espace.h
|
/*
* Espace.h
*
* Created on: 15 mar. 2020
* Author: Zied
*/
#ifndef ESPACE_H_
#define ESPACE_H_
#include <SFML/Graphics.hpp>
#include <vector>
#include "ElementEspace.h"
class Espace {
public:
Espace();
void ajouter(std::unique_ptr<ElementEspace> element);
void actualiser();
void gererCollision();
void afficher(sf::RenderWindow& fenetre) const;
void nettoyer();
void vider();
inline bool estVide() const {return elements.empty() && aAjouter.empty();};
private :
std::vector<std::unique_ptr<ElementEspace>> elements{};
std::vector<std::unique_ptr<ElementEspace>> aAjouter{};
sf::Clock chrono{};
};
#endif /* ESPACE_H_ */
|
7014eaa937fefd91a67c445482f23d69874776a3
|
0f08276e557de8437759659970efc829a9cbc669
|
/problems/p387.h
|
f448363a4e3db0d921e28fa8bc6b4948f7b59022
|
[] |
no_license
|
petru-d/leetcode-solutions-reboot
|
4fb35a58435f18934b9fe7931e01dabcc9d05186
|
680dc63d24df4c0cc58fcad429135e90f7dfe8bd
|
refs/heads/master
| 2023-06-14T21:58:53.553870
| 2021-07-11T20:41:57
| 2021-07-11T20:41:57
| 250,795,996
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 864
|
h
|
p387.h
|
#pragma once
#include <algorithm>
#include <array>
#include <string>
namespace p387
{
class Solution
{
public:
int firstUniqChar(std::string s)
{
if (s.empty())
return -1;
std::array<int, 26> first_occ;
std::fill(first_occ.begin(), first_occ.end(), std::numeric_limits<int>::max());
for (size_t i = 0; i < s.size(); ++i)
{
if (first_occ[s[i] - 'a'] == std::numeric_limits<int>::max())
first_occ[s[i] - 'a'] = static_cast<int>(i);
else
first_occ[s[i] - 'a'] = std::numeric_limits<int>::max() - 1;
}
int res = *std::min_element(first_occ.begin(), first_occ.end());
return ((res == std::numeric_limits<int>::max() - 1) ? -1 : res);
}
};
}
|
9d854b08bde743ba655912505daf872d97c1882e
|
96429a7be74850a8da6c4bcfe5099ecbee346300
|
/SPOJ Coins.cpp
|
3f80ebac07fa680709fd6418e6af39d4d9f66162
|
[] |
no_license
|
OmarELRayes/Problem-Solving
|
d02656c673c633290785eec699e56d88165c6874
|
225ec40c29fa143d55c67666fd24ba664b407155
|
refs/heads/master
| 2021-07-11T07:54:49.915302
| 2017-10-14T00:44:05
| 2017-10-14T00:44:05
| 106,884,135
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 351
|
cpp
|
SPOJ Coins.cpp
|
#include <bits/stdc++.h>
using namespace std;
int n , memo[10000000];
long long dp(long long v){
if(v<1e7)
return memo[v];
return max(v,dp(v/2)+dp(v/3)+dp(v/4));
}
int main()
{
for(int i=1; i<=1e7; i++)
memo[i] = max(i,memo[i/2]+memo[i/3]+memo[i/4]);
while(cin >> n)
cout << dp(n) << endl;
}
|
31e16e42a5fb65ae3eaa574256a333ec8499decd
|
7c5c667d10f01f6cd0e87e6af53a720bd2502bc7
|
/src/杂/1.14dp/A.cpp
|
e9dda65e563eb4e5176f4e397054bf4f58679e66
|
[] |
no_license
|
xyiyy/icpc
|
3306c163a4fdefb190518435c09929194b3aeebc
|
852c53860759772faa052c32f329149f06078e77
|
refs/heads/master
| 2020-04-12T06:15:50.747975
| 2016-10-25T12:16:57
| 2016-10-25T12:16:57
| 40,187,486
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,475
|
cpp
|
A.cpp
|
#include<stdio.h>
#include<stdlib.h>
struct M {
int ban, pri;
} man[105][105];
int n, t, m[105];
double minbp;
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &m[i]);
for (int j = 0; j < m[i]; j++) {
scanf("%d%d", &man[i][j].ban, &man[i][j].pri);
}
}
minbp = 0;
int minPri;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m[i]; j++) {
int minBan = man[i][j].ban;
int sumPri = man[i][j].pri;
for (int k = 0; k < n; k++) {
if (k == i) {
continue;
}
minPri = 0x7FFFFFFF;
for (int l = 0; l < m[k]; l++) {
if (minBan <= man[k][l].ban && minPri > man[k][l].pri) {
minPri = man[k][l].pri;
}
}
if (minPri == 0x7FFFFFFF) {
break;
}
sumPri += minPri;
}
if (minPri == 0x7FFFFFFF) {
break;
}
if (minbp < (double) minBan / sumPri) {
minbp = (double) minBan / sumPri;
}
}
}
printf("%.3lf\n", minbp);
}
return 0;
}
|
e1af1781f9166e25655f997ca7afb879f79dc7d8
|
cb2df482dcebc7afc0ce9f157d5a84ff6a9898fe
|
/examples/popup.hpp
|
ec0b6c2163c31bd35e7ee452cfa96c9e606aa618
|
[] |
no_license
|
lunar-mining/darkrenaissance_tui
|
434eacccbd621f613f518075dc17e4577b135130
|
329d517851220b80a9246ffbb0ee090fb9d1db28
|
refs/heads/master
| 2022-12-08T10:38:57.859615
| 2020-09-04T10:11:29
| 2020-09-04T10:11:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 114
|
hpp
|
popup.hpp
|
class sendw;
class popup
{
public:
popup(sendw* sw);
void foo();
private:
sendw* sw_ = nullptr;
};
|
d4cc8d4fdd430f50e5694a591907ffea294b4b68
|
1b094be71df26f0f74222aa9e2a0a4aa3fdced4c
|
/Cirle Operations in C++/mainfile.cpp
|
2d2d020528bea2fd9995e6c9a8ac065d8347fa18
|
[] |
no_license
|
jaybhagwat/Cplusplus
|
f8136fd7f660b68df768364e62a7a1cf6fc9f196
|
b9c60c308bc0549a62ded3303a9fa6fa9537e437
|
refs/heads/master
| 2020-04-02T04:15:55.066064
| 2019-07-25T09:08:59
| 2019-07-25T09:08:59
| 154,008,607
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 682
|
cpp
|
mainfile.cpp
|
#include<iostream>
using namespace std;
#define pi 3.14
class Circle
{
private:
float radius;
public:
void Accept();
void Display();
void Area();
void Circumference();
};
void Circle :: Accept()
{
cout<<"Enter the radius of the circle"<<endl;
cin>>this->radius;
}
void Circle :: Display()
{
cout<<"Radius is = "<<radius;
}
void Circle :: Area()
{
float iret=0.0f;
iret=pi *( radius *radius);
cout<<"area of circle is :"<<iret<<endl;
}
void Circle :: Circumference()
{
float iret=0.0f;
iret=pi * radius *2;
cout<<"Circumference is:"<<iret<<endl;
}
int main()
{
Circle obj1;
obj1.Accept();
obj1.Display();
obj1.Area();
obj1.Circumference();
return 0;
}
|
c50ea4a3a208b1227912654a99c2555f78a15247
|
206b6a2c39de83820293f9574c6d37556dd2949f
|
/9252_ LSC 2/9252_ LSC 2/Source.cpp
|
af83ad14c93b8ee6c2af0f6533492f7ee75fff75
|
[] |
no_license
|
NOorYes/B-Algorithm
|
f4fdfce243d33af03a0805f6e703ea08b96dbe5b
|
283a1a6b221cd3fa7f531132de46646f5f0862ba
|
refs/heads/master
| 2021-01-11T23:42:07.463178
| 2017-03-08T14:28:41
| 2017-03-08T14:28:41
| 78,626,126
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,847
|
cpp
|
Source.cpp
|
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
char arr[1001];
char arr2[1001];
char temp[1001];
void LCS();
int main()
{
scanf("%s", &arr);
scanf("%s", &arr2);
LCS();
return 0;
}
void LCS()
{
int len = strlen(arr);
int len2 = strlen(arr2);
int result = 0; // 최종 길이
int dp[1001] = { 0, }; // LSC의 길이를 저장
int index[1001] = {-1, }; // 역추적을 위한 인덱스
int max_number = 0; // 가장 큰 숫자의 dp[]값
int max_index = 0; // 가장 큰 숫자의 인덱스
int count = 0;
//char arr_temp[1];
//char arr2_temp[1];
for (int i = 0; i < len; i++) {
//strcpy(arr_temp, &arr[i]);
max_number = 0;
max_index = 0;
for (int j = 0; j < len2; j++) {
//strcpy(arr2_temp, &arr2[j]);
if (j > 0)
{ //max_number = max(max_number, dp[j - 1]); // 가장 큰 값을 계속 갱신
if (dp[j - 1] >= max_number) { // 만약 맥스 넘버보다 dp[]가 더 크다면
max_number = dp[j - 1]; // 맥스 넘버를 dp[]로 바꾸고
max_index = (j - 1); // 맥스 인덱스를 [] 안의 값으로.
}
// 작다면 걍 그대로 가면 됨.
}
if (arr[i] == arr2[j]) { // 만약 일치한다면
dp[j] = max_number + 1; // 맥스 넘버 + 1의 값을 dp[] 에 저장하고,
index[j] = max_index; // 인덱스에 맥스 인덱스를 저장
}
}
}
if (dp[len - 1] < dp[len - 2]) { // 마지막 것이 적은데 중복된다면
dp[len - 1] = max(dp[len - 1], dp[len - 2]);
temp[len2] = arr2[len2 - 2];
}
else
{
temp[len2] = arr2[len2 - 1];
}
result = dp[len2 - 1];
for (int y = (len2 - 1); y>=0 ; y--) {
count = result - 1;
count--;
temp[y] = arr2[index[y]];
if (count == 0) { break; }
}
printf("%d\n", result);
for (int x = (len2 - result) + 1; x <= len2; x++)
printf("%c", temp[x]);
}
|
20d78f4ca532c97562f70fc874d4170c188df49e
|
64e7a0cf9d67467ee5d272ecddba9f79b75ccba5
|
/isnumbertest.cpp
|
7667f3b81f8ddece7f0cbb5e27952782225e13c3
|
[] |
no_license
|
Ruixuan/leetcode
|
736a406669ae486ace0edc6a59d8e5d21daf8eb9
|
ab63651adcc970b166eed68131cf27f40d5f6be9
|
refs/heads/master
| 2021-01-23T07:26:58.594731
| 2014-03-10T03:50:02
| 2014-03-10T03:50:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,154
|
cpp
|
isnumbertest.cpp
|
#include<iostream>
using namespace std;
bool isNumber( char *s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
char * pt;
int flag_start, flag_is_power, flag , number_flag , is_dot;
//first check start
is_dot = 0;
pt = &s[0];
number_flag = 0;
flag_is_power = 0;
// clean up white spaces
while(*pt != NULL && *pt == ' ') pt ++;
// check the chars
if (*pt == '+' || *pt == '-'){
pt ++;
if (*pt == NULL) return false;
}
if (*pt == 'e') return false;
is_dot = 0;
while(*pt != NULL){
if ( *pt>='0' && *pt<='9'){
number_flag = 1;
pt ++;
continue;
}
if (*pt == '.'){
if (is_dot == 0){
is_dot = 1;
pt ++;
continue;
}
}
if ( *pt == ' ' ){// this should be the end
while( *pt != NULL){
if ( *pt != ' ') return false;
pt ++;
}
return number_flag;
}
if ( *pt == 'e'){
if ( !number_flag) return false;
if ( flag_is_power) return false;
number_flag = 0;//reset the number flag
flag_is_power = 1;// set the power flag , make sure no more 'e's
pt ++;
if (*pt == '+' || *pt == '-'){
pt ++;
if (*pt == NULL) return false;
}
continue;
}
// other chars are illegal
return false;
}
return number_flag;
}
int main (){
char a[] = " 0.1 ";
cout<< isNumber(a) << endl;
system("pause");
}
|
a140534c5d8c2ff3e37b0d6d3fc86a21131d4a87
|
823d0ae092660edcec9a6d747c5ff49db6977986
|
/BST.h
|
1b91c625c7c47d86d44b4b9a93e5df1e79d5d013
|
[] |
no_license
|
shawheenattar/lab-10-dual-videogame
|
4d97f48c4cb024da9974a8927274720c83336454
|
14936dc210086f85edbcc9dfc2dfb1287bb6a53e
|
refs/heads/master
| 2020-04-21T11:09:43.423015
| 2019-02-07T03:16:01
| 2019-02-07T03:16:01
| 169,512,653
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,039
|
h
|
BST.h
|
//
// Created by Shawheen Attar on 4/21/18.
//
#ifndef PROJECT8_BST_H
#define PROJECT8_BST_H
#endif //PROJECT8_BST_H
#include <vector>
#include <string>
#include <cstdint>
using namespace std;
class BST {
class Node {
public:
int val;
string name;
Node *left;
Node *right;
Node *parent; // optional
Node(string el, int num) {
this->name = el;
this->val = num;
this->left = 0;
this->right = 0;
this->parent = 0;
}
~Node(){
delete left;
delete right;
}
};
Node *root;
//Node* findMin();
//Node* successor(Node *n);
public:
BST();
~BST(){
delete root;
}
// BST(BST &other)
// BST& operator=(BST &other)
void insert(string el, int num);
bool find(string el);
int outVal(string el);
int setVal(string el, int num);
// void remove(int el);
};
|
ed09c9d99835bf778b68ac06a8ac61b86fb61434
|
34f28d31439ef649e2c7aee38b3b32b2a038eea9
|
/user.h
|
3023acf39dd8ff3ecb25f61fb17ed4ec1deee9ca
|
[
"Apache-2.0"
] |
permissive
|
plewyllie/friendsvpn
|
f332675d138554a137ce10f5a1c6be3af3651bf3
|
925e853067b34bcef6af4acbe514fd54bacd230a
|
refs/heads/master
| 2020-04-12T10:33:04.214280
| 2017-11-13T13:12:33
| 2017-11-13T13:12:33
| 21,093,699
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 448
|
h
|
user.h
|
#ifndef USER_H
#define USER_H
#include <QObject>
#include <QSslCertificate>
#include <QSslKey>
/**
* @brief The User class represents a user of the system.
*/
class User : public QObject
{
Q_OBJECT
public:
const QString* uid;
const QString* ipv6;
const QSslCertificate* cert;
explicit User(QString* uid, QString* ipv6, QSslCertificate* cert, QObject *parent = 0);
~User();
signals:
public slots:
};
#endif // USER_H
|
04e7e151c34bf6bc3646811abf08dba5d99f905f
|
759838e85a8c98b5c35f3086a30a353d549a3016
|
/cme/pacmensl/src/SensFsp/SensDiscreteDistribution.cpp
|
67de016e8db4d7aeb44b5b919e4bf812d76eba0f
|
[] |
no_license
|
voduchuy/StMcmcCme
|
82fa2fc6aaa282a1a7d146245e8dde787c2380a7
|
4950cbb8aecff33d6ba5c7fb41785f9e43ae44f7
|
refs/heads/master
| 2023-06-24T14:55:15.518677
| 2021-07-28T17:07:18
| 2021-07-28T17:07:18
| 271,329,069
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,949
|
cpp
|
SensDiscreteDistribution.cpp
|
//
// Created by Huy Vo on 2019-06-28.
//
#include "SensDiscreteDistribution.h"
pacmensl::SensDiscreteDistribution::SensDiscreteDistribution() : DiscreteDistribution()
{
}
pacmensl::SensDiscreteDistribution::SensDiscreteDistribution(MPI_Comm comm,
double t,
const pacmensl::StateSetBase *state_set,
const Vec &p,
const std::vector<Vec> &dp) : DiscreteDistribution(comm,
t,
state_set,
p)
{
PacmenslErrorCode ierr;
dp_.resize(dp.size());
for (int i{0}; i < dp_.size(); ++i)
{
ierr = VecDuplicate(dp[i], &dp_[i]);
PACMENSLCHKERRTHROW(ierr);
ierr = VecCopy(dp.at(i), dp_.at(i));
PACMENSLCHKERRTHROW(ierr);
}
}
pacmensl::SensDiscreteDistribution::SensDiscreteDistribution(const pacmensl::SensDiscreteDistribution &dist)
: DiscreteDistribution(( const pacmensl::DiscreteDistribution & ) dist)
{
PacmenslErrorCode ierr;
dp_.resize(dist.dp_.size());
for (int i{0}; i < dp_.size(); ++i)
{
VecDuplicate(dist.dp_[i], &dp_[i]);
VecCopy(dist.dp_[i], dp_[i]);
}
}
pacmensl::SensDiscreteDistribution::SensDiscreteDistribution(pacmensl::SensDiscreteDistribution &&dist) noexcept
: DiscreteDistribution(( pacmensl::DiscreteDistribution && ) dist)
{
dp_ = std::move(dist.dp_);
}
pacmensl::SensDiscreteDistribution &pacmensl::SensDiscreteDistribution::operator=(const pacmensl::SensDiscreteDistribution &dist)
{
DiscreteDistribution::operator=(( const DiscreteDistribution & ) dist);
for (int i{0}; i < dp_.size(); ++i)
{
VecDestroy(&dp_[i]);
}
dp_.resize(dist.dp_.size());
for (int i{0}; i < dp_.size(); ++i)
{
VecDuplicate(dist.dp_[i], &dp_[i]);
VecCopy(dist.dp_[i], dp_[i]);
}
return *this;
}
pacmensl::SensDiscreteDistribution &pacmensl::SensDiscreteDistribution::operator=(pacmensl::SensDiscreteDistribution &&dist) noexcept
{
if (this != &dist)
{
DiscreteDistribution::operator=(( DiscreteDistribution && ) dist);
for (int i{0}; i < dp_.size(); ++i)
{
VecDestroy(&dp_[i]);
}
dp_ = std::move(dist.dp_);
}
return *this;
}
PacmenslErrorCode pacmensl::SensDiscreteDistribution::GetSensView(int is, int &num_states, double *&p)
{
int ierr;
if (is >= dp_.size()) return -1;
ierr = VecGetLocalSize(dp_[is], &num_states);
CHKERRQ(ierr);
ierr = VecGetArray(dp_[is], &p);
CHKERRQ(ierr);
return 0;
}
PacmenslErrorCode pacmensl::SensDiscreteDistribution::RestoreSensView(int is, double *&p)
{
PacmenslErrorCode ierr;
if (is >= dp_.size()) return -1;
if (p != nullptr)
{
ierr = VecRestoreArray(dp_[is], &p);
CHKERRQ(ierr);
}
return 0;
}
pacmensl::SensDiscreteDistribution::~SensDiscreteDistribution()
{
for (int i{0}; i < dp_.size(); ++i)
{
VecDestroy(&dp_[i]);
}
}
PacmenslErrorCode pacmensl::SensDiscreteDistribution::WeightedAverage(int is, int nout,
PetscReal *fout,
std::function<PacmenslErrorCode(int,
int *,
int,
PetscReal *,
void *)> weight_func,
void *wf_args)
{
PacmenslErrorCode ierr;
int num_local_states;
PetscReal* plocal;
if (is >= 0){
ierr = GetSensView(is, num_local_states, plocal); PACMENSLCHKERRQ(ierr);
}
else{
ierr = GetProbView(num_local_states, plocal); PACMENSLCHKERRQ(ierr);
}
for (int i = 0; i < nout; ++i)
{
fout[i] = 0.0;
}
PetscReal* wtmp = new PetscReal[nout];
for (int j = 0; j < num_local_states; ++j)
{
ierr = weight_func(states_.n_rows, states_.colptr(j), nout, wtmp, wf_args); PACMENSLCHKERRQ(ierr);
for (int i = 0; i < nout; ++i)
{
fout[i] += wtmp[i]*plocal[j];
}
}
ierr = MPI_Allreduce(MPI_IN_PLACE, fout, nout, MPIU_REAL, MPIU_SUM, comm_);
PACMENSLCHKERRQ(ierr);
delete[] wtmp;
return 0;
}
PacmenslErrorCode pacmensl::Compute1DSensMarginal(const pacmensl::SensDiscreteDistribution &dist,
int is,
int species,
arma::Col<PetscReal> &out)
{
if (is > dist.dp_.size()) PACMENSLCHKERRTHROW(-1);
arma::Col<PetscReal> md_on_proc;
// Find the max molecular count
int num_species = dist.states_.n_rows;
arma::Col<int> max_molecular_counts_on_proc(num_species);
arma::Col<int> max_molecular_counts(num_species);
max_molecular_counts_on_proc = arma::max(dist.states_, 1);
int ierr = MPI_Allreduce(&max_molecular_counts_on_proc[0],
&max_molecular_counts[0],
num_species,
MPI_INT,
MPI_MAX,
dist.comm_);
PACMENSLCHKERRTHROW(ierr);
md_on_proc.resize(max_molecular_counts(species) + 1);
md_on_proc.fill(0.0);
PetscReal *dp_dat;
VecGetArray(dist.dp_[is], &dp_dat);
for (int i{0}; i < dist.states_.n_cols; ++i)
{
md_on_proc(dist.states_(species, i)) += dp_dat[i];
}
VecRestoreArray(dist.dp_[is], &dp_dat);
if (out.is_empty()){
out.set_size(md_on_proc.size());
}
MPI_Allreduce(( void * ) md_on_proc.memptr(),
( void * ) out.memptr(),
md_on_proc.n_elem,
MPIU_REAL,
MPIU_SUM,
dist.comm_);
return 0;
}
PacmenslErrorCode pacmensl::ComputeFIM(SensDiscreteDistribution &dist, arma::Mat<PetscReal> &fim)
{
int ierr;
if (!fim.is_empty() && (fim.n_rows != dist.dp_.size() || fim.n_cols != dist.dp_.size())) return -1;
if (fim.is_empty())
{
fim.set_size(dist.dp_.size(), dist.dp_.size());
}
bool warn{false};
int num_par = dist.dp_.size();
for (int i = 0; i < num_par; ++i)
{
for (int j{0}; j <= i; ++j)
{
fim(i, j) = 0.0;
int num_states;
PetscReal *si;
PetscReal *sj;
PetscReal *p;
ierr = dist.GetProbView(num_states, p); PACMENSLCHKERRQ(ierr);
ierr = dist.GetSensView(i, num_states, si); PACMENSLCHKERRQ(ierr);
if (i!=j)
{
ierr = dist.GetSensView(j, num_states, sj); PACMENSLCHKERRQ(ierr);
}
else{
sj = si;
}
for (int k{0}; k < num_states; ++k)
{
if (p[k] < 1.0e-16)
{
p[k] = 1.0e-16;
warn = true;
}
fim(i, j) += si[k] * sj[k] / p[k];
}
dist.RestoreProbView(p);
dist.RestoreSensView(i, si);
if (i!=j)
{
dist.RestoreSensView(j, sj);
}
PetscReal tmp;
ierr = MPI_Allreduce((void*)(fim.colptr(j) + i), &tmp, 1, MPIU_REAL, MPIU_SUM, dist.comm_); PACMENSLCHKERRQ(ierr);
fim(i,j) = tmp;
}
}
for (int i = 0; i < num_par; ++i){
for (int j{i+1}; j < num_par; ++j){
fim(i, j) = fim(j, i);
}
}
if (warn) PetscPrintf(dist.comm_, "Warning: rounding was done in FIM computation.\n");
return 0;
}
|
5ec1ba03fab97674f4bb1c30239eb356957e720c
|
3a536104dfb32e40d5319edd02d614a911512273
|
/sht21.ino
|
d4107187c7923f820de5c330cd82fcdfff8280c2
|
[] |
no_license
|
coredump-ch/sht21-arduino
|
d2b3e0d77792211652a200b32a13fe64c1b578b5
|
95a0c09efcfd6441bca9919e19c29b5c9358ca10
|
refs/heads/master
| 2021-01-10T13:18:20.752286
| 2015-12-01T20:04:41
| 2015-12-01T20:04:41
| 47,149,876
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,730
|
ino
|
sht21.ino
|
/**
* Sensirion SHT21 humidity and temperature arduino example application.
*
* This is an example app that prints the relative humidity as well as the temperature
* every second to the serial port.
*
* Some Parts of this code are based on the SHT21 humidity and temperature sensor
* driver for Linux by Urs Fleisch.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <Wire.h>
const byte TEMPERATURE = 0xe3;
const byte HUMIDITY = 0xe5;
const byte INVALID_DATA = -300;
void setup() {
Wire.begin(); // join i2c bus as master
Serial.begin(9600); // start serial communication at 9600bps
}
void loop() {
Serial.println("Humidity is: " + getMeasurement(HUMIDITY));
Serial.println("Temperature is: " + getMeasurement(TEMPERATURE));
delay(1000);
}
long getMeasurement(byte type)
{
Wire.beginTransmission(0x40); // transmit to device 0x40 (SHT21)
Wire.write(type); // Trigger measurement based on the given type
Wire.endTransmission();
Wire.requestFrom(0x40, 3); // request 3 bytes from slave device
if (3 == Wire.available()) { // if three bytes were received
byte reading[] = {0,0,0};
reading[0] = Wire.read(); // First part of the measurement
reading[1] = Wire.read(); // Second part of the measurement
reading[2] = Wire.read(); // CRC checksum
if(isValidateCRC(reading, 2, reading[2])){
// Put the effective measured value together
u16 ticks = reading[0] << 8;
ticks |= reading[1];
// Calculate the
switch (type) {
case TEMPERATURE:
// Temparature in milli celsius
return ((21965 * long(ticks)) >> 13) - 46850;
case HUMIDITY:
// one-thousandths of a percent relative humidity
return (((15625 * long(ticks)) >> 13) - 6000);
}
}
}
return INVALID_DATA;
}
byte isValidateCRC(byte data[], byte nbrOfBytes, byte checksum)
{
byte crc = 0;
byte byteCtr;
for (byteCtr = 0; byteCtr < nbrOfBytes; ++byteCtr) {
crc ^= (data[byteCtr]);
for (byte bit = 8; bit > 0; --bit) {
if (crc & 0x80)
crc = (crc << 1) ^ 0x131;
else
crc = (crc << 1);
}
}
return crc == checksum;
}
|
3d60710db5d86af63feda1940a2cf5c58cd5d9e7
|
d83426fd82af6d34a3d3207f2d82239cbb8de471
|
/MultiscreenClient/request/http.h
|
47d51d4225bec2a006d507e478ae265ddebf5fc9
|
[] |
no_license
|
chenbaohai/multiScreenClient
|
6d266ab623f05f5ad38513c52efc7fbfaf78d689
|
fcb42ecd2dca86e3399ce37ed6498c73b944be49
|
refs/heads/master
| 2020-06-03T18:19:25.735320
| 2013-05-25T11:44:10
| 2013-05-25T11:44:10
| null | 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 1,020
|
h
|
http.h
|
#ifndef HTTP_H
#define HTTP_H
/** @file http.h
* @addtogroup Request_Library
* @{
*/
#include <QUrl>
#include <QByteArray>
#include <QMap>
#include <QStringList>
///·¢ËÍRESTÇëÇóµÄÀà
/** @class Http
*
*/
class Http
{
public:
Http();
// static bool get(QUrl url, QMap<QString, QString> data, QByteArray &result, QMap<QString, QString> cookies, int timeout = 1000);
static bool get(QUrl url, QByteArray data, QByteArray &result, QMap<QString, QString> cookies, int timeout = 30000);
// static bool post(QUrl url, QMap<QString, QString> data, QByteArray &result, QMap<QString, QString> cookies, int timeout = 1000);
static bool post(QUrl url, QByteArray data, QByteArray &result, QMap<QString, QString> cookies, int timeout = 30000);
private:
static QByteArray convertData(QMap<QString, QString> data);
static QByteArray convertRequest();
static bool send(QString host, int port, QByteArray data, QByteArray &result, int timeout = 30000);
};
/**
* @}
*/
#endif // HTTP_H
|
e2880cfab126b6bcbdaf0d2c987bf86ac447c1dc
|
53b898fe40133488b5bffe9996146efd1e06df51
|
/ati_netcanoem_ft_driver/src/configure_ati_can_ft_sensor.cpp
|
eda933a9eed91eb1f2341d529ad0d34a2764e33d
|
[] |
no_license
|
calderpg-tri/tri_hardware_drivers
|
63412dfbc82472572b9ad291519b2db9b5ebd259
|
c6f97989a26d879538fbb224dd9e638e0609a149
|
refs/heads/master
| 2023-07-08T06:42:29.052239
| 2022-08-06T04:11:26
| 2022-08-06T04:11:26
| 232,660,009
| 0
| 0
| null | 2020-01-27T19:07:07
| 2020-01-08T21:07:40
|
C++
|
UTF-8
|
C++
| false
| false
| 2,505
|
cpp
|
configure_ati_can_ft_sensor.cpp
|
#include <stdlib.h>
#include <stdio.h>
#include <memory>
#include <ati_netcanoem_ft_driver/ati_netcanoem_ft_driver.hpp>
int main(int argc, char** argv)
{
if (argc >= 5)
{
const std::string can_interface(argv[1]);
const uint8_t sensor_base_can_id
= static_cast<uint8_t>(std::atoi(argv[2]));
const uint8_t new_sensor_base_can_id
= static_cast<uint8_t>(std::atoi(argv[3]));
const uint8_t new_sensor_can_baud_rate_divisor
= static_cast<uint8_t>(std::atoi(argv[4]));
std::cout << "Connecting to ATI F/T sensor with CAN base ID "
<< sensor_base_can_id << " on socketcan interface "
<< can_interface << std::endl;
std::function<void(const std::string&)> logging_fn =
[] (const std::string& message)
{ std::cout << message << std::endl; };
ati_netcanoem_ft_driver::AtiNetCanOemInterface sensor(logging_fn,
can_interface,
sensor_base_can_id);
const std::string serial_num = sensor.ReadSerialNumber();
const auto firmware_version = sensor.ReadFirmwareVersion();
std::cout << "Connected to sensor with serial # " << serial_num
<< " and firmware version " << firmware_version.MajorVersion()
<< " (major version) " << firmware_version.MinorVersion()
<< " (minor version) " << firmware_version.BuildNumber()
<< " (build)" << std::endl;
std::cout << "Setting sensor CAN base ID to "
<< new_sensor_base_can_id << std::endl;
const bool set_base_can_id
= sensor.SetSensorBaseCanID(new_sensor_base_can_id);
if (set_base_can_id == false)
{
std::cerr << "Failed to set new CAN base ID" << std::endl;
return 1;
}
std::cout << "Setting sensor CAN baud rate divisor to "
<< new_sensor_can_baud_rate_divisor << std::endl;
const bool set_sensor_can_baud_rate_divisor
= sensor.SetSensorCanRate(new_sensor_can_baud_rate_divisor);
if (set_sensor_can_baud_rate_divisor == false)
{
std::cerr << "Failed to set new CAN baud rate divisor" << std::endl;
return 1;
}
std::cout << "New settings applied, power cycle sensor" << std::endl;
return 0;
}
else
{
std::cerr << "You must provide 4 arguments: <socketcan interface name>"
" <current sensor base can id> <new sensor base can id>"
" <new sensor can baud rate divisor>" << std::endl;
return -1;
}
}
|
deca8e7a527c856f99236d236136338286d78e69
|
e96140fe29ac734c9985ba8835b13a38deda8a23
|
/extension/test/gui-report/test-stream.cpp
|
925786305e3ffeace4d0a0e02967e46c113bcf0e
|
[
"MIT"
] |
permissive
|
fanzcsoft/wxExtension
|
33efbd379188584d6ef6a2a08fff07ed7fc3e374
|
e99bd2c83502fac64db0aece657a480d0352d2ba
|
refs/heads/master
| 2020-03-27T04:36:04.115835
| 2018-08-17T18:45:56
| 2018-08-17T18:45:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,482
|
cpp
|
test-stream.cpp
|
////////////////////////////////////////////////////////////////////////////////
// Name: test-stream.cpp
// Purpose: Implementation for wxExtension report unit testing
// Author: Anton van Wezenbeek
// Copyright: (c) 2017 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/extension/frd.h>
#include <wx/extension/report/stream.h>
#include "test.h"
TEST_CASE("wxExStreamToListView")
{
wxExTool tool(ID_TOOL_REPORT_FIND);
wxExListView* report = new wxExListView(wxExListViewData().Type(LIST_FIND));
AddPane(GetFrame(), report);
wxExFindReplaceData::Get()->SetFindString("xx");
REQUIRE(wxExStreamToListView::SetupTool(tool, GetFrame(), report));
wxExStreamToListView textFile(GetTestPath("test.h"), tool);
REQUIRE( textFile.RunTool());
REQUIRE(!textFile.GetStatistics().GetElements().GetItems().empty());
REQUIRE( textFile.RunTool()); // do the same test
REQUIRE(!textFile.GetStatistics().GetElements().GetItems().empty());
wxExStreamToListView textFile2(GetTestPath("test.h"), tool);
REQUIRE( textFile2.RunTool());
REQUIRE(!textFile2.GetStatistics().GetElements().GetItems().empty());
wxExTool tool3(ID_TOOL_REPORT_KEYWORD);
REQUIRE(wxExStreamToListView::SetupTool(tool3, GetFrame()));
wxExStreamToListView textFile3(GetTestPath("test.h"), tool3);
REQUIRE( textFile3.RunTool());
REQUIRE(!textFile3.GetStatistics().GetElements().GetItems().empty());
}
|
4751273746ef2d48a5cbdf945327cce64490a86d
|
8dcc3c662f87deeb861c1ae35071fc8c8f67b14b
|
/include/texture.h
|
2fd0faf7ad5fbdf7438a707a3f5b347dfc50bc76
|
[
"MIT"
] |
permissive
|
ECToo/knowledge
|
07c136b0ae4342ceafe48db8cf25c561c494247c
|
ed6a51b9c7a119f453acb8b1151cbf6aa43f3099
|
refs/heads/master
| 2020-03-30T05:24:56.011130
| 2009-10-28T00:40:15
| 2009-10-28T00:40:15
| 32,542,034
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,501
|
h
|
texture.h
|
/*
Copyright (c) 2008-2009 Rômulo Fernandes Machado <romulo@castorgroup.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef _TEXTURE_H
#define _TEXTURE_H
#include "prerequisites.h"
#include "vector2.h"
#include "logger.h"
namespace k
{
/**
* Texture coordinate types.
*/
enum TextureCoordType
{
TEXCOORD_NONE,
TEXCOORD_UV,
TEXCOORD_EYE_LINEAR,
TEXCOORD_SPHERE,
TEXCOORD_CUBEMAP,
TEXCOORD_POS,
TEXCOORD_NORMAL,
TEXCOORD_BINORMAL,
TEXCOORD_TANGENT
};
/**
* Ordering of cube textures.
*/
enum CubeTextureOrdering
{
CUBE_FRONT,
CUBE_BACK,
CUBE_LEFT,
CUBE_RIGHT,
CUBE_UP,
CUBE_DOWN
};
/**
* Texture flags
*/
enum TextureFlags
{
FLAG_REPEAT_S = 0,
FLAG_REPEAT_T,
FLAG_REPEAT_R,
FLAG_CLAMP_EDGE_S,
FLAG_CLAMP_EDGE_T,
FLAG_CLAMP_EDGE_R,
FLAG_CLAMP_S,
FLAG_CLAMP_T,
FLAG_CLAMP_R,
};
/**
* Texture formats
*/
enum TextureFormats
{
TEX_NONE,
TEX_RGB,
TEX_RGBA,
TEX_BGR,
TEX_BGRA,
TEX_WII_TPL,
TEX_WII_RGBA8,
TEX_MAX_FORMATS
};
/**
* \brief Holds a hardware texture or a collection of textures related to each other.
*/
class DLL_EXPORT texture
{
protected:
unsigned int mWidth;
unsigned int mHeight;
unsigned int mFormat;
unsigned int mFlags;
/**
* Platform specific texture pointer, used
* by the render library to bind textures.
*/
platformTexturePointer* mPointer;
/**
* Data allocated by texture library
* or read from file.
*/
void* mRawData;
/**
* Name of texture file. If this is a cubic
* texture.
*/
std::string mFilename;
public:
/**
* On each platform, it will load the right texture file and
* set its flags according.
*/
texture(const std::string& filename, int flags);
/**
* Start a texture made from the render system.
*/
texture(platformTexturePointer* ptr, unsigned int w, unsigned int h, int format)
{
kAssert(ptr);
mPointer = ptr;
mWidth = w;
mHeight = h;
mFormat = format;
}
/**
* Start a texture with data set already.
*/
texture(void* data, unsigned int w, unsigned int h, int flags, int format);
/**
* Must free pointers and raw data.
*/
~texture();
/**
* Needs platform specific implementations.
* Set the texture flags, in case you want to relate the texture
* with special effects or any other stuff you want ;)
*/
void setFlags(unsigned int flags);
/**
* Returns the texture flags.
*/
const unsigned int getFlags() const
{ return mFlags; }
/**
* Returns the texture pointer.
*/
platformTexturePointer* getPointer() const
{ return mPointer; }
/**
* Returns raw texture data (pixel data).
*/
void* getRaw() const
{ return mRawData; }
/**
* Returns the texture filename.
*/
const std::string& getFilename() const
{ return mFilename; }
/**
* Check if the texture contains data from the filename.
*/
const bool containsFilename(const std::string& filename) const
{
if (mFilename.find(filename) != std::string::npos)
return true;
else
return false;
}
/**
* Return texture format. @see TextureFormats
*/
unsigned int getFormat() const
{ return mFormat; }
/**
* Return texture width.
*/
unsigned int getWidth() const
{ return mWidth; }
/**
* Return texture height.
*/
unsigned int getHeight() const
{ return mHeight; }
};
}
#endif
|
d5a92d651ec6a3bf3935db22325d185a11f13e34
|
5daed89c7233c60c65ddfc5f4f2fc4df76d04b80
|
/detModel/Sections/PosXYZ.h
|
1069850ee898da6a32c259d640819ae408f32f40
|
[
"BSD-3-Clause"
] |
permissive
|
fermi-lat/detModel
|
19324d44b80dd48d35f03774c9bc7dc935f07792
|
fd8348a10adb75a669f0e4977448afc5e877f057
|
refs/heads/master
| 2022-03-06T02:35:04.483074
| 2019-08-27T17:29:28
| 2019-08-27T17:29:28
| 103,186,965
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 908
|
h
|
PosXYZ.h
|
#ifndef POSXYZ_H
#define POSXYZ_H
#include "detModel/Sections/SinglePos.h"
#include "detModel/Management/SectionsVisitor.h"
namespace detModel{
/**
* @author D.Favretto & R.Giannitrapani
*/
class PosXYZ :public SinglePos {
public:
/// A standard constructor
PosXYZ():SinglePos(),x(0),y(0),z(0){;}
/// A constructor with the coordinate of the positioned volume
PosXYZ(double x, double y, double z):SinglePos(),
x(x),y(y),z(z){;}
void Accept(SectionsVisitor* v);
virtual void AcceptNotRec(SectionsVisitor* v){v->visitPosXYZ(this);};
void setX(double pX){x=pX;}
void setY(double pY){y=pY;}
void setZ(double pZ){z=pZ;}
double getX()const{return x;}
double getY()const{return y;}
double getZ()const{return z;}
virtual void buildBB();
private:
double x;
double y;
double z;
};
}
#endif //POSXYZ_H
|
17f72fdff2fab33c5f09ef5ddc07326bf487a03d
|
c4eeec079bf08665e607a7409018986d0099c186
|
/BDゲーム/BDゲーム/ObjStage1Clear.h
|
5359fa2044d9eaf5653b55f40ad4e6a1d3130592
|
[] |
no_license
|
ze-ru/BD
|
17833847931f562adca3da8e37bc15c4222b5ac8
|
0a339fd2da15cbc310cda54ff8c382215ca81984
|
refs/heads/master
| 2020-08-14T18:32:53.669967
| 2020-02-14T01:21:26
| 2020-02-14T01:21:26
| 215,215,312
| 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 547
|
h
|
ObjStage1Clear.h
|
#pragma once
//使用ヘッダー
#include"GameL\SceneObjManager.h"
//使用するネームスペース
using namespace GameL;
//オブジェクト:STAGE CLEAR & SCORE
class CObjStage1Clear :public CObj
{
public:
CObjStage1Clear() {};
~CObjStage1Clear() {};
void Init(); //イニシャライズ
void Action(); //アクション
void Draw(); //ドロー
void SetScore(int s) { score += s; }//スコア関数
void Setdead() { deadflag = true; }
private:
bool key;//キーフラグ
int score;
bool deadflag;//BOSS撃破フラグ
};
|
150c7dcf4563177de5414e90aa9f2177ccbcc552
|
4303e53cd29789ea72facc801bcd6990b8507ca1
|
/espnow/multiple_master_slave/mMaster2/mMaster2.ino
|
6f35f6577287b576f7367716326c2716b4a9596e
|
[] |
no_license
|
DDlabAU/esp-boards
|
74232bd2bc7f342ba9fd87f535f6d2b057b44543
|
40c6f0053a3f5ae23b21c637d6e44e0588dfe1b5
|
refs/heads/master
| 2022-03-25T16:18:15.141727
| 2019-12-12T10:45:26
| 2019-12-12T10:45:26
| 68,092,430
| 0
| 0
| null | 2019-12-03T13:08:59
| 2016-09-13T09:03:51
|
JavaScript
|
UTF-8
|
C++
| false
| false
| 2,131
|
ino
|
mMaster2.ino
|
#include <ESP8266WiFi.h>
extern "C" {
#include <espnow.h>
}
int ledStatus = true;
uint8_t thisDevice = 5;
uint32_t runTimes = 0;
struct DATA_STRUCTURE {
uint16_t finger1;
uint16_t finger2;
uint16_t finger3;
uint16_t finger4;
uint16_t finger5;
uint8_t unit;
uint32_t times;
};
void setup () {
Serial.begin(115200);
if (esp_now_init()!=0){
Serial.println("Failed ESP_NOW INIT");
ESP.restart();
delay(1);
}
pinMode(LED_BUILTIN, OUTPUT);
Serial.print("Access Point (softAPmac) MAC of this ESP: "); Serial.println(WiFi.softAPmacAddress());
Serial.print("Station MAC (STA MAC) of this ESP: "); Serial.println(WiFi.macAddress());
esp_now_set_self_role(1);
uint8_t remoteMac[6] = {0x60, 0x01, 0x94, 0x51, 0xEC, 0xCE};
uint8_t role = 2;
uint8_t channel = 3;
uint8_t key[0]={};
uint8_t key_len = sizeof(key);
esp_now_add_peer(remoteMac,role,channel,key, key_len);
}
void loop () {
DATA_STRUCTURE DS;
// DS.primeData = 1000; //analogRead(A0);
// delay(20);
// DS.times = millis();
DS.finger1 = random(1023);
DS.finger2 = random(1023);
DS.finger3 = random(1023);
DS.finger4 = random(1023);
DS.finger5 = random(1023);
DS.unit = thisDevice;
runTimes += 1;
DS.times = runTimes;
// Sending data!!
//uint8_t *da = NULL // Sends data to all ESPs
uint8_t da[6] = {0x62, 0x01, 0x94, 0x51, 0xEC, 0xCE};
uint8_t data[sizeof(DS)]; memcpy(data, &DS, sizeof(DS));
uint8_t len = sizeof(data);
esp_now_send(da, data, len);
led();delay(100);led();
delay(1000); // increase value if data is lost
//did the slave receive the messages
esp_now_register_send_cb([](uint8_t* mac, uint8_t status) {
char MACslave[6];
sprintf(MACslave,"%02X:%02X:%02X:%02X:%02X:%02X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
Serial.print(". Sent to ESP MAC: "); Serial.print(MACslave);
Serial.print(". Recepcion (0=0K - 1=ERROR): "); Serial.println(status);
});
}
void led() {
ledStatus =! ledStatus;
digitalWrite(LED_BUILTIN, ledStatus);
delay(500);
}
|
c73bb248ccd9a64d20c9ba1101cb9477c4b619c6
|
9ab407b9090f7cc1b6f50a1092f7be6234d83560
|
/Nc/Core/Math/Box3D.h
|
038849f775c1232c579975697d3fad94c8bf9bdb
|
[] |
no_license
|
PoncinMatthieu/3dNovac
|
6e8e2b308d8de3c88df747fa838e97f8eb5315b2
|
fe634688a1b54792a89da9219ca5cda3cd81a871
|
refs/heads/dev
| 2020-05-27T01:30:28.047128
| 2013-12-06T17:15:18
| 2013-12-06T17:15:18
| 4,713,732
| 0
| 1
| null | 2015-10-07T12:58:41
| 2012-06-19T13:08:59
|
C++
|
UTF-8
|
C++
| false
| false
| 2,614
|
h
|
Box3D.h
|
/*-----------------------------------------------------------------------------
3dNovac Core
Copyright (C) 2010-2011, The 3dNovac Team
This file is part of 3dNovac.
3dNovac 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.
3dNovac 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 3dNovac. If not, see <http://www.gnu.org/licenses/>.
File Created At: 23/10/2010
File Author(s): Poncin Matthieu
-----------------------------------------------------------------------------*/
#ifndef NC_CORE_MATH_BOX3D_INCLUDED_H_
#define NC_CORE_MATH_BOX3D_INCLUDED_H_
#include "Box.h"
#include "Vector3D.h"
namespace Nc
{
namespace Math
{
/// To manipulate a box in 3 Dimension of type T.
template<typename T>
struct Box3D : public Box<T,3>
{
Box3D() : Box<T,3>() {}
template<typename U>
Box3D(const Box<U,3> &b) : Box<T,3>(b) {}
Box3D(const Vector3f &min, const Vector3f &max) : Box<T,3>(min, max) {}
Box3D(const T &xmin, const T &ymin, const T &zmin, const T &xmax, const T &ymax, const T &zmax);
template<typename U>
Box3D &operator = (const Box3D<U> &b);
static const Box3D<T> EmptyBox; ///< static const empty box.
};
template<typename T>
const Box3D<T> Box3D<T>::EmptyBox;
template<typename T>
Box3D<T>::Box3D(const T &xmin, const T &ymin, const T &zmin, const T &xmax, const T &ymax, const T &zmax)
{
Box<T,3>::_min.data[0] = xmin;
Box<T,3>::_max.data[0] = xmax;
Box<T,3>::_min.data[1] = ymin;
Box<T,3>::_max.data[1] = ymax;
Box<T,3>::_min.data[2] = zmin;
Box<T,3>::_max.data[2] = zmax;
}
template<typename T>
template<typename U>
Box3D<T> &Box3D<T>::operator = (const Box3D<U> &v)
{
static_cast<Box<T,3>*>(this)->operator=(static_cast<Box<T,3> >(v));
return *this;
}
}
}
#endif
|
c6563a5393394b7cf6546c507150cd0e286a2507
|
2ee816cb1336bb030ce4f9282c8bedd1ba3b46df
|
/ascii_read.cpp
|
b135efdd77fcd6b247bd9140626abb1d2c7cd7e3
|
[] |
no_license
|
ChaoticBlack/terminal_ascii_art
|
d4939199a511275f7aab1a88c3896315a1a600a1
|
ee762abd98520564be074804703218038152c733
|
refs/heads/master
| 2023-02-13T11:57:14.088117
| 2021-01-06T17:07:10
| 2021-01-06T17:07:10
| 326,901,114
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,610
|
cpp
|
ascii_read.cpp
|
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <bits/stdc++.h>
#include <array>
#include <map>
#include <regex>
#include <iterator>
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
void clearScreen(void) {
// Tested and working on Ubuntu and Cygwin
#if defined(OS_WIN)
HANDLE hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
if (hStdOut == INVALID_HANDLE_VALUE) return;
/* Get the number of cells in the current buffer */
GetConsoleScreenBufferInfo( hStdOut, &csbi );
cellCount = csbi.dwSize.X *csbi.dwSize.Y;
/* Fill the entire buffer with spaces */
FillConsoleOutputCharacter(hStdOut, (TCHAR) ' ', cellCount, homeCoords, &count);
/* Fill the entire buffer with the current colors and attributes */
FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, cellCount, homeCoords, &count);
SetConsoleCursorPosition( hStdOut, homeCoords );
#elif defined(OS_LINUX) || defined(OS_MAC)
cout << "\033[2J;" << "\033[1;1H"; // Clears screen and moves cursor to home pos on POSIX systems
#endif
}
int main()
{
char n;
cout<<"Select the pattern you want to see: Kaleidoscope or Liquid Fireworks"<<endl;
cout<<"Press 1 for Kaleidoscope, press 2 for Liquid Fireworks"<<endl;
cin>>n;
if(n=='1')
{
int i =0;
while(1)
{
string fileNumber = to_string(i);
string filename = "Kaleidoscope/"+fileNumber+".txt";
ifstream file(filename);
string word;
while(getline(file,word))
{
cout<<word<<endl;
}
usleep(100000);
clearScreen();
//i++;
if(i==30)
i=0;
i++;
}
}
else if(n== '2')
{
int i =0;
while(1)
{
string fileNumber = to_string(i);
string filename = "Liquid_Fireworks/"+fileNumber+".txt";
ifstream file(filename);
string word;
while(getline(file,word))
{
cout<<word<<endl;
}
usleep(100000);
clearScreen();
//i++;
if(i==37)
i=0;
i++;
}
}
else
cout<<"You Trickster, next time, please enter a valid input!"<<endl;
return 0;
}
// int i =0;
// while(1)
// {
// string fileNumber = to_string(i);
// string filename = "pattern/"+fileNumber+".txt";
// ifstream file(filename);
// string word;
// while(getline(file,word))
// {
// cout<<word<<endl;
// }
// usleep(100000);
// clearScreen();
// //i++;
// if(i==30)
// i=0;
// i++;
// }
//loop the folder to open each file
|
da0c0b1d59a8831b7fd32ace787445729013c7f9
|
5709541606b9aa80d57ef334a3adff5a2c5cabab
|
/src/File/Entity/FileEntity.h
|
4f6e762751554f70e0885648a92c2ee572ad8e2a
|
[] |
no_license
|
borutainfo/FileSearchEngine
|
427f2a580fa2e977e6e96ed764382de5742cb572
|
595deebaa7e33ceb04c3c05dde2109ec0bcea5db
|
refs/heads/master
| 2020-05-04T02:46:01.879589
| 2019-04-11T19:46:46
| 2019-04-11T19:46:46
| 178,934,023
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 900
|
h
|
FileEntity.h
|
#ifndef FILESEARCHENGINE_FILEENTITY_H
#define FILESEARCHENGINE_FILEENTITY_H
#include "File/ValueObject/FileName.h"
#include "File/ValueObject/FileContent.h"
/**
* @brief Entity for file storage in object way.
* @struct FileEntity
*/
class FileEntity {
protected:
FileName *fileName = nullptr;
FileContent *fileContent = nullptr;
public:
/**
* @brief Method returns FileName VO.
* @return FileName
*/
FileName *getFileName() const;
/**
* @brief Method sets FileName VO in entity.
* @param FileName *fileName
*/
void setFileName(FileName *fileName);
/**
* @brief Method returns FileContent VO.
* @return FileContent
*/
FileContent *getFileContent() const;
/**
* @brief Method sets FileContent VO in entity.
* @param FileContent *fileContent
*/
void setFileContent(FileContent *fileContent);
};
#endif
|
45a4d67d16c6b5ef86adcc367555ac7c59a7ed08
|
0fb33dbcb51cee03c58e1d8f2b63ed2609d3f971
|
/texted/inc/TXTEDSRC.H
|
eb62bec002d9510ff997acd3381149c2dd453d61
|
[] |
no_license
|
opl-dev/opl-dev
|
2e2166d06a05335ff2a5614beb8990e7aba5fb70
|
625c76115254ee4d2879a34b096c57385b083123
|
refs/heads/master
| 2020-03-16T23:04:51.912087
| 2018-05-11T16:28:34
| 2018-05-11T16:28:34
| 133,064,216
| 4
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 577
|
h
|
TXTEDSRC.H
|
// TXTEDSRC.H
//
// Copyright (c) 1997-2002 Symbian Ltd. All rights reserved.
#ifndef __TEXTSRC_H__
#define __TEXTSRC_H__
#ifndef __TEXTTRAN_H__
#include <texttran.h>
#endif
class CTextEdDocument;
class CApaProcess;
class CTextSource : public CBase , public MTextSource
{
public:
CTextSource(CTextEdDocument* aDoc,CApaProcess* aProcess); // aProcess=NULL if main document
~CTextSource();
TInt Read(TDes& aBuf,TInt aPos);
TInt Read(TDes& aBuf);
void Close(); // will "delete this"
private:
CTextEdDocument* iDoc;
CApaProcess* iProcess;
TInt iCurrentPos;
};
#endif
|
f64738cce57d5fd009539e219fe6109a2de35e8e
|
77d1b09e277b5078f315645751f184656c41bd03
|
/UI_0620/datastack.cpp
|
431e8ee7a9e0b9645e41e6bbf83174dd6aa95f7d
|
[] |
no_license
|
laiqiqi/MotorMeasurement
|
89c674bbf20ab3be76156f39c3060cb7827b92e5
|
853a63b20996de42a0e3c46f8cede7c1a9401e56
|
refs/heads/master
| 2021-12-09T23:25:55.196778
| 2016-06-28T07:37:17
| 2016-06-28T07:37:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 51
|
cpp
|
datastack.cpp
|
#include "datastack.h"
DataStack::DataStack()
{
}
|
da5bb543d5994cdb74c62fe8a8b795052c15bb4c
|
f1524807889ec9b1349e2860f7df6ead06bf42e0
|
/include/magpie/core/scene.hpp
|
17b5a3094f4339bee77ef96387fcaee48284eaf0
|
[
"MIT"
] |
permissive
|
acdemiralp/magpie
|
f120fc061aa8b6d0900bf8efe0a1218a1d87c0f6
|
adc6594784363278e06f1edb1868a72ca6c45612
|
refs/heads/master
| 2021-02-09T06:56:29.180938
| 2020-03-02T02:14:36
| 2020-03-02T02:14:36
| 244,254,660
| 4
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 728
|
hpp
|
scene.hpp
|
#ifndef MAKINA_CORE_SCENE_HPP
#define MAKINA_CORE_SCENE_HPP
#include <memory>
#include <vector>
#include <ec/entity.hpp>
#include <ec/scene.hpp>
#include <magpie/core/metadata.hpp>
#include <magpie/input/controller.hpp>
#include <magpie/graphics/projection.hpp>
#include <magpie/graphics/transform.hpp>
namespace mp
{
class behavior ;
using behaviors = std::vector<std::shared_ptr<behavior>>;
using entity = ec::entity<
// Common
metadata ,
transform ,
// Rendering
projection ,
// Scripting
behaviors ,
controller >;
using scene = ec::scene<entity>;
MAGPIE_EXPORT void append_scene(scene* source, scene* target);
MAGPIE_EXPORT void print_scene (const scene* scene);
}
#endif
|
88359778f833bf3575dd475f3257fc034f315cac
|
09db853490f551b11a50ac868bfc9a597aea28c0
|
/Lab_7/main.cpp
|
1e285c66558903b133b4e59d5aa5fd5948733bca
|
[] |
no_license
|
Xorsiphus/Algorithms-and-Data-Structures
|
3ca4e838050d3e2cc1b5ae3a4212e5e402c49a29
|
a9b74a73fb181d16e80725c16eafde30ac0cded5
|
refs/heads/master
| 2022-12-09T04:33:56.285680
| 2020-08-28T08:32:56
| 2020-08-28T08:32:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,346
|
cpp
|
main.cpp
|
#include <iostream>
#include <string>
#include "inputFunc.h"
#include "dfs.h"
#define MAX 999999999
using namespace std;
int main() {
int temp = NUMBER_ERROR;
string str;
while (temp == NUMBER_ERROR) {
cout << "Введите количество вершин: ";
cin >> str;
temp = Checker(str);
if (temp == NUMBER_ERROR) cout << "Некорректные данные\n";
}
vector<pair <int, int>> data[temp];
int wayLength[temp];
for (int i = 0; i < temp; i++)
wayLength[i] = MAX;
int size = temp;
int v = 0;
int u = 0;
getline(cin, str);
while (true){
cout << "Введите две вершины графа и длинну ребра для его создания(для выхода введите -1):\n";
temp = NUMBER_ERROR;
while (temp == NUMBER_ERROR || temp < 0 || temp > size) {
cout << "Первая вершина: ";
getline(cin, str);
temp = Checker(str);
if (temp == -1) break;
if (temp == NUMBER_ERROR || temp < 0 || temp > size)
cout << "Некорректные данные\n";
}
if (temp == -1) break;
v = temp - 1;
temp = NUMBER_ERROR;
while (temp == NUMBER_ERROR || temp < 0 || temp > size) {
cout << "Вторая вершина: ";
getline(cin, str);
temp = Checker(str);
if (temp == NUMBER_ERROR || temp < 0 || temp > size)
cout << "Некорректные данные\n";
}
u = temp - 1;
temp = NUMBER_ERROR;
while (temp == NUMBER_ERROR || temp < 0) {
cout << "Вес: ";
getline(cin, str);
temp = Checker(str);
if (temp == NUMBER_ERROR || temp < 0)
cout << "Некорректные данные\n";
}
data[v].emplace_back(u, temp);
}
wayLength[0] = 0;
dfs(data, wayLength, size, 0);
cout << "\nРасстояния до каждой из вершин от первой:\n";
for (int i = 0; i < size; i++)
if (wayLength[i] == MAX) cout << i+1 << ") Пути нет!\n";
else
cout << i + 1 << ") " << wayLength[i] << endl;
return 0;
}
|
d93b00dcf1bdeff51bf23886612b573d780c1440
|
5ada0481f57e7c5c3f791ed335260ada992360e8
|
/Parqueadero_interfaceWifi/Parker.ino
|
b3bda3d6682833344e4b4b24809e8f5b36b7276f
|
[] |
no_license
|
angelriosoberti/Parqueadero_estados_finitos
|
955a8c42bd161818a6b16135dfd29a2f69f3d93a
|
24ba184cad11a6d163e2f7da5bd9d9e486feb8fb
|
refs/heads/main
| 2023-03-06T22:08:45.295160
| 2021-02-16T21:57:14
| 2021-02-16T21:57:14
| 328,760,883
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,489
|
ino
|
Parker.ino
|
#include <Wire.h>
#include <LedControl.h>
#include <EEPROM.h>
//Los pines deben estar sipre conectados a puertos PWM
// DEBEN SER CONECTADOS EN PINES CON PWM EN EL NODEMCU ES 2,5,6 Y 7
int DIN = 12; //
int CLK = 11; //
int CS = 10; //
int estados[] = {8, 7, 6, 5, 4, 3, 2, 1};
int eco = 7;
int trig = 8;
int intensidad; // La intensidad es de luz de la matriz son 14 niveles
//Variables para el guardado en EPPROM
int distDeteccion_ino;
int distAlto_ino;
int adressDistDeteccion_ino=0;
int adressDistAlto_ino=100 ;
struct dataTransfer {
int txKyori;
};
struct dataRecived{
int distDeteccion_esp;
int distAlto_esp;
bool peticion ;
};
dataTransfer envio;
dataRecived recibe;
bool newTxData = false;
bool newRxData = false;
const byte arduiono_nano = 8; // arduiono nano
const byte ESP8266 = 9; //ESP8266
unsigned long prevUpdateTime = 0;
unsigned long updateInterval = 500;
int kyori;
int detector = 0;
int distancia ;
bool sync = false ;
LedControl lc = LedControl(DIN, CLK, CS, 1);
//funciones para la transmision
void madarData()
{
if (newTxData == true)
{
//inicia la transmision a otro dispositivo
Wire.beginTransmission(ESP8266);
Wire.write((byte *)&envio, sizeof(envio));
Wire.endTransmission();
/*
Serial.print("Sent ");
Serial.print(txData.textA);
Serial.print(' ');
Serial.print(txData.valA);
Serial.print(' ');
Serial.println(txData.valB);*/
newTxData = false;
}
}
void receiveEvent(int numBytesReceived)
{
if (newRxData == false)
{
// copy the data to rxData
Wire.readBytes((byte *)&recibe, numBytesReceived);
EEPROM.put(adressDistAlto_ino,recibe.distAlto_esp);
EEPROM.put(adressDistDeteccion_ino,recibe.distDeteccion_esp);
sync = recibe.peticion;
newRxData = true;
}
}
// en esta funcion asigno los valores a
void updateDataToSend()
{
if (millis() - prevUpdateTime >= updateInterval)
{
prevUpdateTime = millis();
if (newTxData == false)
{ // ensure previous message has been sent
envio.txKyori= kyori;
newTxData = true;
}
}
}
int lumen()
{
// tomo lectura de un puerto analogico
int lecturaLuz = analogRead(A2);
int luzLevel; // este numero debe ser entre 1 y 14
// dividor de voltaje vcc a cupula y a tierra 330R
luzLevel = map(lecturaLuz, 0, 900, 3, 14);
return luzLevel;
}
void matrixDraw(int columna)
{
if (columna >= 9)
{
Serial.print("ALERTA PROBLEMA DE CARGADO DE ILAS EXCESIVAS");
}
else
{
for (int fila = 0; fila < 8; fila++)
{
for (int row = 0; row < columna; row++)
{
lc.setLed(0, fila, row, true);
delay(1);
}
}
}
}
int distancia_cm()
{
float duracion;
float large;
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duracion = pulseIn(eco, HIGH);
large = duracion / 58.2;
delay(100);
return large;
}
void lighSignal(int d)
{
int indice;
int dot;
int dist;
dist = d - distAlto_ino;
dot = distDeteccion_ino / 8;
indice = dist / dot;
Serial.print(indice);
if (indice > 7)
{
// no se muestra nada
lc.clearDisplay(0);
}
else
{
matrixDraw(estados[indice]);
}
}
void operacion(){
distancia = distancia_cm();
/* Serial.print("distancia:");
Serial.println(distancia);*/
//regula intensidad de luz de la matrix
intensidad = lumen(); // intensidad tomara un valor del 3 al 14
lc.setIntensity(0, intensidad);
// obtenemos la distancia y la guardamos en variable kyori
kyori = distancia - distAlto_ino;
if (distancia <= distDeteccion_ino && distancia >= distAlto_ino + 20)
{
detector = 1;
Serial.println("DETECTADO");
}
if (detector == 1)
{
if (kyori <= distAlto_ino)
{
Serial.println("PARKING");
matrixDraw(8);
delay(10000);
lc.clearDisplay(0);
detector = 0;
sync = false;
}
else
{
Serial.print("MIDIENDO d=");
Serial.println(kyori);
lighSignal(distancia);
delay(350);
lc.clearDisplay(0);
}
}
else
{
Serial.print("Modo sleep");
}
}
void setup()
{
Serial.begin(9600);
lc.shutdown(0, false);
lc.clearDisplay(0);
pinMode(trig, OUTPUT);
pinMode(eco, INPUT);
Wire.begin(arduiono_nano);
// Cuando el Maestro le hace una petición,realiza el requestEvent
Wire.onRequest(receiveEvent);
}
void loop()
{
if (newRxData == true)
{
newRxData = false;
}
operacion();
updateDataToSend();
if(sync = true){
madarData();
}
}
|
72c3c0d2420f63affec24254c4dbf44eb21e503b
|
1a8331d4d2220a5c37232f766b726d0429622cfb
|
/google-codejam/2015/gcj_r2_c.cpp
|
5e1a81b759f69fffc817a3715a807b7af4de5b37
|
[] |
no_license
|
ngthanhvinh/competitive-programming
|
90918dda51b7020348d2c63b68320a52702eba47
|
cad90ac623e362d54df9a7d71c317de555d35080
|
refs/heads/master
| 2022-04-21T07:02:07.239086
| 2020-04-18T08:05:59
| 2020-04-18T08:05:59
| 176,119,804
| 0
| 1
| null | 2020-04-18T08:06:01
| 2019-03-17T15:19:38
|
Roff
|
UTF-8
|
C++
| false
| false
| 2,250
|
cpp
|
gcj_r2_c.cpp
|
#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9 + 7;
struct Dinic {
int n; int s; int t;
struct edge {
int u; int v; int c; int f;
edge(int u=0, int v=0, int c=0, int f=0): u(u), v(v), c(c), f(f) {}
};
vector<edge> e;
vector< vector<int> > G;
Dinic(int n=0, int s=0, int t=0): n(n), s(s), t(t) { G.assign(n + 1, vector<int>()); }
void add(int u, int v, int c) {
G[u].push_back(e.size()); e.push_back(edge(u, v, c, 0));
G[v].push_back(e.size()); e.push_back(edge(v, u, 0, 0));
}
vector<int> d, hd, ptr;
bool bfs() {
d.assign(n + 1, -1); hd.assign(n + 1, -1); ptr.assign(n + 1, 0); queue<int> q;
d[s] = 0; q.push(s);
while(!q.empty()) {
int u = q.front(); q.pop();
for (int id : G[u]) if (e[id].c > e[id].f && d[e[id].v] == -1) {
d[e[id].v] = d[u] + 1; hd[e[id].v] = id; q.push(e[id].v);
}
}
return d[t] != -1;
}
int dfs(int u, int fl) {
if (u == t || !fl) return fl;
for (int &i = ptr[u]; i < (int)G[u].size(); ++i) {
int id = G[u][i];
if (d[e[id].v] != d[u] + 1 || e[id].f >= e[id].c) continue;
int nxt = dfs(e[id].v, min(fl, e[id].c - e[id].f));
if (nxt) {
e[id].f += nxt; e[id ^ 1].f -= nxt;
return nxt;
}
}
return 0;
}
int maxFlow() {
int res = 0;
while(bfs()) while(dfs(s, inf));
for (int id : G[s]) res += e[id].f;
return res;
}
} mf;
const int N = 205;
int n;
string s;
map <string, int> mp;
vector <int> G[6010];
int nWords;
int solve() {
cin >> n; nWords = 0;
mp.clear(); cin.ignore();
for (int i = 1; i <= n; ++i) {
getline(cin, s); s += ' '; string tmp = "";
for (int j = 0; j < (int)s.size(); ++j) {
if (s[j] == ' ') {
if (!mp.count(tmp)) mp[tmp] = ++nWords;
G[mp[tmp]].push_back(i); tmp = "";
} else tmp += s[j];
}
}
int tot = n;
tot = n + nWords * 2;
int s = 1, t = 2;
mf = Dinic(tot, s, t);
for (int i = 1; i <= nWords; ++i) {
mf.add(n + 2 * i - 1, n + 2 * i, 1);
for (int u : G[i]) {
mf.add(u, n + 2 * i - 1, inf);
mf.add(n + 2 * i, u, inf);
}
}
for (int i = 1; i <= nWords; ++i) G[i].clear();
return mf.maxFlow();
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
int tt; cin >> tt;
for (int it = 1; it <= tt; ++it) {
printf("Case #%d: %d\n", it, solve());
}
}
|
ad1faedd80170c9320e26378eed43b8caa9fc57b
|
5f24784f6bae58f2e15809819e485ca5442c8377
|
/ch07/ProgressBar/ProgressBar.cpp
|
ee0ddadc98e3eaa5a489ab0e82dc22a479a7f982
|
[] |
no_license
|
farukshin/qt_edu
|
a2a7a18efc3ff56cba5c4609f502c44dde036f86
|
46d7e9a4d117676bc8a1551d83a7d507233a3aee
|
refs/heads/master
| 2023-01-31T13:05:51.165064
| 2020-10-10T18:08:00
| 2020-10-10T18:08:00
| 263,385,997
| 8
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 846
|
cpp
|
ProgressBar.cpp
|
#include <QtWidgets>
#include <ProgressBar.h>
ProgressBar::ProgressBar(QWidget* pwgt/*=0*/)
:QWidget(pwgt)
, m_nStep(0)
{
m_pprb = new QProgressBar;
m_pprb->setRange(0, 5);
m_pprb->setMinimumWidth(200);
m_pprb->setAlignment(Qt::AlignCenter);
QPushButton* pcmdStep = new QPushButton("&Step");
QPushButton* pcmdReset = new QPushButton("&Reset");
QObject::connect(pcmdStep, SIGNAL(clicked()), SLOT(slotStep()));
QObject::connect(pcmdReset, SIGNAL(clicked()), SLOT(slotReset()));
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(m_pprb);
phbxLayout->addWidget(pcmdStep);
phbxLayout->addWidget(pcmdReset);
setLayout(phbxLayout);
}
void ProgressBar::slotStep()
{
m_pprb->setValue(++m_nStep);
}
void ProgressBar::slotReset()
{
m_nStep = 0;
m_pprb->reset();
}
|
5ae0b650b4474ddfad771ed4a1a83cea39b74224
|
37b1cc093229626cb58199379f39b6b1ec6f6fb0
|
/compute_kernel_writer/prototype/include/ckw/KernelWriter.h
|
72f85c78aa234b42d5949ade092ce5a121d69b51
|
[
"MIT",
"LicenseRef-scancode-dco-1.1",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
ARM-software/ComputeLibrary
|
d4dfccb6a75b9f7bb79ae6c61b2338d519497211
|
874e0c7b3fe93a6764ecb2d8cfad924af19a9d25
|
refs/heads/main
| 2023-09-04T07:01:32.449866
| 2023-08-23T13:06:10
| 2023-08-23T13:06:10
| 84,570,214
| 2,706
| 810
|
MIT
| 2023-01-16T16:04:32
| 2017-03-10T14:51:43
|
C++
|
UTF-8
|
C++
| false
| false
| 13,303
|
h
|
KernelWriter.h
|
/*
* Copyright (c) 2023 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef CKW_PROTOTYPE_INCLUDE_CKW_KERNELWRITER_H
#define CKW_PROTOTYPE_INCLUDE_CKW_KERNELWRITER_H
#include "ckw/Kernel.h"
#include "ckw/TensorInfo.h"
#include "ckw/TensorOperand.h"
#include "ckw/TileInfo.h"
#include "ckw/TileOperand.h"
#include "ckw/types/ConvertPolicy.h"
#include "ckw/types/Functions.h"
#include "ckw/types/Operators.h"
#include <memory>
namespace ckw
{
namespace prototype
{
struct GpuKernelWriterAttribute;
class IGpuKernelWriter;
} // namespace prototype
/** Kernel writer. */
class KernelWriter
{
public:
// =============================================================================================
// Constructors and destructor
// =============================================================================================
/** Initialize a new instance of kernel writer.
*
* @param[in] kernel The kernel to be written to.
*/
explicit KernelWriter(Kernel &kernel);
/** Destructor */
~KernelWriter();
/** No copy constructor. */
KernelWriter(const KernelWriter &) = delete;
/** No copy assignment. */
KernelWriter &operator=(const KernelWriter &) = delete;
// =============================================================================================
// Scope management
// =============================================================================================
/** Get the current ID space. */
int32_t id_space() const;
/** Set the current ID space. */
KernelWriter &id_space(int32_t id_space);
/** Switch to and return a new ID space. */
int32_t next_id_space();
// =============================================================================================
// Tensor and tile declaration
// =============================================================================================
/** Declare a tensor argument.
*
* @param[in] name The name of the tensor.
* @param[in] info The tensor info.
* @param[in] storage_type The tensor storage type.
*
* @return The @ref TensorOperand object.
*/
TensorOperand &declare_tensor_argument(const std::string &name, const TensorInfo &info, TensorStorageType storage_type = TensorStorageType::BufferUint8Ptr);
/** Declare a compile-time constant scalar argument.
*
* @param[in] name The name of the tile.
* @param[in] value The value of the tile.
*
* @return The @ref TileOperand object.
*/
TileOperand &declare_tile_argument(const std::string &name, int32_t value);
/** Declare a new tile.
*
* The name of the tile must be unique in the current ID space.
*
* @param[in] name The name of the tile.
* @param[in] ... The necessary arguments to create a new @ref TileOperand.
*
* @return The @ref TileOperand object.
*/
template <typename... TArgs>
TileOperand &declare_tile(const std::string &name, TArgs &&...args)
{
const auto var_name = generate_variable_name(name);
auto operand = std::make_unique<TileOperand>(var_name, ::std::forward<TArgs>(args)...);
return declare_tile_operand(std::move(operand));
}
// =============================================================================================
// Load and store
// =============================================================================================
/** Load the data from the tensor memory to the tile using the sampling information.
*
* @param[out] tile The tile to be loaded.
* @param[in] tensor The tensor to be read.
* @param[in] sampler The tensor sampling information.
* @param[in] dilation_y Dilation in the Y dimension.
*/
void op_load(TileOperand &tile, const TensorOperand &tensor, const TensorTileSampler &sampler, const TileOperand &dilation_y = TileOperand("dil_y", 1));
/** Load the data from the tensor memory to the tile using the indirect buffer approach and respective of the sampling information.
*
* @param[out] tile The tile to be loaded.
* @param[in] tensor The tensor to be read.
* @param[in] sampler The tensor sampling information.
*/
void op_load_indirect(TileOperand &tile, const TensorOperand &tensor, const TensorTileSampler &sampler);
/** Construct an indirection buffer in @p tile containing the precalculated addresses of elements in the source tensor.
*
* @param[out] tile The tile to be loaded.
* @param[in] tensor The tensor the be read.
* @param[in] sampler The tensor sampling information.
* @param[in] x The X coordinate.
* @param[in] y The Y coordinate.
* @param[in] x_off Offset in the X dimension.
* @param[in] y_off Offset in the Y dimension.
*/
void util_get_indirect_buffer(TileOperand &tile,
const TensorOperand &tensor,
const TensorTileSampler &sampler,
const TileOperand &x,
const TileOperand &y,
const TileOperand &x_off,
const TileOperand &y_off);
/** Store the tile to the tensor using the specified sampling information.
*
* @param[out] dst The tensor that the tile is written to.
* @param[in] src The tile to be stored.
* @param[in] sampler The tensor sampling information.
*/
void op_store(TensorOperand &tensor, const TileOperand &tile, const TensorTileSampler &sampler);
// =============================================================================================
// Data processing
// =============================================================================================
/** Write assignment: `<dst> = <src>;`.
*
* @param[out] dst The destination tile.
* @param[in] src The source tile.
*/
void op_assign(const TileOperand &dst, const TileOperand &src);
/** Write the cast: `<dst> = convert_<dst.type><_sat>(<src>);`.
*
* @param[out] dst The destination tile.
* @param[in] src The source tile.
* @param[in] policy The policy governing the behavior of the cast.
*/
void op_cast_expression(const TileOperand &dst, const TileOperand &src, ConvertPolicy policy);
/** Write the unary expression: `<dst> = <op> <src>`.
*
* @param[out] dst The destination tile.
* @param[in] op The unary operator.
* @param[in] src The source tile.
*/
void op_unary_expression(const TileOperand &dst, UnaryOp op, const TileOperand &src);
/** Write binary expression: `<dst> = <lhs> <op> <rhs>;`.
*
* @param[out] dst The destination tile.
* @param[in] lhs The LHS tile.
* @param[in] op The binary operator.
* @param[in] rhs The RHS tile.
*/
void op_binary_expression(const TileOperand &dst, const TileOperand &lhs, BinaryOp op, const TileOperand &rhs);
/** Write function applied to scalar value: `<dst> = <func>(<src>);`.
*
* @param[out] dst The destination tile.
* @param[in] func The function to be applied to the source tile.
* @param[in] src The source tile.
*/
void op_unary_elementwise_function(const TileOperand &dst, UnaryFunction func, const TileOperand &src);
/** Write function applied to scalar value: `<dst> = <func>(<first>, <second>);`.
*
* @param[out] dst The destination tile.
* @param[in] func The function to be applied to the source tiles.
* @param[in] first The first argument tile.
* @param[in] second The second argument tile.
*/
void op_binary_elementwise_function(const TileOperand &dst, BinaryFunction func, const TileOperand &first, const TileOperand &second);
/** Write function applied to scalar value: `<dst> = <func>(<first>, <second>, <third>);`.
*
* @param[out] dst The destination tile.
* @param[in] func The function to be applied to the source tiles.
* @param[in] first The first argument tile.
* @param[in] second The second argument tile.
* @param[in] third The third argument tile.
*/
void op_ternary_elementwise_function(const TileOperand &dst, TernaryFunction func, const TileOperand &first, const TileOperand &second, const TileOperand &third);
/** Write if-statement: `if(<lhs> <op> <rhs>) { <body> }`.
*
* @param[in] lhs The LHS tile of the condition.
* @param[in] op The relational binary operator.
* @param[in] rhs The RHS tile of the condition.
* @param[in] body The body of the if-statement.
*/
void op_if(const TileOperand &lhs, BinaryOp op, const TileOperand &rhs, const std::function<void()> &body);
/** Write else-if-statement: `else if(<lhs> <op> <rhs>) { <body> }`.
*
* @param[in] lhs The LHS tile of the condition.
* @param[in] op The relational binary operator.
* @param[in] rhs The RHS tile of the condition.
* @param[in] body The body of the else-if-statement.
*/
void op_else_if(const TileOperand &lhs, BinaryOp op, const TileOperand &rhs, const std::function<void()> &body);
/** Write an else-statement: `else { <body> }`.
*
* @param[in] body The body of the else-statement.
*/
void op_else(const std::function<void()> &body);
/** Write for-loops: `for(; <var> <cond_op> <cond_value>; <var> <update_op> <update_value>) { body }`.
*
* @param[in] var_name The name of the variable used in condition.
* @param[in] cond_op The relational binary operator used in condition.
* @param[in] cond_value_name The value which the variable is compared against.
* @param[in] update_var_name The name of the variable which is updated.
* @param[in] update_op The assignment operator used for updating the update value.
* @param[in, out] update_value The value which is updated at every iteration.
* @param[in] body The body of the for-loop.
*/
void op_for_loop(const TileOperand &var_name, BinaryOp cond_op, const TileOperand &cond_value_name, const TileOperand &update_var_name, AssignmentOp update_op, const TileOperand &update_value_name, const std::function<void()> &body);
/** Write the return statement: `return;`
*/
void op_return();
// =============================================================================================
// Misc
// =============================================================================================
/** Set `dst` the global ID of dimension `dim`.
*
* @param[out] dst The tile to be written to.
* @param[in] dim The global ID dimension.
*/
void op_get_global_id(TileOperand &dst, int32_t dim);
// =============================================================================================
// Code generation
// =============================================================================================
/** Generate the source code of the kernel. */
::std::string generate_code();
private:
/** Generate the full variable name based on the original name and the ID space.
*
* @param[in] name The name of the variable.
*
* @return The full variable name.
*/
::std::string generate_variable_name(const std::string &name) const;
/** Declare the tile operand.
*
* @param[in] operand The tile operand to be declared.
*/
TileOperand &declare_tile_operand(std::unique_ptr<TileOperand> operand);
private:
Kernel *_kernel;
::std::unique_ptr<prototype::GpuKernelWriterAttribute> _impl_attr;
::std::unique_ptr<prototype::IGpuKernelWriter> _impl;
int32_t _id_space{ 0 };
int32_t _max_id_space{ 0 };
};
} // namespace ckw
#endif // CKW_PROTOTYPE_INCLUDE_CKW_KERNELWRITER_H
|
4bb8e873b14d7ffecd40511819d07547615590bd
|
58f844528ed19e4d71f13fb79e68c267a02627f4
|
/playpen/MPI_Init/test.cpp
|
834491bbaeda3a3774d87c2a321c828abbbd1346
|
[] |
no_license
|
schmidtbt/real-time-frmi
|
4b8f7eec920e5b8c279d31612341b4c65e717908
|
a0a943ae3928860fd7cb2960e107bd723be431a9
|
refs/heads/master
| 2021-01-19T15:02:30.029636
| 2014-01-07T17:59:57
| 2014-01-07T17:59:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,343
|
cpp
|
test.cpp
|
/*
* MPI/LOG/QUERY Merger
*
*
* Created by Benjamin Schmidt on 5/27/10.
* Copyright 2010 __University of Pittsburgh__. All rights reserved.
*
*/
#define DEBUG_MODE 1
//include "test.h"
#include <iostream>
#include "Log.h"
#include <mpi.h>
#include <math.h>
#include <string>
#include "query.h"
#include "HelloWorld.cxx"
using namespace MPI;
int main(int argc, char* argv[]) {
//Initialize MPI
int myid, numprocs;
Init(argc,argv);
myid=COMM_WORLD.Get_rank();
numprocs=COMM_WORLD.Get_size();
MPI::Status status;
//Create a Logger
Logger mylog(myid);
mylog.begin();
//Initialize some values
int master = 0;
double wtime = Wtime(); //the current time
//toy values
int sendval = 5, j = 0, k, cont = 1;
char temp;
if (myid == master)
{
system( "sleep 3" );
query dirmon( "." ); //create query object
//A loop over number of files anticipated
for(int i = 1; i < 5; i++)
{
temp = dirmon.monitor();
if(i == 4)
{
COMM_WORLD.Bcast(&cont, 1, INT, 0);
std::cout << "Broadcast new value for cont to everyone" << std::endl;
}
COMM_WORLD.Send( &sendval, 1, INT, master+1, 1);
mylog.log_event( "File creation event detected" );
//std::cout << temp << std::endl;
}
//Now log the vector of files
mylog.log_event( dirmon.files );
}
//Ring Structures
{
std::cout << "Node " << myid << ": Reporting" << std::endl;
while(cont == 1)
{
std::cout << "Node " << myid << ": " << cont << std::endl;
if( myid == master) // Returned to master -- ring complete
{
COMM_WORLD.Recv (&k, 1, INT, numprocs-1, 1, status);
std::cout << "Node " << myid << ": Ring Complete" << std::endl;
}
else if(myid == numprocs-1) // end of ring, pass to master
{
COMM_WORLD.Recv (&k, 1, INT, myid-1, 1, status);
std::cout << "Node " << myid << ": Message Received... Passing" << std::endl;
COMM_WORLD.Send( &k, 1, INT, master, 1 );
}
else // middle of ring, keep passing
{
COMM_WORLD.Recv (&k, 1, INT, myid-1, 1, status);
std::cout << "Node " << myid << ": Message Received... Passing" << std::endl;
COMM_WORLD.Send( &k, 1, INT, myid+1, 1 );
}
}
}
double time = Wtime();
//Done
Finalize();
#if DEBUG_MODE==1
std::cout << "Time: " << time - wtime << " on node: " << myid << std::endl;
#endif
return 1;
}
|
e8a439ef41d11e57a52606dd91e2fc46eba442e3
|
085f59477009f38844b19e5d077307fcc9954d88
|
/trunk/zjucad/linear_solver/src/solver_pack/base/include/solver.h
|
9dec13f6278514c2bc10a773495fc94ee92fdb17
|
[] |
no_license
|
senjay/zju_geo_sim_sdk
|
e58916bde012bf747a5e91d9a1fc99b5f717ac71
|
38edc0ad9fcc5ff8f12f9d13b508c9418c989cb8
|
refs/heads/master
| 2021-06-07T05:33:39.091411
| 2016-08-19T01:33:47
| 2016-08-19T01:33:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,984
|
h
|
solver.h
|
#ifndef HJ_SPARSE_SOLVER_H_
#define HJ_SPARSE_SOLVER_H_
#include "config.h"
extern "C" {
//! sizeof_val = sizeof(float,double), not sizeof(complex<float>, complex<double>)
///! direct solver
HJ_SPARSE_API
void *hj_sparse_direct_solver_A_create(
unsigned char sizeof_int, unsigned char sizeof_val, unsigned char real_or_complex,
size_t nrows, size_t ncols,
const void *ptr, const void *idx, const void *val, //< link for internal use
const char *name, //< copy to internal
void *opts); //< link for internal use
HJ_SPARSE_API
int hj_sparse_direct_solver_A_solve(void *ctx, const void *b, void *x, const size_t nrhs, void *opts);
HJ_SPARSE_API
void hj_sparse_direct_solver_A_destroy(void *ctx);
///! iterative solver
HJ_SPARSE_API
void *hj_sparse_iterative_solver_A_create(
unsigned char sizeof_int, unsigned char sizeof_val, unsigned char real_or_complex,
size_t nrows, size_t ncols,
const void *ptr, const void *idx, const void *val, //< link for internal use
const char *name, //< copy to internal
void *opts); //< link for internal use
HJ_SPARSE_API
int hj_sparse_iterative_solver_A_solve(void *ctx, const void *b, void *x, const size_t nrhs, void *opts);
HJ_SPARSE_API
void hj_sparse_iterative_solver_A_destroy(void *ctx);
struct laspack_opts
{
laspack_opts(const char *iter_name, const char *precond_name)
:iter_name_(iter_name), precond_name_(precond_name){}
const char *iter_name_, *precond_name_;
size_t iter_num_;
double precision_, relax_;
};
}
#include <complex>
#include "./type_traits.h"
namespace hj { namespace sparse {
class solver_base
{
public:
virtual ~solver_base(){}
virtual int solve(const void *b, void *x, size_t nrhs = 1, void *opts = 0) = 0;
protected:
solver_base(void *ctx):ctx_(ctx){}
void *ctx_;
};
//! direct solvers
//! @brief solve Ax=b
class direct_solver_A : public solver_base
{
public:
template <typename VAL_TYPE, typename INT_TYPE>
static direct_solver_A *create(
const VAL_TYPE * val, const INT_TYPE *idx, const INT_TYPE *ptr,
const size_t nnz, const size_t row, const size_t col,
const char *name = 0, void *opts = 0) {
void *ctx = hj_sparse_direct_solver_A_create(
sizeof(INT_TYPE), value_type<VAL_TYPE>::size, value_type<VAL_TYPE>::type,
row, col, ptr, idx, val, name, opts);
if(ctx)
return new direct_solver_A(ctx);
return 0;
}
virtual int solve(const void *b, void *x, size_t nrhs = 1, void *opts = 0) {
return hj_sparse_direct_solver_A_solve(ctx_, b, x, nrhs, opts);
}
~direct_solver_A(void) {
hj_sparse_direct_solver_A_destroy(ctx_);
}
protected:
direct_solver_A(void *ctx):solver_base(ctx){}
};
//! @brief solve AA^Tx=Ab
class direct_solver_AAT : public solver_base
{
public:
template <typename VAL_TYPE, typename INT_TYPE>
static direct_solver_AAT *create(
const VAL_TYPE * val, const INT_TYPE *idx, const INT_TYPE *ptr,
const size_t nnz, const size_t row, const size_t col,
const char *name = 0, void *opts = 0) {
return 0;
}
virtual int solve(const void *b, void *x, const void *nrhs = 0, void *opts = 0) {
return 0;
}
protected:
direct_solver_AAT(void *ctx):solver_base(ctx){}
};
//! @brief solve Ax=b with iterative method
class iterative_solver_A : public solver_base
{
public:
template <typename VAL_TYPE, typename INT_TYPE>
static iterative_solver_A *create(
const VAL_TYPE * val, const INT_TYPE *idx, const INT_TYPE *ptr,
const size_t nnz, const size_t row, const size_t col,
const char *name = 0, void *opts = 0) {
void *ctx = hj_sparse_iterative_solver_A_create(
sizeof(INT_TYPE), value_type<VAL_TYPE>::size, value_type<VAL_TYPE>::type,
row, col, ptr, idx, val, name, opts);
if(ctx)
return new iterative_solver_A(ctx);
return 0;
}
virtual int solve(const void *b, void *x, size_t nrhs = 1, void *opts = 0) {
return hj_sparse_iterative_solver_A_solve(ctx_, b, x, nrhs, opts);
}
~iterative_solver_A(void) {
hj_sparse_iterative_solver_A_destroy(ctx_);
}
protected:
iterative_solver_A(void *ctx):solver_base(ctx){}
};
class solver
{
public:
/**
@param id "umfpack" or "cholmod", default 0 is current best
implementation
*/
template <typename VAL_TYPE, typename INT_TYPE>
static solver *create(const VAL_TYPE * val, const INT_TYPE *idx, const INT_TYPE *ptr,
const size_t nnz, const size_t row, const size_t col,
const char *id = 0) {
#if __cplusplus == 201103L
std::unique_ptr<direct_solver_A> slv(direct_solver_A::create(val, idx, ptr, nnz, row, col, id));
#else
std::auto_ptr<direct_solver_A> slv(direct_solver_A::create(val, idx, ptr, nnz, row, col, idx, id));
#endif
if(slv.get())
return new solver(slv.release());
return 0;
}
virtual bool solve(const double *b, double *x, int nrhs = 1) {
return !slv_->solve(b, x, nrhs);
}
private:
solver(direct_solver_A *slv)
:slv_(slv) {
}
#if __cplusplus == 201103L
std::unique_ptr<direct_solver_A> slv_;
#else
std::auto_ptr<direct_solver_A> slv_;
#endif
};
}}
#endif
|
d877b29dbba3539ef11f9c55f4fc2107cb603ceb
|
8c5f7ef81a92887fcadfe9ef0c62db5d68d49659
|
/src/parser/statement/call_statement.cpp
|
56430d823f7b6cb94e1a42c24f82f36c196e2a63
|
[
"MIT"
] |
permissive
|
xunliu/guinsoodb
|
37657f00456a053558e3abc433606bc6113daee5
|
0e90f0743c3b69f8a8c2c03441f5bb1232ffbcf0
|
refs/heads/main
| 2023-04-10T19:53:35.624158
| 2021-04-21T03:25:44
| 2021-04-21T03:25:44
| 378,399,976
| 0
| 1
|
MIT
| 2021-06-19T11:51:49
| 2021-06-19T11:51:48
| null |
UTF-8
|
C++
| false
| false
| 351
|
cpp
|
call_statement.cpp
|
#include "guinsoodb/parser/statement/call_statement.hpp"
namespace guinsoodb {
CallStatement::CallStatement() : SQLStatement(StatementType::CALL_STATEMENT) {
}
unique_ptr<SQLStatement> CallStatement::Copy() const {
auto result = make_unique<CallStatement>();
result->function = function->Copy();
return move(result);
}
} // namespace guinsoodb
|
0645b675794609a3d3ed65ddea3f765094e6496a
|
17416939b9afdf56e67782bd6dbff0e5e46376e8
|
/src/visitor/semantic/pass2Visitor.hh
|
67ec15e86b9c9f01d6acd910b55533584f267722
|
[] |
no_license
|
jack695/VSOPC
|
89e0c3cc7e42ea10a467c4d6e51b90e13bbd94d1
|
73471a8f2dc6c10d9f6051ae1999632dc7b7a091
|
refs/heads/main
| 2023-03-03T04:35:39.762920
| 2021-02-10T12:48:59
| 2021-02-10T12:48:59
| 337,718,580
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 783
|
hh
|
pass2Visitor.hh
|
//
// Created by jack on 02/04/2020.
//
#ifndef PART_2_PASS2VISITOR_HH
#define PART_2_PASS2VISITOR_HH
#include "visitor/visitor.hh"
#include "semanticVisitor.hh"
#include "pass3Visitor.hh"
/***************** CHECK VISITOR CLASS ***********************/
/**
* This class is in charge to check the classes and the inheritance constraints ( as seen in the VSOP manual)
*/
class FieldVisitor : public SemanticVisitor {
public:
FieldVisitor();
~FieldVisitor() = default;
void visit(ProgramNode& program) override ;
void visit(ClassNode& cl) override ;
void visit(FieldNode& field) override ;
void visit(MethodNode& method) override ;
void visit(FormalNode& formal) override ;
private:
MethodVisitor pass3;
};
#endif //PART_2_PASS2VISITOR_HH
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.