blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
525dc432cbc1aa592d1cc4f09afd5951c45fab66 | e96656f1032e7ba7e23693f010e74b4da90a48ca | /C++/LinkedList/Pairwise swap elements of a given linked list.cpp | 2b1153ac44276555eed01b2249ed54260aca7c3f | [] | no_license | SelvaBalasubramanian/GeeksForGeeks | 1d1c7f32cdff62e380020fd9ec84d6eb9dbc3180 | 13f28ad42b03befc4aa5840761b9f14969bf127a | refs/heads/master | 2020-03-16T17:45:47.663647 | 2019-08-21T06:20:14 | 2019-08-21T06:20:14 | 132,846,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,115 | cpp |
// https://www.geeksforgeeks.org/pairwise-swap-elements-of-a-given-linked-list/
#include<iostream>
using namespace std;
struct node{
int data;
node *next;
};
node* insert(node* head , int d){
if(head == NULL){
head = new node();
head->data = d;
head->next = NULL;
}
else{
node* ptr , *temp;
for(ptr = head ; ptr->next != NULL ; ptr = ptr->next){;}
temp = new node();
temp->data = d;
temp->next = NULL;
ptr->next = temp;
}
return head;
}
void print(node *head){
node *ptr;
if(head == NULL)cout<<"No elements present";
for(ptr = head ; ptr != NULL ; ptr = ptr->next)cout<<ptr->data<<" ";
cout<<endl;
}
void pairwiseSwapNode(node *head){
if(head->next == NULL){
return ;
}
int temp = head->data;
head->data = head->next->data;
head->next->data = temp;
pairwiseSwapNode(head->next->next);
return;
}
int main(){
node *head;
head = NULL;
head = insert(head , 1);
head = insert(head , 2);
head = insert(head , 2);
head = insert(head , 4);
head = insert(head , 5);
print(head);
pairwiseSwapNode(head);
print(head);
return 0 ;
}
| [
"selva6101996@gmail.com"
] | selva6101996@gmail.com |
3ab8776644dae1d34121f33ca72ae47e95c8a21e | 1c2962381e983bec0858f6724bbc3437c9c75bfc | /spoj/the-double-helix.cpp | 2b6397fddd209587f4b204b2f629c67fbf59d02a | [] | no_license | ranti-iitg/CODE | f2871a5cde8fa6f9bc5649e7f3ae25b9d7baccc8 | f75e88ef6593deb64fcf2f84d5e0c084753a41d3 | refs/heads/master | 2020-06-06T17:31:14.220098 | 2017-04-13T05:34:58 | 2017-04-13T05:34:58 | 25,700,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 683 | cpp | #include<iostream>
#include <algorithm>
using namespace std;
const int MAX = 10009;
int A[MAX], B[MAX];
int main() {
int na, nb, i, j;
while(cin>>na&& na) {
for(i=1; i<=na; i++) cin>>A[i];
cin>>nb;
for(j=1; j<=nb; j++)cin>>B[j];
for(i=j=1; i<=na || j<=nb; ) {
if(i<=na && j<=nb && A[i]==B[j]) {
A[i] += A[i-1];
B[j] += B[j-1];
A[i] = B[j] = max(A[i], B[j]);
i++, j++;
}
else if(i>na) {
B[j] += B[j-1];
j++;
}
else if(j>nb) {
A[i] += A[i-1];
i++;
}
else if(A[i] < B[j]) {
A[i] += A[i-1];
i++;
}
else if(A[i] > B[j]) {
B[j] += B[j-1];
j++;
}
}
cout<<max(A[na], B[nb])<<endl;
}
return 0;
}
| [
"ranti.iitg@gmail.com"
] | ranti.iitg@gmail.com |
21874b89443d1950678c09d1c936b1796fe2f7e1 | 85455876309135778cba6bbf16933ca514f457f8 | /2600/2659.cpp | 4ec946d62b69037a4658c5742a8dd7a8b8fa831f | [] | no_license | kks227/BOJ | 679598042f5d5b9c3cb5285f593231a4cd508196 | 727a5d5def7dbbc937bd39713f9c6c96b083ab59 | refs/heads/master | 2020-04-12T06:42:59.890166 | 2020-03-09T14:30:54 | 2020-03-09T14:30:54 | 64,221,108 | 83 | 19 | null | null | null | null | UTF-8 | C++ | false | false | 642 | cpp | #include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int a[4];
vector<int> clocks;
int getClock(){
int m = 9999;
for(int i=0; i<4; i++)
m = min(m, a[i]*1000+a[(i+1)%4]*100+a[(i+2)%4]*10+a[(i+3)%4]);
return m;
}
void DFS(int pos){
if(pos==4){
clocks.push_back(getClock());
return;
}
for(int i=1; i<10; i++){
a[pos] = i;
DFS(pos+1);
}
}
int main(){
DFS(0);
for(int i=0; i<4; i++)
scanf("%d", a+i);
sort(clocks.begin(), clocks.end());
clocks.resize(unique(clocks.begin(), clocks.end())-clocks.begin());
printf("%d\n", lower_bound(clocks.begin(), clocks.end(), getClock())-clocks.begin()+1);
} | [
"wongrikera@nate.com"
] | wongrikera@nate.com |
a7c70ec36ceaf72e5f092cf8b11f433b7a88a472 | f6ba0d8c3743729eeab14e82423a9d2bc8193da0 | /AstroHaven.h | 8de38a4f170e26feaacd0e2d19fa513388482302 | [] | no_license | rpineau/AstroHaven | fb30af66fd83b9a8c00362d90de2d9a10279962c | 6a88b6f7e8fe41beddf5cdbecd288ab422d4fe9a | refs/heads/master | 2022-07-10T16:18:19.591528 | 2020-01-13T20:52:50 | 2020-01-13T20:52:50 | 203,291,745 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,948 | h | //
// AstroHaven.h
// CAstroHaven
//
// Created by Rodolphe Pineau on 2017-4-6
// AstroHaven X2 plugin
#ifndef __AstroHaven__
#define __AstroHaven__
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <memory.h>
#ifdef SB_MAC_BUILD
#include <unistd.h>
#endif
#ifdef SB_WIN_BUILD
#include <time.h>
#endif
#include <math.h>
#include <string.h>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include "../../licensedinterfaces/sberrorx.h"
#include "../../licensedinterfaces/serxinterface.h"
#include "../../licensedinterfaces/loggerinterface.h"
#include "../../licensedinterfaces/sleeperinterface.h"
#include "StopWatch.h"
#define DRIVER_VERSION 1.12
// #define PLUGIN_DEBUG 2
#define SERIAL_BUFFER_SIZE 256
#define MAX_TIMEOUT 500
#define ND_LOG_BUFFER_SIZE 256
#define INTER_COMMAND_WAIT 500 // tested with 100 and 250 and that was causing timeout, 500 works well.
// error codes
enum AstroHavenErrors {PluginOK=0, NOT_CONNECTED, CANT_CONNECT, BAD_CMD_RESPONSE, COMMAND_FAILED, NO_DATA_TIMEOUT};
// Error code
enum AstroHavenShutterState {OPEN=1, OPENING, OPENING_A, OPENING_B, CLOSED, CLOSING, CLOSING_A, CLOSING_B, UNKNOWN};
class CAstroHaven
{
public:
CAstroHaven();
~CAstroHaven();
int Connect(const char *szPort);
void Disconnect(void);
bool IsConnected(void) { return m_bIsConnected; }
void SetSerxPointer(SerXInterface *p) { m_pSerx = p; }
void setSleeper(SleeperInterface *pSleeper) { m_pSleeper = pSleeper; };
// Dome commands
int syncDome(double dAz, double dEl);
int parkDome(void);
int unparkDome(void);
int gotoAzimuth(double dNewAz);
int openShutter();
int closeShutter();
int findHome();
// command complete functions
int isGoToComplete(bool &bComplete);
int isOpenComplete(bool &bComplete);
int isCloseComplete(bool &bComplete);
int isParkComplete(bool &bComplete);
int isUnparkComplete(bool &bComplete);
int isFindHomeComplete(bool &bComplete);
double getCurrentAz();
double getCurrentEl();
protected:
int readResponse(char *pszRespBuffer, unsigned int nBufferLen, unsigned long nExpectRespLen = 1, int nTimeOut = MAX_TIMEOUT);
int domeCommand(const char *pszCmd, char *pszResult, int nResultMaxLen);
int setShutterStateToClosed();
SleeperInterface *m_pSleeper;
bool m_bIsConnected;
double m_dCurrentAzPosition;
double m_dCurrentElPosition;
int m_nASideState;
int m_nBSideState;
int m_nCurrentShutterAction;
SerXInterface *m_pSerx;
int m_nShutterState;
CStopWatch m_cmdDelayTimer;
#ifdef PLUGIN_DEBUG
std::string m_sLogfilePath;
// timestamp for logs
char *timestamp;
time_t ltime;
FILE *Logfile; // LogFile
#endif
};
#endif
| [
"pineau@rti-zone.org"
] | pineau@rti-zone.org |
2f20174fd6c49f8d35b2744936040f7573d3c52a | 110cb4a0e4f205cfca825b18c12d912130e81f83 | /main.cpp | 0e632eee2c5c3ddee06b18b749bb761411eb4091 | [] | no_license | jjzhang166/UberQuick | 127beb39c9c4d3694ed64d8757b4f0076ac4e7f4 | 979c6ef1838397afc34ae55290fecf9b23844e20 | refs/heads/master | 2021-01-02T08:13:24.387062 | 2013-08-19T14:31:11 | 2013-08-19T14:31:11 | 98,964,673 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 755 | cpp | #include <QtWidgets/QApplication>
#include "qtquick2applicationviewer.h"
#include "system/System.h"
#include "_2RealDatatypes.h"
#include "_2RealApplication.h"
//#include "vld.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qRegisterMetaType<CustomTypeRef>("CustomTypeRef");
Uber::System *system = Uber::System::getInstance();
//QObject::connect(system->getWindow(), SIGNAL(clicked()), qApp, SLOT(quit()));
system->loadBundles();
system->loadInterfaceBlocks();
system->registerQmlTypes();
system->setContextProperties();
system->loadQmlFiles();
system->enableTransparentWindows();
system->showWindows();
int res = app.exec();
delete system;
//qApp->quit();
return res;
}
| [
"psaroudakis@gmail.com"
] | psaroudakis@gmail.com |
67a11f4a583078c83a11c0a31b52bd8bceb21ab7 | 4dbe74e208988015fd7b6cffed86163328c1d35e | /src/crt/stl/xlexp.cpp | fb0287c4ffa09cf6f6caa4285765fc09a7c84a94 | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | permissive | MiroKaku/ucxxrt | c27abdcdfda7ac71b8781e2b2f65045a2169378c | bd8cafa60823afd03a0533f7bcb23171f1565fb1 | refs/heads/main | 2023-08-31T03:50:03.968791 | 2023-08-25T13:57:31 | 2023-08-25T13:57:31 | 243,931,531 | 287 | 87 | MIT | 2023-07-04T02:31:46 | 2020-02-29T08:24:52 | C++ | UTF-8 | C++ | false | false | 2,015 | cpp | // Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// _LExp function
#include "xmath.hpp"
_EXTERN_C_UNLESS_PURE
// coefficients
static const long double p[] = {42.038913947607355L, 10096.353102778762831L, 333228.767219512631062L};
static const long double q[] = {1.0L, 841.167880526530790L, 75730.834075476293976L, 666457.534439025262146L};
static const long double c1 = (22713.0L / 32768.0L);
static const long double c2 = 1.4286068203094172321214581765680755e-6L;
static const long double hugexp = LHUGE_EXP;
static const long double invln2 = 1.4426950408889634073599246810018921L;
_CRTIMP2_PURE short __CLRCALL_PURE_OR_CDECL _LExp(
long double* px, long double y, short eoff) { // compute y * e^(*px), (*px) finite, |y| not huge
if (y == 0.0L) { // zero
*px = y;
return 0;
} else if (*px < -hugexp) { // certain underflow
*px = _Xfe_underflow(y);
return 0;
} else if (hugexp < *px) { // certain overflow
*px = _Xfe_overflow(y);
return _INFCODE;
} else { // xexp won't overflow
long double g = *px * invln2;
short xexp = static_cast<short>(g + (g < 0 ? -0.5L : +0.5L));
g = xexp;
g = (*px - g * c1) - g * c2;
if (-_LEps._Long_double < g && g < _LEps._Long_double) {
*px = y;
} else { // g * g worth computing
const long double z = g * g;
const long double w = ((z + q[1]) * z + q[2]) * z + q[3];
g *= (p[0] * z + p[1]) * z + p[2];
*px = (w + g) / (w - g) * 2.0L * y;
--xexp;
}
const short result_code = _LDscale(px, static_cast<long>(xexp) + eoff);
switch (result_code) {
case 0:
*px = _Xfe_underflow(y);
break;
case _INFCODE:
*px = _Xfe_overflow(y);
break;
default:
break;
}
return result_code;
}
}
_END_EXTERN_C_UNLESS_PURE
| [
"50670906+MiroKaku@users.noreply.github.com"
] | 50670906+MiroKaku@users.noreply.github.com |
24f9f2cfdb6aefd01ea38b1ff7f7d072f9d7042f | 4f3531026c2cc3d15e15f28388fa4d8c2320a9b3 | /C++ progrsmming/CodeForces/Round_1_A.cpp | 147b1d4876e9f68678d8156c9146a742a2e8bfd4 | [] | no_license | hmahmudul852/Programming | 29914e93b7c1c31c2270042e8c55009a32df4704 | 96f7457221b471539237d66f0cc1e335d793672f | refs/heads/master | 2021-01-11T15:45:22.029400 | 2019-08-11T03:30:25 | 2019-08-11T03:30:25 | 79,919,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 248 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
double a;
cin>>n>>m>>a;
double ans=ceil(n/a),ans1=ceil(m/a);
unsigned long long x=ans,y=ans1;
unsigned long long z=x*y;
cout<<z<<endl;
return 0;
}
| [
"hmahmudul852@gmail.com"
] | hmahmudul852@gmail.com |
a80d9211154dcadf6d6cf35de394c2a3a2ba0adc | 8b156f329c0717b46428ff97989164fb31ff1673 | /chapter2/bubbleSort.cpp | 381ba07b1469ba03284d1b6362446a62b1e62ea6 | [] | no_license | a-daydream/Algorithms | 5c6ed75a795544c93c8d0fbe544763d4a5d7b101 | 1a37a37ed5a9dc085b8618203e0822fb1578acef | refs/heads/master | 2022-01-08T22:57:29.165525 | 2019-05-30T08:30:56 | 2019-05-30T08:30:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 908 | cpp | #include<iostream>
#include<cstdlib>
#include<ctime>
void generateArray(int a[],int size);
void printArray(int a[],int size);
void bubbleSort(int a[],int size);
int main(void)
{
int array[100];
int length = sizeof(array) / sizeof(array[0]);
generateArray(array,length);
printArray(array,length);
bubbleSort(array,length);
printArray(array,length);
return 0;
}
void bubbleSort(int a[],int size)
{
int j,i;
for(j=size-1;j>0;j--){
for(i = 0;i<j;i++){
if(a[i]>a[i+1]){
int temp = a[i+1] ;
a[i+1] = a[i];
a[i]=temp;
}
}
}
}
void generateArray(int a[],int size)
{
srand(time(NULL));
for(int i=0;i<size;i++){
a[i] = rand()%100;
}
}
void printArray(int a[],int size)
{
for(int i=0;i<size;i++){
std::cout<<a[i]<<" ";
}
std::cout<<std::endl;
} | [
"18370723707@163.com"
] | 18370723707@163.com |
d45f9912fcdd45e80bd2337891c3eb3b92bf8313 | 8ddc81be3ae40c2c1055c8b0df6483c01a8ec2d5 | /c project.cpp | d0912f4f5ecd4e851ae8228b63dd4a0fa0795eb4 | [] | no_license | chinedu0507/C-Programming-Proj | eacf534987d813e0d569d4355fd9917658027144 | fb59f9eeabcd91423fa573b0ef27b1795a063e9d | refs/heads/master | 2021-07-14T02:20:58.934776 | 2017-10-10T16:52:18 | 2017-10-10T16:52:18 | 105,142,721 | 0 | 0 | null | 2017-09-29T23:27:59 | 2017-09-28T11:58:14 | C | UTF-8 | C++ | false | false | 8,883 | cpp | // This will be my main file
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "time.h"
#include "apartments.h"
#include "calculations.h"
#include "fileHandling.h"
#include "linkedLists.h"
#define SIZE 720
void printApartmentReport(double waterUsage[], ApartmentData data);
int main()
{
// Program variables
int option;
int menu_seven;
int apartment;
int i, j, k;
char filename[50];
ListNodePtr startPtr = NULL;
// setbuf(stdout, 0);
// Occupants data
ApartmentData AptOne;
ApartmentData AptTwo;
ApartmentData AptThree;
double apartment1Usage[SIZE];
double apartment2Usage[SIZE];
double apartment3Usage[SIZE];
// Reading in data from files
readMetadataFromFile(&AptOne, &AptTwo, &AptThree);
readUsageFromFile(apartment1Usage, apartment2Usage, apartment3Usage);
// Menu
puts("\nRP143 Water Calculator");
puts("1. Print usage patter for apartment");
puts("2. Calculate and print total usage for apartment (in kl)");
puts("3. Calculate and print total bill for apartment (in R)");
puts("4. Print apartment usage report to screen");
puts("5. Check building for leaks and print leak report");
puts("6. Write building water usage report to text file");
puts("7. Save or print compact binary usage file for apartment");
puts("8. Determine and print hour with greatest usage for apartment");
puts("10. Exit");
printf("\nChoose an item from the menu: ");
scanf_s(" %d", &option);
while (option != 10)
{
printf("\nChoose apartment(1, 2 or 3): ");
scanf_s(" %d", &apartment);
switch (option)
{
case 1:
puts("\nActive water usage report:");
if (apartment == 1)
{
for (i = 0; i < SIZE; i++)
{
if (apartment1Usage[i] != 0)
{
printf("Day %02d %02d:00 : %.3f kl\n", monthHourToDay(i), monthHourToDailyHour(i), apartment1Usage[i]);
}
}
}
else if (apartment == 2)
{
for (j = 0; j < SIZE; j++)
{
if (apartment2Usage[j] != 0)
{
printf("Day %02d %02d:00 : %.3f kl\n", monthHourToDay(j), monthHourToDailyHour(j), apartment2Usage[j]);
}
}
} else if (apartment == 3)
{
for (k = 0; k < SIZE; k++)
{
if (apartment3Usage[k] != 0)
{
printf("Day %02d %02d:00 : %.3f kl\n", monthHourToDay(k), monthHourToDailyHour(k), apartment3Usage[k]);
}
}
}
break;
case 2:
if (apartment == 1)
{
printf("\nTotal usage from apartment %d: %.3f kl\n ", apartment, getTotalWaterUsage(apartment1Usage));
}
else if (apartment == 2)
{
printf("\nTotal usage from apartment %d: %.3f kl\n ", apartment, getTotalWaterUsage(apartment2Usage));
}
else if (apartment == 3)
{
printf("\nTotal usage from apartment %d: %.3f kl\n ", apartment, getTotalWaterUsage(apartment3Usage));
}
break;
case 3:
if (apartment == 1)
{
printf("\nTotal bill for apartment %d for this month: R%.2f\n ", apartment, getTotalBill(apartment1Usage, AptOne.tariff));
}
else if (apartment == 2)
{
printf("\nTotal bill for apartment %d for this month: R%.2f\n ", apartment, getTotalBill(apartment2Usage, AptTwo.tariff));
}
else if (apartment == 3)
{
printf("\nTotal bill for apartment %d for this month: R%.2f\n ", apartment, getTotalBill(apartment3Usage, AptThree.tariff));
}
break;
case 4:
if (apartment == 1)
{
printApartmentReport(apartment1Usage, AptOne);
}
else if (apartment == 2)
{
printApartmentReport(apartment2Usage, AptTwo);
}
else if (apartment == 3)
{
printApartmentReport(apartment3Usage, AptThree);
}
break;
case 5:
if (apartment == 1)
{
if (checkForLeak(apartment1Usage) == 0)
printf("Apartment %d: No leak\n", apartment);
else printf("Apartment %d: Leak on day %d\n", apartment, checkForLeak(apartment1Usage));
}
else if (apartment == 2)
{
if (checkForLeak(apartment2Usage) == 0)
printf("Apartment %d: No leak\n", apartment);
else printf("Apartment %d: Leak on day %d\n", apartment, checkForLeak(apartment2Usage));
}
else if (apartment == 3)
{
if (checkForLeak(apartment3Usage) == 0)
printf("Apartment %d: No leak\n", apartment);
else printf("Apartment %d: Leak on day %d\n", apartment, checkForLeak(apartment3Usage));
}
break;
case 6:
printf("Enter a filename: ");
scanf(" %s", filename);
writeBuildingReport(apartment1Usage, apartment2Usage, apartment3Usage, AptOne, AptTwo, AptThree, filename);
break;
case 7:
// Binary file
printf("\nSave(1) or print (2) compact usage file: ");
scanf(" %d", &menu_seven);
printf("\n");
if (menu_seven == 1)
{
if (apartment == 1)
{
saveCompactUsage(apartment1Usage, apartment);
}
if (apartment == 2)
{
saveCompactUsage(apartment2Usage, apartment);
}
if (apartment == 3)
{
saveCompactUsage(apartment3Usage, apartment);
}
}
else if (menu_seven == 2)
{
if (apartment == 1)
{
double usage1; // to save usage not equals 0
int i; // index variable
FILE *ReadPtr;
if ((ReadPtr = fopen("compact_usage_1.bin", "rb")) == NULL)
{
puts("WARNING: Save compact usage to file before printing");
}
else
{
printf("\nActive water usage report:\n");
while (!feof(ReadPtr))
{
fread(&i, sizeof(int), 1, ReadPtr);
fread(&usage1, sizeof(double), 1, ReadPtr);
printf("Day %02d %02d:00 : %.3lf kl\n", monthHourToDay(i), monthHourToDailyHour(i), usage1);
}
}
fclose(ReadPtr);
}
if (apartment == 2)
{
double usage2; // to save usage not equals 0
int i; // index variable
FILE *ReadPtr;
if ((ReadPtr = fopen("compact_usage_2.bin", "rb")) == NULL)
{
puts("WARNING: Save compact usage to file before printing");
}
else
{
printf("\nActive water usage report:\n");
while (!feof(ReadPtr))
{
fread(&i, sizeof(int), 1, ReadPtr);
fread(&usage2, sizeof(double), 1, ReadPtr);
printf("Day %02d %02d:00 : %.3lf kl\n", monthHourToDay(i), monthHourToDailyHour(i), usage2);
}
}
fclose(ReadPtr);
}
if (apartment == 3)
{
double usage3; // to save usage not equals 0
int i; // index variable
FILE *ReadPtr;
if ((ReadPtr = fopen("compact_usage_3.bin", "rb")) == NULL)
{
puts("WARNING: Save compact usage to file before printing");
}
else
{
printf("\nActive water usage report:\n");
while (!feof(ReadPtr))
{
fread(&i, sizeof(int), 1, ReadPtr);
fread(&usage3, sizeof(double), 1, ReadPtr);
printf("Day %02d %02d:00 : %.3lf kl\n", monthHourToDay(i), monthHourToDailyHour(i), usage3);
}
}
fclose(ReadPtr);
}
}
break;
case 8:
// Linked Lists
if (apartment == 1)
{
//int i;
for (i = 0; i < SIZE; i++)
{
if (apartment1Usage[i] != 0)
{
addNode(&startPtr, i, apartment1Usage[i]);
}
}
printList(startPtr);
}
if (apartment == 2)
{
for (i = 0; i < SIZE; i++)
{
if (apartment2Usage[i] != 0)
{
addNode(&startPtr, i, apartment2Usage[i]);
}
}
// play around with the * and & operators
// play around with the * and & operators
// play around with the * and & operators
printList(startPtr);
}
if (apartment == 3)
{
for (i = 0; i < SIZE; i++)
{
if (apartment3Usage[i] != 0)
{
addNode(&startPtr, i, apartment3Usage[i]);
}
}
printList(startPtr);
printf("\nMaximum usage for apartment %d:\n", apartment);
j = monthHourOfMaxUsage(startPtr);
printf("Day %02d %02d:00 : %.3lf kl\n", monthHourToDay(j), monthHourToDailyHour(j), apartment3Usage[j]);
}
break;
}
puts("\nRP143 Water Calculator");
puts("1. Print usage patter for apartment");
puts("2. Calculate and print total usage for apartment (in kl)");
puts("3. Calculate and print total bill for apartment (in R)");
puts("4. Print apartment usage report to screen");
puts("5. Check building for leaks and print leak report");
puts("6. Write building water usage report to text file");
puts("7. Save or print compact binary usage file for apartment");
puts("8. Determine and print hour with greatest usage for apartment");
puts("10. Exit");
printf("\nChoose an item from the menu: ");
scanf_s(" %d", &option);
}
return 0;
}
void printApartmentReport(double waterUsage[], ApartmentData data)
{
printf("\nApartment water usage report\n");
printf("Owner: %s %s\n", data.ownerName, data.ownerSurname);
printf("Tariff for apartment: R%.2f per kl\n", data.tariff);
printf("Total usage for this month: %.3f kl\n", getTotalWaterUsage(waterUsage));
printf("Total bill for this month: R%.2f\n", getTotalBill(waterUsage, data.tariff));
}
| [
"chinedu0507@gmail.com"
] | chinedu0507@gmail.com |
0834d81cf1b2ffcc3bc859757dc9653d1db11110 | db469b70a031a2850c3f56affa61530a8adc6032 | /FocusingLens.cpp | ce5189e6451770dd09b9464d9d7de888c983cca9 | [] | no_license | andershelmsworth/templeOfPrimalEvil | f94f389d3abbf1dd4abee3ea90e5ae726be5f6ab | be0902f23fd90541be478bcd06e5304a760db8f2 | refs/heads/master | 2020-12-29T12:01:23.017139 | 2020-02-06T03:10:53 | 2020-02-06T03:10:53 | 238,597,354 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,175 | cpp | /*********************************************************************
** Program Name: The Temple of Primal Evil
** Author: Andrew Helmsworth
** Date: 2019/12/08
** Description: Player Character object traverses linked list of Space objects,
** Description: ...& interacts with Spaces and InventoryObjects in a timed scenario.
** Sources: See works cited at end-of-program comment-block in main.cpp.
*********************************************************************/
//Inclusions
#include "FocusingLens.hpp"
/*********************************************************************
** FocusingLens default constructor
** Paramaters are: none
** What it does: Initializes FocusingLens name
** Returns: No return data.
*********************************************************************/
FocusingLens::FocusingLens()
{
name = "Focusing Lens";
}
/*********************************************************************
** FocusingLens destructor
** Paramaters are: none
** What it does: destroys FocusingLens
** Returns: No return data.
*********************************************************************/
FocusingLens::~FocusingLens()
{
}
| [
"andy.helmsworth@gmail.com"
] | andy.helmsworth@gmail.com |
9b71f336acbf348d308b79ee252ea1c8916a2151 | 070ce743a5bb01852fb3f79ba07a20091157e630 | /code/src/align/src/otherMainFiles/alignAll_openMP_PE_old_old.cpp | 1a0d54a8b56223d93eeca061200c701a71d2adc2 | [] | no_license | LiuBioinfo/iMapSplice | f4d641ade9aa882cb4cdec5efd3d21daea83b2ae | ecf2b1b79014e8a5f3ba8ee19ce5aa833ac292dd | refs/heads/master | 2020-03-22T00:06:42.136338 | 2019-02-08T04:17:05 | 2019-02-08T04:17:05 | 139,225,150 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 74,123 | cpp | // This file is a part of iMapSplice. Please refer to LICENSE.TXT for the LICENSE
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <malloc.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
//#include <hash_map>
#include <map>
#include <set>
#include <omp.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
//#include "csapp.h"
#include <sys/stat.h>
#include <errno.h>
#ifdef CAL_TIME
clock_t read_file_begin, read_file_end, read_file_end2, read_file_end3,
align_begin, align_end, align_cost = 0,
overall_begin, overall_end, overall_cost = 0,
input_begin, input_end, input_cost = 0,
output_begin, output_end, output_cost = 0,
segMap_begin, segMap_end, segMap_cost = 0,
getPath_begin, getPath_end, getPath_cost = 0,
fixGap_begin, fixGap_end, fixGap_cost = 0,
fixGap_1_begin, fixGap_1_end, fixGap_1_cost = 0,
fixGap_2_begin, fixGap_2_end, fixGap_2_cost = 0,
getChrLocation_begin, getChrLocation_end, getChrLocation_cost = 0,
getInterval_begin, getInterval_end, getInterval_cost = 0,
getFirstInterval_begin, getFirstInterval_end, getFirstInterval_cost = 0,
getLcp_begin_1, getLcp_end_1, getLcp_cost_1 = 0,
getLcp_begin_2, getLcp_end_2, getLcp_cost_2 = 0,
getLcp_begin_3, getLcp_end_3, getLcp_cost_3 = 0,
score_string_begin, score_string_end, score_string_cost = 0,
checkTwoStringMatch_begin, checkTwoStringMatch_end, checkTwoStringMatch_cost = 0,
searchPrefix_begin, searchPrefix_end, searchPrefix_cost = 0,
searchInSA_begin, searchInSA_end, searchInSA_cost = 0,
insert2SegInfo_begin, insert2SegInfo_end, insert2SegInfo_cost = 0,
readFromFile_begin, readFromFile_end, readFromFile_cost = 0,
readPreProcess_begin, readPreProcess_end, readPreProcess_cost = 0,
getPEalignInfo_begin, getPEalignInfo_end, getPEalignInfo_cost = 0,
selectBestAlign_begin, selectBestAlign_end, selectBestAlign_cost = 0,
getSamFormat_begin, getSamFormat_end, getSamFormat_cost = 0,
insertSamFormat_begin, insertSamFormat_end, insertSamFormat_cost = 0,
getReadInfo_begin, getReadInfo_end, getReadInfo_cost = 0,
freeMem_begin, freeMem_end, freeMem_cost = 0;
#endif
#include "phase1/arrayQueue_phase1.h"
#include "stats_info.h"
#include "constantDefinitions.h"
#include "general/option_info.h"
#include "general/read_block_test.h"
#include "general/bwtmap_info.h"
#include "general/DoubleAnchorScore.h"
#include "general/sbndm.h"
#include "general/otherFunc.h"
#include "general/index_info.h"
#include "general/enhanced_suffix_array_info.h"
#include "general/annotation_info.h"
#include "phase1/repeatRegion.h"
#include "general/segmentMapping.h"
//#include "segmentMapping_secondLevel.h"
#include "general/splice_info.h"
#include "general/fixGapRelationParameters.h"
#include "general/read_info.h"
#include "general/seg_info.h"
//#include "general/fixDoubleAnchor_annotation_info.h"
#include "general/fixDoubleAnchorMatch_info.h"
#include "general/fixDoubleAnchorInsertion_info.h"
#include "general/fixDoubleAnchorDeletion_info.h"
#include "general/fixDoubleAnchorSplice_complicate_info.h"
#include "general/fixDoubleAnchorSplice_info.h"
#include "general/path_info.h"
#include "general/gap_info.h"
#include "general/align_info.h"
#include "general/peAlign_info.h"
#include "phase2/spliceJunctionHash_info.h"
#include "phase2/unmapEnd_info.h"
#include "phase2/unfixedHead.h"
#include "phase2/unfixedTail.h"
#include "phase2/incompleteLongHead.h"
#include "phase2/incompleteLongTail.h"
#include "phase2/sam2junc.h"
#include "fixHeadTail.h"
#include "phase2/fixOneEndUnmapped.h"
#include "fixPhase1.h"
#include "general/readSeqPreProcessing.h"
#include "general/headerSection_info.h"
#include "general/otherFunc2.h"
#include "general/alignmentToJunc.h"
#include "phase1/phase1_parallelProcesses.h"
using namespace std;
int main(int argc, char**argv)
{
bool checkQualSeqForShortAnchorSeqToTargetMap = false;
cout << "Attention! checkQualSeqForShortAnchorSeqToTargetMap true or not: "
<< checkQualSeqForShortAnchorSeqToTargetMap << endl;
bool checkQualSeqForReadSegSeq = false;
cout << "Attention! checkQualSeqForReadSegSeq true or not: "
<< checkQualSeqForReadSegSeq << endl;
#ifdef CAL_TIME
overall_begin = clock();
#endif
///////////////// get option from command line ////////////////////
Option_Info* optionInfo = new Option_Info();
optionInfo->getOpt_long(argc, argv);
//exit(1);
//////////////////////////////////////////////////
string outputDirStr = optionInfo->outputFolder_path; //argv[3];
string mkdirOutputCommand = "mkdir -p " + outputDirStr;
system(mkdirOutputCommand.c_str());
string settingsLogStr = outputDirStr + "/settings.log";
ofstream settings_log_ofs(settingsLogStr.c_str());
string progressLogStr = outputDirStr + "/process.log";
ofstream log_ofs(progressLogStr.c_str());
string inputLogStr = outputDirStr + "/input.log";
ofstream input_log_ofs(inputLogStr.c_str());
string outputLogStr = outputDirStr + "/output.log";
ofstream output_log_ofs(outputLogStr.c_str());
string mappingLogStr = outputDirStr + "/mapping.log";
ofstream mapping_log_ofs(mappingLogStr.c_str());
string runtimeLogStr = outputDirStr + "/runtime.log";
ofstream runtime_log_ofs(runtimeLogStr.c_str());
string statsStr = outputDirStr + "/stats.txt";
ofstream stats_ofs(statsStr.c_str());
optionInfo->outputOptStr(settings_log_ofs);
///////////////////////////////////////////////////////////////////////////////////////////
/////////////////////// switches of seperate processes ///////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
bool annotation_provided_bool = optionInfo->annotation_provided_bool;
bool Do_annotation_only_bool = false;//annotation_provided_bool;
bool Do_Phase1_Only = optionInfo->Do_phase1_only_bool;
bool outputAlignInfoAndSamForAllPairedAlignmentBool = false;
//outputAlignInfoAndSamForAllPairedAlignmentBool = true;
bool removeAllIntermediateFilesBool = false;
//removeAllIntermediateFilesBool = true;
bool DoSam2JuncBool = false;
DoSam2JuncBool = true;
bool load2ndLevelIndexBool = false;
load2ndLevelIndexBool = true;
bool load2ndLevelIndexBool_compressedSize = false;
load2ndLevelIndexBool_compressedSize = true;
bool DoRemappingOnUnmapEndReadsBool = false;
DoRemappingOnUnmapEndReadsBool = true;
bool DoRemappingOnUnfixedHeadTailAlignmentBool = false;
DoRemappingOnUnfixedHeadTailAlignmentBool = true;
bool outputDirectlyBool_Phase1Only = true;
outputDirectlyBool_Phase1Only = false;
bool Do_cirRNA = true;
Do_cirRNA = false;
//bool Do_extendHeadTail = true;
//Do_extendHeadTail = false;
bool Do_extendHeadTail_phase1 = true;
//Do_extendHeadTail_phase1 = false;
bool Do_extendHeadTail_fixOneEndUnmapped = true;
//Do_extendHeadTail_fixOneEndUnmapped = false;
bool Do_extendHeadTail_fixHeadTail = true;
//Do_extendHeadTail_fixHeadTail = false;
bool Do_fixHeadTail_remapping = true;
//Do_fixHeadTail_remapping = false;
bool Do_fixHeadTail_greedyMapping = true;
//Do_fixHeadTail_greedyMapping = false;
bool Do_fixHeadTail_remappingAndTargetMapping = true;
//Do_fixHeadTail_remappingAndTargetMapping = false;
bool Do_fixHeadTail_remappingAgain = true;
Do_fixHeadTail_remappingAgain = false;
if(Do_Phase1_Only)
{
settings_log_ofs << "Do_Phase1 only!" << endl;
DoSam2JuncBool = false;
load2ndLevelIndexBool = false;
load2ndLevelIndexBool_compressedSize = false;
DoRemappingOnUnmapEndReadsBool = false;
DoRemappingOnUnfixedHeadTailAlignmentBool = false;
}
else
{
settings_log_ofs << "Do_Phase1_Phase2! " << endl;
DoSam2JuncBool = true;//false;
load2ndLevelIndexBool = true;//false;
load2ndLevelIndexBool_compressedSize = true;//false;
DoRemappingOnUnmapEndReadsBool = true;//false;
DoRemappingOnUnfixedHeadTailAlignmentBool = true;//false;
}
int normalRecordNum_1stMapping = 2000000;
int normalRecordNum_fixOneEndUnmapped = 2000000;
int normalRecordNum_fixHeadTail = 2000000;
int readTotalNum = 0;
optionInfo->outputSwitchInfo(Do_Phase1_Only, outputAlignInfoAndSamForAllPairedAlignmentBool,
removeAllIntermediateFilesBool, Do_cirRNA, outputDirectlyBool_Phase1Only,
normalRecordNum_1stMapping, normalRecordNum_fixOneEndUnmapped,
normalRecordNum_fixHeadTail, Do_extendHeadTail_phase1,
Do_extendHeadTail_fixOneEndUnmapped, Do_extendHeadTail_fixHeadTail,
Do_fixHeadTail_remapping, Do_fixHeadTail_greedyMapping,
Do_fixHeadTail_remappingAndTargetMapping, Do_fixHeadTail_remappingAgain, settings_log_ofs);
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
time_t nowtime;
nowtime = time(NULL);
struct tm *local;
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... MPS starts ......" << endl << endl;
log_ofs << endl << "[" << asctime(local) << "... MPS starts ......" << endl << endl;
////////////////////////////////////////////// LOAD INDEX ////////////////////////////////////////////////////////////////
string InputReadFile = optionInfo->read_file_path_1;//read sample, exacted from fastq file every time
string InputReadFile_PE = optionInfo->read_file_path_2;// another end read for pair-end reads
//string threadsNumStr = argv[4];
int threads_num = optionInfo->threads_num;//atoi(threadsNumStr.c_str());
#ifdef CAL_TIME
threads_num = 1;
#endif
#ifdef MAP_INFO
threads_num = 1;
#endif
bool InputAsFastq = (!(optionInfo->fasta_or_fastq_bool));
bool fasta_or_fastq_bool = optionInfo->fasta_or_fastq_bool;
if((checkQualSeqForShortAnchorSeqToTargetMap && fasta_or_fastq_bool)||(checkQualSeqForReadSegSeq && fasta_or_fastq_bool))
{
cout << "if checkQualSeqForShortAnchorSeqToTargetMap, fasta_or_fastq_bool must be true" << endl;
log_ofs << "if checkQualSeqForShortAnchorSeqToTargetMap, fasta_or_fastq_bool must be true" << endl;
cout << "if checkQualSeqForReadSegSeq, fasta_or_fastq_bool must be true" << endl;
log_ofs << "if checkQualSeqForReadSegSeq, fasta_or_fastq_bool must be true" << endl;
exit(1);
}
///////////////////////////////////// LOAD INDEX ////////////////////////////////////////////////////////////////
#ifdef CAL_TIME
read_file_begin = clock();
#endif
nowtime = time(NULL);
//struct tm *local;
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... start to load whole genome index ......" << endl << endl;
log_ofs << endl << "[" << asctime(local) << "... start to load whole genome index ......" << endl << endl;
//cout << "start to load preIndex ..." << endl;
log_ofs << "start to load preIndex ..." << endl;
string preIndexArrayPreStr;
string indexStr;// = "/data/homes/lxauky/adSA_table/mm9_table/testAll2_table/testAll2Index";
string chromDirStr;
string secondLevelIndexStr;
indexStr = optionInfo->global_index_file_path_prefix; //argv[6];
preIndexArrayPreStr = indexStr;
chromDirStr = optionInfo->chromsome_file_path_prefix; //argv[8];
secondLevelIndexStr = optionInfo->local_index_file_path_prefix; //argv[7];
preIndexArrayPreStr.append("/");
indexStr.append("/");
chromDirStr.append("/");
secondLevelIndexStr.append("/");
string preIndexMapLengthArrayStr = preIndexArrayPreStr; preIndexMapLengthArrayStr.append("_MapLength"); ifstream preIndexMapLengthArray_ifs(preIndexMapLengthArrayStr.c_str(), ios::binary);
string preIndexIntervalStartArrayStr = preIndexArrayPreStr; preIndexIntervalStartArrayStr.append("_IntervalStart"); ifstream preIndexIntervalStartArray_ifs(preIndexIntervalStartArrayStr.c_str(), ios::binary);
string preIndexIntervalEndArrayStr = preIndexArrayPreStr; preIndexIntervalEndArrayStr.append("_IntervalEnd"); ifstream preIndexIntervalEndArray_ifs(preIndexIntervalEndArrayStr.c_str(), ios::binary);
int* preIndexMapLengthArray; preIndexMapLengthArray = (int*)malloc(PreIndexSize * sizeof(int)); preIndexMapLengthArray_ifs.read((char*)preIndexMapLengthArray, PreIndexSize * sizeof(int));
unsigned int *preIndexIntervalStartArray; preIndexIntervalStartArray = (unsigned int*)malloc(PreIndexSize * sizeof(unsigned int)); preIndexIntervalStartArray_ifs.read((char*)preIndexIntervalStartArray, PreIndexSize * sizeof(int));
unsigned int *preIndexIntervalEndArray; preIndexIntervalEndArray = (unsigned int*)malloc(PreIndexSize * sizeof(unsigned int)); preIndexIntervalEndArray_ifs.read((char*)preIndexIntervalEndArray, PreIndexSize * sizeof(int));
log_ofs << "finish loading preIndex ..." << endl;
string chrom_bit_file = indexStr; chrom_bit_file.append("_chrom"); ifstream chrom_bit_file_ifs(chrom_bit_file.c_str(),ios::binary);
string parameter_file = indexStr; parameter_file.append("_parameter"); ifstream parameter_file_ifs(parameter_file.c_str(),ios::binary);
Index_Info* indexInfo = new Index_Info(parameter_file_ifs, settings_log_ofs);
settings_log_ofs << "index: " << indexStr << endl;
///////////////////////////////////////
log_ofs << "start to load whole genome" << endl;
char *chrom; chrom = (char*)malloc((indexInfo->returnIndexSize()) * sizeof(char)); chrom_bit_file_ifs.read((char*)chrom, (indexInfo->returnIndexSize()) * sizeof(char));
settings_log_ofs << "indexSize: " << indexInfo->returnIndexSize() << endl;
indexInfo->readGenome(chrom);
settings_log_ofs << "chromSize: " << indexInfo->returnChromStringLength() << endl;
log_ofs << "start to load every chromosome" << endl;
indexInfo->initiate();
log_ofs << "start to initiate chrNameIndexArray" << endl;
indexInfo->initiateChrNameIndexArray(1000);
log_ofs << "finish loading chromosomes" << endl;
///////////////////////////////////// start to load annotation /////////////////////////////////////
nowtime = time(NULL);
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... start to load annotation file (SJs)......" << endl << endl;
log_ofs << endl << "[" << asctime(local) << "... start to load annotation file (SJs) ......" << endl << endl;
string annotation_file_path = optionInfo->annotation_file_path; // junction files
ifstream annotation_ifs(annotation_file_path.c_str());
Annotation_Info* annotationInfo = new Annotation_Info();
if(annotation_provided_bool)
{
//annotation_ifs.open(annotation_file_path);
annotationInfo->initiateAndReadAnnotationFile(indexInfo, annotation_ifs);
}
///////////////////////////////////// finish loading annotation /////////////////////////////////////
string SA_file = indexStr; SA_file.append("_SA");
string lcpCompress_file = indexStr; lcpCompress_file.append("_lcpCompress");
string childTab_file = indexStr; childTab_file.append("_childTab");
string verifyChild_file = indexStr; verifyChild_file.append("_detChild");
unsigned int *sa; sa = (unsigned int*)malloc((indexInfo->returnIndexSize()) * sizeof(unsigned int));
unsigned int *childTab; childTab = (unsigned int*)malloc((indexInfo->returnIndexSize()) * sizeof(unsigned int));
BYTE *lcpCompress; lcpCompress = (BYTE*)malloc((indexInfo->returnIndexSize()) * sizeof(BYTE));
BYTE *verifyChild; verifyChild = (BYTE*)malloc((indexInfo->returnIndexSize()) * sizeof(BYTE));
int *lcpCompress_test; lcpCompress_test = (int*)malloc((indexInfo->returnIndexSize()) * sizeof(int));
int *verifyChild_test; verifyChild_test = (int*)malloc((indexInfo->returnIndexSize()) * sizeof(int));
ifstream SA_file_ifs(SA_file.c_str(),ios::binary);
ifstream lcpCompress_file_ifs(lcpCompress_file.c_str(),ios::binary);
ifstream childTab_file_ifs(childTab_file.c_str(),ios::binary);
ifstream verifyChild_file_ifs(verifyChild_file.c_str(),ios::binary);
nowtime = time(NULL);
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... start to load enhanced Suffix Array ......" << endl << endl;
log_ofs << endl << "[" << asctime(local) << "... start to load enhanced Suffix Array ......" << endl << endl;
log_ofs << "start to load SA" << endl;
SA_file_ifs.read((char*)sa, (indexInfo->returnIndexSize()) * sizeof(unsigned int));
log_ofs << "start to load lcpCompress" << endl;
lcpCompress_file_ifs.read((char*)lcpCompress, (indexInfo->returnIndexSize()) * sizeof(BYTE));
log_ofs << "start to load childTab " << endl;
childTab_file_ifs.read((char*)childTab, (indexInfo->returnIndexSize()) * sizeof(unsigned int));
log_ofs << "start to load detChild" << endl;
verifyChild_file_ifs.read((char*)verifyChild, (indexInfo->returnIndexSize()) * sizeof(BYTE));
log_ofs << "All index files loaded" << endl;
nowtime = time(NULL);
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... all index loaded ......" << endl << endl;
log_ofs << endl << "[" << asctime(local) << "... all index loaded ......" << endl << endl;
runtime_log_ofs << endl << "[" << asctime(local) << "... all index loaded ......" << endl << endl;
#ifdef CAL_TIME
read_file_end = clock();
double read_file_time = (double)(read_file_end - read_file_begin)/CLOCKS_PER_SEC;
log_ofs << "read_file cpu time = " << read_file_time << endl;
#endif
//////////////////////////////////////////////////
HeaderSection_Info* headerSectionInfo = new HeaderSection_Info(indexInfo);
////////////////////////////////////////////////// finish LOADing INDEX ////////////////////////////////////////////////////////////////
////////////////////////////////////////////////// finish LOADing INDEX ////////////////////////////////////////////////////////////////
Stats_Info* statsInfo = new Stats_Info();
statsInfo->initiate_stats_info_PE(threads_num);
////////////////////////////////////////////////// 1st Mapping Process ////////////////////////////////////////////////////////////////
////////////////////////////////////////////////// 1st Mapping Process ////////////////////////////////////////////////////////////////
/* align main*/
string tmpHeadSectionInfo = outputDirStr + "/headSectionInfo";
ofstream tmpHeadSectionInfo_ofs(tmpHeadSectionInfo.c_str());
tmpHeadSectionInfo_ofs << headerSectionInfo->returnHeaderSectionInfoStr() << endl;
tmpHeadSectionInfo_ofs.close();
string mkdirOutputCommand_phase1 = "mkdir -p " + outputDirStr + "/phase1_output";
system(mkdirOutputCommand_phase1.c_str());
string mkdirOutputCommand_repeatRegionFile = mkdirOutputCommand_phase1 + "/repeat_region";
system(mkdirOutputCommand_repeatRegionFile.c_str());
string repeatRegionFile = outputDirStr + "/phase1_output/repeat_region/repeatRegion";
ofstream repeatRegionFile_ofs(repeatRegionFile.c_str());
string mkdirOutputCommand_tmpAlignCompleteRead = mkdirOutputCommand_phase1 + "/completePair";
system(mkdirOutputCommand_tmpAlignCompleteRead.c_str());
string tmpAlignCompleteRead = outputDirStr + "/phase1_output/completePair/completePair.sam";
ofstream tmpAlignCompleteRead_ofs(tmpAlignCompleteRead.c_str());
string tmpAlignCompleteRead_alignInfo = outputDirStr + "/phase1_output/completePair/completePair.sam_alignInfo";
ofstream tmpAlignCompleteRead_alignInfo_ofs(tmpAlignCompleteRead_alignInfo.c_str());
#ifdef CHECK_MULTI
string tmpAlignCompleteRead_multi = outputDirStr + "/phase1_output/completePair/completePair.sam.multi";
ofstream tmpAlignCompleteRead_multi_ofs(tmpAlignCompleteRead_multi.c_str());
string tmpAlignCompleteRead_unique = outputDirStr + "/phase1_output/completePair/completePair.sam.unique";
ofstream tmpAlignCompleteRead_unique_ofs(tmpAlignCompleteRead_unique.c_str());
#endif
string mkdirOutputCommand_tmpAlignOneEndUnmapped = mkdirOutputCommand_phase1 + "/oneEndUnmapped";
system(mkdirOutputCommand_tmpAlignOneEndUnmapped.c_str());
string tmpAlignOneEndUnmapped = outputDirStr + "/phase1_output/oneEndUnmapped/oneEndUnmapped";
if(Do_Phase1_Only)
tmpAlignOneEndUnmapped += ".sam";
else
tmpAlignOneEndUnmapped += ".alignInfo";
ofstream tmpAlignOneEndUnmapped_ofs(tmpAlignOneEndUnmapped.c_str());
//string mkdirOutputCommand_tmpAlignBothEndsUnmapped_mappedToRepeatRegionFile = mkdirOutputCommand_phase1 + "/bothEndsUnmapped_mappedToRepeatRegion";
//system(mkdirOutputCommand_tmpAlignBothEndsUnmapped_mappedToRepeatRegionFile.c_str());
string tmpAlignBothEndsUnmapped_mappedToRepeatRegionFile
= outputDirStr + "/phase1_output/repeat_region/bothEndsUnmapped_mappedToRepeatRegion.sam";
ofstream tmpAlignBothEndsUnmapped_mappedToRepeatRegionFile_ofs(
tmpAlignBothEndsUnmapped_mappedToRepeatRegionFile.c_str());
string mkdirOutputCommand_tmpAlignBothEndsUnmapped = mkdirOutputCommand_phase1 + "/bothEndsUnmapped";
system(mkdirOutputCommand_tmpAlignBothEndsUnmapped.c_str());
string tmpAlignBothEndsUnmapped = outputDirStr + "/phase1_output/bothEndsUnmapped/bothEndsUnmapped.sam";
ofstream tmpAlignBothEndsUnmapped_ofs(tmpAlignBothEndsUnmapped.c_str());
string tmpAlignBothEndsUnmapped_lowScore = outputDirStr + "/phase1_output/bothEndsUnmapped/bothEndsUnmapped_lowScore.sam";
ofstream tmpAlignBothEndsUnmapped_lowScore_ofs(tmpAlignBothEndsUnmapped_lowScore.c_str());
string mkdirOutputCommand_tmpAlignIncompletePair = mkdirOutputCommand_phase1 + "/incomplete";
system(mkdirOutputCommand_tmpAlignIncompletePair.c_str());
string tmpAlignIncompletePair = outputDirStr + "/phase1_output/incomplete/incomplete.alignInfo";
ofstream tmpAlignIncompletePair_ofs(tmpAlignIncompletePair.c_str());
string tmpAlignIncompletePair_SAM = outputDirStr + "/phase1_output/incomplete/incompletePair.sam";
ofstream tmpAlignIncompletePair_SAM_ofs(tmpAlignIncompletePair_SAM.c_str());
string tmpIntermediateJunctionFile = outputDirStr + "/phase2_output/inter.junc";
ifstream inputRead_ifs(InputReadFile.c_str());
ifstream inputRead_PE_ifs(InputReadFile_PE.c_str());
vector< RepeatRegion_Info* > repeatRegionInfoVec;
for(int tmp = 0; tmp < threads_num; tmp++)
{
RepeatRegion_Info* repeatRegionInfo = new RepeatRegion_Info();
repeatRegionInfoVec.push_back(repeatRegionInfo);
}
nowtime = time(NULL);
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... 1st mapping process starts ......" << endl << endl;
log_ofs << endl << "[" << asctime(local) << "... 1st mapping process starts ......" << endl << endl;
runtime_log_ofs << endl << "[" << asctime(local) << "... 1st mapping process starts ......" << endl << endl;
InputReadPreProcess* readPreProcessInfo = new InputReadPreProcess();
Read_Array_Queue* readArrayQueue = new Read_Array_Queue();
Result_Array_Queue* resultArrayQueue = new Result_Array_Queue();
int inputReadNumInBatchArray = TotalReadNumInReadArray;
bool endOfFile_bool = false;
bool endOfProcessing_bool = false;
omp_set_num_threads(2);
omp_set_nested(1);
#pragma omp parallel
{
#pragma omp sections
{
#pragma omp section
io_stage_phase1(inputRead_ifs,
inputRead_PE_ifs,
readArrayQueue,
resultArrayQueue,
endOfFile_bool,
endOfProcessing_bool,
inputReadNumInBatchArray,
log_ofs,
readPreProcessInfo,
tmpAlignCompleteRead_ofs,
tmpAlignIncompletePair_ofs,
tmpAlignOneEndUnmapped_ofs,
tmpAlignBothEndsUnmapped_ofs,
tmpAlignBothEndsUnmapped_lowScore_ofs,
tmpAlignBothEndsUnmapped_mappedToRepeatRegionFile_ofs,
tmpAlignIncompletePair_SAM_ofs, input_log_ofs, output_log_ofs);
// #pragma omp section
// test(2);
#pragma omp section
process_stage_phase1(
readArrayQueue,
resultArrayQueue,
endOfFile_bool,
endOfProcessing_bool,
threads_num-1,
sa,
lcpCompress,
childTab,
chrom,
verifyChild,
indexInfo,
preIndexMapLengthArray,
preIndexIntervalStartArray,
preIndexIntervalEndArray,
repeatRegionInfoVec,
Do_cirRNA,
Do_extendHeadTail_phase1,
annotation_provided_bool,
Do_annotation_only_bool,
annotationInfo,
outputDirectlyBool_Phase1Only,
Do_Phase1_Only,
statsInfo,
fasta_or_fastq_bool, mapping_log_ofs,//, mapping_log_ofs_vec
checkQualSeqForReadSegSeq
);
}
}
//log_ofs << "perfectMatch_pair #: " << perfectMatch_pair << endl;
repeatRegionFile_ofs << "Repeat Region Info: size = " << repeatRegionInfoVec.size() << endl;
for(int tmpThread = 0; tmpThread < threads_num; tmpThread++)
{
repeatRegionInfoVec[tmpThread]->outputRepeatRegion(tmpThread+1, indexInfo, sa, 100, repeatRegionFile_ofs);
//repeatRegionInfoVec[tmpThread]->outputRepeatRegion(esaInfo, tmpThread+1, indexInfo, //sa,
// 100, repeatRegionFile_ofs);
}
settings_log_ofs << "readTotalNum: " << readTotalNum << endl;
inputRead_ifs.close();
inputRead_PE_ifs.close();
tmpAlignCompleteRead_ofs.close();
tmpAlignOneEndUnmapped_ofs.close();
tmpAlignBothEndsUnmapped_ofs.close();
tmpAlignBothEndsUnmapped_mappedToRepeatRegionFile_ofs.close();
tmpAlignIncompletePair_SAM_ofs.close();
if(Do_Phase1_Only)
{
tmpAlignIncompletePair_ofs.close();
}
//fclose(fp_in);
free(preIndexMapLengthArray); free(preIndexIntervalStartArray); free(preIndexIntervalEndArray);
free(sa);free(lcpCompress);//free(child_up);free(child_down);free(child_next);
free(childTab);
free(verifyChild);
free(chrom);
//esaInfo->freeMem();
//delete esaInfo;
#ifdef CAL_TIME
overall_end = clock();
#endif
nowtime = time(NULL);
//struct tm *local;
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... 1st mapping process ends ......" << endl << endl;
log_ofs << endl << "[" << asctime(local) << "... 1st mapping process ends ......" << endl << endl;
runtime_log_ofs << endl << "[" << asctime(local) << "... 1st mapping process ends ......" << endl << endl;
log_ofs << endl << "**********************************" << endl << "**********************************";
runtime_log_ofs << endl << "**********************************" << endl << "**********************************";
#ifdef CAL_TIME
//if(threads_num == 1)
//{
double overall_time = (double)(overall_end - overall_begin)/CLOCKS_PER_SEC;
double input_time = (double)input_cost/CLOCKS_PER_SEC;
double align_time = (double)align_cost/CLOCKS_PER_SEC;
double ouput_time = (double)output_cost/CLOCKS_PER_SEC;
double getReadInfo_time = (double)getReadInfo_cost/CLOCKS_PER_SEC;
double segMap_time = (double)segMap_cost/CLOCKS_PER_SEC;
double getPath_time = (double)getPath_cost/CLOCKS_PER_SEC;
double fixGap_time = (double)fixGap_cost/CLOCKS_PER_SEC;
double fixGap_1_time = (double)fixGap_1_cost/CLOCKS_PER_SEC;
double fixGap_2_time = (double)fixGap_2_cost/CLOCKS_PER_SEC;
double getChrLocation_time = (double)getChrLocation_cost/CLOCKS_PER_SEC;
double getPEalignInfo_time = (double)getPEalignInfo_cost/CLOCKS_PER_SEC;
double selectBestAlign_time = (double)selectBestAlign_cost/CLOCKS_PER_SEC;
double getSamFormat_time = (double)getSamFormat_cost/CLOCKS_PER_SEC;
double freeMem_time = (double)freeMem_cost/CLOCKS_PER_SEC;
double getInterval_time = (double)getInterval_cost/CLOCKS_PER_SEC;
double getFirstInterval_time = (double)getFirstInterval_cost/CLOCKS_PER_SEC;
double getLcp_1_time = (double)getLcp_cost_1/CLOCKS_PER_SEC;
double getLcp_2_time = (double)getLcp_cost_2/CLOCKS_PER_SEC;
double getLcp_3_time = (double)getLcp_cost_3/CLOCKS_PER_SEC;
double searchPrefix_time = (double)searchPrefix_cost/CLOCKS_PER_SEC;
double searchInSA_time = (double)searchInSA_cost/CLOCKS_PER_SEC;
double insert2SegInfo_time = (double)insert2SegInfo_cost/CLOCKS_PER_SEC;
double readFromFile_time = (double)readFromFile_cost/CLOCKS_PER_SEC;
double readPreProcess_time = (double)readPreProcess_cost/CLOCKS_PER_SEC;
double score_string_time = (double)score_string_cost/CLOCKS_PER_SEC;
double checkTwoStringMatch_time = (double)checkTwoStringMatch_cost/CLOCKS_PER_SEC;
log_ofs << endl << "overall_time = " << overall_time << endl;
log_ofs << endl << "input_time = " << input_time << endl;
log_ofs << endl << "align_time = " << align_time << endl << endl;
log_ofs << endl << "getReadInfo_time = " << getReadInfo_time << endl;
log_ofs << endl << "segMap_time = " << segMap_time << endl;
log_ofs << endl << "getPath_time = " << getPath_time << endl;
log_ofs << endl << "fixGap_time = " << fixGap_time << endl;
log_ofs << endl << "fixGap_1_time = " << fixGap_1_time << endl;
log_ofs << endl << "fixGap_2_time = " << fixGap_2_time << endl;
log_ofs << endl << "getChrLocation_time = " << getChrLocation_time << endl;
log_ofs << endl << "getPEalignInfo_time = " << getPEalignInfo_time << endl;
log_ofs << endl << "selectBestAlign_time = " << selectBestAlign_time << endl;
log_ofs << endl << "getSamFormat_time = " << getSamFormat_time << endl;
log_ofs << endl << "freeMem_time = " << freeMem_time << endl;
log_ofs << endl << endl << "ouput_time = " << ouput_time << endl;
log_ofs << endl << "getInterval_time = " << getInterval_time << endl;
log_ofs << endl << "getFirstInterval_time = " << getFirstInterval_time << endl;
log_ofs << endl << "getLcp_time_1 = " << getLcp_1_time << endl;
log_ofs << endl << "getLcp_time_2 = " << getLcp_2_time << endl;
log_ofs << endl << "getLcp_time_3 = " << getLcp_3_time << endl;
log_ofs << endl << "searchPrefix_time = " << searchPrefix_time << endl;
log_ofs << endl << "searchInSA_time = " << searchInSA_time << endl;
log_ofs << endl << "insert2SegInfo_time = " << insert2SegInfo_time << endl;
log_ofs << endl << "readFromFile_time = " << readFromFile_time << endl;
log_ofs << endl << "readPreProcess_time = " << readPreProcess_time << endl;
log_ofs << endl << "score_string_time = " << score_string_time << endl;
log_ofs << endl << "checkTwoStringMatch_time = " << checkTwoStringMatch_time << endl;
if(threads_num != 1)
log_ofs << "!!! set thread=1 to get the time-cost information ... !!!" << endl;
#endif
log_ofs << endl << "**********************************" << endl << "**********************************" << endl;
//cout << endl << "totalReadNum = " << read_num << endl;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////// Load Second Level Index ////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
nowtime = time(NULL);
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... start to load 2nd level index ......" << endl << endl;
log_ofs << endl << "[" << asctime(local) << "... load 2nd level index starts ......" << endl << endl;
vector<char*> secondLevelChrom;
vector<unsigned int*> secondLevelSa;
vector<BYTE*> secondLevelLcpCompress;
vector<unsigned int*> secondLevelChildTab;
vector<BYTE*> secondLevelDetChild;
if(load2ndLevelIndexBool)
{
log_ofs << "start to load second-level index ..." << endl;
int secondLevelIndexNO = 0;
for(int tmpChrNO = 0; tmpChrNO < indexInfo->returnChromNum(); tmpChrNO ++)
{
for(int tmpSecondLevelIndexNO = 1; tmpSecondLevelIndexNO <= (indexInfo->returnSecondLevelIndexPartsNum(tmpChrNO)); tmpSecondLevelIndexNO ++)
{
char tmpFileNumChar[4];
sprintf(tmpFileNumChar, "%d", tmpSecondLevelIndexNO);
string tmpFileNumStr = tmpFileNumChar;
string inputIndexFileStr = secondLevelIndexStr + "/" +
//indexInfo->chrNameStr[tmpChrNO]
indexInfo->returnChrNameStr(tmpChrNO)
+ "/"
//+ indexInfo->chrNameStr[tmpChrNO] + "_part."
+ tmpFileNumStr + "/";//"." + "test3_";
string secondLevelIndexFileChromStr = inputIndexFileStr + "chrom";
ifstream secondLevelChrom_file_ifs(secondLevelIndexFileChromStr.c_str(), ios::binary);
string secondLevelIndexFileSaStr = inputIndexFileStr + "SA";
ifstream secondLevelSA_file_ifs(secondLevelIndexFileSaStr.c_str(), ios::binary);
string secondLevelIndexFileLcpCompressStr = inputIndexFileStr + "_lcpCompress";
ifstream secondLevelLcpCompress_file_ifs(secondLevelIndexFileLcpCompressStr.c_str(), ios::binary);
string secondLevelIndexFileChildTabStr = inputIndexFileStr + "childTab";
ifstream secondLevelChildTab_file_ifs(secondLevelIndexFileChildTabStr.c_str(), ios::binary);
string secondLevelIndexFileDetChildStr = inputIndexFileStr + "detChild";
ifstream secondLevelDetChild_file_ifs(secondLevelIndexFileDetChildStr.c_str(), ios::binary);
int sizeOfIndex = indexInfo->returnSecondLevelIndexNormalSize() + 1;
char* tmpSecondLevelChrom = (char*)malloc(sizeOfIndex * sizeof(char));
for(int tmpMallocSpace = 0; tmpMallocSpace < sizeOfIndex; tmpMallocSpace++)
{
tmpSecondLevelChrom[tmpMallocSpace] = '0';
}
secondLevelChrom_file_ifs.read((char*)tmpSecondLevelChrom, sizeOfIndex * sizeof(char));
if(tmpSecondLevelChrom[sizeOfIndex-1] != 'X')
{
//(indexInfo->invalidSecondLevelIndexNOset).insert(secondLevelIndexNO + 1);
indexInfo->insert2invalidSecondLevelIndexNOset(secondLevelIndexNO + 1);
}
bool No_ATGC_Bool = true;
for(int tmpMallocSpace = 0; tmpMallocSpace < sizeOfIndex; tmpMallocSpace++)
{
char ch = tmpSecondLevelChrom[tmpMallocSpace];
if((ch == 'A')||(ch == 'T')||(ch == 'G')||(ch == 'C'))
{
No_ATGC_Bool = false;
break;
}
}
if(No_ATGC_Bool)
{
//(indexInfo->invalidSecondLevelIndexNOset).insert(secondLevelIndexNO + 1);
indexInfo->insert2invalidSecondLevelIndexNOset(secondLevelIndexNO + 1);
}
secondLevelChrom.push_back(tmpSecondLevelChrom);
unsigned int* tmpSecondLevelSa = (unsigned int*)malloc(sizeOfIndex * sizeof(unsigned int));
secondLevelSA_file_ifs.read((char*)tmpSecondLevelSa, sizeOfIndex * sizeof(unsigned int));
secondLevelSa.push_back(tmpSecondLevelSa);
BYTE* tmpSecondLevelLcpCompress = (BYTE*)malloc(sizeOfIndex * sizeof(BYTE));
secondLevelLcpCompress_file_ifs.read((char*)tmpSecondLevelLcpCompress, sizeOfIndex * sizeof(BYTE));
secondLevelLcpCompress.push_back(tmpSecondLevelLcpCompress);
unsigned int* tmpSecondLevelChildTab = (unsigned int*)malloc(sizeOfIndex * sizeof(unsigned int));
secondLevelChildTab_file_ifs.read((char*)tmpSecondLevelChildTab, sizeOfIndex * sizeof(unsigned int));
secondLevelChildTab.push_back(tmpSecondLevelChildTab);
BYTE* tmpSecondLevelDetChild = (BYTE*)malloc(sizeOfIndex * sizeof(BYTE));
secondLevelDetChild_file_ifs.read((char*)tmpSecondLevelDetChild, sizeOfIndex * sizeof(BYTE));
secondLevelDetChild.push_back(tmpSecondLevelDetChild);
secondLevelChrom_file_ifs.close();
secondLevelSA_file_ifs.close();
secondLevelLcpCompress_file_ifs.close();
secondLevelChildTab_file_ifs.close();
secondLevelDetChild_file_ifs.close();
secondLevelIndexNO ++;
}
log_ofs << "finish loading 2nd-level index of " << indexInfo->returnChrNameStr(tmpChrNO) << endl;
}
log_ofs << "finish loading ALL 2nd-level index !" << endl;
log_ofs << indexInfo->getInvalidSecondLevelIndexNOstr() << endl;
//loadIndex_end = clock();
}
nowtime = time(NULL);
//struct tm *local;
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... load 2nd level index ends ......" << endl << endl ;
log_ofs << endl << "[" << asctime(local) << "... load 2nd level index ends ......" << endl << endl ;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// Do REMAPPING On one end unmapped Reads ///////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
nowtime = time(NULL);
//struct tm *local;
local = localtime(&nowtime);
cout << endl << endl << "[" << asctime(local)
<< "... fixing oneEndUnmapped reads starts ......" << endl << endl ;
log_ofs << endl << endl << "[" << asctime(local)
<< "... fixing oneEndUnmapped reads starts ......" << endl << endl ;
runtime_log_ofs << endl << endl << "[" << asctime(local)
<< "... fixing oneEndUnmapped reads starts ......" << endl << endl ;
string mkdirOutputCommand_phase2 = "mkdir -p " + outputDirStr + "/phase2_output";
system(mkdirOutputCommand_phase2.c_str());
string OutputSamFile_oneEndMapped = outputDirStr + "/phase2_output/oneEndUnmapped.pairedComplete.sam";
ofstream OutputSamFile_oneEndMapped_ofs(OutputSamFile_oneEndMapped.c_str());
string OutputSamFile_oneEndMapped_bothEndsUnmapped_lowScore = outputDirStr + "/phase2_output/oneEndUnmapped.bothEndsUnmapped_lowScore.sam";
ofstream OutputSamFile_oneEndMapped_bothEndsUnmapped_lowScore_ofs(OutputSamFile_oneEndMapped_bothEndsUnmapped_lowScore.c_str());
string OutputSamFile_oneEndMapped_unpair = outputDirStr + "/phase2_output/oneEndUnmapped.unpaired.sam";
ofstream OutputSamFile_oneEndMapped_unpair_ofs(OutputSamFile_oneEndMapped_unpair.c_str());
string OutputSamFile_oneEndMapped_alignInfo = outputDirStr + "/phase2_output/oneEndUnmapped.pairedComplete.sam_alignInfo";
ofstream OutputSamFile_oneEndMapped_alignInfo_ofs(OutputSamFile_oneEndMapped_alignInfo.c_str());
int tmpRecordNum_oneEndUnmapped = 0;
if(DoRemappingOnUnmapEndReadsBool)
{
nowtime = time(NULL);
local = localtime(&nowtime);
log_ofs << endl << endl << "[" << asctime(local) << "start doing remapping on unmapped end reads" << endl;
runtime_log_ofs << endl << endl << "[" << asctime(local) << "start doing remapping on unmapped end reads" << endl;
cout << endl << endl << "[" << asctime(local) << "start doing remapping on unmapped end reads" << endl;
string oneEndMappedFileStr = tmpAlignOneEndUnmapped;
ifstream inputRecord_ifs(oneEndMappedFileStr.c_str());
int normalRecordNum = normalRecordNum_fixOneEndUnmapped; //1000000;
bool EndOfRecord = false;
int tmpTurn = 0;
int realRecordNum;// = normalRecordNum;
//getline(inputRecord_ifs, line11);
for(tmpTurn = 0; /*tmpTurn < TurnNum*/; tmpTurn++)
{
vector<string> line1StrVec(normalRecordNum);
vector<string> line2StrVec(normalRecordNum);
vector<string> line3StrVec(normalRecordNum);
vector<string> line4StrVec(normalRecordNum);
vector<string> line5StrVec(normalRecordNum);
vector<string> line6StrVec(normalRecordNum);
vector<string> line7StrVec(normalRecordNum);
vector<string> line8StrVec(normalRecordNum);
vector<string> line9StrVec(normalRecordNum);
vector<string> line10StrVec(normalRecordNum);
vector<string> peAlignInfoVec_fixUnpair(normalRecordNum);
vector<string> peAlignSamVec_fixUnpair(normalRecordNum);
vector<string> peAlignSamVec_unpair_fixUnpair(normalRecordNum);
vector<string> peAlignInfoVec_pair_complete_fixUnpair(normalRecordNum);
vector<string> peAlignSamVec_bothEndsUnmapped_lowScore_fixUnpair(normalRecordNum);
if(EndOfRecord)
break;
int recordNum = normalRecordNum;
nowtime = time(NULL);
local = localtime(&nowtime);
runtime_log_ofs << endl << endl << "[" << asctime(local)
<< "start to input oneEndUnmapped records, turn: " << tmpTurn+1 << endl;
cout << endl << endl << "[" << asctime(local)
<< "start to input oneEndUnmapped records, turn: " << tmpTurn+1 << endl;
realRecordNum = normalRecordNum;
for(int recordNumTmp = 0; recordNumTmp < recordNum; recordNumTmp++)
{
string line1, line2, line3, line4, line5, line6, line7,
line8, line9, line10, line11;
if(inputRecord_ifs.eof())
{
realRecordNum = recordNumTmp;
EndOfRecord = true;
break;
}
getline(inputRecord_ifs, line11);
if(inputRecord_ifs.eof())
{
realRecordNum = recordNumTmp;
EndOfRecord = true;
break;
}
getline(inputRecord_ifs, line1);
getline(inputRecord_ifs, line2);
getline(inputRecord_ifs, line3);
getline(inputRecord_ifs, line4);
getline(inputRecord_ifs, line5);
getline(inputRecord_ifs, line6);
getline(inputRecord_ifs, line7);
getline(inputRecord_ifs, line8);
getline(inputRecord_ifs, line9);
getline(inputRecord_ifs, line10);
//getline(inputRecord_ifs, line11);
line1StrVec[recordNumTmp] = line1;
line2StrVec[recordNumTmp] = line2;
line3StrVec[recordNumTmp] = line3;
line4StrVec[recordNumTmp] = line4;
line5StrVec[recordNumTmp] = line5;
line6StrVec[recordNumTmp] = line6;
line7StrVec[recordNumTmp] = line7;
line8StrVec[recordNumTmp] = line8;
line9StrVec[recordNumTmp] = line9;
line10StrVec[recordNumTmp] = line10;
}
runtime_log_ofs << "realRecordNum: " << realRecordNum << " turn: " << tmpTurn+1 << endl;
nowtime = time(NULL);
local = localtime(&nowtime);
runtime_log_ofs << endl << "[" << asctime(local)
<< "finish reading record, turn: " << tmpTurn+1 << endl;
runtime_log_ofs << endl << "[" << asctime(local)
<< "start to fix oneEndUnmapped, turn: " << tmpTurn+1 << endl;
cout << endl << "[" << asctime(local)
<< "finish reading record, turn: " << tmpTurn+1 << endl;
cout << endl << "[" << asctime(local)
<< "start to fix oneEndUnmapped, turn: " << tmpTurn+1 << endl;
omp_set_num_threads(threads_num);
//omp_set_num_threads(1);
#pragma omp parallel for schedule(dynamic)
for(int tmpOpenMP = 0; tmpOpenMP < realRecordNum; tmpOpenMP++)
{
//////////////// parse long head reads record after 1-mapping process ///////////////////////////////////////
//tmpRecordNum_oneEndUnmapped ++;
int threadNO = omp_get_thread_num();
PE_Read_Info peReadInfo;// = new PE_Read_Info();
PE_Read_Alignment_Info* peAlignInfo = new PE_Read_Alignment_Info();
peAlignInfo->generatePeReadInfoAndPeAlignInfo_toFixOneEndUnmapped_getline(
line1StrVec[tmpOpenMP], line2StrVec[tmpOpenMP], line3StrVec[tmpOpenMP],
line4StrVec[tmpOpenMP], line5StrVec[tmpOpenMP], line6StrVec[tmpOpenMP],
line7StrVec[tmpOpenMP], line8StrVec[tmpOpenMP], //line9StrVec[tmpOpenMP],
line9StrVec[tmpOpenMP], line10StrVec[tmpOpenMP], peReadInfo, indexInfo, fasta_or_fastq_bool);
FixOneEndUnmappedInfo* fixOneEndUnmappedInfo = new FixOneEndUnmappedInfo();
fixOneEndUnmappedInfo->fixOneEndUnmapped(peReadInfo, peAlignInfo,
secondLevelChrom,
secondLevelSa,
secondLevelLcpCompress,
secondLevelChildTab,
secondLevelDetChild,
indexInfo, Do_extendHeadTail_fixOneEndUnmapped,
annotation_provided_bool, Do_annotation_only_bool, annotationInfo, MAX_SPLICE_DISTANCE_PHASE2,
checkQualSeqForReadSegSeq);
peAlignInfo->alignmentFilter_fixOneEndUnmapped_SJpenalty(peReadInfo.returnReadSeqLength_1(),
peReadInfo.returnReadSeqLength_2());
bool pairExistsBool = peAlignInfo->finalPairExistsBool();
bool allAlignmentCompleteBool = peAlignInfo->allAlignmentInFinalPairCompleted();
bool allUnpairedAlignmentCompleteBool = peAlignInfo->allUnpairedAlignmentCompleted();
bool unique_bool = peAlignInfo->checkUniqueOrMulti();
statsInfo->increNum_fixUnpaired(threadNO, pairExistsBool, allAlignmentCompleteBool,
allUnpairedAlignmentCompleteBool, unique_bool);
peAlignSamVec_fixUnpair[tmpOpenMP] = "";
peAlignInfoVec_fixUnpair[tmpOpenMP] = "";
peAlignSamVec_unpair_fixUnpair[tmpOpenMP] = "";
peAlignSamVec_bothEndsUnmapped_lowScore_fixUnpair[tmpOpenMP] = "";
if(pairExistsBool && allAlignmentCompleteBool) // some pair exists, all completed, print out paired SAM info
{
int alignment_score_min_output
//= peReadInfo.returnAlignmentScoreMinOutput_withComplement(
// ALIGNMENT_SCORE_MIN_OUTPUT_COMPLEMENT);
= peReadInfo.returnAlignmentScoreMinOutput_withComplement_perHundredBases(
ALIGNMENT_SCORE_MIN_OUTPUT_COMPLEMENT_PerHundredBases);
bool completeAlign_lowScore_bool
= peAlignInfo->alignPairScoreTooLow_bool(alignment_score_min_output);
if(completeAlign_lowScore_bool)
{
statsInfo->increLowScoreComplete_fixUnpair(threadNO, unique_bool);
peAlignSamVec_bothEndsUnmapped_lowScore_fixUnpair[tmpOpenMP]
= peAlignInfo->getSAMformatForBothEndsUnmapped(peReadInfo, fasta_or_fastq_bool);
}
else
{
peAlignSamVec_fixUnpair[tmpOpenMP]
= peAlignInfo->getSAMformatForFinalPair_secondaryOrNot(peReadInfo,
fasta_or_fastq_bool);
}
}
else if(pairExistsBool && (!allAlignmentCompleteBool)) // pair exists, incomplete
{
peAlignInfoVec_fixUnpair[tmpOpenMP]
= peAlignInfo->getTmpAlignInfoForFinalPair(
peReadInfo.returnReadName_1(), peReadInfo.returnReadName_2(),
peReadInfo.returnReadSeq_1(), peReadInfo.returnReadSeq_2(),
peReadInfo.returnReadQual_1(), peReadInfo.returnReadQual_2(),
fasta_or_fastq_bool);
}
else
{
peAlignSamVec_unpair_fixUnpair[tmpOpenMP]
= peAlignInfo->getSAMformatForUnpairedAlignments_secondaryOrNot(
peReadInfo, fasta_or_fastq_bool);
}
delete fixOneEndUnmappedInfo;
peAlignInfo->memoryFree();
delete peAlignInfo;
}
nowtime = time(NULL);
local = localtime(&nowtime);
runtime_log_ofs << endl << "[" << asctime(local)
<< "finish fixing oneEndUnmapped, turn: " << tmpTurn+1 << endl;// << endl;
runtime_log_ofs << "start to output ... turn: " << tmpTurn+1 << endl;
cout << endl << "[" << asctime(local)
<< "finish fixing oneEndUnmapped, turn: " << tmpTurn+1 << endl;// << endl;
cout << "start to output ... turn: " << tmpTurn+1 << endl;
for(int tmp = 0; tmp < realRecordNum; tmp++)
{
if(peAlignSamVec_fixUnpair[tmp] != "")
{
OutputSamFile_oneEndMapped_ofs << peAlignSamVec_fixUnpair[tmp] << endl;
}
if(peAlignInfoVec_fixUnpair[tmp] != "")
{
tmpAlignIncompletePair_ofs << peAlignInfoVec_fixUnpair[tmp] << endl;
}
if(peAlignSamVec_unpair_fixUnpair[tmp] != "")
{
OutputSamFile_oneEndMapped_unpair_ofs << peAlignSamVec_unpair_fixUnpair[tmp] << endl;
}
if(peAlignSamVec_bothEndsUnmapped_lowScore_fixUnpair[tmp] != "")
{
OutputSamFile_oneEndMapped_bothEndsUnmapped_lowScore_ofs << peAlignSamVec_bothEndsUnmapped_lowScore_fixUnpair[tmp] << endl;
}
}
nowtime = time(NULL);
local = localtime(&nowtime);
runtime_log_ofs << endl << "[" << asctime(local)
<< "finish output, turn: " << tmpTurn+1 << endl << endl;// << endl;
cout << endl << "[" << asctime(local)
<< "finish output, turn: " << tmpTurn+1 << endl << endl;// << endl;
}
inputRecord_ifs.close();
}
OutputSamFile_oneEndMapped_ofs.close();
OutputSamFile_oneEndMapped_unpair_ofs.close();
tmpAlignIncompletePair_ofs.close();
OutputSamFile_oneEndMapped_bothEndsUnmapped_lowScore_ofs.close();
//tmpAlignInfoForDebugFile_oneEndMapped_ofs.close();
nowtime = time(NULL);
//struct tm *local;
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... fixing oneEndUnmapped reads ends ......" << endl << endl;
log_ofs << endl << "[" << asctime(local) << "... fixing oneEndUnmapped reads ends ......" << endl << endl;
runtime_log_ofs << endl << "[" << asctime(local) << "... fixing oneEndUnmapped reads ends ......" << endl << endl;
log_ofs << endl << "**********************************************************************************" << endl << endl;
runtime_log_ofs << endl << "**********************************************************************************" << endl << endl;
/////////////////////////////////////// merging incomplete alignment files ///////////////////////////////////////////
if(outputDirectlyBool_Phase1Only)
{
log_ofs << "start to merge incomplete alignment files ..." << endl;
string cat_cmd_tmpAlignIncompletePair = "cat";
for(int tmp = 1; tmp <= threads_num; tmp++)
{
cat_cmd_tmpAlignIncompletePair = cat_cmd_tmpAlignIncompletePair + " " + tmpAlignIncompletePair + "." + int_to_str(tmp);
}
cat_cmd_tmpAlignIncompletePair = cat_cmd_tmpAlignIncompletePair + " " + tmpAlignIncompletePair;
cat_cmd_tmpAlignIncompletePair = cat_cmd_tmpAlignIncompletePair + " > " + tmpAlignIncompletePair + ".all";
system(cat_cmd_tmpAlignIncompletePair.c_str());
log_ofs << "finish merging incomplete alignment files ..." << endl;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// Sam 2 Junc ///////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
nowtime = time(NULL);
//struct tm *local;
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... Sam 2 Junc starts ......" << endl << endl;
log_ofs << endl << "[" << asctime(local) << "... Sam 2 Junc starts ......" << endl << endl;
runtime_log_ofs << endl << "[" << asctime(local) << "... Sam 2 Junc starts ......" << endl << endl;
// new alignment2junc results:
if(DoSam2JuncBool)
{
string juncfile = tmpIntermediateJunctionFile;
log_ofs << "... initiate align2juncInfo ..." << endl;
AlignmentToJunc_Info* align2juncInfo = new AlignmentToJunc_Info();
int chromNum = indexInfo->returnChromNum();
align2juncInfo->initiateAlignmentToJuncInfo(chromNum);
log_ofs << "start to insert SJs into SJmap" << endl;
vector<string> tmpAlignmentFileVec;
tmpAlignmentFileVec.push_back(tmpAlignCompleteRead);
tmpAlignmentFileVec.push_back(tmpAlignIncompletePair_SAM);
tmpAlignmentFileVec.push_back(OutputSamFile_oneEndMapped);
align2juncInfo->insertJuncFromAlignmentFileVec(tmpAlignmentFileVec, indexInfo);
log_ofs << "finish inserting SJs into SJ map" << endl;
align2juncInfo->outputSJmapVec(juncfile, indexInfo);
}
nowtime = time(NULL);
//struct tm *local;
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... Sam 2 Junc ends ......" << endl << endl;
log_ofs << endl << "[" << asctime(local) << "... Sam 2 Junc ends ......" << endl << endl;
runtime_log_ofs << endl << "[" << asctime(local) << "... Sam 2 Junc ends ......" << endl << endl;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// Do REMAPPING On unfixed head/tail Reads ///////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
nowtime = time(NULL);
//struct tm *local;
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... fixing unfixed-head/tail reads starts ......" << endl << endl ;
log_ofs << endl << "[" << asctime(local) << "... fixing unfixed-head/tail reads starts ......" << endl << endl ;
runtime_log_ofs << endl << "[" << asctime(local) << "... fixing unfixed-head/tail reads starts ......" << endl << endl ;
string OutputSamFile_fixHeadTail_complete_pair = outputDirStr + "/phase2_output/fixHeadTail_complete_pair.sam";
ofstream OutputSamFile_fixHeadTail_complete_pair_ofs(OutputSamFile_fixHeadTail_complete_pair.c_str());
string OutputSamFile_fixHeadTail_complete_pair_alignInfo = outputDirStr + "/phase2_output/fixHeadTail_complete_pair.sam_alignInfo";
ofstream OutputSamFile_fixHeadTail_complete_pair_alignInfo_ofs(OutputSamFile_fixHeadTail_complete_pair_alignInfo.c_str());
string OutputSamFile_fixHeadTail_incomplete_pair = outputDirStr + "/phase2_output/fixHeadTail_incomplete_pair.sam";
ofstream OutputSamFile_fixHeadTail_incomplete_pair_ofs(OutputSamFile_fixHeadTail_incomplete_pair.c_str());
string OutputSamFile_fixHeadTail_incomplete_pair_alignInfo = outputDirStr + "/phase2_output/fixHeadTail_incomplete_pair.sam_alignInfo";
ofstream OutputSamFile_fixHeadTail_incomplete_pair_alignInfo_ofs(OutputSamFile_fixHeadTail_incomplete_pair_alignInfo.c_str());
string OutputSamFile_fixHeadTail_complete_unpair = outputDirStr + "/phase2_output/fixHeadTail_complete_unpair.sam";
ofstream OutputSamFile_fixHeadTail_complete_unpair_ofs(OutputSamFile_fixHeadTail_complete_unpair.c_str());
string OutputSamFile_fixHeadTail_incomplete_unpair = outputDirStr + "/phase2_output/fixHeadTail_incomplete_unpair.sam";
ofstream OutputSamFile_fixHeadTail_incomplete_unpair_ofs(OutputSamFile_fixHeadTail_incomplete_unpair.c_str());
string OutputSamFile_fixHeadTail_pair_lowScore = outputDirStr + "/phase2_output/fixHeadTail_pair_lowScore.sam";
ofstream OutputSamFile_fixHeadTail_pair_lowScore_ofs(OutputSamFile_fixHeadTail_pair_lowScore.c_str());
// start to read splice junction
int junctionNum = 0;
SJhash_Info* SJ = new SJhash_Info();
SJ->initiateAreaAndStringHash(indexInfo->returnChromNum());
string InputSpliceJunction = tmpIntermediateJunctionFile;
//////// take annotation as reference for remapping //////////////
//InputSpliceJunction = "/data/homes/lxauky/GroundTruth2sam/resutls/sim1_test1/simulated_reads_test1_twoEnds.sam.noRandom.junc";
settings_log_ofs << "InputSpliceJunction: " << InputSpliceJunction << endl;
log_ofs << "InputSpliceJunction: " << InputSpliceJunction << endl;
cout << "InputSpliceJunction: " << InputSpliceJunction << endl;
///////////////////////////////////////////////////////////////////
//if(annotation_provided_bool && Do_annotation_only_bool)
// InputSpliceJunction = annotation_file_path;
if(DoRemappingOnUnfixedHeadTailAlignmentBool)
{
log_ofs << "start to build spliceJunction Hash" << endl;
cout << "start to build spliceJunction Hash" << endl;
bool spliceJunctionHashExists = true;
string entryString;
int tabLocation1, tabLocation2, tabLocation3, tabLocation4, tabLocation5;
char entry[500];
int chrInt;
int spliceStartPos;
int spliceEndPos;
string chrIntString;
string spliceStartPosString;
string spliceEndPosString;
/////////////////////////////////////////////////////////////////////////////
////////////////////// string hash /////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
if(!Do_annotation_only_bool)
{
// loading SJs generated from aligned reads.
FILE *fp_spliceJunction = fopen(InputSpliceJunction.c_str(), "r");
fgets(entry, sizeof(entry), fp_spliceJunction);
while(!feof(fp_spliceJunction))
{
fgets(entry, sizeof(entry), fp_spliceJunction);
if(feof(fp_spliceJunction))
break;
junctionNum ++;
entryString = entry;
tabLocation1 = entryString.find('\t', 0);
tabLocation2 = entryString.find('\t', tabLocation1+1);
tabLocation3 = entryString.find('\t', tabLocation2+1);
chrIntString = entryString.substr(0, tabLocation1);
spliceStartPosString = entryString.substr(tabLocation1+1, tabLocation2-tabLocation1-1);
spliceEndPosString = entryString.substr(tabLocation2+1, tabLocation3-tabLocation2-1);
chrInt = indexInfo->convertStringToInt(chrIntString);
spliceStartPos = atoi(spliceStartPosString.c_str());
spliceEndPos = atoi(spliceEndPosString.c_str());
SJ->insert2AreaAndStringHash(chrInt, spliceStartPos, spliceEndPos, indexInfo);
}
fclose(fp_spliceJunction);
}
log_ofs << "after inserting SJs generated from alignments, junctionNum = " << junctionNum << endl;
log_ofs << "start to insert SJs generated from annotation (if provided) " << endl;
settings_log_ofs << "after inserting SJs generated from alignments, junctionNum = " << junctionNum << endl;
settings_log_ofs << "start to insert SJs generated from annotation (if provided) " << endl;
cout << "after inserting SJs generated from alignments, junctionNum = " << junctionNum << endl;
cout << "start to insert SJs generated from annotation (if provided) " << endl;
if(annotation_provided_bool)
{
// loading SJs in annotation file (if provided)
FILE *fp_annotatedSJ_file = fopen(annotation_file_path.c_str(), "r");
fgets(entry, sizeof(entry), fp_annotatedSJ_file);
while(!feof(fp_annotatedSJ_file))
{
fgets(entry, sizeof(entry), fp_annotatedSJ_file);
if(feof(fp_annotatedSJ_file))
break;
junctionNum ++;
entryString = entry;
tabLocation1 = entryString.find('\t', 0);
tabLocation2 = entryString.find('\t', tabLocation1+1);
tabLocation3 = entryString.find('\t', tabLocation2+1);
chrIntString = entryString.substr(0, tabLocation1);
spliceStartPosString = entryString.substr(tabLocation1+1, tabLocation2-tabLocation1-1);
spliceEndPosString = entryString.substr(tabLocation2+1, tabLocation3-tabLocation2-1);
chrInt = indexInfo->convertStringToInt(chrIntString);
spliceStartPos = atoi(spliceStartPosString.c_str());
spliceEndPos = atoi(spliceEndPosString.c_str());
SJ->insert2AreaAndStringHash(chrInt, spliceStartPos, spliceEndPos, indexInfo);
}
fclose(fp_annotatedSJ_file);
}
if(junctionNum == 0)
{
spliceJunctionHashExists = false;
}
log_ofs << "After inserting SJs generated from alignments and annotation, junctionNum = " << junctionNum << endl;
log_ofs << "finish building spliceJunction Hash" << endl;
log_ofs << "start doing remapping on unfixed head/tail alignments" << endl;
settings_log_ofs << "After inserting SJs generated from alignments and annotation, junctionNum = " << junctionNum << endl;
settings_log_ofs << "finish building spliceJunction Hash" << endl;
settings_log_ofs << "start doing remapping on unfixed head/tail alignments" << endl;
cout << "After inserting SJs generated from alignments and annotation, junctionNum = " << junctionNum << endl;
cout << "finish building spliceJunction Hash" << endl;
cout << "start doing remapping on unfixed head/tail alignments" << endl;
string headTailSoftClippingFile = tmpAlignIncompletePair;// + ".all";
if(outputDirectlyBool_Phase1Only)
headTailSoftClippingFile += ".all";
ifstream inputUnfixedHeadTailRecord_ifs(headTailSoftClippingFile.c_str());
int normalRecordNum = normalRecordNum_fixHeadTail; //1000000;
bool EndOfRecord = false;
int tmpTurn = 0;
int realRecordNum;// = normalRecordNum;
for(tmpTurn = 0; /*tmpTurn < TurnNum*/; tmpTurn++)
{
vector<string> line1StrVec(normalRecordNum);
vector<string> line2StrVec(normalRecordNum);
vector<string> line3StrVec(normalRecordNum);
vector<string> line4StrVec(normalRecordNum);
vector<string> line5StrVec(normalRecordNum);
vector<string> line6StrVec(normalRecordNum);
vector<string> line7StrVec(normalRecordNum);
vector<string> line8StrVec(normalRecordNum);
vector<string> line9StrVec(normalRecordNum);
vector<string> line10StrVec(normalRecordNum);
vector<string> peAlignSamVec_complete_pair(normalRecordNum);
vector<string> peAlignSamVec_incomplete_pair(normalRecordNum);
vector<string> peAlignSamVec_complete_unpair(normalRecordNum);
vector<string> peAlignSamVec_incomplete_unpair(normalRecordNum);
vector<string> peAlignSamVec_pair_lowScore(normalRecordNum);
if(EndOfRecord)
break;
int recordNum = normalRecordNum;
nowtime = time(NULL);
local = localtime(&nowtime);
runtime_log_ofs << endl << "[" << asctime(local)
<< "start to read Head/Tail file record, turn: " << tmpTurn+1 << endl;
cout << endl << "[" << asctime(local)
<< "start to read Head/Tail file record, turn: " << tmpTurn+1 << endl;
realRecordNum = normalRecordNum;
for(int recordNumTmp = 0; recordNumTmp < recordNum; recordNumTmp++)
{
string line1, line2, line3, line4, line5, line6, line7,
line8, line9, line10, line11;
if(inputUnfixedHeadTailRecord_ifs.eof())
{
realRecordNum = recordNumTmp;
EndOfRecord = true;
break;
}
getline(inputUnfixedHeadTailRecord_ifs, line11);
if(inputUnfixedHeadTailRecord_ifs.eof())
{
realRecordNum = recordNumTmp;
EndOfRecord = true;
break;
}
getline(inputUnfixedHeadTailRecord_ifs, line1);
getline(inputUnfixedHeadTailRecord_ifs, line2);
getline(inputUnfixedHeadTailRecord_ifs, line3);
getline(inputUnfixedHeadTailRecord_ifs, line4);
getline(inputUnfixedHeadTailRecord_ifs, line5);
getline(inputUnfixedHeadTailRecord_ifs, line6);
getline(inputUnfixedHeadTailRecord_ifs, line7);
getline(inputUnfixedHeadTailRecord_ifs, line8);
getline(inputUnfixedHeadTailRecord_ifs, line9);
getline(inputUnfixedHeadTailRecord_ifs, line10);
//getline(inputUnfixedHeadTailRecord_ifs, line11);
line1StrVec[recordNumTmp] = line1;
line2StrVec[recordNumTmp] = line2;
line3StrVec[recordNumTmp] = line3;
line4StrVec[recordNumTmp] = line4;
line5StrVec[recordNumTmp] = line5;
line6StrVec[recordNumTmp] = line6;
line7StrVec[recordNumTmp] = line7;
line8StrVec[recordNumTmp] = line8;
line9StrVec[recordNumTmp] = line9;
line10StrVec[recordNumTmp] = line10;
}
runtime_log_ofs << "realRecordNum: " << realRecordNum << " turn: " << tmpTurn+1 << endl;
cout << "realRecordNum: " << realRecordNum << " turn: " << tmpTurn+1 << endl;
nowtime = time(NULL);
local = localtime(&nowtime);
runtime_log_ofs << endl << "[" << asctime(local)
<< "finish reading Head/Tail records file, turn: " << tmpTurn+1 << endl;
runtime_log_ofs << endl << "[" << asctime(local)
<< "start to fix Head/Tail, turn: " << tmpTurn+1 << endl;
cout << endl << "[" << asctime(local)
<< "finish reading Head/Tail records file, turn: " << tmpTurn+1 << endl;
cout << endl << "[" << asctime(local)
<< "start to fix Head/Tail, turn: " << tmpTurn+1 << endl;
omp_set_num_threads(threads_num);
//omp_set_num_threads(1);
#pragma omp parallel for schedule(dynamic)
for(int tmpOpenMP = 0; tmpOpenMP < realRecordNum; tmpOpenMP++)
{
//////////////// parse long head reads record after 1-mapping process ///////////////////////////////////////
int threadNO = omp_get_thread_num();
PE_Read_Info peReadInfo;// = new PE_Read_Info();
PE_Read_Alignment_Info* peAlignInfo = new PE_Read_Alignment_Info();
peAlignInfo->generatePeReadInfoAndPeAlignInfo_toFixIncompleteAlignment_getline(
line1StrVec[tmpOpenMP], line2StrVec[tmpOpenMP], line3StrVec[tmpOpenMP],
line4StrVec[tmpOpenMP], line5StrVec[tmpOpenMP], line6StrVec[tmpOpenMP],
line7StrVec[tmpOpenMP], line8StrVec[tmpOpenMP], //line9StrVec[tmpOpenMP],
line9StrVec[tmpOpenMP], line10StrVec[tmpOpenMP], peReadInfo,
indexInfo, fasta_or_fastq_bool);
#ifdef MAP_INFO
cout << "start fixHeadTail: " << endl;
cout << "PeAlignInfo:" << endl << peAlignInfo->returnPeAlignInfoStr() << endl;
#endif
FixHeadTailInfo* fixHeadTailInfo = new FixHeadTailInfo();
if(Do_fixHeadTail_remapping)
{
fixHeadTailInfo->fixHeadTail_areaAndStringHash_new_remappingOnly(
peReadInfo, peAlignInfo, SJ,
secondLevelChrom,
secondLevelSa,
secondLevelLcpCompress,
secondLevelChildTab,
secondLevelDetChild,
spliceJunctionHashExists,
indexInfo, Do_extendHeadTail_fixHeadTail);
}
#ifdef MAP_INFO
cout << "after remapping:" << endl;
cout << "PeAlignInfo: " << endl << peAlignInfo->returnPeAlignInfoStr() << endl;
#endif
if(Do_fixHeadTail_greedyMapping)
{
fixHeadTailInfo->fixHeadTail_areaAndStringHash_new_greedyMappingOnly(
peReadInfo, peAlignInfo, SJ,
secondLevelChrom,
secondLevelSa,
secondLevelLcpCompress,
secondLevelChildTab,
secondLevelDetChild,
spliceJunctionHashExists,
indexInfo, Do_extendHeadTail_fixHeadTail,
annotation_provided_bool, Do_annotation_only_bool, annotationInfo,
MAX_SPLICE_DISTANCE_PHASE2, checkQualSeqForReadSegSeq
);
}
#ifdef MAP_INFO
cout << "after greedyMapping:" << endl;
cout << "PeAlignInfo: " << endl << peAlignInfo->returnPeAlignInfoStr() << endl;
#endif
if(Do_fixHeadTail_remappingAndTargetMapping)
{
fixHeadTailInfo->fixHeadTail_areaAndStringHash_new_remappingAndTargetMapping(
peReadInfo, peAlignInfo, SJ,
secondLevelChrom,
secondLevelSa,
secondLevelLcpCompress,
secondLevelChildTab,
secondLevelDetChild,
spliceJunctionHashExists,
indexInfo, Do_extendHeadTail_fixHeadTail,
checkQualSeqForShortAnchorSeqToTargetMap);
}
#ifdef MAP_INFO
cout << "after remapping And Target Mapping:" << endl;
cout << "PeAlignInfo: " << endl << peAlignInfo->returnPeAlignInfoStr() << endl;
#endif
if(Do_fixHeadTail_remappingAgain)
{
fixHeadTailInfo->fixHeadTail_areaAndStringHash_new_remappingOnly(
peReadInfo, peAlignInfo, SJ,
secondLevelChrom,
secondLevelSa,
secondLevelLcpCompress,
secondLevelChildTab,
secondLevelDetChild,
spliceJunctionHashExists,
indexInfo, Do_extendHeadTail_fixHeadTail);
}
fixHeadTailInfo->fixHeadTail_extend2end(peReadInfo, peAlignInfo, indexInfo);
#ifdef MAP_INFO
cout << "after extending: " << endl;
cout << "PeAlignInfo: " << endl << peAlignInfo->returnPeAlignInfoStr() << endl;
#endif
// remove duplicate mismatch
peAlignInfo->removeDuplicateMismatch();
peAlignInfo->chooseBestAlignment_selectAllIfMultiBest_filterOutNoncanonical_SJpenalty();
bool pairExistsBool = peAlignInfo->finalPairExistsBool();
peAlignSamVec_complete_pair[tmpOpenMP] = "";
peAlignSamVec_incomplete_pair[tmpOpenMP] = "";
peAlignSamVec_complete_unpair[tmpOpenMP] = "";
peAlignSamVec_incomplete_unpair[tmpOpenMP] = "";
peAlignSamVec_pair_lowScore[tmpOpenMP] = "";
if(pairExistsBool) // some pair exists, all completed, print out paired SAM info
{
bool allFinalPairAlignmentCompleteBool = peAlignInfo->allAlignmentInFinalPairCompleted();
bool unique_bool = peAlignInfo->checkUniqueOrMulti();
statsInfo->increPairedNum_fixHeadTail(threadNO, allFinalPairAlignmentCompleteBool, unique_bool);
int alignment_score_min_output
//= peReadInfo.returnAlignmentScoreMinOutput_withComplement(
// ALIGNMENT_SCORE_MIN_OUTPUT_COMPLEMENT);
= peReadInfo.returnAlignmentScoreMinOutput_withComplement_perHundredBases(
ALIGNMENT_SCORE_MIN_OUTPUT_COMPLEMENT_PerHundredBases);
bool align_lowScore_bool
= peAlignInfo->alignPairScoreTooLow_bool(alignment_score_min_output);
if(align_lowScore_bool)
{
statsInfo->increLowScoreComplete_fixHeadTail(
threadNO, allFinalPairAlignmentCompleteBool, unique_bool);
peAlignSamVec_pair_lowScore[tmpOpenMP]
= peAlignInfo->getSAMformatForBothEndsUnmapped(peReadInfo, fasta_or_fastq_bool);
}
else if(allFinalPairAlignmentCompleteBool)
{
peAlignSamVec_complete_pair[tmpOpenMP]
= peAlignInfo->getSAMformatForFinalPair_secondaryOrNot(
peReadInfo, fasta_or_fastq_bool);
}
else
{
peAlignSamVec_incomplete_pair[tmpOpenMP]
= peAlignInfo->getSAMformatForFinalPair_secondaryOrNot(
peReadInfo, fasta_or_fastq_bool);
}
}
else //if((!pairExistsBool) && (allAlignmentCompleteBool)) // no pair exists, all complete, print out original SAM info
{
bool allUnpairAlignmentCompleteBool = peAlignInfo->allUnpairedAlignmentCompleted();
statsInfo->increUnpairedNum_fixHeadTail(threadNO, allUnpairAlignmentCompleteBool);
if(allUnpairAlignmentCompleteBool)
{
peAlignSamVec_complete_unpair[tmpOpenMP] = peAlignInfo->getSAMformatForUnpairedAlignments_secondaryOrNot(
peReadInfo, fasta_or_fastq_bool);
}
else
{
peAlignSamVec_incomplete_unpair[tmpOpenMP] = peAlignInfo->getSAMformatForUnpairedAlignments_secondaryOrNot(
peReadInfo, fasta_or_fastq_bool);
}
}
delete fixHeadTailInfo;
peAlignInfo->memoryFree();
delete peAlignInfo;
}
nowtime = time(NULL);
local = localtime(&nowtime);
runtime_log_ofs << endl << "[" << asctime(local)
<< "finish fixing Head/Tail, turn: " << tmpTurn+1 << endl;// << endl;
runtime_log_ofs << endl << "[" << asctime(local)
<< "start to output ... turn: " << tmpTurn+1 << endl;
cout << endl << "[" << asctime(local)
<< "finish fixing Head/Tail, turn: " << tmpTurn+1 << endl;// << endl;
cout << endl << "[" << asctime(local)
<< "start to output ... turn: " << tmpTurn+1 << endl;
for(int tmp = 0; tmp < realRecordNum; tmp++)
{
if(peAlignSamVec_complete_pair[tmp] != "")
{
OutputSamFile_fixHeadTail_complete_pair_ofs << peAlignSamVec_complete_pair[tmp] << endl;
//PairedReadNum ++;
string().swap(peAlignSamVec_complete_pair[tmp]);
}
if(peAlignSamVec_incomplete_pair[tmp] != "")
{
OutputSamFile_fixHeadTail_incomplete_pair_ofs << peAlignSamVec_incomplete_pair[tmp] << endl;
//PairedReadNum ++;
string().swap(peAlignSamVec_incomplete_pair[tmp]);
}
if(peAlignSamVec_complete_unpair[tmp] != "")
{
OutputSamFile_fixHeadTail_complete_unpair_ofs << peAlignSamVec_complete_unpair[tmp] << endl;
//UnpairedReadNum ++;
string().swap(peAlignSamVec_complete_unpair[tmp]);
}
if(peAlignSamVec_incomplete_unpair[tmp] != "")
{
OutputSamFile_fixHeadTail_incomplete_unpair_ofs << peAlignSamVec_incomplete_unpair[tmp] << endl;
//UnpairedReadNum ++;
string().swap(peAlignSamVec_incomplete_unpair[tmp]);
}
if(peAlignSamVec_pair_lowScore[tmp] != "")
{
OutputSamFile_fixHeadTail_pair_lowScore_ofs << peAlignSamVec_pair_lowScore[tmp] << endl;
string().swap(peAlignSamVec_pair_lowScore[tmp]);
}
}
nowtime = time(NULL);
local = localtime(&nowtime);
runtime_log_ofs << endl << "[" << asctime(local)
<< "finish output, turn: " << tmpTurn+1 << endl << endl;
cout << endl << "[" << asctime(local)
<< "finish output, turn: " << tmpTurn+1 << endl << endl;
}
inputUnfixedHeadTailRecord_ifs.close();
}
delete(SJ);
OutputSamFile_fixHeadTail_complete_pair_ofs.close();
OutputSamFile_fixHeadTail_incomplete_pair_ofs.close();
OutputSamFile_fixHeadTail_complete_unpair_ofs.close();
OutputSamFile_fixHeadTail_incomplete_unpair_ofs.close();
OutputSamFile_fixHeadTail_pair_lowScore_ofs.close();
nowtime = time(NULL);
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... fixing unfixed-head/tail reads ends ......" << endl << endl ;
log_ofs << endl << "[" << asctime(local) << "... fixing unfixed-head/tail reads ends ......" << endl << endl ;
runtime_log_ofs << endl << "[" << asctime(local) << "... fixing unfixed-head/tail reads ends ......" << endl << endl ;
statsInfo->getPhase1Stats();
statsInfo->getFixUnpairedStats();
statsInfo->getFixHeadTailStats();
//statsInfo->outputAllStats(log_ofs, readTotalNum);
statsInfo->outputAllStats(stats_ofs, readTotalNum);
statsInfo->outputFinalStats(stats_ofs, Do_Phase1_Only, readTotalNum);
nowtime = time(NULL);
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... start to prepare for final output files ......" << endl << endl ;
log_ofs << endl << "[" << asctime(local) << "... start to prepare for final output files ......" << endl << endl ;
runtime_log_ofs << endl << "[" << asctime(local) << "... start to prepare for final output files ......" << endl << endl ;
string finalOutputSam = outputDirStr + "/output.sam";
if(Do_Phase1_Only)
{
string cat_cmd = "cat "
+ tmpHeadSectionInfo
+ " " + tmpAlignCompleteRead
//+ " " + tmpAlignOneEndUnmapped
+ " " + tmpAlignIncompletePair_SAM
+ " " + tmpAlignOneEndUnmapped
+ " " + tmpAlignBothEndsUnmapped_mappedToRepeatRegionFile
+ " " + tmpAlignBothEndsUnmapped_lowScore
+ " " + tmpAlignBothEndsUnmapped
+ " > " + finalOutputSam;
system(cat_cmd.c_str());
}
else
{
string cat_cmd = "cat "
+ tmpHeadSectionInfo
+ " " + tmpAlignCompleteRead
+ " " + OutputSamFile_oneEndMapped
+ " " + OutputSamFile_fixHeadTail_complete_pair
+ " " + OutputSamFile_fixHeadTail_incomplete_pair
+ " " + OutputSamFile_fixHeadTail_complete_unpair
+ " " + OutputSamFile_fixHeadTail_incomplete_unpair
+ " " + OutputSamFile_oneEndMapped_unpair
+ " " + tmpAlignBothEndsUnmapped_mappedToRepeatRegionFile
+ " " + tmpAlignBothEndsUnmapped_lowScore
+ " " + OutputSamFile_oneEndMapped_bothEndsUnmapped_lowScore
+ " " + OutputSamFile_fixHeadTail_pair_lowScore
+ " " + tmpAlignBothEndsUnmapped
+ " > " + finalOutputSam;
system(cat_cmd.c_str());
}
if(removeAllIntermediateFilesBool)
{
remove(InputSpliceJunction.c_str());
//remove(juncInsFile.c_str());
remove(tmpAlignIncompletePair.c_str());
remove(OutputSamFile_fixHeadTail_complete_pair.c_str());
remove(OutputSamFile_fixHeadTail_incomplete_pair.c_str());
remove(OutputSamFile_fixHeadTail_complete_unpair.c_str());
remove(OutputSamFile_fixHeadTail_incomplete_unpair.c_str());
remove(OutputSamFile_oneEndMapped.c_str());
remove(OutputSamFile_oneEndMapped_unpair.c_str());
remove(tmpAlignOneEndUnmapped.c_str());
remove(tmpAlignIncompletePair_SAM.c_str());
remove(tmpAlignBothEndsUnmapped_mappedToRepeatRegionFile.c_str());
remove(tmpAlignBothEndsUnmapped.c_str());
remove(tmpAlignIncompletePair.c_str());
remove(tmpAlignCompleteRead_alignInfo.c_str());
remove(OutputSamFile_oneEndMapped_alignInfo.c_str());
remove(tmpAlignCompleteRead.c_str());
remove(tmpHeadSectionInfo.c_str());
remove(tmpAlignBothEndsUnmapped_lowScore.c_str());
remove(OutputSamFile_fixHeadTail_pair_lowScore.c_str());
remove(OutputSamFile_oneEndMapped_bothEndsUnmapped_lowScore.c_str());
}
annotation_ifs.close();
delete annotationInfo;
delete indexInfo;
nowtime = time(NULL);
//struct tm *local;
local = localtime(&nowtime);
cout << endl << "[" << asctime(local) << "... all jobs done ......" << endl << endl ;
log_ofs << endl << "[" << asctime(local) << "... all jobs done ......" << endl << endl ;
runtime_log_ofs << endl << "[" << asctime(local) << "... all jobs done ......" << endl << endl ;
return 0;
} //end main | [
"Jinze.liu@uky.edu"
] | Jinze.liu@uky.edu |
a23defc754195ec449dc4a694a26656916a65b41 | 484c987e590d24eaae1ed648ed738269e6cb7614 | /CrazyLang/OutRabDialog.h | d6bf68b4a276faebcb6992f5e3c427419aacca2c | [
"BSD-3-Clause"
] | permissive | ssmSeven/crazylanguage | 92d14efc9247fceb01b039875422e743a6b610d0 | c5d4c2f8c55bb3712cd02065e53bd83a5a62affc | refs/heads/master | 2021-01-15T21:10:07.277835 | 2013-08-26T04:27:16 | 2013-08-26T04:27:16 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 388 | h | #pragma once
// OutRabDialog 대화 상자입니다.
class OutRabDialog : public CDialog
{
DECLARE_DYNAMIC(OutRabDialog)
public:
OutRabDialog(CWnd* pParent = NULL); // 표준 생성자입니다.
virtual ~OutRabDialog();
// 대화 상자 데이터입니다.
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
DECLARE_MESSAGE_MAP()
};
| [
"speedwall0262@gmail.com"
] | speedwall0262@gmail.com |
f7cf95246b4633df327d51bee3ae50bf2f93fc10 | 21c0a8588978cf4ecc31d827d4e5b778401f9eee | /uva/10346.cpp | efd176f8cf778be82be2719154ae0512a34e3afc | [
"MIT"
] | permissive | cosmicray001/Online_judge_Solutions | c082faa9cc8c9448fa7be8504a150a822d0d5b8a | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | refs/heads/master | 2022-03-01T12:35:28.985743 | 2022-02-07T10:29:16 | 2022-02-07T10:29:16 | 116,611,495 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 318 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int a, b;
while(scanf("%d %d", &a, &b) != EOF){
int sum = a;
while(a >= b){
sum += a / b;
a = a / b + a % b;
}
printf("%d\n", sum);
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
c377e8922e13f5bc58fac893664e7b85a17f4efd | d03d052c0ca220d06ec17d170e2b272f4e935a0c | /gen/mojo/services/native_support/interfaces/process.mojom.cc | 4e783dfa010ad5f2e0c67f451eff2d9d1405d6c7 | [
"Apache-2.0"
] | permissive | amplab/ray-artifacts | f7ae0298fee371d9b33a40c00dae05c4442dc211 | 6954850f8ef581927df94be90313c1e783cd2e81 | refs/heads/master | 2023-07-07T20:45:43.526694 | 2016-08-06T19:53:55 | 2016-08-06T19:53:55 | 65,099,400 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 28,829 | cc | // NOTE: This file was generated by the Mojo bindings generator.
#include "mojo/services/native_support/interfaces/process.mojom.h"
#include <math.h>
#include <ostream>
#include "mojo/public/cpp/bindings/lib/array_serialization.h"
#include "mojo/public/cpp/bindings/lib/bindings_serialization.h"
#include "mojo/public/cpp/bindings/lib/bounds_checker.h"
#include "mojo/public/cpp/bindings/lib/map_data_internal.h"
#include "mojo/public/cpp/bindings/lib/map_serialization.h"
#include "mojo/public/cpp/bindings/lib/message_builder.h"
#include "mojo/public/cpp/bindings/lib/message_validation.h"
#include "mojo/public/cpp/bindings/lib/string_serialization.h"
#include "mojo/public/cpp/bindings/lib/validate_params.h"
#include "mojo/public/cpp/bindings/lib/validation_errors.h"
#include "mojo/public/cpp/bindings/lib/validation_util.h"
#include "mojo/public/cpp/environment/logging.h"
namespace native_support {
// --- Interface definitions ---
class Process_Spawn_ForwardToCallback
: public mojo::MessageReceiver {
public:
Process_Spawn_ForwardToCallback(
const Process::SpawnCallback& callback)
: callback_(callback) {
}
bool Accept(mojo::Message* message) override;
private:
Process::SpawnCallback callback_;
MOJO_DISALLOW_COPY_AND_ASSIGN(Process_Spawn_ForwardToCallback);
};
bool Process_Spawn_ForwardToCallback::Accept(
mojo::Message* message) {
internal::Process_Spawn_ResponseParams_Data* params =
reinterpret_cast<internal::Process_Spawn_ResponseParams_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
mojo::files::Error p_error {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_error = static_cast<mojo::files::Error>(params->error);
} while (false);
callback_.Run(p_error);
return true;
}
class Process_SpawnWithTerminal_ForwardToCallback
: public mojo::MessageReceiver {
public:
Process_SpawnWithTerminal_ForwardToCallback(
const Process::SpawnWithTerminalCallback& callback)
: callback_(callback) {
}
bool Accept(mojo::Message* message) override;
private:
Process::SpawnWithTerminalCallback callback_;
MOJO_DISALLOW_COPY_AND_ASSIGN(Process_SpawnWithTerminal_ForwardToCallback);
};
bool Process_SpawnWithTerminal_ForwardToCallback::Accept(
mojo::Message* message) {
internal::Process_SpawnWithTerminal_ResponseParams_Data* params =
reinterpret_cast<internal::Process_SpawnWithTerminal_ResponseParams_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
mojo::files::Error p_error {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_error = static_cast<mojo::files::Error>(params->error);
} while (false);
callback_.Run(p_error);
return true;
}
ProcessProxy::ProcessProxy(mojo::MessageReceiverWithResponder* receiver)
: ControlMessageProxy(receiver) {
}
void ProcessProxy::Spawn(
mojo::Array<uint8_t> in_path, mojo::Array<mojo::Array<uint8_t> > in_argv, mojo::Array<mojo::Array<uint8_t> > in_envp, mojo::InterfaceHandle<mojo::files::File> in_stdin_file, mojo::InterfaceHandle<mojo::files::File> in_stdout_file, mojo::InterfaceHandle<mojo::files::File> in_stderr_file, mojo::InterfaceRequest<ProcessController> in_process_controller, const SpawnCallback& callback) {
size_t size = sizeof(internal::Process_Spawn_Params_Data);
size += GetSerializedSize_(in_path);
size += GetSerializedSize_(in_argv);
size += GetSerializedSize_(in_envp);
mojo::RequestMessageBuilder builder(
static_cast<uint32_t>(internal::Process_Base::MessageOrdinals::Spawn), size);
internal::Process_Spawn_Params_Data* params =
internal::Process_Spawn_Params_Data::New(builder.buffer());
{
const mojo::internal::ArrayValidateParams path_validate_params(
0, false, nullptr);mojo::SerializeArray_(&in_path, builder.buffer(), ¶ms->path.ptr,
&path_validate_params);
}
if (!params->path.ptr) {
MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING(mojo::internal::ValidationError::UNEXPECTED_NULL_POINTER, "null path in Process.Spawn request");
}
{
const mojo::internal::ArrayValidateParams argv_validate_params(
0, false, new mojo::internal::ArrayValidateParams(0, false, nullptr));mojo::SerializeArray_(&in_argv, builder.buffer(), ¶ms->argv.ptr,
&argv_validate_params);
}
{
const mojo::internal::ArrayValidateParams envp_validate_params(
0, false, new mojo::internal::ArrayValidateParams(0, false, nullptr));mojo::SerializeArray_(&in_envp, builder.buffer(), ¶ms->envp.ptr,
&envp_validate_params);
}
mojo::internal::InterfaceHandleToData(in_stdin_file.Pass(),
¶ms->stdin_file);
mojo::internal::InterfaceHandleToData(in_stdout_file.Pass(),
¶ms->stdout_file);
mojo::internal::InterfaceHandleToData(in_stderr_file.Pass(),
¶ms->stderr_file);
params->process_controller = in_process_controller.PassMessagePipe().release();
if (!params->process_controller.is_valid()) {
MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING(mojo::internal::ValidationError::UNEXPECTED_INVALID_HANDLE, "invalid process_controller in Process.Spawn request");
}
params->EncodePointersAndHandles(builder.message()->mutable_handles());
mojo::MessageReceiver* responder =
new Process_Spawn_ForwardToCallback(callback);
if (!receiver_->AcceptWithResponder(builder.message(), responder))
delete responder;
}
void ProcessProxy::SpawnWithTerminal(
mojo::Array<uint8_t> in_path, mojo::Array<mojo::Array<uint8_t> > in_argv, mojo::Array<mojo::Array<uint8_t> > in_envp, mojo::InterfaceHandle<mojo::files::File> in_terminal_file, mojo::InterfaceRequest<ProcessController> in_process_controller, const SpawnWithTerminalCallback& callback) {
size_t size = sizeof(internal::Process_SpawnWithTerminal_Params_Data);
size += GetSerializedSize_(in_path);
size += GetSerializedSize_(in_argv);
size += GetSerializedSize_(in_envp);
mojo::RequestMessageBuilder builder(
static_cast<uint32_t>(internal::Process_Base::MessageOrdinals::SpawnWithTerminal), size);
internal::Process_SpawnWithTerminal_Params_Data* params =
internal::Process_SpawnWithTerminal_Params_Data::New(builder.buffer());
{
const mojo::internal::ArrayValidateParams path_validate_params(
0, false, nullptr);mojo::SerializeArray_(&in_path, builder.buffer(), ¶ms->path.ptr,
&path_validate_params);
}
if (!params->path.ptr) {
MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING(mojo::internal::ValidationError::UNEXPECTED_NULL_POINTER, "null path in Process.SpawnWithTerminal request");
}
{
const mojo::internal::ArrayValidateParams argv_validate_params(
0, false, new mojo::internal::ArrayValidateParams(0, false, nullptr));mojo::SerializeArray_(&in_argv, builder.buffer(), ¶ms->argv.ptr,
&argv_validate_params);
}
{
const mojo::internal::ArrayValidateParams envp_validate_params(
0, false, new mojo::internal::ArrayValidateParams(0, false, nullptr));mojo::SerializeArray_(&in_envp, builder.buffer(), ¶ms->envp.ptr,
&envp_validate_params);
}
mojo::internal::InterfaceHandleToData(in_terminal_file.Pass(),
¶ms->terminal_file);
if (!params->terminal_file.handle.is_valid()) {
MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING(mojo::internal::ValidationError::UNEXPECTED_INVALID_HANDLE, "invalid terminal_file in Process.SpawnWithTerminal request");
}
params->process_controller = in_process_controller.PassMessagePipe().release();
if (!params->process_controller.is_valid()) {
MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING(mojo::internal::ValidationError::UNEXPECTED_INVALID_HANDLE, "invalid process_controller in Process.SpawnWithTerminal request");
}
params->EncodePointersAndHandles(builder.message()->mutable_handles());
mojo::MessageReceiver* responder =
new Process_SpawnWithTerminal_ForwardToCallback(callback);
if (!receiver_->AcceptWithResponder(builder.message(), responder))
delete responder;
}
// This class implements a method's response callback: it serializes the
// response args into a mojo message and passes it to the MessageReceiver it
// was created with.
class Process_Spawn_ProxyToResponder
: public Process::SpawnCallback::Runnable {
public:
~Process_Spawn_ProxyToResponder() override {
// Is the Mojo application destroying the callback without running it
// and without first closing the pipe?
bool callback_was_dropped = responder_ && responder_->IsValid();
// If the Callback was dropped then deleting the responder will close
// the pipe so the calling application knows to stop waiting for a reply.
delete responder_;
MOJO_DCHECK(!callback_was_dropped) << "The callback passed to "
"Process::Spawn(p_path.Pass(), p_argv.Pass(), p_envp.Pass(), p_stdin_file.Pass(), p_stdout_file.Pass(), p_stderr_file.Pass(), p_process_controller.Pass(), callback) "
"was never run.";
}
Process_Spawn_ProxyToResponder(
uint64_t request_id,
mojo::MessageReceiverWithStatus* responder)
: request_id_(request_id),
responder_(responder) {
}
void Run(mojo::files::Error in_error) const override;
private:
uint64_t request_id_;
mutable mojo::MessageReceiverWithStatus* responder_;
MOJO_DISALLOW_COPY_AND_ASSIGN(Process_Spawn_ProxyToResponder);
};
void Process_Spawn_ProxyToResponder::Run(
mojo::files::Error in_error) const {
size_t size = sizeof(internal::Process_Spawn_ResponseParams_Data);
mojo::ResponseMessageBuilder builder(
static_cast<uint32_t>(internal::Process_Base::MessageOrdinals::Spawn), size, request_id_);
internal::Process_Spawn_ResponseParams_Data* params =
internal::Process_Spawn_ResponseParams_Data::New(builder.buffer());
params->error =
static_cast<int32_t>(in_error);
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = responder_->Accept(builder.message());
MOJO_ALLOW_UNUSED_LOCAL(ok);
// TODO(darin): !ok returned here indicates a malformed message, and that may
// be good reason to close the connection. However, we don't have a way to do
// that from here. We should add a way.
delete responder_;
responder_ = nullptr;
}
// This class implements a method's response callback: it serializes the
// response args into a mojo message and passes it to the MessageReceiver it
// was created with.
class Process_SpawnWithTerminal_ProxyToResponder
: public Process::SpawnWithTerminalCallback::Runnable {
public:
~Process_SpawnWithTerminal_ProxyToResponder() override {
// Is the Mojo application destroying the callback without running it
// and without first closing the pipe?
bool callback_was_dropped = responder_ && responder_->IsValid();
// If the Callback was dropped then deleting the responder will close
// the pipe so the calling application knows to stop waiting for a reply.
delete responder_;
MOJO_DCHECK(!callback_was_dropped) << "The callback passed to "
"Process::SpawnWithTerminal(p_path.Pass(), p_argv.Pass(), p_envp.Pass(), p_terminal_file.Pass(), p_process_controller.Pass(), callback) "
"was never run.";
}
Process_SpawnWithTerminal_ProxyToResponder(
uint64_t request_id,
mojo::MessageReceiverWithStatus* responder)
: request_id_(request_id),
responder_(responder) {
}
void Run(mojo::files::Error in_error) const override;
private:
uint64_t request_id_;
mutable mojo::MessageReceiverWithStatus* responder_;
MOJO_DISALLOW_COPY_AND_ASSIGN(Process_SpawnWithTerminal_ProxyToResponder);
};
void Process_SpawnWithTerminal_ProxyToResponder::Run(
mojo::files::Error in_error) const {
size_t size = sizeof(internal::Process_SpawnWithTerminal_ResponseParams_Data);
mojo::ResponseMessageBuilder builder(
static_cast<uint32_t>(internal::Process_Base::MessageOrdinals::SpawnWithTerminal), size, request_id_);
internal::Process_SpawnWithTerminal_ResponseParams_Data* params =
internal::Process_SpawnWithTerminal_ResponseParams_Data::New(builder.buffer());
params->error =
static_cast<int32_t>(in_error);
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = responder_->Accept(builder.message());
MOJO_ALLOW_UNUSED_LOCAL(ok);
// TODO(darin): !ok returned here indicates a malformed message, and that may
// be good reason to close the connection. However, we don't have a way to do
// that from here. We should add a way.
delete responder_;
responder_ = nullptr;
}
ProcessStub::ProcessStub()
: sink_(nullptr),
control_message_handler_(Process::Version_) {
}
ProcessStub::~ProcessStub() {}
bool ProcessStub::Accept(mojo::Message* message) {
if (mojo::internal::ControlMessageHandler::IsControlMessage(message))
return control_message_handler_.Accept(message);
internal::Process_Base::MessageOrdinals method_ordinal =
static_cast<internal::Process_Base::MessageOrdinals>(message->header()->name);
switch (method_ordinal) {
case internal::Process_Base::MessageOrdinals::Spawn: {
break;
}
case internal::Process_Base::MessageOrdinals::SpawnWithTerminal: {
break;
}
}
return false;
}
bool ProcessStub::AcceptWithResponder(
mojo::Message* message, mojo::MessageReceiverWithStatus* responder) {
if (mojo::internal::ControlMessageHandler::IsControlMessage(message))
return control_message_handler_.AcceptWithResponder(message, responder);
internal::Process_Base::MessageOrdinals method_ordinal =
static_cast<internal::Process_Base::MessageOrdinals>(message->header()->name);
switch (method_ordinal) {
case internal::Process_Base::MessageOrdinals::Spawn: {
internal::Process_Spawn_Params_Data* params =
reinterpret_cast<internal::Process_Spawn_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
Process::SpawnCallback::Runnable* runnable =
new Process_Spawn_ProxyToResponder(
message->request_id(), responder);
Process::SpawnCallback callback(runnable);
mojo::Array<uint8_t> p_path {};
mojo::Array<mojo::Array<uint8_t> > p_argv {};
mojo::Array<mojo::Array<uint8_t> > p_envp {};
mojo::InterfaceHandle<mojo::files::File> p_stdin_file {};
mojo::InterfaceHandle<mojo::files::File> p_stdout_file {};
mojo::InterfaceHandle<mojo::files::File> p_stderr_file {};
mojo::InterfaceRequest<ProcessController> p_process_controller {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
Deserialize_(params->path.ptr, &p_path);
Deserialize_(params->argv.ptr, &p_argv);
Deserialize_(params->envp.ptr, &p_envp);
mojo::internal::InterfaceDataToHandle(¶ms->stdin_file, &p_stdin_file);
mojo::internal::InterfaceDataToHandle(¶ms->stdout_file, &p_stdout_file);
mojo::internal::InterfaceDataToHandle(¶ms->stderr_file, &p_stderr_file);
p_process_controller.Bind(mojo::MakeScopedHandle(mojo::internal::FetchAndReset(¶ms->process_controller)));
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->Spawn(p_path.Pass(), p_argv.Pass(), p_envp.Pass(), p_stdin_file.Pass(), p_stdout_file.Pass(), p_stderr_file.Pass(), p_process_controller.Pass(), callback);
return true;
}
case internal::Process_Base::MessageOrdinals::SpawnWithTerminal: {
internal::Process_SpawnWithTerminal_Params_Data* params =
reinterpret_cast<internal::Process_SpawnWithTerminal_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
Process::SpawnWithTerminalCallback::Runnable* runnable =
new Process_SpawnWithTerminal_ProxyToResponder(
message->request_id(), responder);
Process::SpawnWithTerminalCallback callback(runnable);
mojo::Array<uint8_t> p_path {};
mojo::Array<mojo::Array<uint8_t> > p_argv {};
mojo::Array<mojo::Array<uint8_t> > p_envp {};
mojo::InterfaceHandle<mojo::files::File> p_terminal_file {};
mojo::InterfaceRequest<ProcessController> p_process_controller {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
Deserialize_(params->path.ptr, &p_path);
Deserialize_(params->argv.ptr, &p_argv);
Deserialize_(params->envp.ptr, &p_envp);
mojo::internal::InterfaceDataToHandle(¶ms->terminal_file, &p_terminal_file);
p_process_controller.Bind(mojo::MakeScopedHandle(mojo::internal::FetchAndReset(¶ms->process_controller)));
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->SpawnWithTerminal(p_path.Pass(), p_argv.Pass(), p_envp.Pass(), p_terminal_file.Pass(), p_process_controller.Pass(), callback);
return true;
}
}
return false;
}
class ProcessController_Wait_ForwardToCallback
: public mojo::MessageReceiver {
public:
ProcessController_Wait_ForwardToCallback(
const ProcessController::WaitCallback& callback)
: callback_(callback) {
}
bool Accept(mojo::Message* message) override;
private:
ProcessController::WaitCallback callback_;
MOJO_DISALLOW_COPY_AND_ASSIGN(ProcessController_Wait_ForwardToCallback);
};
bool ProcessController_Wait_ForwardToCallback::Accept(
mojo::Message* message) {
internal::ProcessController_Wait_ResponseParams_Data* params =
reinterpret_cast<internal::ProcessController_Wait_ResponseParams_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
mojo::files::Error p_error {};
int32_t p_exit_status {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_error = static_cast<mojo::files::Error>(params->error);
p_exit_status = params->exit_status;
} while (false);
callback_.Run(p_error, p_exit_status);
return true;
}
class ProcessController_Kill_ForwardToCallback
: public mojo::MessageReceiver {
public:
ProcessController_Kill_ForwardToCallback(
const ProcessController::KillCallback& callback)
: callback_(callback) {
}
bool Accept(mojo::Message* message) override;
private:
ProcessController::KillCallback callback_;
MOJO_DISALLOW_COPY_AND_ASSIGN(ProcessController_Kill_ForwardToCallback);
};
bool ProcessController_Kill_ForwardToCallback::Accept(
mojo::Message* message) {
internal::ProcessController_Kill_ResponseParams_Data* params =
reinterpret_cast<internal::ProcessController_Kill_ResponseParams_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
mojo::files::Error p_error {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_error = static_cast<mojo::files::Error>(params->error);
} while (false);
callback_.Run(p_error);
return true;
}
ProcessControllerProxy::ProcessControllerProxy(mojo::MessageReceiverWithResponder* receiver)
: ControlMessageProxy(receiver) {
}
void ProcessControllerProxy::Wait(
const WaitCallback& callback) {
size_t size = sizeof(internal::ProcessController_Wait_Params_Data);
mojo::RequestMessageBuilder builder(
static_cast<uint32_t>(internal::ProcessController_Base::MessageOrdinals::Wait), size);
internal::ProcessController_Wait_Params_Data* params =
internal::ProcessController_Wait_Params_Data::New(builder.buffer());
params->EncodePointersAndHandles(builder.message()->mutable_handles());
mojo::MessageReceiver* responder =
new ProcessController_Wait_ForwardToCallback(callback);
if (!receiver_->AcceptWithResponder(builder.message(), responder))
delete responder;
}
void ProcessControllerProxy::Kill(
int32_t in_signal, const KillCallback& callback) {
size_t size = sizeof(internal::ProcessController_Kill_Params_Data);
mojo::RequestMessageBuilder builder(
static_cast<uint32_t>(internal::ProcessController_Base::MessageOrdinals::Kill), size);
internal::ProcessController_Kill_Params_Data* params =
internal::ProcessController_Kill_Params_Data::New(builder.buffer());
params->signal = in_signal;
params->EncodePointersAndHandles(builder.message()->mutable_handles());
mojo::MessageReceiver* responder =
new ProcessController_Kill_ForwardToCallback(callback);
if (!receiver_->AcceptWithResponder(builder.message(), responder))
delete responder;
}
// This class implements a method's response callback: it serializes the
// response args into a mojo message and passes it to the MessageReceiver it
// was created with.
class ProcessController_Wait_ProxyToResponder
: public ProcessController::WaitCallback::Runnable {
public:
~ProcessController_Wait_ProxyToResponder() override {
// Is the Mojo application destroying the callback without running it
// and without first closing the pipe?
bool callback_was_dropped = responder_ && responder_->IsValid();
// If the Callback was dropped then deleting the responder will close
// the pipe so the calling application knows to stop waiting for a reply.
delete responder_;
MOJO_DCHECK(!callback_was_dropped) << "The callback passed to "
"ProcessController::Wait(callback) "
"was never run.";
}
ProcessController_Wait_ProxyToResponder(
uint64_t request_id,
mojo::MessageReceiverWithStatus* responder)
: request_id_(request_id),
responder_(responder) {
}
void Run(mojo::files::Error in_error, int32_t in_exit_status) const override;
private:
uint64_t request_id_;
mutable mojo::MessageReceiverWithStatus* responder_;
MOJO_DISALLOW_COPY_AND_ASSIGN(ProcessController_Wait_ProxyToResponder);
};
void ProcessController_Wait_ProxyToResponder::Run(
mojo::files::Error in_error, int32_t in_exit_status) const {
size_t size = sizeof(internal::ProcessController_Wait_ResponseParams_Data);
mojo::ResponseMessageBuilder builder(
static_cast<uint32_t>(internal::ProcessController_Base::MessageOrdinals::Wait), size, request_id_);
internal::ProcessController_Wait_ResponseParams_Data* params =
internal::ProcessController_Wait_ResponseParams_Data::New(builder.buffer());
params->error =
static_cast<int32_t>(in_error);
params->exit_status = in_exit_status;
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = responder_->Accept(builder.message());
MOJO_ALLOW_UNUSED_LOCAL(ok);
// TODO(darin): !ok returned here indicates a malformed message, and that may
// be good reason to close the connection. However, we don't have a way to do
// that from here. We should add a way.
delete responder_;
responder_ = nullptr;
}
// This class implements a method's response callback: it serializes the
// response args into a mojo message and passes it to the MessageReceiver it
// was created with.
class ProcessController_Kill_ProxyToResponder
: public ProcessController::KillCallback::Runnable {
public:
~ProcessController_Kill_ProxyToResponder() override {
// Is the Mojo application destroying the callback without running it
// and without first closing the pipe?
bool callback_was_dropped = responder_ && responder_->IsValid();
// If the Callback was dropped then deleting the responder will close
// the pipe so the calling application knows to stop waiting for a reply.
delete responder_;
MOJO_DCHECK(!callback_was_dropped) << "The callback passed to "
"ProcessController::Kill(p_signal, callback) "
"was never run.";
}
ProcessController_Kill_ProxyToResponder(
uint64_t request_id,
mojo::MessageReceiverWithStatus* responder)
: request_id_(request_id),
responder_(responder) {
}
void Run(mojo::files::Error in_error) const override;
private:
uint64_t request_id_;
mutable mojo::MessageReceiverWithStatus* responder_;
MOJO_DISALLOW_COPY_AND_ASSIGN(ProcessController_Kill_ProxyToResponder);
};
void ProcessController_Kill_ProxyToResponder::Run(
mojo::files::Error in_error) const {
size_t size = sizeof(internal::ProcessController_Kill_ResponseParams_Data);
mojo::ResponseMessageBuilder builder(
static_cast<uint32_t>(internal::ProcessController_Base::MessageOrdinals::Kill), size, request_id_);
internal::ProcessController_Kill_ResponseParams_Data* params =
internal::ProcessController_Kill_ResponseParams_Data::New(builder.buffer());
params->error =
static_cast<int32_t>(in_error);
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = responder_->Accept(builder.message());
MOJO_ALLOW_UNUSED_LOCAL(ok);
// TODO(darin): !ok returned here indicates a malformed message, and that may
// be good reason to close the connection. However, we don't have a way to do
// that from here. We should add a way.
delete responder_;
responder_ = nullptr;
}
ProcessControllerStub::ProcessControllerStub()
: sink_(nullptr),
control_message_handler_(ProcessController::Version_) {
}
ProcessControllerStub::~ProcessControllerStub() {}
bool ProcessControllerStub::Accept(mojo::Message* message) {
if (mojo::internal::ControlMessageHandler::IsControlMessage(message))
return control_message_handler_.Accept(message);
internal::ProcessController_Base::MessageOrdinals method_ordinal =
static_cast<internal::ProcessController_Base::MessageOrdinals>(message->header()->name);
switch (method_ordinal) {
case internal::ProcessController_Base::MessageOrdinals::Wait: {
break;
}
case internal::ProcessController_Base::MessageOrdinals::Kill: {
break;
}
}
return false;
}
bool ProcessControllerStub::AcceptWithResponder(
mojo::Message* message, mojo::MessageReceiverWithStatus* responder) {
if (mojo::internal::ControlMessageHandler::IsControlMessage(message))
return control_message_handler_.AcceptWithResponder(message, responder);
internal::ProcessController_Base::MessageOrdinals method_ordinal =
static_cast<internal::ProcessController_Base::MessageOrdinals>(message->header()->name);
switch (method_ordinal) {
case internal::ProcessController_Base::MessageOrdinals::Wait: {
internal::ProcessController_Wait_Params_Data* params =
reinterpret_cast<internal::ProcessController_Wait_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
ProcessController::WaitCallback::Runnable* runnable =
new ProcessController_Wait_ProxyToResponder(
message->request_id(), responder);
ProcessController::WaitCallback callback(runnable);
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->Wait(callback);
return true;
}
case internal::ProcessController_Base::MessageOrdinals::Kill: {
internal::ProcessController_Kill_Params_Data* params =
reinterpret_cast<internal::ProcessController_Kill_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
ProcessController::KillCallback::Runnable* runnable =
new ProcessController_Kill_ProxyToResponder(
message->request_id(), responder);
ProcessController::KillCallback callback(runnable);
int32_t p_signal {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_signal = params->signal;
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->Kill(p_signal, callback);
return true;
}
}
return false;
}
} // namespace native_support
| [
"pcmoritz@gmail.com"
] | pcmoritz@gmail.com |
281bc53e24417be4bc7f448f71a8de43ccd2d1eb | 0911c1f1d15ba1408acd632ec0b3fcdd2452de25 | /Lab8/Board.h | 4459b1eb1a0d3a3361fe9e383800b4125a9c0423 | [] | no_license | grzegorzsabiniok/Lab8 | 19fbe1676d2cb12199b5699f7b362eacc145422a | 8b0fa53324c3938f5138a6cb63460bb6bfe056b4 | refs/heads/master | 2020-12-30T13:59:52.271932 | 2017-05-14T20:19:31 | 2017-05-14T20:19:31 | 91,268,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,013 | h | #pragma once
#include<list>
#include"Object.h"
#include"Interactive.h"
#include"Enemy.h"
#include"Potion.h"
#include"Player.h"
#include"ItemContainer.h"
#include"Item.h"
#include <time.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include<conio.h>
class Board {
int x, y;
std::list<Object*> objects;
std::list<Interactive*> interactive;
Player* player;
public:
void Start() {
while (true) {
char input = _getch();
if (input == 'q') {
std::cout << "wyjscie";
return;
}
player->Move(input);
for (Object* i : objects) {
if (Enemy* temp = dynamic_cast<Enemy*>(i)) {
temp->Move(player->GetPosition());
}
}
Show();
std::cout << "zycie: " << player->GetHp() << " sila: "<<player->GetStrength()
<<"\n__________________________\nwydarzenia:\n" ;
int enemyCount = 0;
for (Interactive* i : interactive) {
if (dynamic_cast<Enemy*>(i)) {
enemyCount++;
}
if (i->Interact(player)) {
interactive.remove(i);
objects.remove(dynamic_cast<Object*>(i));
break;
}
}
std::cout << "\n___________________________\ndo zabicia " << enemyCount<<"\n";
if (enemyCount < 1) {
system("cls");
std::cout << "Wygrales";
return;
}
if (player->GetHp() <= 0) {
system("cls");
std::cout << "koniec gry";
return;
}
}
}
void Show() {
system("cls");
for (int Y = 0; Y < y; Y++) {
for (int X = 0; X < x; X++) {
bool t = false;
for (Object* i : objects) {
if (i->GetPosition().x == X && i->GetPosition().y == Y) {
std::cout << i->GetIcon();
t = true;
break;
}
}
if(!t)
std::cout << " ";
}
std::cout <<(char)475<< "\n";
}
for (int X = -1; X < x; X++) {
std::cout << (char)475;
}
std::cout << "\n";
}
void RandomMap(int _x,int _y,int _enemy,int _potion,int _item,int _max) {
player = new Player();
objects.push_front(player);
x = _x;
y = _y;
srand(time(NULL));
for (int i = 0; i < _enemy; i++) {
Enemy* temp = new Enemy(_max);
temp->SetPosition(rand() % x, rand() % y);
objects.push_back(temp);
interactive.push_back(temp);
}
for (int i = 0; i < _potion; i++) {
Potion* temp = new Potion(_max);
temp->SetPosition(rand() % x, rand() % y);
objects.push_back(temp);
interactive.push_back(temp);
}
for (int i = 0; i < _item; i++) {
Item* t = new Item(_max);
ItemContainer* temp = new ItemContainer(t);
temp->SetPosition(rand() % x, rand() % y);
objects.push_back(temp);
interactive.push_back(temp);
}
}
void Write(std::string name) {
std::ofstream file(name);
file << objects.size() << " " << x << " " << y <<"\n";
for (Object* i : objects) {
file << i->GetIcon() << " " <<i->GetPosition().x << " " << i->GetPosition().y << " " <<i->GetValue()<< "\n";
}
file.close();
}
void Read(std::string name) {
std::ifstream file(name);
int size;
file >> size;
file >> x;
file >> y;
for (int i = 0; i < size; i++) {
char type;
file >> type;
switch (type)
{
case 'X': {
int tx, ty, t;
file >> tx;
file >> ty;
file >> t;
player = new Player();
player->Damage(-t);
player->SetPosition(tx, ty);
objects.push_front(player);
}
break;
case 'P': {
int tx,ty,t;
file >> tx;
file >> ty;
file >> t;
Potion* temp = new Potion(t);
temp->SetPosition(tx,ty);
objects.push_back(temp);
interactive.push_back(temp);
}
break;
case 'E': {
int tx, ty, t;
file >> tx;
file >> ty;
file >> t;
Enemy* temp = new Enemy(t);
temp->SetPosition(tx, ty);
objects.push_back(temp);
interactive.push_back(temp);
}
break;
case 'I': {
int tx, ty, t;
file >> tx;
file >> ty;
file >> t;
Item *t2 = new Item(t);
ItemContainer* temp = new ItemContainer(t2);
temp->SetPosition(tx, ty);
objects.push_back(temp);
interactive.push_back(temp);
}
break;
default:
break;
}
}
}
}; | [
"grzesab111@gmail.com"
] | grzesab111@gmail.com |
bd5306bb93807e5f97fc807e4934376e5bf0ec4b | 2c6123f5b615aca2b9720a2a84aac3f06837460c | /content/browser/background_fetch/background_fetch_metrics.h | 4de20a206bca405b19e212e6a986b8e3112d7228 | [
"BSD-3-Clause"
] | permissive | dianpeng/chromium | 50e3a015bbad425bfe98ac8d8f1a584c2d0f7d06 | 7f6f0f6a7cb3b0845cd39f930c17d4c915ed8c9b | refs/heads/master | 2023-02-26T04:54:54.484913 | 2018-11-09T02:21:06 | 2018-11-09T02:21:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,315 | h | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_METRICS_H_
#define CONTENT_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_METRICS_H_
#include "content/public/browser/background_fetch_delegate.h"
#include "third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom.h"
namespace content {
namespace background_fetch {
// Records the number of registrations that have unfinished fetches found on
// start-up.
void RecordRegistrationsOnStartup(int num_registrations);
// Records the BackgroundFetch UKM event. Must be called before a Background
// Fetch registration has been created. Will be a no-op if |frame_tree_node_id|
// does not identify a valid, live frame.
void RecordBackgroundFetchUkmEvent(
const url::Origin& origin,
const std::vector<ServiceWorkerFetchRequest>& requests,
const BackgroundFetchOptions& options,
const SkBitmap& icon,
blink::mojom::BackgroundFetchUkmDataPtr ukm_data,
int frame_tree_node_id,
BackgroundFetchPermission permission);
} // namespace background_fetch
} // namespace content
#endif // CONTENT_BROWSER_BACKGROUND_FETCH_BACKGROUND_FETCH_METRICS_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
472fd0d11c1944cf2dc1013d8c97f347fd571018 | ec38d2660788a02fc6b097b9eea6f11002605258 | /source/LibFgBase/src/FgHex.hpp | 892d4760ef754583c9645ac36ede817cfdc8023e | [
"MIT"
] | permissive | mul1sh/FaceGenBaseLibrary | 004eaab741063759bd8b88611dfbb61a2eff2c14 | 2fbe55a24f74817a3721fac95fda997b6d9d1ac5 | refs/heads/master | 2020-09-07T09:58:08.717200 | 2019-11-10T00:35:54 | 2019-11-10T00:35:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 904 | hpp | //
// Copyright (c) 2019 Singular Inversions Inc. (facegen.com)
// Use, modification and distribution is subject to the MIT License,
// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt
//
//
// Useful to create strings directly rather than going through ostringstream with 'std::hex'
// and 'std::uppercase' and uint-casting for uchar.
//
// Big-endian (ie highest order digits printed first)
//
#ifndef FGHEX_HPP
#define FGHEX_HPP
#include "FgTypes.hpp"
#include "FgStdString.hpp"
namespace Fg {
String
fgAsHex(uchar c);
// Returns hex encoding in string of length 2:
String
fgAsHex(
const uchar *arr,
uint numBytes);
// Returns hex encoding in string of length 4:
String
fgAsHex(uint16 val);
// Returns hex encoding in string of length 8
String
fgAsHex(uint32 val);
// Returns hex encoding in string of length 16:
String
fgAsHex(uint64 val);
}
#endif
| [
"abeatty@facegen.com"
] | abeatty@facegen.com |
b89d1280859f7e5e8d266df230532ed9054f64c1 | b8296749985bff249033f248b07e51009fa75a45 | /workflow/scripts/remove_outlier_sequences-v0.9.5-dist/CSplit2.h | df12a87a21d09a7dbf2ed7f269dc155751b5d59c | [
"MIT"
] | permissive | ZFMK/TEnriAn | 007828297082ecbe236f62394a08a3cbf7489d30 | c6194a61972b60b18a9a53fbbd56473ff226ab25 | refs/heads/main | 2023-07-18T05:13:41.855209 | 2021-09-01T08:25:40 | 2021-09-01T08:25:40 | 346,700,856 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,038 | h | #ifndef CSplitH
#define CSplitH
#include "fast-dynamic-bitset/fast-dynamic-bitset.h"
#include <iostream>
#include <vector>
#include <fstream>
//#include "number2cstring.h"
class CSplit
{
private:
fast_dynamic_bitset split;
public:
// Bitset with a specfied number of bits, here taxa
CSplit(unsigned long size):split(size) {
split.clear();
}
CSplit(const fast_dynamic_bitset& b):split(b){}
CSplit(const CSplit& b):split(b.split){}
// CSplit(unsigned long, const vector<unsigned long>&);
// CSplit(unsigned long, unsigned long*, unsigned long);
friend bool operator ==(const CSplit&, const CSplit&);
friend bool operator <(const CSplit&, const CSplit&);
friend bool lessThan_mod_flip_friend(const CSplit&, const CSplit&);
fast_dynamic_bitset& get_split()
{
return split;
}
void reset()
{
split.reset();
}
void set(unsigned i)
{
split.set(i);
}
void reset(unsigned i)
{
split.reset(i);
}
bool test(unsigned i) const
{
return split.test(i);
}
void set(std::vector<int> vec)
{
int i=0, n=vec.size();
for (; i<n; ++i)
{
split.set(vec[i]);
}
}
void flip()
{
split.flip();
}
void flip(unsigned i)
{
split.flip(i);
}
unsigned count_taxa_in_ingroup()
{
return split.count();
}
unsigned size()
{
return split.size();
}
bool compatible_with(const CSplit& s_b) const
{
CSplit s_a_flipped(split);
CSplit s_b_flipped(s_b.split);
s_a_flipped.split.flip();
s_b_flipped.split.flip();
if( ((split & s_b.split).none()) || ((split & s_b_flipped.split).none()) ||
((s_a_flipped.split & s_b.split).none()) || ((s_a_flipped.split & s_b_flipped.split).none()) )
return true;
else
return false;
}
// Returns true if all 1s in (*this) are also 1s in s_b
bool is_this_a_subset_of_the_parameter(const CSplit& s_b) const
{
CSplit s_b_flipped(s_b.split);
s_b_flipped.split.flip();
// Some debug code:
// std::cout << "*this & parameter_flipped: " << (split & s_b_flipped.split) << std::endl;
return (split & s_b_flipped.split).none();
}
// Returns true if all 1s in s_b are also 1s in (*this)
bool is_parameter_a_subset_of_this(const CSplit& s_b) const
{
CSplit s_a_flipped(split);
s_a_flipped.split.flip();
// Some debug code:
// std::cout << "*this flipped & parameter: " << (s_a_flipped.split & s_b.split) << std::endl;
return (s_a_flipped.split & s_b.split).none();
}
void print(std::ostream& os) const
{
os << split;
}
const std::string as_string_lowBitsFirst() const
{
return split.as_string_lowBitsFirst();
}
const std::string as_string_highBitsFirst() const
{
return split.as_string_highBitsFirst();
}
};
/* // Neue Reihenfolge der Argumente */
/* CSplit::CSplit(unsigned long len, const vector<unsigned long>& vec):split(len) { */
/* vector<unsigned long>::const_iterator it; */
/* it = vec.begin(); */
/* while( it != vec.end() ) { */
/* split.set(*it); //indexerror */
/* ++it; */
/* } */
/* } */
/* // Neue Reihenfolge der Argumente */
/* CSplit::CSplit(unsigned long len, unsigned long *u, unsigned long array_len):split(len) { */
/* split.clear(); */
/* int i = 0; */
/* while(i < array_len) { */
/* split.set(u[i]); //indexerror */
/* i++; */
/* *u++; */
/* } */
/* } */
inline bool operator ==(const CSplit& split_a, const CSplit& split_b) {
if ( split_a.split == split_b.split ) {
return true;
} else {
CSplit split_b_flipped(split_b);
split_b_flipped.split.flip();
if( split_a.split == split_b_flipped.split ) {
return true;
} else {
return false;
}
}
}
inline bool operator <(const CSplit& split_a, const CSplit& split_b)
{
if ( split_a.split < split_b.split ) {
return true;
}
else {
return false;
}
}
/* inline bool lessThan_mod_flip_friend(const CSplit& split_a, const CSplit& split_b) */
/* { */
/* CSplit s_a_flipped(split_a); */
/* CSplit s_b_flipped(split_b); */
/* s_a_flipped.split.flip(); */
/* s_b_flipped.split.flip(); */
/* // return (split_a < split_b) || (s_a_flipped < s_b_flipped); */
/* return (s_a_flipped < s_b_flipped); */
/* } */
/* struct lessThan_mod_flip */
/* { */
/* bool operator()(const CSplit& split_a, const CSplit& split_b) const */
/* { */
/* return lessThan_mod_flip_friend(split_a, split_b); */
/* } */
/* }; */
//
// Split with branch length:
//
class CSplit_l : public CSplit
{
double b_length;
public:
CSplit_l(unsigned long u):CSplit(u), b_length(-1)
{}
CSplit_l(const fast_dynamic_bitset& b, double bl = -1):CSplit(b), b_length(bl) {}
CSplit_l(const CSplit& b, double bl = -1):CSplit(b), b_length(bl){}
CSplit_l(const CSplit_l& b):CSplit(b), b_length(b.b_length){}
void set_b_length(double b_l)
{
b_length = b_l;
}
double get_b_length() const
{
return b_length;
}
};
#endif
| [
"s.martin@leibniz-zfmk.de"
] | s.martin@leibniz-zfmk.de |
c540a587dc1ad982038ff50e2ffb7cfc27deb9fc | f95975d9454984803586de7f0600f3ecf9918f60 | /examples/cpp/source/datasource/datastructures_packedsymmetric.cpp | 2403aeaa273f6c684616d600f50b55d30f8b05bd | [
"Intel",
"Apache-2.0"
] | permissive | jjuribe/daal | f4e05656ca5f01e56debdbd2de51eeb2f506ca3d | 242d358db584dd4c9c65826b345fe63313ff8f2a | refs/heads/master | 2020-09-15T01:33:34.752543 | 2019-11-21T08:27:26 | 2019-11-21T08:27:26 | 223,316,648 | 0 | 0 | Apache-2.0 | 2019-11-22T03:33:41 | 2019-11-22T03:33:39 | null | UTF-8 | C++ | false | false | 3,093 | cpp | /* file: datastructures_packedsymmetric.cpp */
/*******************************************************************************
* Copyright 2014-2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*
! Content:
! C++ example of using packed data structures
!******************************************************************************/
/**
* <a name="DAAL-EXAMPLE-CPP-DATASTRUCTURES_PACKEDSYMMETRIC">
* \example datastructures_packedsymmetric.cpp
*/
#include "daal.h"
#include "service.h"
using namespace daal;
typedef PackedSymmetricMatrix<NumericTableIface::lowerPackedSymmetricMatrix> LowerPackedSymmetricMatrix;
typedef services::SharedPtr<LowerPackedSymmetricMatrix> LowerPackedSymmetricMatrixPtr;
int main()
{
std::cout << "Packed symmetric matrix example" << std::endl << std::endl;
const size_t nDim = 5;
const size_t firstReadRow = 0;
const size_t nRead = 5;
size_t readFeatureIdx;
/*Example of using a packed symmetric matrix */
float data[nDim * (nDim + 1) / 2] =
{
0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f, 1.1f, 1.2f, 1.3f, 1.4f
};
LowerPackedSymmetricMatrixPtr dataTable = LowerPackedSymmetricMatrix::create(data, nDim);
checkPtr(dataTable.get());
BlockDescriptor<> block;
/* Read a block of rows */
dataTable->getBlockOfRows(firstReadRow, nRead, readOnly, block);
std::cout << block.getNumberOfRows() << " rows are read" << std::endl;
printArray<float>(block.getBlockPtr(), nDim, block.getNumberOfRows(), "Print 3 rows from packed symmetric matrix as float:");
/* Read a feature(column) and write into it */
readFeatureIdx = 2;
dataTable->getBlockOfColumnValues(readFeatureIdx, firstReadRow, nDim, readWrite, block);
printArray<float>(block.getBlockPtr(), 1, block.getNumberOfRows(), "Print the third feature of packed symmetric matrix:");
/* Set new value to a buffer and release it */
float* dataBlock = block.getBlockPtr();
dataBlock[readFeatureIdx - 1] = -1;
dataBlock[readFeatureIdx + 1] = -2;
dataTable->releaseBlockOfColumnValues(block);
/* Read a block of rows. Ensure that data has changed */
dataTable->getBlockOfRows(firstReadRow, nRead, readOnly, block);
std::cout << block.getNumberOfRows() << " rows are read" << std::endl;
printArray<float>(block.getBlockPtr(), nDim, block.getNumberOfRows(), "Print 3 rows from packed symmetric matrix as float:");
return 0;
}
| [
"nikolay.a.petrov@intel.com"
] | nikolay.a.petrov@intel.com |
b27b84b3f3377a4318f70c0ec4b93dd31d8c16de | 4bab98acf65c4625a8b3c757327a8a386f90dd32 | /ros2-windows/include/std_srvs/srv/detail/empty__builder.hpp | a60e0f264e3684007937c881b3593359b4d7628b | [] | no_license | maojoejoe/Peach-Thinning-GTRI-Agricultural-Robotics-VIP | e2afb08b8d7b3ac075e071e063229f76b25f883a | 8ed707edb72692698f270317113eb215b57ae9f9 | refs/heads/master | 2023-01-15T06:00:22.844468 | 2020-11-25T04:16:15 | 2020-11-25T04:16:15 | 289,108,482 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,055 | hpp | // generated from rosidl_generator_cpp/resource/idl__builder.hpp.em
// with input from std_srvs:srv\Empty.idl
// generated code does not contain a copyright notice
#ifndef STD_SRVS__SRV__DETAIL__EMPTY__BUILDER_HPP_
#define STD_SRVS__SRV__DETAIL__EMPTY__BUILDER_HPP_
#include "std_srvs/srv/detail/empty__struct.hpp"
#include <rosidl_runtime_cpp/message_initialization.hpp>
#include <algorithm>
#include <utility>
namespace std_srvs
{
namespace srv
{
} // namespace srv
template<typename MessageType>
auto build();
template<>
inline
auto build<::std_srvs::srv::Empty_Request>()
{
return ::std_srvs::srv::Empty_Request(rosidl_runtime_cpp::MessageInitialization::ZERO);
}
} // namespace std_srvs
namespace std_srvs
{
namespace srv
{
} // namespace srv
template<typename MessageType>
auto build();
template<>
inline
auto build<::std_srvs::srv::Empty_Response>()
{
return ::std_srvs::srv::Empty_Response(rosidl_runtime_cpp::MessageInitialization::ZERO);
}
} // namespace std_srvs
#endif // STD_SRVS__SRV__DETAIL__EMPTY__BUILDER_HPP_
| [
"aidencfarrar@gmail.com"
] | aidencfarrar@gmail.com |
9b3775c46540dd15c86ccc782632afc179cbb681 | ffcb92a3b0abb65f0ca9869a19cc120c8c540968 | /AD9850_Freq_Gen_Encoder.ino | 8ca6c18da5761eaa03d6a3ebb011fc3a311275d7 | [] | no_license | fmilburn3/AD9850_with_Encoder_BackPack | cecb68ea2d45f72161a1c9e5179cfe632e1c7d7a | 779f437f8200078805799318c60eefb317538ca6 | refs/heads/master | 2021-01-10T11:42:19.516407 | 2019-05-07T17:08:52 | 2019-05-07T17:08:52 | 52,846,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,531 | ino | /*
Energia sketch for an encoder with push button to control a AD9850 frequency generator.
Displays to the FR6989 LCD if available.
The button is coded to increment/decrement the change associated with turning the encoder. For
example, the encoder can be set to increase or decrease the value by 100 with each turn of the
knob. When the button is pushed it can be made to reduce the increment or decrement to 10
(instead of 100). This allows the user to rapidly change values or achieve fine control as
desired.
The sketch uses the FR6989 LCD if available and will automatically switch from Hz to kHz to MHz
as the frequency increases. The increment amount from the encoder is displayed via the battery
symbol. No bars means it is incrementing or decrementing one Hz at a time, one bar means 10 Hz,
2 bars means 100 Hz, and so on.
Includes code and ideas from the following:
- Encoder sketch by m3tr0g33k at playground.arduino.cc/Main/RotaryEncoders
Encoder Connections
There are 5 pins on the encoder. On one side are 3 pins denoted here as 1, 2, and 3 that
control the rotary encoder. The two on the other side (pins 4 and 5) are the push button.
Encoder MSP430 Pin Comments
------------------------------------------------------------
Pin 1 19 outside encoder pin (Channel A)
Pin 2 GND middle encoder pin (Common)
Pin 3 18 outside encoder pin (Channel B)
Pin 4 13 push button
Pin 5 GND push button
Placing a 0.1 uF capacitor between the push button and ground; and 1 nF capacitors
between the encoder pins and ground reduced bounce on some of the circuits tried.
Notes: Connect encoder pins 1, 3, and 4 to microcontroller pins that accept external interrupts.
(Ports 1 and 2 generally have interrupt capability on the MSP series)
If the encoder is turning the wrong way, swap pins or swap the pin definition below.
AD9850 Connections
AD9850 MSP430 Pin Comments
-------------------------------------------------------
VCC 3V3
W_CLK 5
FQ_UD 6
DATA 11
RESET 12
GND GND
QOUT1 Square wave out
QOUT2 Square wave out
ZOUT1 Sine wave out
ZOUT2 Sine wave out
Notes: Only one of the outputs can be active at a time; i.e. not possible to generate a sine
and square wave at the same time. The small pot on the board may need adjustment to
get a good square wave and has limited frequency.
Created by Frank Milburn January 2015
Tested on MSP-EXP430FR6989 and Energia V17
EK-TM4123GXL and Energia V17
MSP-EXP432P401R and Energia V17
*/
// libraries
#include "energia.h"
#if defined (__MSP430FR6989)
#include "LCD_Launchpad.h"
LCD_LAUNCHPAD lcd;
#endif
// simplify pulsing the AD9850
#define pulseHigh(pin) {digitalWrite(pin, HIGH); digitalWrite(pin, LOW); }
// pin assignments
const int buttonPin = 13; // connect the pushbutton to this LP pin
const int encoderPin1 = 19; // connect one encoder pin to this LP pin
const int encoderPin2 = 18; // connect the other encoder pin to this LP pin
const int W_CLK = 5; // connect to AD9850 module word load clock pin (CLK)
const int FQ_UD = 6; // connect to AD9850 freq update pin (FQ)
const int DATA = 11; // connect to AD9850 serial data load pin (DATA)
const int RESET = 12; // connect to AD9850 reset pin (RST)
// variables used to control program behavior
const long startVal = 1000; // set this to whatever starting value is desired
const long minVal = 0; // minimum value that will be allowed as input
const long maxVal = 32000000; // maximum value that will be allowed as input
// limiting to 32000000 in order to use integers
const long startInc = 1000; // values increase/decrease by this value to start
const long minInc = 1; // minimum increment/decrement allowed when turning
const long maxInc = 1000000; // maximum increment/decrement allowed when turning
const long divInc = 10; // factor for decreasing the increment for improved
// control when the pushbutton is pushed
// variables used in ISRs
volatile long encoderVal = startVal;
volatile long encoderInc = startInc;
volatile boolean encoderLH1 = false;
volatile boolean encoderLH2 = false;
void setup() {
Serial.begin (115200);
// FR6989 LCD
#if defined (__MSP430FR6989)
lcd.init();
#endif
// Encoder
pinMode(buttonPin, INPUT_PULLUP);
pinMode(encoderPin1, INPUT_PULLUP);
pinMode(encoderPin2, INPUT_PULLUP);
attachInterrupt(encoderPin1, ISR_Encoder1, CHANGE); // interrupt for encoderPin1
attachInterrupt(encoderPin2, ISR_Encoder2, CHANGE); // interrupt for encoderPin2
attachInterrupt(buttonPin, ISR_Button, FALLING); // interrupt for encoder button
// AD9850
pinMode(FQ_UD, OUTPUT);
pinMode(W_CLK, OUTPUT);
pinMode(DATA, OUTPUT);
pinMode(RESET, OUTPUT);
analogReadResolution(12); // MCU dependent
pulseHigh(RESET);
pulseHigh(W_CLK);
pulseHigh(FQ_UD); // this pulse enables serial mode - Datasheet page 12 figure 10
}
void loop(){
// variables used to track whether or not a change has occurred
static long lastEncoderVal = 1;
static long lastEncoderInc = 0;
//check for change in encoder
if (lastEncoderVal != encoderVal) {
if (encoderVal > maxVal) encoderVal = maxVal ; // do not exceed max input value
if (encoderVal < minVal) encoderVal = minVal; // do not drop beneath min input value
sendFrequency(encoderVal);
printFreq(encoderVal);
lastEncoderVal = encoderVal;
}
// check for change in button
if (lastEncoderInc != encoderInc) {
if (encoderInc < minInc) encoderInc = maxInc; // if below min increment, set to max
printInc(encoderInc);
lastEncoderInc = encoderInc;
}
}
void ISR_Button() {
encoderInc /= divInc; // change the increment amount
}
void ISR_Encoder1(){
// Low to High transition?
if (digitalRead(encoderPin1) == HIGH) {
encoderLH1 = true;
if (!encoderLH2) {
encoderVal += encoderInc; // increase the value+
}
}
// High-to-low transition?
if (digitalRead(encoderPin1) == LOW) {
encoderLH1 = false;
}
}
void ISR_Encoder2(){
// Low-to-high transition?
if (digitalRead(encoderPin2) == HIGH) {
encoderLH2 = true;
if (!encoderLH1) {
encoderVal -= encoderInc; // decrease the value
}
}
// High-to-low transition?
if (digitalRead(encoderPin2) == LOW) {
encoderLH2 = false;
}
}
// transfers a byte, a bit at a time, LSB first to the 9850 via serial DATA line
void tfr_byte(byte data)
{
for (int i=0; i<8; i++, data>>=1) {
digitalWrite(DATA, data & 0x01);
pulseHigh(W_CLK); //after each bit sent, CLK is pulsed high
}
}
// frequency calc from datasheet page 8 = <sys clock> * <frequency tuning word>/2^32
void sendFrequency(double frequency) {
int32_t freq = frequency * 4294967295/125000000; // note 125 MHz clock on 9850
for (int b=0; b<4; b++, freq>>=8) {
tfr_byte(freq & 0xFF);
}
tfr_byte(0x000); // Final control byte, all 0 for 9850 chip
pulseHigh(FQ_UD); // Done! Should see output
}
// FR6989 LCD frequency print function
// uses the battery segment indicator to show range of output
void printFreq(long freq) {
Serial.print("Frequency: "); Serial.print(freq, DEC); Serial.println(" Hz");
#if defined (__MSP430FR6989)
// note that the lcd library will only print 16 bit integers (i.e. smaller than 65,536)
// We need to go up to 40,000 so using unsigned integer
lcd.clear();
if (freq > 9999999) {
lcd.println(freq/1000); // Displays MHz if above 10 MHz
lcd.showSymbol(LCD_SEG_DOT1, 0);
lcd.showSymbol(LCD_SEG_DOT2, 1);
lcd.showSymbol(LCD_SEG_DOT3, 0);
lcd.showSymbol(LCD_SEG_DOT4, 0);
lcd.showSymbol(LCD_SEG_DOT5, 0);
lcd.showChar('M', 5);
printInc(encoderInc);
}
else if (freq > 999999) {
lcd.println(int(freq / 1000)); // Displays MHz if 1 MHz to 10 MHz
lcd.showSymbol(LCD_SEG_DOT1, 1);
lcd.showSymbol(LCD_SEG_DOT2, 0);
lcd.showSymbol(LCD_SEG_DOT3, 0);
lcd.showSymbol(LCD_SEG_DOT4, 0);
lcd.showSymbol(LCD_SEG_DOT5, 0);
lcd.showChar('M', 5);
printInc(encoderInc);
}
else if (freq > 99999) {
lcd.println(int(freq / 100)); // Displays kHz if 100,000 Hz to 1 MHz
lcd.showSymbol(LCD_SEG_DOT1, 0);
lcd.showSymbol(LCD_SEG_DOT2, 0);
lcd.showSymbol(LCD_SEG_DOT3, 1);
lcd.showSymbol(LCD_SEG_DOT4, 0);
lcd.showSymbol(LCD_SEG_DOT5, 0);
lcd.showChar('k', 5);
printInc(encoderInc);
}
else if (freq > 9999) {
lcd.println(int(freq / 10)); // Displays kHz if between 10,000 Hz and 100,000 Hz
lcd.showSymbol(LCD_SEG_DOT1, 0);
lcd.showSymbol(LCD_SEG_DOT2, 1);
lcd.showSymbol(LCD_SEG_DOT3, 0);
lcd.showSymbol(LCD_SEG_DOT4, 0);
lcd.showSymbol(LCD_SEG_DOT5, 0);
lcd.showChar('k', 5);
printInc(encoderInc);
}
else {
lcd.println(int(freq)); // Displays Hz if below 10,000
lcd.showSymbol(LCD_SEG_DOT1, 0);
lcd.showSymbol(LCD_SEG_DOT2, 0);
lcd.showSymbol(LCD_SEG_DOT3, 0);
lcd.showSymbol(LCD_SEG_DOT4, 0);
lcd.showSymbol(LCD_SEG_DOT5, 0);
printInc(encoderInc);
}
#endif
}
// FR6989 LCD increment indication function
// uses the battery indicator to show increments from encoder
void printInc(long increment) {
Serial.print("Inc/Dec: "); Serial.print(increment, DEC); Serial.println(" Hz");
#if defined (__MSP430FR6989) // allows display on the LCD if using a FR6989 LaunchPad
if (encoderInc == 1000000) {
lcd.showSymbol(LCD_SEG_BAT0, 1);
lcd.showSymbol(LCD_SEG_BAT1, 1);
lcd.showSymbol(LCD_SEG_BAT2, 1);
lcd.showSymbol(LCD_SEG_BAT3, 1);
lcd.showSymbol(LCD_SEG_BAT4, 1);
lcd.showSymbol(LCD_SEG_BAT5, 1);
}
else if (encoderInc == 100000) {
lcd.showSymbol(LCD_SEG_BAT0, 1);
lcd.showSymbol(LCD_SEG_BAT1, 1);
lcd.showSymbol(LCD_SEG_BAT2, 1);
lcd.showSymbol(LCD_SEG_BAT3, 1);
lcd.showSymbol(LCD_SEG_BAT4, 1);
lcd.showSymbol(LCD_SEG_BAT5, 0);
}
else if (encoderInc == 10000) {
lcd.showSymbol(LCD_SEG_BAT0, 1);
lcd.showSymbol(LCD_SEG_BAT1, 1);
lcd.showSymbol(LCD_SEG_BAT2, 1);
lcd.showSymbol(LCD_SEG_BAT3, 1);
lcd.showSymbol(LCD_SEG_BAT4, 0);
lcd.showSymbol(LCD_SEG_BAT5, 0);
}
else if (encoderInc == 1000) {
lcd.showSymbol(LCD_SEG_BAT0, 1);
lcd.showSymbol(LCD_SEG_BAT1, 1);
lcd.showSymbol(LCD_SEG_BAT2, 1);
lcd.showSymbol(LCD_SEG_BAT3, 0);
lcd.showSymbol(LCD_SEG_BAT4, 0);
lcd.showSymbol(LCD_SEG_BAT5, 0);
}
else if (encoderInc == 100) {
lcd.showSymbol(LCD_SEG_BAT0, 1);
lcd.showSymbol(LCD_SEG_BAT1, 1);
lcd.showSymbol(LCD_SEG_BAT2, 0);
lcd.showSymbol(LCD_SEG_BAT3, 0);
lcd.showSymbol(LCD_SEG_BAT4, 0);
lcd.showSymbol(LCD_SEG_BAT5, 0);
}
else if (encoderInc == 10) {
lcd.showSymbol(LCD_SEG_BAT0, 1);
lcd.showSymbol(LCD_SEG_BAT1, 0);
lcd.showSymbol(LCD_SEG_BAT2, 0);
lcd.showSymbol(LCD_SEG_BAT3, 0);
lcd.showSymbol(LCD_SEG_BAT4, 0);
lcd.showSymbol(LCD_SEG_BAT5, 0);
}
else {
lcd.showSymbol(LCD_SEG_BAT0, 0);
lcd.showSymbol(LCD_SEG_BAT1, 0);
lcd.showSymbol(LCD_SEG_BAT2, 0);
lcd.showSymbol(LCD_SEG_BAT3, 0);
lcd.showSymbol(LCD_SEG_BAT4, 0);
lcd.showSymbol(LCD_SEG_BAT5, 0);
}
#endif
}
| [
"fmilburn3@users.noreply.github.com"
] | fmilburn3@users.noreply.github.com |
a06f0f9d728ee714ee471da611946a9faf189404 | f8df0470893e10f25f4362b84feecb9011293f43 | /build/iOS/Preview/include/Fuse.Reactive.VarArgFunction.Subscription.h | 5bfc2309e1720cbc9ba2c4021caf5a74992e6dc2 | [] | no_license | cekrem/PlateNumber | 0593a84a5ff56ebd9663382905dc39ae4e939b08 | 3a4e40f710bb0db109a36d65000dca50e79a22eb | refs/heads/master | 2021-08-23T02:06:58.388256 | 2017-12-02T11:01:03 | 2017-12-02T11:01:03 | 112,779,024 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,672 | h | // This file was generated based on /usr/local/share/uno/Packages/Fuse.Reactive.Expressions/1.4.0/VarArgFunction.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Reactive.IListener.h>
#include <Fuse.Reactive.InnerListener.h>
#include <Uno.IDisposable.h>
namespace g{namespace Fuse{namespace Reactive{struct VarArgFunction;}}}
namespace g{namespace Fuse{namespace Reactive{struct VarArgFunction__Argument;}}}
namespace g{namespace Fuse{namespace Reactive{struct VarArgFunction__Subscription;}}}
namespace g{
namespace Fuse{
namespace Reactive{
// protected abstract class VarArgFunction.Subscription :58
// {
struct VarArgFunction__Subscription_type : ::g::Fuse::Reactive::InnerListener_type
{
void(*fp_OnNewArguments)(::g::Fuse::Reactive::VarArgFunction__Subscription*, uArray*);
void(*fp_OnNewPartialArguments)(::g::Fuse::Reactive::VarArgFunction__Subscription*, uArray*);
};
VarArgFunction__Subscription_type* VarArgFunction__Subscription_typeof();
void VarArgFunction__Subscription__ctor_1_fn(VarArgFunction__Subscription* __this, ::g::Fuse::Reactive::VarArgFunction* func, uObject* context);
void VarArgFunction__Subscription__Dispose_fn(VarArgFunction__Subscription* __this);
void VarArgFunction__Subscription__Init_fn(VarArgFunction__Subscription* __this);
void VarArgFunction__Subscription__OnNewArguments_fn(VarArgFunction__Subscription* __this, uArray* args);
void VarArgFunction__Subscription__OnNewData_fn(VarArgFunction__Subscription* __this, uObject* source, uObject* value);
void VarArgFunction__Subscription__OnNewPartialArguments_fn(VarArgFunction__Subscription* __this, uArray* args);
void VarArgFunction__Subscription__PushData_fn(VarArgFunction__Subscription* __this);
struct VarArgFunction__Subscription : ::g::Fuse::Reactive::InnerListener
{
uStrong< ::g::Fuse::Reactive::VarArgFunction*> _func;
uStrong<uArray*> _arguments;
uStrong<uObject*> _context;
void ctor_1(::g::Fuse::Reactive::VarArgFunction* func, uObject* context);
void Init();
void OnNewArguments(uArray* args) { (((VarArgFunction__Subscription_type*)__type)->fp_OnNewArguments)(this, args); }
void OnNewPartialArguments(uArray* args) { (((VarArgFunction__Subscription_type*)__type)->fp_OnNewPartialArguments)(this, args); }
void PushData();
static void OnNewArguments(VarArgFunction__Subscription* __this, uArray* args) { VarArgFunction__Subscription__OnNewArguments_fn(__this, args); }
static void OnNewPartialArguments(VarArgFunction__Subscription* __this, uArray* args) { VarArgFunction__Subscription__OnNewPartialArguments_fn(__this, args); }
};
// }
}}} // ::g::Fuse::Reactive
| [
"cekrem@Christians-MacBook-Pro.local"
] | cekrem@Christians-MacBook-Pro.local |
91d05e50b7bef35238c5e19726101f2989c79d24 | a5caf0ef32591c280c951a6b5d330d4c6ed2678d | /include/account.hpp | 391e24f1c001ed1f26a8430d66d3ada0c2afa73b | [] | no_license | soupcty/Twitter-API-C-Library | b48b30d33aa51bdd884ba53e11c1060bfa17139a | 95144c7a63d8770958c63d387cfe2b7d84579cbb | refs/heads/master | 2021-01-01T20:10:08.255767 | 2017-07-20T20:06:58 | 2017-07-20T20:06:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 913 | hpp | #ifndef ACCOUNT_HPP
#define ACCOUNT_HPP
#include <string>
#include <utility>
namespace tal {
/// Represets a Twitter account, with access token and secret.
class Account {
public:
Account() = default;
/// Set the token and token secret at construction.
Account(std::string token, std::string secret)
: token_{std::move(token)}, token_secret_{std::move(secret)} {}
// Account(const Account&) = default;
/// returns the token.
std::string token() const { return token_; }
/// Returns the token secret.
std::string secret() const { return token_secret_; }
/// Set the token.
void set_token(const std::string& token) { token_ = token; }
/// Set the token secret.
void set_secret(const std::string& secret) { token_secret_ = secret; }
private:
std::string token_;
std::string token_secret_;
};
} // namespace tal
#endif // ACCOUNT_HPP
| [
"anthonym.leedom@gmail.com"
] | anthonym.leedom@gmail.com |
782d13d981eb81b54c8f47d02111582a7cbec8c9 | a8613a1f083399524df09fa35825de39fe606cd4 | /Counting Graphs.cpp | 17e7eca805e50d03b5be37a72564dad6b7414a68 | [] | no_license | amitmeena242/CodeChef | 782b0db78a3d11da85c7773b0973244a9e73d94e | ef1454cc2fef94a30d84277a6404ddcc9d3fb3a7 | refs/heads/master | 2022-12-27T11:48:23.703183 | 2020-10-11T07:00:23 | 2020-10-11T07:00:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,339 | cpp | #pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define lb lower_bound
#define ub upper_bound
#define ins insert
#define ull unsigned long long
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ff first
#define ss second
#define fast ios::sync_with_stdio(0) , cin.tie(0) , cout.tie(0);
#define nl "\n"
#define sz(a) (int)(a).size()
#define all(a) (a).begin(),(a).end()
#define fl(a,x) memset(a,x,sizeof(a));
#define pt(a,x) cout << get<x>(a) << " " ;
#define mt make_tuple
#define vec vector
#define int long long
const int mod = (int) 1e9 + 7 ;
const int MOD = (int) 998244353 ;
const int INF = (int) 1e18 ;
typedef vector<int> vii;
typedef pair<int,int> pii;
typedef vector<pii> vpi;
typedef vector<vector<int> > vv;
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << endl;
err(++it, args...);
}
int power(int a,int b) {
a %= mod ;
if(b == 0 ) return 1;
int p = power(a,b/2) % mod ;
p = p * p % mod ;
return b & 1 ? p * a % mod : p ;
}
const int mxN = 2e5 + 5;
const int M = (int) 1e9 + 7 ;
ll fact[mxN];
ll ifact[mxN];
ll invMod(ll a) {
return power(a,M-2) % M ;
}
void factorial() {
fact[0] = 1 ;
for(ll i = 1;i< mxN;++i)
fact[i] = ( i * fact[i-1] ) % M ;
}
void inverseFact() {
ifact[mxN-1] = invMod(fact[mxN-1]) ;
for(ll i = mxN-1 ; i>0 ;--i)
ifact[i-1] = ( ifact[i] * i ) % M ;
}
ll nCr(ll n, ll r) {
if (n < r || r < 0 || n < 0) return 0;
ll res = (ifact[r] * ifact[n-r]) % M ;
res = ( res * fact[n]) % M ;
return res ;
}
void solve() {
int n,m; cin >> n >> m ;
int h[n] = {} ;
h[0] = 1 ;
int a[n]; rep(i,1,n) cin >> a[i] , h[a[i]]++ ;
for(int i = 1 ; i < n ; ++i) {
if(h[i]>0 and h[i-1] == 0 ) {
cout << 0 << nl ; return ;
}
}
int dp[n]; dp[0] = 1 ;
for(int i = 1 ; i < n ; ++i ) {
dp[i] = (dp[i-1] * power(h[i-1], h[i])) % mod ;
}
int al = 0 ;
rep(i,1,n) al += (h[i] * (h[i]-1) /2 ) ;
int e = m - n + 1 ;
if(e == 0 ) {
for(int i = 1 ; i < n ; ++i ) if(h[i] == 0 ) {
cout << dp[i-1] << nl ; return ;
}
cout << dp[n-1] << nl ; return ;
}
if(al < e) { cout << 0 << nl ; return ; }
int ans = 1 ;
for(int i = al-e+1 ; i <= al ; ++i) {
ans = (ans * i) % mod ;
}
int b = 1;
for(int i = 1 ; i <= e ; ++i ) b = b * i % mod ;
ans = (ans * power(b,mod-2)) % mod ;
rep(i,1,n) {
if(h[i] == 0) {
cout << (dp[i-1] * ans ) % mod << nl ;
return ;
}
}
cout << dp[n-1] * ans % mod << nl ;
}
int32_t main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
freopen("error.txt", "w", stderr);
#endif
// factorial();
// inverseFact() ;
fast;
int t; cin >> t; while(t--)
solve() ;
// cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
7bf56ab4c588839b4afefc3975982f2cae8f36a2 | 0cde6c6d01b39d600ee75d1b538d99afdf4bc0e5 | /aieBootstrap-master/PhysicsEngine/PhysicsEngineApp.cpp | c9b1bf25d02ceb2d0d43d684d1bba840acc13947 | [
"MIT"
] | permissive | Jezzalittle/PhysicsEngineBootStrapC- | db7d21e83e7ee085ff9507ff9e4ae7bfeb173c5f | d92dd39c206c6357c2be344590595c7d0ddbf5c3 | refs/heads/master | 2021-05-03T10:27:45.412786 | 2018-03-13T05:57:04 | 2018-03-13T05:57:04 | 120,534,593 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,229 | cpp | #include <math.h>
#define _USE_MATH_DEFINES
#include "PhysicsEngineApp.h"
#include "Texture.h"
#include "Font.h"
#include "Input.h"
#include <Gizmos.h>
#include "Sphere.h"
#include "SceneManager.h"
#include "BallDropScene.h"
#include "BallThrowScene.h"
#include "CollisionTestScene.h"
#include "ConvexShapesScene.h"
PhysicsEngineApp::PhysicsEngineApp() {
}
PhysicsEngineApp::~PhysicsEngineApp() {
}
bool PhysicsEngineApp::startup() {
m_2dRenderer = new aie::Renderer2D();
aie::Gizmos::create(225U, 225U, 65535U, 65535U);
// TODO: remember to change this when redistributing a build!
// the following path would be used instead: "./font/consolas.ttf"
m_font = new aie::Font("../bin/font/consolas.ttf", 32);
sceneManager = std::make_shared<SceneManager>();
ballDropScene = std::make_unique<BallDropScene>(sceneManager, 0.005f, glm::vec2{ 0, -9.8f });
ballThrowScene = std::make_unique<BallThrowScene>(sceneManager, 0.005f, glm::vec2{ 0, -9.8f });
collisionScene = std::make_unique<CollisionTestScene>(sceneManager, 0.005f, glm::vec2{ 0, -9.8f });
convexScene = std::make_unique<ConvexShapesScene>(sceneManager, 0.005f, glm::vec2{ 0, -9.8f });
return true;
}
void PhysicsEngineApp::shutdown() {
delete m_font;
delete m_2dRenderer;
//delete ballThrowScene;
}
void PhysicsEngineApp::update(float deltaTime) {
// input example
aie::Input* input = aie::Input::getInstance();
sceneManager->UpdateScene(deltaTime);
if (input->wasKeyPressed(aie::INPUT_KEY_RIGHT))
{
sceneManager->NextScene();
}
if (input->wasKeyPressed(aie::INPUT_KEY_LEFT))
{
sceneManager->PreviousScene();
}
// exit the application
if (input->isKeyDown(aie::INPUT_KEY_ESCAPE))
quit();
}
void PhysicsEngineApp::draw() {
// wipe the screen to the background colour
clearScreen();
// begin drawing sprites
m_2dRenderer->begin();
// draw your stuff here!
static float aspectRatio = getWindowWidth() / (float)getWindowHeight();
aie::Gizmos::draw2D(glm::ortho<float>(-100.0f, 100.0f, -100.0f / aspectRatio, 100.0f / aspectRatio, -1.0f, 1.0f));
// output some text, uses the last used colour
m_2dRenderer->drawText(m_font, "Press ESC to quit", 0.5f, 8.0f);
// done drawing sprites
m_2dRenderer->end();
}
| [
"jezzalittle20@gmail.com"
] | jezzalittle20@gmail.com |
104b356bd0a481a533e3513e925146e9015a4670 | ad737f6b2872819b8ea88835edee8356da58a82e | /software/tools/arm/arm-none-eabi/include/c++/7.3.1/bits/random.h | c3fbb0fff164b349c004787c6323720e75595d79 | [
"MIT"
] | permissive | UASLab/RAPTRS | e4f3240aaa41000f8d4843cbc26e537ccedf2d48 | ebcebf87b5195623a228f9844a66c34d557d2714 | refs/heads/master | 2022-05-03T02:23:16.231397 | 2022-04-04T14:02:07 | 2022-04-04T14:02:07 | 208,188,913 | 4 | 3 | MIT | 2022-04-11T18:13:21 | 2019-09-13T03:29:57 | C++ | UTF-8 | C++ | false | false | 175,292 | h | // random number generation -*- C++ -*-
// Copyright (C) 2009-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/**
* @file bits/random.h
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{random}
*/
#ifndef _RANDOM_H
#define _RANDOM_H 1
#include <vector>
#include <bits/uniform_int_dist.h>
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
// [26.4] Random number generation
/**
* @defgroup random Random Number Generation
* @ingroup numerics
*
* A facility for generating random numbers on selected distributions.
* @{
*/
/**
* @brief A function template for converting the output of a (integral)
* uniform random number generator to a floatng point result in the range
* [0-1).
*/
template<typename _RealType, size_t __bits,
typename _UniformRandomNumberGenerator>
_RealType
generate_canonical(_UniformRandomNumberGenerator& __g);
_GLIBCXX_END_NAMESPACE_VERSION
/*
* Implementation-space details.
*/
namespace __detail
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
template<typename _UIntType, size_t __w,
bool = __w < static_cast<size_t>
(std::numeric_limits<_UIntType>::digits)>
struct _Shift
{ static const _UIntType __value = 0; };
template<typename _UIntType, size_t __w>
struct _Shift<_UIntType, __w, true>
{ static const _UIntType __value = _UIntType(1) << __w; };
template<int __s,
int __which = ((__s <= __CHAR_BIT__ * sizeof (int))
+ (__s <= __CHAR_BIT__ * sizeof (long))
+ (__s <= __CHAR_BIT__ * sizeof (long long))
/* assume long long no bigger than __int128 */
+ (__s <= 128))>
struct _Select_uint_least_t
{
static_assert(__which < 0, /* needs to be dependent */
"sorry, would be too much trouble for a slow result");
};
template<int __s>
struct _Select_uint_least_t<__s, 4>
{ typedef unsigned int type; };
template<int __s>
struct _Select_uint_least_t<__s, 3>
{ typedef unsigned long type; };
template<int __s>
struct _Select_uint_least_t<__s, 2>
{ typedef unsigned long long type; };
#ifdef _GLIBCXX_USE_INT128
template<int __s>
struct _Select_uint_least_t<__s, 1>
{ typedef unsigned __int128 type; };
#endif
// Assume a != 0, a < m, c < m, x < m.
template<typename _Tp, _Tp __m, _Tp __a, _Tp __c,
bool __big_enough = (!(__m & (__m - 1))
|| (_Tp(-1) - __c) / __a >= __m - 1),
bool __schrage_ok = __m % __a < __m / __a>
struct _Mod
{
typedef typename _Select_uint_least_t<std::__lg(__a)
+ std::__lg(__m) + 2>::type _Tp2;
static _Tp
__calc(_Tp __x)
{ return static_cast<_Tp>((_Tp2(__a) * __x + __c) % __m); }
};
// Schrage.
template<typename _Tp, _Tp __m, _Tp __a, _Tp __c>
struct _Mod<_Tp, __m, __a, __c, false, true>
{
static _Tp
__calc(_Tp __x);
};
// Special cases:
// - for m == 2^n or m == 0, unsigned integer overflow is safe.
// - a * (m - 1) + c fits in _Tp, there is no overflow.
template<typename _Tp, _Tp __m, _Tp __a, _Tp __c, bool __s>
struct _Mod<_Tp, __m, __a, __c, true, __s>
{
static _Tp
__calc(_Tp __x)
{
_Tp __res = __a * __x + __c;
if (__m)
__res %= __m;
return __res;
}
};
template<typename _Tp, _Tp __m, _Tp __a = 1, _Tp __c = 0>
inline _Tp
__mod(_Tp __x)
{ return _Mod<_Tp, __m, __a, __c>::__calc(__x); }
/*
* An adaptor class for converting the output of any Generator into
* the input for a specific Distribution.
*/
template<typename _Engine, typename _DInputType>
struct _Adaptor
{
static_assert(std::is_floating_point<_DInputType>::value,
"template argument must be a floating point type");
public:
_Adaptor(_Engine& __g)
: _M_g(__g) { }
_DInputType
min() const
{ return _DInputType(0); }
_DInputType
max() const
{ return _DInputType(1); }
/*
* Converts a value generated by the adapted random number generator
* into a value in the input domain for the dependent random number
* distribution.
*/
_DInputType
operator()()
{
return std::generate_canonical<_DInputType,
std::numeric_limits<_DInputType>::digits,
_Engine>(_M_g);
}
private:
_Engine& _M_g;
};
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace __detail
_GLIBCXX_BEGIN_NAMESPACE_VERSION
/**
* @addtogroup random_generators Random Number Generators
* @ingroup random
*
* These classes define objects which provide random or pseudorandom
* numbers, either from a discrete or a continuous interval. The
* random number generator supplied as a part of this library are
* all uniform random number generators which provide a sequence of
* random number uniformly distributed over their range.
*
* A number generator is a function object with an operator() that
* takes zero arguments and returns a number.
*
* A compliant random number generator must satisfy the following
* requirements. <table border=1 cellpadding=10 cellspacing=0>
* <caption align=top>Random Number Generator Requirements</caption>
* <tr><td>To be documented.</td></tr> </table>
*
* @{
*/
/**
* @brief A model of a linear congruential random number generator.
*
* A random number generator that produces pseudorandom numbers via
* linear function:
* @f[
* x_{i+1}\leftarrow(ax_{i} + c) \bmod m
* @f]
*
* The template parameter @p _UIntType must be an unsigned integral type
* large enough to store values up to (__m-1). If the template parameter
* @p __m is 0, the modulus @p __m used is
* std::numeric_limits<_UIntType>::max() plus 1. Otherwise, the template
* parameters @p __a and @p __c must be less than @p __m.
*
* The size of the state is @f$1@f$.
*/
template<typename _UIntType, _UIntType __a, _UIntType __c, _UIntType __m>
class linear_congruential_engine
{
static_assert(std::is_unsigned<_UIntType>::value,
"result_type must be an unsigned integral type");
static_assert(__m == 0u || (__a < __m && __c < __m),
"template argument substituting __m out of bounds");
public:
/** The type of the generated random value. */
typedef _UIntType result_type;
/** The multiplier. */
static constexpr result_type multiplier = __a;
/** An increment. */
static constexpr result_type increment = __c;
/** The modulus. */
static constexpr result_type modulus = __m;
static constexpr result_type default_seed = 1u;
/**
* @brief Constructs a %linear_congruential_engine random number
* generator engine with seed @p __s. The default seed value
* is 1.
*
* @param __s The initial seed value.
*/
explicit
linear_congruential_engine(result_type __s = default_seed)
{ seed(__s); }
/**
* @brief Constructs a %linear_congruential_engine random number
* generator engine seeded from the seed sequence @p __q.
*
* @param __q the seed sequence.
*/
template<typename _Sseq, typename = typename
std::enable_if<!std::is_same<_Sseq, linear_congruential_engine>::value>
::type>
explicit
linear_congruential_engine(_Sseq& __q)
{ seed(__q); }
/**
* @brief Reseeds the %linear_congruential_engine random number generator
* engine sequence to the seed @p __s.
*
* @param __s The new seed.
*/
void
seed(result_type __s = default_seed);
/**
* @brief Reseeds the %linear_congruential_engine random number generator
* engine
* sequence using values from the seed sequence @p __q.
*
* @param __q the seed sequence.
*/
template<typename _Sseq>
typename std::enable_if<std::is_class<_Sseq>::value>::type
seed(_Sseq& __q);
/**
* @brief Gets the smallest possible value in the output range.
*
* The minimum depends on the @p __c parameter: if it is zero, the
* minimum generated must be > 0, otherwise 0 is allowed.
*/
static constexpr result_type
min()
{ return __c == 0u ? 1u : 0u; }
/**
* @brief Gets the largest possible value in the output range.
*/
static constexpr result_type
max()
{ return __m - 1u; }
/**
* @brief Discard a sequence of random numbers.
*/
void
discard(unsigned long long __z)
{
for (; __z != 0ULL; --__z)
(*this)();
}
/**
* @brief Gets the next random number in the sequence.
*/
result_type
operator()()
{
_M_x = __detail::__mod<_UIntType, __m, __a, __c>(_M_x);
return _M_x;
}
/**
* @brief Compares two linear congruential random number generator
* objects of the same type for equality.
*
* @param __lhs A linear congruential random number generator object.
* @param __rhs Another linear congruential random number generator
* object.
*
* @returns true if the infinite sequences of generated values
* would be equal, false otherwise.
*/
friend bool
operator==(const linear_congruential_engine& __lhs,
const linear_congruential_engine& __rhs)
{ return __lhs._M_x == __rhs._M_x; }
/**
* @brief Writes the textual representation of the state x(i) of x to
* @p __os.
*
* @param __os The output stream.
* @param __lcr A % linear_congruential_engine random number generator.
* @returns __os.
*/
template<typename _UIntType1, _UIntType1 __a1, _UIntType1 __c1,
_UIntType1 __m1, typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::linear_congruential_engine<_UIntType1,
__a1, __c1, __m1>& __lcr);
/**
* @brief Sets the state of the engine by reading its textual
* representation from @p __is.
*
* The textual representation must have been previously written using
* an output stream whose imbued locale and whose type's template
* specialization arguments _CharT and _Traits were the same as those
* of @p __is.
*
* @param __is The input stream.
* @param __lcr A % linear_congruential_engine random number generator.
* @returns __is.
*/
template<typename _UIntType1, _UIntType1 __a1, _UIntType1 __c1,
_UIntType1 __m1, typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::linear_congruential_engine<_UIntType1, __a1,
__c1, __m1>& __lcr);
private:
_UIntType _M_x;
};
/**
* @brief Compares two linear congruential random number generator
* objects of the same type for inequality.
*
* @param __lhs A linear congruential random number generator object.
* @param __rhs Another linear congruential random number generator
* object.
*
* @returns true if the infinite sequences of generated values
* would be different, false otherwise.
*/
template<typename _UIntType, _UIntType __a, _UIntType __c, _UIntType __m>
inline bool
operator!=(const std::linear_congruential_engine<_UIntType, __a,
__c, __m>& __lhs,
const std::linear_congruential_engine<_UIntType, __a,
__c, __m>& __rhs)
{ return !(__lhs == __rhs); }
/**
* A generalized feedback shift register discrete random number generator.
*
* This algorithm avoids multiplication and division and is designed to be
* friendly to a pipelined architecture. If the parameters are chosen
* correctly, this generator will produce numbers with a very long period and
* fairly good apparent entropy, although still not cryptographically strong.
*
* The best way to use this generator is with the predefined mt19937 class.
*
* This algorithm was originally invented by Makoto Matsumoto and
* Takuji Nishimura.
*
* @tparam __w Word size, the number of bits in each element of
* the state vector.
* @tparam __n The degree of recursion.
* @tparam __m The period parameter.
* @tparam __r The separation point bit index.
* @tparam __a The last row of the twist matrix.
* @tparam __u The first right-shift tempering matrix parameter.
* @tparam __d The first right-shift tempering matrix mask.
* @tparam __s The first left-shift tempering matrix parameter.
* @tparam __b The first left-shift tempering matrix mask.
* @tparam __t The second left-shift tempering matrix parameter.
* @tparam __c The second left-shift tempering matrix mask.
* @tparam __l The second right-shift tempering matrix parameter.
* @tparam __f Initialization multiplier.
*/
template<typename _UIntType, size_t __w,
size_t __n, size_t __m, size_t __r,
_UIntType __a, size_t __u, _UIntType __d, size_t __s,
_UIntType __b, size_t __t,
_UIntType __c, size_t __l, _UIntType __f>
class mersenne_twister_engine
{
static_assert(std::is_unsigned<_UIntType>::value,
"result_type must be an unsigned integral type");
static_assert(1u <= __m && __m <= __n,
"template argument substituting __m out of bounds");
static_assert(__r <= __w, "template argument substituting "
"__r out of bound");
static_assert(__u <= __w, "template argument substituting "
"__u out of bound");
static_assert(__s <= __w, "template argument substituting "
"__s out of bound");
static_assert(__t <= __w, "template argument substituting "
"__t out of bound");
static_assert(__l <= __w, "template argument substituting "
"__l out of bound");
static_assert(__w <= std::numeric_limits<_UIntType>::digits,
"template argument substituting __w out of bound");
static_assert(__a <= (__detail::_Shift<_UIntType, __w>::__value - 1),
"template argument substituting __a out of bound");
static_assert(__b <= (__detail::_Shift<_UIntType, __w>::__value - 1),
"template argument substituting __b out of bound");
static_assert(__c <= (__detail::_Shift<_UIntType, __w>::__value - 1),
"template argument substituting __c out of bound");
static_assert(__d <= (__detail::_Shift<_UIntType, __w>::__value - 1),
"template argument substituting __d out of bound");
static_assert(__f <= (__detail::_Shift<_UIntType, __w>::__value - 1),
"template argument substituting __f out of bound");
public:
/** The type of the generated random value. */
typedef _UIntType result_type;
// parameter values
static constexpr size_t word_size = __w;
static constexpr size_t state_size = __n;
static constexpr size_t shift_size = __m;
static constexpr size_t mask_bits = __r;
static constexpr result_type xor_mask = __a;
static constexpr size_t tempering_u = __u;
static constexpr result_type tempering_d = __d;
static constexpr size_t tempering_s = __s;
static constexpr result_type tempering_b = __b;
static constexpr size_t tempering_t = __t;
static constexpr result_type tempering_c = __c;
static constexpr size_t tempering_l = __l;
static constexpr result_type initialization_multiplier = __f;
static constexpr result_type default_seed = 5489u;
// constructors and member function
explicit
mersenne_twister_engine(result_type __sd = default_seed)
{ seed(__sd); }
/**
* @brief Constructs a %mersenne_twister_engine random number generator
* engine seeded from the seed sequence @p __q.
*
* @param __q the seed sequence.
*/
template<typename _Sseq, typename = typename
std::enable_if<!std::is_same<_Sseq, mersenne_twister_engine>::value>
::type>
explicit
mersenne_twister_engine(_Sseq& __q)
{ seed(__q); }
void
seed(result_type __sd = default_seed);
template<typename _Sseq>
typename std::enable_if<std::is_class<_Sseq>::value>::type
seed(_Sseq& __q);
/**
* @brief Gets the smallest possible value in the output range.
*/
static constexpr result_type
min()
{ return 0; };
/**
* @brief Gets the largest possible value in the output range.
*/
static constexpr result_type
max()
{ return __detail::_Shift<_UIntType, __w>::__value - 1; }
/**
* @brief Discard a sequence of random numbers.
*/
void
discard(unsigned long long __z);
result_type
operator()();
/**
* @brief Compares two % mersenne_twister_engine random number generator
* objects of the same type for equality.
*
* @param __lhs A % mersenne_twister_engine random number generator
* object.
* @param __rhs Another % mersenne_twister_engine random number
* generator object.
*
* @returns true if the infinite sequences of generated values
* would be equal, false otherwise.
*/
friend bool
operator==(const mersenne_twister_engine& __lhs,
const mersenne_twister_engine& __rhs)
{ return (std::equal(__lhs._M_x, __lhs._M_x + state_size, __rhs._M_x)
&& __lhs._M_p == __rhs._M_p); }
/**
* @brief Inserts the current state of a % mersenne_twister_engine
* random number generator engine @p __x into the output stream
* @p __os.
*
* @param __os An output stream.
* @param __x A % mersenne_twister_engine random number generator
* engine.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _UIntType1,
size_t __w1, size_t __n1,
size_t __m1, size_t __r1,
_UIntType1 __a1, size_t __u1,
_UIntType1 __d1, size_t __s1,
_UIntType1 __b1, size_t __t1,
_UIntType1 __c1, size_t __l1, _UIntType1 __f1,
typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::mersenne_twister_engine<_UIntType1, __w1, __n1,
__m1, __r1, __a1, __u1, __d1, __s1, __b1, __t1, __c1,
__l1, __f1>& __x);
/**
* @brief Extracts the current state of a % mersenne_twister_engine
* random number generator engine @p __x from the input stream
* @p __is.
*
* @param __is An input stream.
* @param __x A % mersenne_twister_engine random number generator
* engine.
*
* @returns The input stream with the state of @p __x extracted or in
* an error state.
*/
template<typename _UIntType1,
size_t __w1, size_t __n1,
size_t __m1, size_t __r1,
_UIntType1 __a1, size_t __u1,
_UIntType1 __d1, size_t __s1,
_UIntType1 __b1, size_t __t1,
_UIntType1 __c1, size_t __l1, _UIntType1 __f1,
typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::mersenne_twister_engine<_UIntType1, __w1, __n1, __m1,
__r1, __a1, __u1, __d1, __s1, __b1, __t1, __c1,
__l1, __f1>& __x);
private:
void _M_gen_rand();
_UIntType _M_x[state_size];
size_t _M_p;
};
/**
* @brief Compares two % mersenne_twister_engine random number generator
* objects of the same type for inequality.
*
* @param __lhs A % mersenne_twister_engine random number generator
* object.
* @param __rhs Another % mersenne_twister_engine random number
* generator object.
*
* @returns true if the infinite sequences of generated values
* would be different, false otherwise.
*/
template<typename _UIntType, size_t __w,
size_t __n, size_t __m, size_t __r,
_UIntType __a, size_t __u, _UIntType __d, size_t __s,
_UIntType __b, size_t __t,
_UIntType __c, size_t __l, _UIntType __f>
inline bool
operator!=(const std::mersenne_twister_engine<_UIntType, __w, __n, __m,
__r, __a, __u, __d, __s, __b, __t, __c, __l, __f>& __lhs,
const std::mersenne_twister_engine<_UIntType, __w, __n, __m,
__r, __a, __u, __d, __s, __b, __t, __c, __l, __f>& __rhs)
{ return !(__lhs == __rhs); }
/**
* @brief The Marsaglia-Zaman generator.
*
* This is a model of a Generalized Fibonacci discrete random number
* generator, sometimes referred to as the SWC generator.
*
* A discrete random number generator that produces pseudorandom
* numbers using:
* @f[
* x_{i}\leftarrow(x_{i - s} - x_{i - r} - carry_{i-1}) \bmod m
* @f]
*
* The size of the state is @f$r@f$
* and the maximum period of the generator is @f$(m^r - m^s - 1)@f$.
*/
template<typename _UIntType, size_t __w, size_t __s, size_t __r>
class subtract_with_carry_engine
{
static_assert(std::is_unsigned<_UIntType>::value,
"result_type must be an unsigned integral type");
static_assert(0u < __s && __s < __r,
"0 < s < r");
static_assert(0u < __w && __w <= std::numeric_limits<_UIntType>::digits,
"template argument substituting __w out of bounds");
public:
/** The type of the generated random value. */
typedef _UIntType result_type;
// parameter values
static constexpr size_t word_size = __w;
static constexpr size_t short_lag = __s;
static constexpr size_t long_lag = __r;
static constexpr result_type default_seed = 19780503u;
/**
* @brief Constructs an explicitly seeded % subtract_with_carry_engine
* random number generator.
*/
explicit
subtract_with_carry_engine(result_type __sd = default_seed)
{ seed(__sd); }
/**
* @brief Constructs a %subtract_with_carry_engine random number engine
* seeded from the seed sequence @p __q.
*
* @param __q the seed sequence.
*/
template<typename _Sseq, typename = typename
std::enable_if<!std::is_same<_Sseq, subtract_with_carry_engine>::value>
::type>
explicit
subtract_with_carry_engine(_Sseq& __q)
{ seed(__q); }
/**
* @brief Seeds the initial state @f$x_0@f$ of the random number
* generator.
*
* N1688[4.19] modifies this as follows. If @p __value == 0,
* sets value to 19780503. In any case, with a linear
* congruential generator lcg(i) having parameters @f$ m_{lcg} =
* 2147483563, a_{lcg} = 40014, c_{lcg} = 0, and lcg(0) = value
* @f$, sets @f$ x_{-r} \dots x_{-1} @f$ to @f$ lcg(1) \bmod m
* \dots lcg(r) \bmod m @f$ respectively. If @f$ x_{-1} = 0 @f$
* set carry to 1, otherwise sets carry to 0.
*/
void
seed(result_type __sd = default_seed);
/**
* @brief Seeds the initial state @f$x_0@f$ of the
* % subtract_with_carry_engine random number generator.
*/
template<typename _Sseq>
typename std::enable_if<std::is_class<_Sseq>::value>::type
seed(_Sseq& __q);
/**
* @brief Gets the inclusive minimum value of the range of random
* integers returned by this generator.
*/
static constexpr result_type
min()
{ return 0; }
/**
* @brief Gets the inclusive maximum value of the range of random
* integers returned by this generator.
*/
static constexpr result_type
max()
{ return __detail::_Shift<_UIntType, __w>::__value - 1; }
/**
* @brief Discard a sequence of random numbers.
*/
void
discard(unsigned long long __z)
{
for (; __z != 0ULL; --__z)
(*this)();
}
/**
* @brief Gets the next random number in the sequence.
*/
result_type
operator()();
/**
* @brief Compares two % subtract_with_carry_engine random number
* generator objects of the same type for equality.
*
* @param __lhs A % subtract_with_carry_engine random number generator
* object.
* @param __rhs Another % subtract_with_carry_engine random number
* generator object.
*
* @returns true if the infinite sequences of generated values
* would be equal, false otherwise.
*/
friend bool
operator==(const subtract_with_carry_engine& __lhs,
const subtract_with_carry_engine& __rhs)
{ return (std::equal(__lhs._M_x, __lhs._M_x + long_lag, __rhs._M_x)
&& __lhs._M_carry == __rhs._M_carry
&& __lhs._M_p == __rhs._M_p); }
/**
* @brief Inserts the current state of a % subtract_with_carry_engine
* random number generator engine @p __x into the output stream
* @p __os.
*
* @param __os An output stream.
* @param __x A % subtract_with_carry_engine random number generator
* engine.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _UIntType1, size_t __w1, size_t __s1, size_t __r1,
typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::subtract_with_carry_engine<_UIntType1, __w1,
__s1, __r1>& __x);
/**
* @brief Extracts the current state of a % subtract_with_carry_engine
* random number generator engine @p __x from the input stream
* @p __is.
*
* @param __is An input stream.
* @param __x A % subtract_with_carry_engine random number generator
* engine.
*
* @returns The input stream with the state of @p __x extracted or in
* an error state.
*/
template<typename _UIntType1, size_t __w1, size_t __s1, size_t __r1,
typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::subtract_with_carry_engine<_UIntType1, __w1,
__s1, __r1>& __x);
private:
/// The state of the generator. This is a ring buffer.
_UIntType _M_x[long_lag];
_UIntType _M_carry; ///< The carry
size_t _M_p; ///< Current index of x(i - r).
};
/**
* @brief Compares two % subtract_with_carry_engine random number
* generator objects of the same type for inequality.
*
* @param __lhs A % subtract_with_carry_engine random number generator
* object.
* @param __rhs Another % subtract_with_carry_engine random number
* generator object.
*
* @returns true if the infinite sequences of generated values
* would be different, false otherwise.
*/
template<typename _UIntType, size_t __w, size_t __s, size_t __r>
inline bool
operator!=(const std::subtract_with_carry_engine<_UIntType, __w,
__s, __r>& __lhs,
const std::subtract_with_carry_engine<_UIntType, __w,
__s, __r>& __rhs)
{ return !(__lhs == __rhs); }
/**
* Produces random numbers from some base engine by discarding blocks of
* data.
*
* 0 <= @p __r <= @p __p
*/
template<typename _RandomNumberEngine, size_t __p, size_t __r>
class discard_block_engine
{
static_assert(1 <= __r && __r <= __p,
"template argument substituting __r out of bounds");
public:
/** The type of the generated random value. */
typedef typename _RandomNumberEngine::result_type result_type;
// parameter values
static constexpr size_t block_size = __p;
static constexpr size_t used_block = __r;
/**
* @brief Constructs a default %discard_block_engine engine.
*
* The underlying engine is default constructed as well.
*/
discard_block_engine()
: _M_b(), _M_n(0) { }
/**
* @brief Copy constructs a %discard_block_engine engine.
*
* Copies an existing base class random number generator.
* @param __rng An existing (base class) engine object.
*/
explicit
discard_block_engine(const _RandomNumberEngine& __rng)
: _M_b(__rng), _M_n(0) { }
/**
* @brief Move constructs a %discard_block_engine engine.
*
* Copies an existing base class random number generator.
* @param __rng An existing (base class) engine object.
*/
explicit
discard_block_engine(_RandomNumberEngine&& __rng)
: _M_b(std::move(__rng)), _M_n(0) { }
/**
* @brief Seed constructs a %discard_block_engine engine.
*
* Constructs the underlying generator engine seeded with @p __s.
* @param __s A seed value for the base class engine.
*/
explicit
discard_block_engine(result_type __s)
: _M_b(__s), _M_n(0) { }
/**
* @brief Generator construct a %discard_block_engine engine.
*
* @param __q A seed sequence.
*/
template<typename _Sseq, typename = typename
std::enable_if<!std::is_same<_Sseq, discard_block_engine>::value
&& !std::is_same<_Sseq, _RandomNumberEngine>::value>
::type>
explicit
discard_block_engine(_Sseq& __q)
: _M_b(__q), _M_n(0)
{ }
/**
* @brief Reseeds the %discard_block_engine object with the default
* seed for the underlying base class generator engine.
*/
void
seed()
{
_M_b.seed();
_M_n = 0;
}
/**
* @brief Reseeds the %discard_block_engine object with the default
* seed for the underlying base class generator engine.
*/
void
seed(result_type __s)
{
_M_b.seed(__s);
_M_n = 0;
}
/**
* @brief Reseeds the %discard_block_engine object with the given seed
* sequence.
* @param __q A seed generator function.
*/
template<typename _Sseq>
void
seed(_Sseq& __q)
{
_M_b.seed(__q);
_M_n = 0;
}
/**
* @brief Gets a const reference to the underlying generator engine
* object.
*/
const _RandomNumberEngine&
base() const noexcept
{ return _M_b; }
/**
* @brief Gets the minimum value in the generated random number range.
*/
static constexpr result_type
min()
{ return _RandomNumberEngine::min(); }
/**
* @brief Gets the maximum value in the generated random number range.
*/
static constexpr result_type
max()
{ return _RandomNumberEngine::max(); }
/**
* @brief Discard a sequence of random numbers.
*/
void
discard(unsigned long long __z)
{
for (; __z != 0ULL; --__z)
(*this)();
}
/**
* @brief Gets the next value in the generated random number sequence.
*/
result_type
operator()();
/**
* @brief Compares two %discard_block_engine random number generator
* objects of the same type for equality.
*
* @param __lhs A %discard_block_engine random number generator object.
* @param __rhs Another %discard_block_engine random number generator
* object.
*
* @returns true if the infinite sequences of generated values
* would be equal, false otherwise.
*/
friend bool
operator==(const discard_block_engine& __lhs,
const discard_block_engine& __rhs)
{ return __lhs._M_b == __rhs._M_b && __lhs._M_n == __rhs._M_n; }
/**
* @brief Inserts the current state of a %discard_block_engine random
* number generator engine @p __x into the output stream
* @p __os.
*
* @param __os An output stream.
* @param __x A %discard_block_engine random number generator engine.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RandomNumberEngine1, size_t __p1, size_t __r1,
typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::discard_block_engine<_RandomNumberEngine1,
__p1, __r1>& __x);
/**
* @brief Extracts the current state of a % subtract_with_carry_engine
* random number generator engine @p __x from the input stream
* @p __is.
*
* @param __is An input stream.
* @param __x A %discard_block_engine random number generator engine.
*
* @returns The input stream with the state of @p __x extracted or in
* an error state.
*/
template<typename _RandomNumberEngine1, size_t __p1, size_t __r1,
typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::discard_block_engine<_RandomNumberEngine1,
__p1, __r1>& __x);
private:
_RandomNumberEngine _M_b;
size_t _M_n;
};
/**
* @brief Compares two %discard_block_engine random number generator
* objects of the same type for inequality.
*
* @param __lhs A %discard_block_engine random number generator object.
* @param __rhs Another %discard_block_engine random number generator
* object.
*
* @returns true if the infinite sequences of generated values
* would be different, false otherwise.
*/
template<typename _RandomNumberEngine, size_t __p, size_t __r>
inline bool
operator!=(const std::discard_block_engine<_RandomNumberEngine, __p,
__r>& __lhs,
const std::discard_block_engine<_RandomNumberEngine, __p,
__r>& __rhs)
{ return !(__lhs == __rhs); }
/**
* Produces random numbers by combining random numbers from some base
* engine to produce random numbers with a specifies number of bits @p __w.
*/
template<typename _RandomNumberEngine, size_t __w, typename _UIntType>
class independent_bits_engine
{
static_assert(std::is_unsigned<_UIntType>::value,
"result_type must be an unsigned integral type");
static_assert(0u < __w && __w <= std::numeric_limits<_UIntType>::digits,
"template argument substituting __w out of bounds");
public:
/** The type of the generated random value. */
typedef _UIntType result_type;
/**
* @brief Constructs a default %independent_bits_engine engine.
*
* The underlying engine is default constructed as well.
*/
independent_bits_engine()
: _M_b() { }
/**
* @brief Copy constructs a %independent_bits_engine engine.
*
* Copies an existing base class random number generator.
* @param __rng An existing (base class) engine object.
*/
explicit
independent_bits_engine(const _RandomNumberEngine& __rng)
: _M_b(__rng) { }
/**
* @brief Move constructs a %independent_bits_engine engine.
*
* Copies an existing base class random number generator.
* @param __rng An existing (base class) engine object.
*/
explicit
independent_bits_engine(_RandomNumberEngine&& __rng)
: _M_b(std::move(__rng)) { }
/**
* @brief Seed constructs a %independent_bits_engine engine.
*
* Constructs the underlying generator engine seeded with @p __s.
* @param __s A seed value for the base class engine.
*/
explicit
independent_bits_engine(result_type __s)
: _M_b(__s) { }
/**
* @brief Generator construct a %independent_bits_engine engine.
*
* @param __q A seed sequence.
*/
template<typename _Sseq, typename = typename
std::enable_if<!std::is_same<_Sseq, independent_bits_engine>::value
&& !std::is_same<_Sseq, _RandomNumberEngine>::value>
::type>
explicit
independent_bits_engine(_Sseq& __q)
: _M_b(__q)
{ }
/**
* @brief Reseeds the %independent_bits_engine object with the default
* seed for the underlying base class generator engine.
*/
void
seed()
{ _M_b.seed(); }
/**
* @brief Reseeds the %independent_bits_engine object with the default
* seed for the underlying base class generator engine.
*/
void
seed(result_type __s)
{ _M_b.seed(__s); }
/**
* @brief Reseeds the %independent_bits_engine object with the given
* seed sequence.
* @param __q A seed generator function.
*/
template<typename _Sseq>
void
seed(_Sseq& __q)
{ _M_b.seed(__q); }
/**
* @brief Gets a const reference to the underlying generator engine
* object.
*/
const _RandomNumberEngine&
base() const noexcept
{ return _M_b; }
/**
* @brief Gets the minimum value in the generated random number range.
*/
static constexpr result_type
min()
{ return 0U; }
/**
* @brief Gets the maximum value in the generated random number range.
*/
static constexpr result_type
max()
{ return __detail::_Shift<_UIntType, __w>::__value - 1; }
/**
* @brief Discard a sequence of random numbers.
*/
void
discard(unsigned long long __z)
{
for (; __z != 0ULL; --__z)
(*this)();
}
/**
* @brief Gets the next value in the generated random number sequence.
*/
result_type
operator()();
/**
* @brief Compares two %independent_bits_engine random number generator
* objects of the same type for equality.
*
* @param __lhs A %independent_bits_engine random number generator
* object.
* @param __rhs Another %independent_bits_engine random number generator
* object.
*
* @returns true if the infinite sequences of generated values
* would be equal, false otherwise.
*/
friend bool
operator==(const independent_bits_engine& __lhs,
const independent_bits_engine& __rhs)
{ return __lhs._M_b == __rhs._M_b; }
/**
* @brief Extracts the current state of a % subtract_with_carry_engine
* random number generator engine @p __x from the input stream
* @p __is.
*
* @param __is An input stream.
* @param __x A %independent_bits_engine random number generator
* engine.
*
* @returns The input stream with the state of @p __x extracted or in
* an error state.
*/
template<typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::independent_bits_engine<_RandomNumberEngine,
__w, _UIntType>& __x)
{
__is >> __x._M_b;
return __is;
}
private:
_RandomNumberEngine _M_b;
};
/**
* @brief Compares two %independent_bits_engine random number generator
* objects of the same type for inequality.
*
* @param __lhs A %independent_bits_engine random number generator
* object.
* @param __rhs Another %independent_bits_engine random number generator
* object.
*
* @returns true if the infinite sequences of generated values
* would be different, false otherwise.
*/
template<typename _RandomNumberEngine, size_t __w, typename _UIntType>
inline bool
operator!=(const std::independent_bits_engine<_RandomNumberEngine, __w,
_UIntType>& __lhs,
const std::independent_bits_engine<_RandomNumberEngine, __w,
_UIntType>& __rhs)
{ return !(__lhs == __rhs); }
/**
* @brief Inserts the current state of a %independent_bits_engine random
* number generator engine @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %independent_bits_engine random number generator engine.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RandomNumberEngine, size_t __w, typename _UIntType,
typename _CharT, typename _Traits>
std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::independent_bits_engine<_RandomNumberEngine,
__w, _UIntType>& __x)
{
__os << __x.base();
return __os;
}
/**
* @brief Produces random numbers by combining random numbers from some
* base engine to produce random numbers with a specifies number of bits
* @p __k.
*/
template<typename _RandomNumberEngine, size_t __k>
class shuffle_order_engine
{
static_assert(1u <= __k, "template argument substituting "
"__k out of bound");
public:
/** The type of the generated random value. */
typedef typename _RandomNumberEngine::result_type result_type;
static constexpr size_t table_size = __k;
/**
* @brief Constructs a default %shuffle_order_engine engine.
*
* The underlying engine is default constructed as well.
*/
shuffle_order_engine()
: _M_b()
{ _M_initialize(); }
/**
* @brief Copy constructs a %shuffle_order_engine engine.
*
* Copies an existing base class random number generator.
* @param __rng An existing (base class) engine object.
*/
explicit
shuffle_order_engine(const _RandomNumberEngine& __rng)
: _M_b(__rng)
{ _M_initialize(); }
/**
* @brief Move constructs a %shuffle_order_engine engine.
*
* Copies an existing base class random number generator.
* @param __rng An existing (base class) engine object.
*/
explicit
shuffle_order_engine(_RandomNumberEngine&& __rng)
: _M_b(std::move(__rng))
{ _M_initialize(); }
/**
* @brief Seed constructs a %shuffle_order_engine engine.
*
* Constructs the underlying generator engine seeded with @p __s.
* @param __s A seed value for the base class engine.
*/
explicit
shuffle_order_engine(result_type __s)
: _M_b(__s)
{ _M_initialize(); }
/**
* @brief Generator construct a %shuffle_order_engine engine.
*
* @param __q A seed sequence.
*/
template<typename _Sseq, typename = typename
std::enable_if<!std::is_same<_Sseq, shuffle_order_engine>::value
&& !std::is_same<_Sseq, _RandomNumberEngine>::value>
::type>
explicit
shuffle_order_engine(_Sseq& __q)
: _M_b(__q)
{ _M_initialize(); }
/**
* @brief Reseeds the %shuffle_order_engine object with the default seed
for the underlying base class generator engine.
*/
void
seed()
{
_M_b.seed();
_M_initialize();
}
/**
* @brief Reseeds the %shuffle_order_engine object with the default seed
* for the underlying base class generator engine.
*/
void
seed(result_type __s)
{
_M_b.seed(__s);
_M_initialize();
}
/**
* @brief Reseeds the %shuffle_order_engine object with the given seed
* sequence.
* @param __q A seed generator function.
*/
template<typename _Sseq>
void
seed(_Sseq& __q)
{
_M_b.seed(__q);
_M_initialize();
}
/**
* Gets a const reference to the underlying generator engine object.
*/
const _RandomNumberEngine&
base() const noexcept
{ return _M_b; }
/**
* Gets the minimum value in the generated random number range.
*/
static constexpr result_type
min()
{ return _RandomNumberEngine::min(); }
/**
* Gets the maximum value in the generated random number range.
*/
static constexpr result_type
max()
{ return _RandomNumberEngine::max(); }
/**
* Discard a sequence of random numbers.
*/
void
discard(unsigned long long __z)
{
for (; __z != 0ULL; --__z)
(*this)();
}
/**
* Gets the next value in the generated random number sequence.
*/
result_type
operator()();
/**
* Compares two %shuffle_order_engine random number generator objects
* of the same type for equality.
*
* @param __lhs A %shuffle_order_engine random number generator object.
* @param __rhs Another %shuffle_order_engine random number generator
* object.
*
* @returns true if the infinite sequences of generated values
* would be equal, false otherwise.
*/
friend bool
operator==(const shuffle_order_engine& __lhs,
const shuffle_order_engine& __rhs)
{ return (__lhs._M_b == __rhs._M_b
&& std::equal(__lhs._M_v, __lhs._M_v + __k, __rhs._M_v)
&& __lhs._M_y == __rhs._M_y); }
/**
* @brief Inserts the current state of a %shuffle_order_engine random
* number generator engine @p __x into the output stream
@p __os.
*
* @param __os An output stream.
* @param __x A %shuffle_order_engine random number generator engine.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RandomNumberEngine1, size_t __k1,
typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::shuffle_order_engine<_RandomNumberEngine1,
__k1>& __x);
/**
* @brief Extracts the current state of a % subtract_with_carry_engine
* random number generator engine @p __x from the input stream
* @p __is.
*
* @param __is An input stream.
* @param __x A %shuffle_order_engine random number generator engine.
*
* @returns The input stream with the state of @p __x extracted or in
* an error state.
*/
template<typename _RandomNumberEngine1, size_t __k1,
typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::shuffle_order_engine<_RandomNumberEngine1, __k1>& __x);
private:
void _M_initialize()
{
for (size_t __i = 0; __i < __k; ++__i)
_M_v[__i] = _M_b();
_M_y = _M_b();
}
_RandomNumberEngine _M_b;
result_type _M_v[__k];
result_type _M_y;
};
/**
* Compares two %shuffle_order_engine random number generator objects
* of the same type for inequality.
*
* @param __lhs A %shuffle_order_engine random number generator object.
* @param __rhs Another %shuffle_order_engine random number generator
* object.
*
* @returns true if the infinite sequences of generated values
* would be different, false otherwise.
*/
template<typename _RandomNumberEngine, size_t __k>
inline bool
operator!=(const std::shuffle_order_engine<_RandomNumberEngine,
__k>& __lhs,
const std::shuffle_order_engine<_RandomNumberEngine,
__k>& __rhs)
{ return !(__lhs == __rhs); }
/**
* The classic Minimum Standard rand0 of Lewis, Goodman, and Miller.
*/
typedef linear_congruential_engine<uint_fast32_t, 16807UL, 0UL, 2147483647UL>
minstd_rand0;
/**
* An alternative LCR (Lehmer Generator function).
*/
typedef linear_congruential_engine<uint_fast32_t, 48271UL, 0UL, 2147483647UL>
minstd_rand;
/**
* The classic Mersenne Twister.
*
* Reference:
* M. Matsumoto and T. Nishimura, Mersenne Twister: A 623-Dimensionally
* Equidistributed Uniform Pseudo-Random Number Generator, ACM Transactions
* on Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30.
*/
typedef mersenne_twister_engine<
uint_fast32_t,
32, 624, 397, 31,
0x9908b0dfUL, 11,
0xffffffffUL, 7,
0x9d2c5680UL, 15,
0xefc60000UL, 18, 1812433253UL> mt19937;
/**
* An alternative Mersenne Twister.
*/
typedef mersenne_twister_engine<
uint_fast64_t,
64, 312, 156, 31,
0xb5026f5aa96619e9ULL, 29,
0x5555555555555555ULL, 17,
0x71d67fffeda60000ULL, 37,
0xfff7eee000000000ULL, 43,
6364136223846793005ULL> mt19937_64;
typedef subtract_with_carry_engine<uint_fast32_t, 24, 10, 24>
ranlux24_base;
typedef subtract_with_carry_engine<uint_fast64_t, 48, 5, 12>
ranlux48_base;
typedef discard_block_engine<ranlux24_base, 223, 23> ranlux24;
typedef discard_block_engine<ranlux48_base, 389, 11> ranlux48;
typedef shuffle_order_engine<minstd_rand0, 256> knuth_b;
typedef minstd_rand0 default_random_engine;
/**
* A standard interface to a platform-specific non-deterministic
* random number generator (if any are available).
*/
class random_device
{
public:
/** The type of the generated random value. */
typedef unsigned int result_type;
// constructors, destructors and member functions
#ifdef _GLIBCXX_USE_RANDOM_TR1
explicit
random_device(const std::string& __token = "default")
{
_M_init(__token);
}
~random_device()
{ _M_fini(); }
#else
explicit
random_device(const std::string& __token = "mt19937")
{ _M_init_pretr1(__token); }
public:
#endif
static constexpr result_type
min()
{ return std::numeric_limits<result_type>::min(); }
static constexpr result_type
max()
{ return std::numeric_limits<result_type>::max(); }
double
entropy() const noexcept
{ return 0.0; }
result_type
operator()()
{
#ifdef _GLIBCXX_USE_RANDOM_TR1
return this->_M_getval();
#else
return this->_M_getval_pretr1();
#endif
}
// No copy functions.
random_device(const random_device&) = delete;
void operator=(const random_device&) = delete;
private:
void _M_init(const std::string& __token);
void _M_init_pretr1(const std::string& __token);
void _M_fini();
result_type _M_getval();
result_type _M_getval_pretr1();
union
{
void* _M_file;
mt19937 _M_mt;
};
};
/* @} */ // group random_generators
/**
* @addtogroup random_distributions Random Number Distributions
* @ingroup random
* @{
*/
/**
* @addtogroup random_distributions_uniform Uniform Distributions
* @ingroup random_distributions
* @{
*/
// std::uniform_int_distribution is defined in <bits/uniform_int_dist.h>
/**
* @brief Return true if two uniform integer distributions have
* different parameters.
*/
template<typename _IntType>
inline bool
operator!=(const std::uniform_int_distribution<_IntType>& __d1,
const std::uniform_int_distribution<_IntType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief Inserts a %uniform_int_distribution random number
* distribution @p __x into the output stream @p os.
*
* @param __os An output stream.
* @param __x A %uniform_int_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _IntType, typename _CharT, typename _Traits>
std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>&,
const std::uniform_int_distribution<_IntType>&);
/**
* @brief Extracts a %uniform_int_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %uniform_int_distribution random number generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _IntType, typename _CharT, typename _Traits>
std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>&,
std::uniform_int_distribution<_IntType>&);
/**
* @brief Uniform continuous distribution for random numbers.
*
* A continuous random distribution on the range [min, max) with equal
* probability throughout the range. The URNG should be real-valued and
* deliver number in the range [0, 1).
*/
template<typename _RealType = double>
class uniform_real_distribution
{
static_assert(std::is_floating_point<_RealType>::value,
"result_type must be a floating point type");
public:
/** The type of the range of the distribution. */
typedef _RealType result_type;
/** Parameter type. */
struct param_type
{
typedef uniform_real_distribution<_RealType> distribution_type;
explicit
param_type(_RealType __a = _RealType(0),
_RealType __b = _RealType(1))
: _M_a(__a), _M_b(__b)
{
__glibcxx_assert(_M_a <= _M_b);
}
result_type
a() const
{ return _M_a; }
result_type
b() const
{ return _M_b; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
_RealType _M_a;
_RealType _M_b;
};
public:
/**
* @brief Constructs a uniform_real_distribution object.
*
* @param __a [IN] The lower bound of the distribution.
* @param __b [IN] The upper bound of the distribution.
*/
explicit
uniform_real_distribution(_RealType __a = _RealType(0),
_RealType __b = _RealType(1))
: _M_param(__a, __b)
{ }
explicit
uniform_real_distribution(const param_type& __p)
: _M_param(__p)
{ }
/**
* @brief Resets the distribution state.
*
* Does nothing for the uniform real distribution.
*/
void
reset() { }
result_type
a() const
{ return _M_param.a(); }
result_type
b() const
{ return _M_param.b(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the inclusive lower bound of the distribution range.
*/
result_type
min() const
{ return this->a(); }
/**
* @brief Returns the inclusive upper bound of the distribution range.
*/
result_type
max() const
{ return this->b(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{
__detail::_Adaptor<_UniformRandomNumberGenerator, result_type>
__aurng(__urng);
return (__aurng() * (__p.b() - __p.a())) + __p.a();
}
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two uniform real distributions have
* the same parameters.
*/
friend bool
operator==(const uniform_real_distribution& __d1,
const uniform_real_distribution& __d2)
{ return __d1._M_param == __d2._M_param; }
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
};
/**
* @brief Return true if two uniform real distributions have
* different parameters.
*/
template<typename _IntType>
inline bool
operator!=(const std::uniform_real_distribution<_IntType>& __d1,
const std::uniform_real_distribution<_IntType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief Inserts a %uniform_real_distribution random number
* distribution @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %uniform_real_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RealType, typename _CharT, typename _Traits>
std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>&,
const std::uniform_real_distribution<_RealType>&);
/**
* @brief Extracts a %uniform_real_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %uniform_real_distribution random number generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _RealType, typename _CharT, typename _Traits>
std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>&,
std::uniform_real_distribution<_RealType>&);
/* @} */ // group random_distributions_uniform
/**
* @addtogroup random_distributions_normal Normal Distributions
* @ingroup random_distributions
* @{
*/
/**
* @brief A normal continuous distribution for random numbers.
*
* The formula for the normal probability density function is
* @f[
* p(x|\mu,\sigma) = \frac{1}{\sigma \sqrt{2 \pi}}
* e^{- \frac{{x - \mu}^ {2}}{2 \sigma ^ {2}} }
* @f]
*/
template<typename _RealType = double>
class normal_distribution
{
static_assert(std::is_floating_point<_RealType>::value,
"result_type must be a floating point type");
public:
/** The type of the range of the distribution. */
typedef _RealType result_type;
/** Parameter type. */
struct param_type
{
typedef normal_distribution<_RealType> distribution_type;
explicit
param_type(_RealType __mean = _RealType(0),
_RealType __stddev = _RealType(1))
: _M_mean(__mean), _M_stddev(__stddev)
{
__glibcxx_assert(_M_stddev > _RealType(0));
}
_RealType
mean() const
{ return _M_mean; }
_RealType
stddev() const
{ return _M_stddev; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return (__p1._M_mean == __p2._M_mean
&& __p1._M_stddev == __p2._M_stddev); }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
_RealType _M_mean;
_RealType _M_stddev;
};
public:
/**
* Constructs a normal distribution with parameters @f$mean@f$ and
* standard deviation.
*/
explicit
normal_distribution(result_type __mean = result_type(0),
result_type __stddev = result_type(1))
: _M_param(__mean, __stddev), _M_saved_available(false)
{ }
explicit
normal_distribution(const param_type& __p)
: _M_param(__p), _M_saved_available(false)
{ }
/**
* @brief Resets the distribution state.
*/
void
reset()
{ _M_saved_available = false; }
/**
* @brief Returns the mean of the distribution.
*/
_RealType
mean() const
{ return _M_param.mean(); }
/**
* @brief Returns the standard deviation of the distribution.
*/
_RealType
stddev() const
{ return _M_param.stddev(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return std::numeric_limits<result_type>::lowest(); }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two normal distributions have
* the same parameters and the sequences that would
* be generated are equal.
*/
template<typename _RealType1>
friend bool
operator==(const std::normal_distribution<_RealType1>& __d1,
const std::normal_distribution<_RealType1>& __d2);
/**
* @brief Inserts a %normal_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %normal_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::normal_distribution<_RealType1>& __x);
/**
* @brief Extracts a %normal_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %normal_distribution random number generator engine.
*
* @returns The input stream with @p __x extracted or in an error
* state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::normal_distribution<_RealType1>& __x);
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
result_type _M_saved;
bool _M_saved_available;
};
/**
* @brief Return true if two normal distributions are different.
*/
template<typename _RealType>
inline bool
operator!=(const std::normal_distribution<_RealType>& __d1,
const std::normal_distribution<_RealType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief A lognormal_distribution random number distribution.
*
* The formula for the normal probability mass function is
* @f[
* p(x|m,s) = \frac{1}{sx\sqrt{2\pi}}
* \exp{-\frac{(\ln{x} - m)^2}{2s^2}}
* @f]
*/
template<typename _RealType = double>
class lognormal_distribution
{
static_assert(std::is_floating_point<_RealType>::value,
"result_type must be a floating point type");
public:
/** The type of the range of the distribution. */
typedef _RealType result_type;
/** Parameter type. */
struct param_type
{
typedef lognormal_distribution<_RealType> distribution_type;
explicit
param_type(_RealType __m = _RealType(0),
_RealType __s = _RealType(1))
: _M_m(__m), _M_s(__s)
{ }
_RealType
m() const
{ return _M_m; }
_RealType
s() const
{ return _M_s; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_m == __p2._M_m && __p1._M_s == __p2._M_s; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
_RealType _M_m;
_RealType _M_s;
};
explicit
lognormal_distribution(_RealType __m = _RealType(0),
_RealType __s = _RealType(1))
: _M_param(__m, __s), _M_nd()
{ }
explicit
lognormal_distribution(const param_type& __p)
: _M_param(__p), _M_nd()
{ }
/**
* Resets the distribution state.
*/
void
reset()
{ _M_nd.reset(); }
/**
*
*/
_RealType
m() const
{ return _M_param.m(); }
_RealType
s() const
{ return _M_param.s(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return result_type(0); }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ return std::exp(__p.s() * _M_nd(__urng) + __p.m()); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two lognormal distributions have
* the same parameters and the sequences that would
* be generated are equal.
*/
friend bool
operator==(const lognormal_distribution& __d1,
const lognormal_distribution& __d2)
{ return (__d1._M_param == __d2._M_param
&& __d1._M_nd == __d2._M_nd); }
/**
* @brief Inserts a %lognormal_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %lognormal_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::lognormal_distribution<_RealType1>& __x);
/**
* @brief Extracts a %lognormal_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %lognormal_distribution random number
* generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::lognormal_distribution<_RealType1>& __x);
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
std::normal_distribution<result_type> _M_nd;
};
/**
* @brief Return true if two lognormal distributions are different.
*/
template<typename _RealType>
inline bool
operator!=(const std::lognormal_distribution<_RealType>& __d1,
const std::lognormal_distribution<_RealType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief A gamma continuous distribution for random numbers.
*
* The formula for the gamma probability density function is:
* @f[
* p(x|\alpha,\beta) = \frac{1}{\beta\Gamma(\alpha)}
* (x/\beta)^{\alpha - 1} e^{-x/\beta}
* @f]
*/
template<typename _RealType = double>
class gamma_distribution
{
static_assert(std::is_floating_point<_RealType>::value,
"result_type must be a floating point type");
public:
/** The type of the range of the distribution. */
typedef _RealType result_type;
/** Parameter type. */
struct param_type
{
typedef gamma_distribution<_RealType> distribution_type;
friend class gamma_distribution<_RealType>;
explicit
param_type(_RealType __alpha_val = _RealType(1),
_RealType __beta_val = _RealType(1))
: _M_alpha(__alpha_val), _M_beta(__beta_val)
{
__glibcxx_assert(_M_alpha > _RealType(0));
_M_initialize();
}
_RealType
alpha() const
{ return _M_alpha; }
_RealType
beta() const
{ return _M_beta; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return (__p1._M_alpha == __p2._M_alpha
&& __p1._M_beta == __p2._M_beta); }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
void
_M_initialize();
_RealType _M_alpha;
_RealType _M_beta;
_RealType _M_malpha, _M_a2;
};
public:
/**
* @brief Constructs a gamma distribution with parameters
* @f$\alpha@f$ and @f$\beta@f$.
*/
explicit
gamma_distribution(_RealType __alpha_val = _RealType(1),
_RealType __beta_val = _RealType(1))
: _M_param(__alpha_val, __beta_val), _M_nd()
{ }
explicit
gamma_distribution(const param_type& __p)
: _M_param(__p), _M_nd()
{ }
/**
* @brief Resets the distribution state.
*/
void
reset()
{ _M_nd.reset(); }
/**
* @brief Returns the @f$\alpha@f$ of the distribution.
*/
_RealType
alpha() const
{ return _M_param.alpha(); }
/**
* @brief Returns the @f$\beta@f$ of the distribution.
*/
_RealType
beta() const
{ return _M_param.beta(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return result_type(0); }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two gamma distributions have the same
* parameters and the sequences that would be generated
* are equal.
*/
friend bool
operator==(const gamma_distribution& __d1,
const gamma_distribution& __d2)
{ return (__d1._M_param == __d2._M_param
&& __d1._M_nd == __d2._M_nd); }
/**
* @brief Inserts a %gamma_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %gamma_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::gamma_distribution<_RealType1>& __x);
/**
* @brief Extracts a %gamma_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %gamma_distribution random number generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::gamma_distribution<_RealType1>& __x);
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
std::normal_distribution<result_type> _M_nd;
};
/**
* @brief Return true if two gamma distributions are different.
*/
template<typename _RealType>
inline bool
operator!=(const std::gamma_distribution<_RealType>& __d1,
const std::gamma_distribution<_RealType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief A chi_squared_distribution random number distribution.
*
* The formula for the normal probability mass function is
* @f$p(x|n) = \frac{x^{(n/2) - 1}e^{-x/2}}{\Gamma(n/2) 2^{n/2}}@f$
*/
template<typename _RealType = double>
class chi_squared_distribution
{
static_assert(std::is_floating_point<_RealType>::value,
"result_type must be a floating point type");
public:
/** The type of the range of the distribution. */
typedef _RealType result_type;
/** Parameter type. */
struct param_type
{
typedef chi_squared_distribution<_RealType> distribution_type;
explicit
param_type(_RealType __n = _RealType(1))
: _M_n(__n)
{ }
_RealType
n() const
{ return _M_n; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_n == __p2._M_n; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
_RealType _M_n;
};
explicit
chi_squared_distribution(_RealType __n = _RealType(1))
: _M_param(__n), _M_gd(__n / 2)
{ }
explicit
chi_squared_distribution(const param_type& __p)
: _M_param(__p), _M_gd(__p.n() / 2)
{ }
/**
* @brief Resets the distribution state.
*/
void
reset()
{ _M_gd.reset(); }
/**
*
*/
_RealType
n() const
{ return _M_param.n(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{
_M_param = __param;
typedef typename std::gamma_distribution<result_type>::param_type
param_type;
_M_gd.param(param_type{__param.n() / 2});
}
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return result_type(0); }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return 2 * _M_gd(__urng); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{
typedef typename std::gamma_distribution<result_type>::param_type
param_type;
return 2 * _M_gd(__urng, param_type(__p.n() / 2));
}
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate_impl(__f, __t, __urng); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ typename std::gamma_distribution<result_type>::param_type
__p2(__p.n() / 2);
this->__generate_impl(__f, __t, __urng, __p2); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate_impl(__f, __t, __urng); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ typename std::gamma_distribution<result_type>::param_type
__p2(__p.n() / 2);
this->__generate_impl(__f, __t, __urng, __p2); }
/**
* @brief Return true if two Chi-squared distributions have
* the same parameters and the sequences that would be
* generated are equal.
*/
friend bool
operator==(const chi_squared_distribution& __d1,
const chi_squared_distribution& __d2)
{ return __d1._M_param == __d2._M_param && __d1._M_gd == __d2._M_gd; }
/**
* @brief Inserts a %chi_squared_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %chi_squared_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::chi_squared_distribution<_RealType1>& __x);
/**
* @brief Extracts a %chi_squared_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %chi_squared_distribution random number
* generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::chi_squared_distribution<_RealType1>& __x);
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const typename
std::gamma_distribution<result_type>::param_type& __p);
param_type _M_param;
std::gamma_distribution<result_type> _M_gd;
};
/**
* @brief Return true if two Chi-squared distributions are different.
*/
template<typename _RealType>
inline bool
operator!=(const std::chi_squared_distribution<_RealType>& __d1,
const std::chi_squared_distribution<_RealType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief A cauchy_distribution random number distribution.
*
* The formula for the normal probability mass function is
* @f$p(x|a,b) = (\pi b (1 + (\frac{x-a}{b})^2))^{-1}@f$
*/
template<typename _RealType = double>
class cauchy_distribution
{
static_assert(std::is_floating_point<_RealType>::value,
"result_type must be a floating point type");
public:
/** The type of the range of the distribution. */
typedef _RealType result_type;
/** Parameter type. */
struct param_type
{
typedef cauchy_distribution<_RealType> distribution_type;
explicit
param_type(_RealType __a = _RealType(0),
_RealType __b = _RealType(1))
: _M_a(__a), _M_b(__b)
{ }
_RealType
a() const
{ return _M_a; }
_RealType
b() const
{ return _M_b; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
_RealType _M_a;
_RealType _M_b;
};
explicit
cauchy_distribution(_RealType __a = _RealType(0),
_RealType __b = _RealType(1))
: _M_param(__a, __b)
{ }
explicit
cauchy_distribution(const param_type& __p)
: _M_param(__p)
{ }
/**
* @brief Resets the distribution state.
*/
void
reset()
{ }
/**
*
*/
_RealType
a() const
{ return _M_param.a(); }
_RealType
b() const
{ return _M_param.b(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return std::numeric_limits<result_type>::lowest(); }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two Cauchy distributions have
* the same parameters.
*/
friend bool
operator==(const cauchy_distribution& __d1,
const cauchy_distribution& __d2)
{ return __d1._M_param == __d2._M_param; }
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
};
/**
* @brief Return true if two Cauchy distributions have
* different parameters.
*/
template<typename _RealType>
inline bool
operator!=(const std::cauchy_distribution<_RealType>& __d1,
const std::cauchy_distribution<_RealType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief Inserts a %cauchy_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %cauchy_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RealType, typename _CharT, typename _Traits>
std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::cauchy_distribution<_RealType>& __x);
/**
* @brief Extracts a %cauchy_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %cauchy_distribution random number
* generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _RealType, typename _CharT, typename _Traits>
std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::cauchy_distribution<_RealType>& __x);
/**
* @brief A fisher_f_distribution random number distribution.
*
* The formula for the normal probability mass function is
* @f[
* p(x|m,n) = \frac{\Gamma((m+n)/2)}{\Gamma(m/2)\Gamma(n/2)}
* (\frac{m}{n})^{m/2} x^{(m/2)-1}
* (1 + \frac{mx}{n})^{-(m+n)/2}
* @f]
*/
template<typename _RealType = double>
class fisher_f_distribution
{
static_assert(std::is_floating_point<_RealType>::value,
"result_type must be a floating point type");
public:
/** The type of the range of the distribution. */
typedef _RealType result_type;
/** Parameter type. */
struct param_type
{
typedef fisher_f_distribution<_RealType> distribution_type;
explicit
param_type(_RealType __m = _RealType(1),
_RealType __n = _RealType(1))
: _M_m(__m), _M_n(__n)
{ }
_RealType
m() const
{ return _M_m; }
_RealType
n() const
{ return _M_n; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_m == __p2._M_m && __p1._M_n == __p2._M_n; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
_RealType _M_m;
_RealType _M_n;
};
explicit
fisher_f_distribution(_RealType __m = _RealType(1),
_RealType __n = _RealType(1))
: _M_param(__m, __n), _M_gd_x(__m / 2), _M_gd_y(__n / 2)
{ }
explicit
fisher_f_distribution(const param_type& __p)
: _M_param(__p), _M_gd_x(__p.m() / 2), _M_gd_y(__p.n() / 2)
{ }
/**
* @brief Resets the distribution state.
*/
void
reset()
{
_M_gd_x.reset();
_M_gd_y.reset();
}
/**
*
*/
_RealType
m() const
{ return _M_param.m(); }
_RealType
n() const
{ return _M_param.n(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return result_type(0); }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return (_M_gd_x(__urng) * n()) / (_M_gd_y(__urng) * m()); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{
typedef typename std::gamma_distribution<result_type>::param_type
param_type;
return ((_M_gd_x(__urng, param_type(__p.m() / 2)) * n())
/ (_M_gd_y(__urng, param_type(__p.n() / 2)) * m()));
}
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate_impl(__f, __t, __urng); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate_impl(__f, __t, __urng); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two Fisher f distributions have
* the same parameters and the sequences that would
* be generated are equal.
*/
friend bool
operator==(const fisher_f_distribution& __d1,
const fisher_f_distribution& __d2)
{ return (__d1._M_param == __d2._M_param
&& __d1._M_gd_x == __d2._M_gd_x
&& __d1._M_gd_y == __d2._M_gd_y); }
/**
* @brief Inserts a %fisher_f_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %fisher_f_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::fisher_f_distribution<_RealType1>& __x);
/**
* @brief Extracts a %fisher_f_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %fisher_f_distribution random number
* generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::fisher_f_distribution<_RealType1>& __x);
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
std::gamma_distribution<result_type> _M_gd_x, _M_gd_y;
};
/**
* @brief Return true if two Fisher f distributions are different.
*/
template<typename _RealType>
inline bool
operator!=(const std::fisher_f_distribution<_RealType>& __d1,
const std::fisher_f_distribution<_RealType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief A student_t_distribution random number distribution.
*
* The formula for the normal probability mass function is:
* @f[
* p(x|n) = \frac{1}{\sqrt(n\pi)} \frac{\Gamma((n+1)/2)}{\Gamma(n/2)}
* (1 + \frac{x^2}{n}) ^{-(n+1)/2}
* @f]
*/
template<typename _RealType = double>
class student_t_distribution
{
static_assert(std::is_floating_point<_RealType>::value,
"result_type must be a floating point type");
public:
/** The type of the range of the distribution. */
typedef _RealType result_type;
/** Parameter type. */
struct param_type
{
typedef student_t_distribution<_RealType> distribution_type;
explicit
param_type(_RealType __n = _RealType(1))
: _M_n(__n)
{ }
_RealType
n() const
{ return _M_n; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_n == __p2._M_n; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
_RealType _M_n;
};
explicit
student_t_distribution(_RealType __n = _RealType(1))
: _M_param(__n), _M_nd(), _M_gd(__n / 2, 2)
{ }
explicit
student_t_distribution(const param_type& __p)
: _M_param(__p), _M_nd(), _M_gd(__p.n() / 2, 2)
{ }
/**
* @brief Resets the distribution state.
*/
void
reset()
{
_M_nd.reset();
_M_gd.reset();
}
/**
*
*/
_RealType
n() const
{ return _M_param.n(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return std::numeric_limits<result_type>::lowest(); }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return _M_nd(__urng) * std::sqrt(n() / _M_gd(__urng)); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{
typedef typename std::gamma_distribution<result_type>::param_type
param_type;
const result_type __g = _M_gd(__urng, param_type(__p.n() / 2, 2));
return _M_nd(__urng) * std::sqrt(__p.n() / __g);
}
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate_impl(__f, __t, __urng); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate_impl(__f, __t, __urng); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two Student t distributions have
* the same parameters and the sequences that would
* be generated are equal.
*/
friend bool
operator==(const student_t_distribution& __d1,
const student_t_distribution& __d2)
{ return (__d1._M_param == __d2._M_param
&& __d1._M_nd == __d2._M_nd && __d1._M_gd == __d2._M_gd); }
/**
* @brief Inserts a %student_t_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %student_t_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::student_t_distribution<_RealType1>& __x);
/**
* @brief Extracts a %student_t_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %student_t_distribution random number
* generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::student_t_distribution<_RealType1>& __x);
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
std::normal_distribution<result_type> _M_nd;
std::gamma_distribution<result_type> _M_gd;
};
/**
* @brief Return true if two Student t distributions are different.
*/
template<typename _RealType>
inline bool
operator!=(const std::student_t_distribution<_RealType>& __d1,
const std::student_t_distribution<_RealType>& __d2)
{ return !(__d1 == __d2); }
/* @} */ // group random_distributions_normal
/**
* @addtogroup random_distributions_bernoulli Bernoulli Distributions
* @ingroup random_distributions
* @{
*/
/**
* @brief A Bernoulli random number distribution.
*
* Generates a sequence of true and false values with likelihood @f$p@f$
* that true will come up and @f$(1 - p)@f$ that false will appear.
*/
class bernoulli_distribution
{
public:
/** The type of the range of the distribution. */
typedef bool result_type;
/** Parameter type. */
struct param_type
{
typedef bernoulli_distribution distribution_type;
explicit
param_type(double __p = 0.5)
: _M_p(__p)
{
__glibcxx_assert((_M_p >= 0.0) && (_M_p <= 1.0));
}
double
p() const
{ return _M_p; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_p == __p2._M_p; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
double _M_p;
};
public:
/**
* @brief Constructs a Bernoulli distribution with likelihood @p p.
*
* @param __p [IN] The likelihood of a true result being returned.
* Must be in the interval @f$[0, 1]@f$.
*/
explicit
bernoulli_distribution(double __p = 0.5)
: _M_param(__p)
{ }
explicit
bernoulli_distribution(const param_type& __p)
: _M_param(__p)
{ }
/**
* @brief Resets the distribution state.
*
* Does nothing for a Bernoulli distribution.
*/
void
reset() { }
/**
* @brief Returns the @p p parameter of the distribution.
*/
double
p() const
{ return _M_param.p(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return std::numeric_limits<result_type>::min(); }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{
__detail::_Adaptor<_UniformRandomNumberGenerator, double>
__aurng(__urng);
if ((__aurng() - __aurng.min())
< __p.p() * (__aurng.max() - __aurng.min()))
return true;
return false;
}
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng, const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two Bernoulli distributions have
* the same parameters.
*/
friend bool
operator==(const bernoulli_distribution& __d1,
const bernoulli_distribution& __d2)
{ return __d1._M_param == __d2._M_param; }
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
};
/**
* @brief Return true if two Bernoulli distributions have
* different parameters.
*/
inline bool
operator!=(const std::bernoulli_distribution& __d1,
const std::bernoulli_distribution& __d2)
{ return !(__d1 == __d2); }
/**
* @brief Inserts a %bernoulli_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %bernoulli_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _CharT, typename _Traits>
std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::bernoulli_distribution& __x);
/**
* @brief Extracts a %bernoulli_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %bernoulli_distribution random number generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _CharT, typename _Traits>
std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::bernoulli_distribution& __x)
{
double __p;
__is >> __p;
__x.param(bernoulli_distribution::param_type(__p));
return __is;
}
/**
* @brief A discrete binomial random number distribution.
*
* The formula for the binomial probability density function is
* @f$p(i|t,p) = \binom{t}{i} p^i (1 - p)^{t - i}@f$ where @f$t@f$
* and @f$p@f$ are the parameters of the distribution.
*/
template<typename _IntType = int>
class binomial_distribution
{
static_assert(std::is_integral<_IntType>::value,
"result_type must be an integral type");
public:
/** The type of the range of the distribution. */
typedef _IntType result_type;
/** Parameter type. */
struct param_type
{
typedef binomial_distribution<_IntType> distribution_type;
friend class binomial_distribution<_IntType>;
explicit
param_type(_IntType __t = _IntType(1), double __p = 0.5)
: _M_t(__t), _M_p(__p)
{
__glibcxx_assert((_M_t >= _IntType(0))
&& (_M_p >= 0.0)
&& (_M_p <= 1.0));
_M_initialize();
}
_IntType
t() const
{ return _M_t; }
double
p() const
{ return _M_p; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_t == __p2._M_t && __p1._M_p == __p2._M_p; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
void
_M_initialize();
_IntType _M_t;
double _M_p;
double _M_q;
#if _GLIBCXX_USE_C99_MATH_TR1
double _M_d1, _M_d2, _M_s1, _M_s2, _M_c,
_M_a1, _M_a123, _M_s, _M_lf, _M_lp1p;
#endif
bool _M_easy;
};
// constructors and member function
explicit
binomial_distribution(_IntType __t = _IntType(1),
double __p = 0.5)
: _M_param(__t, __p), _M_nd()
{ }
explicit
binomial_distribution(const param_type& __p)
: _M_param(__p), _M_nd()
{ }
/**
* @brief Resets the distribution state.
*/
void
reset()
{ _M_nd.reset(); }
/**
* @brief Returns the distribution @p t parameter.
*/
_IntType
t() const
{ return _M_param.t(); }
/**
* @brief Returns the distribution @p p parameter.
*/
double
p() const
{ return _M_param.p(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return 0; }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return _M_param.t(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two binomial distributions have
* the same parameters and the sequences that would
* be generated are equal.
*/
friend bool
operator==(const binomial_distribution& __d1,
const binomial_distribution& __d2)
#ifdef _GLIBCXX_USE_C99_MATH_TR1
{ return __d1._M_param == __d2._M_param && __d1._M_nd == __d2._M_nd; }
#else
{ return __d1._M_param == __d2._M_param; }
#endif
/**
* @brief Inserts a %binomial_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %binomial_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _IntType1,
typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::binomial_distribution<_IntType1>& __x);
/**
* @brief Extracts a %binomial_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %binomial_distribution random number generator engine.
*
* @returns The input stream with @p __x extracted or in an error
* state.
*/
template<typename _IntType1,
typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::binomial_distribution<_IntType1>& __x);
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
template<typename _UniformRandomNumberGenerator>
result_type
_M_waiting(_UniformRandomNumberGenerator& __urng,
_IntType __t, double __q);
param_type _M_param;
// NB: Unused when _GLIBCXX_USE_C99_MATH_TR1 is undefined.
std::normal_distribution<double> _M_nd;
};
/**
* @brief Return true if two binomial distributions are different.
*/
template<typename _IntType>
inline bool
operator!=(const std::binomial_distribution<_IntType>& __d1,
const std::binomial_distribution<_IntType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief A discrete geometric random number distribution.
*
* The formula for the geometric probability density function is
* @f$p(i|p) = p(1 - p)^{i}@f$ where @f$p@f$ is the parameter of the
* distribution.
*/
template<typename _IntType = int>
class geometric_distribution
{
static_assert(std::is_integral<_IntType>::value,
"result_type must be an integral type");
public:
/** The type of the range of the distribution. */
typedef _IntType result_type;
/** Parameter type. */
struct param_type
{
typedef geometric_distribution<_IntType> distribution_type;
friend class geometric_distribution<_IntType>;
explicit
param_type(double __p = 0.5)
: _M_p(__p)
{
__glibcxx_assert((_M_p > 0.0) && (_M_p < 1.0));
_M_initialize();
}
double
p() const
{ return _M_p; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_p == __p2._M_p; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
void
_M_initialize()
{ _M_log_1_p = std::log(1.0 - _M_p); }
double _M_p;
double _M_log_1_p;
};
// constructors and member function
explicit
geometric_distribution(double __p = 0.5)
: _M_param(__p)
{ }
explicit
geometric_distribution(const param_type& __p)
: _M_param(__p)
{ }
/**
* @brief Resets the distribution state.
*
* Does nothing for the geometric distribution.
*/
void
reset() { }
/**
* @brief Returns the distribution parameter @p p.
*/
double
p() const
{ return _M_param.p(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return 0; }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two geometric distributions have
* the same parameters.
*/
friend bool
operator==(const geometric_distribution& __d1,
const geometric_distribution& __d2)
{ return __d1._M_param == __d2._M_param; }
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
};
/**
* @brief Return true if two geometric distributions have
* different parameters.
*/
template<typename _IntType>
inline bool
operator!=(const std::geometric_distribution<_IntType>& __d1,
const std::geometric_distribution<_IntType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief Inserts a %geometric_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %geometric_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _IntType,
typename _CharT, typename _Traits>
std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::geometric_distribution<_IntType>& __x);
/**
* @brief Extracts a %geometric_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %geometric_distribution random number generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _IntType,
typename _CharT, typename _Traits>
std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::geometric_distribution<_IntType>& __x);
/**
* @brief A negative_binomial_distribution random number distribution.
*
* The formula for the negative binomial probability mass function is
* @f$p(i) = \binom{n}{i} p^i (1 - p)^{t - i}@f$ where @f$t@f$
* and @f$p@f$ are the parameters of the distribution.
*/
template<typename _IntType = int>
class negative_binomial_distribution
{
static_assert(std::is_integral<_IntType>::value,
"result_type must be an integral type");
public:
/** The type of the range of the distribution. */
typedef _IntType result_type;
/** Parameter type. */
struct param_type
{
typedef negative_binomial_distribution<_IntType> distribution_type;
explicit
param_type(_IntType __k = 1, double __p = 0.5)
: _M_k(__k), _M_p(__p)
{
__glibcxx_assert((_M_k > 0) && (_M_p > 0.0) && (_M_p <= 1.0));
}
_IntType
k() const
{ return _M_k; }
double
p() const
{ return _M_p; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_k == __p2._M_k && __p1._M_p == __p2._M_p; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
_IntType _M_k;
double _M_p;
};
explicit
negative_binomial_distribution(_IntType __k = 1, double __p = 0.5)
: _M_param(__k, __p), _M_gd(__k, (1.0 - __p) / __p)
{ }
explicit
negative_binomial_distribution(const param_type& __p)
: _M_param(__p), _M_gd(__p.k(), (1.0 - __p.p()) / __p.p())
{ }
/**
* @brief Resets the distribution state.
*/
void
reset()
{ _M_gd.reset(); }
/**
* @brief Return the @f$k@f$ parameter of the distribution.
*/
_IntType
k() const
{ return _M_param.k(); }
/**
* @brief Return the @f$p@f$ parameter of the distribution.
*/
double
p() const
{ return _M_param.p(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return result_type(0); }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng);
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate_impl(__f, __t, __urng); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate_impl(__f, __t, __urng); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two negative binomial distributions have
* the same parameters and the sequences that would be
* generated are equal.
*/
friend bool
operator==(const negative_binomial_distribution& __d1,
const negative_binomial_distribution& __d2)
{ return __d1._M_param == __d2._M_param && __d1._M_gd == __d2._M_gd; }
/**
* @brief Inserts a %negative_binomial_distribution random
* number distribution @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %negative_binomial_distribution random number
* distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _IntType1, typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::negative_binomial_distribution<_IntType1>& __x);
/**
* @brief Extracts a %negative_binomial_distribution random number
* distribution @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %negative_binomial_distribution random number
* generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _IntType1, typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::negative_binomial_distribution<_IntType1>& __x);
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
std::gamma_distribution<double> _M_gd;
};
/**
* @brief Return true if two negative binomial distributions are different.
*/
template<typename _IntType>
inline bool
operator!=(const std::negative_binomial_distribution<_IntType>& __d1,
const std::negative_binomial_distribution<_IntType>& __d2)
{ return !(__d1 == __d2); }
/* @} */ // group random_distributions_bernoulli
/**
* @addtogroup random_distributions_poisson Poisson Distributions
* @ingroup random_distributions
* @{
*/
/**
* @brief A discrete Poisson random number distribution.
*
* The formula for the Poisson probability density function is
* @f$p(i|\mu) = \frac{\mu^i}{i!} e^{-\mu}@f$ where @f$\mu@f$ is the
* parameter of the distribution.
*/
template<typename _IntType = int>
class poisson_distribution
{
static_assert(std::is_integral<_IntType>::value,
"result_type must be an integral type");
public:
/** The type of the range of the distribution. */
typedef _IntType result_type;
/** Parameter type. */
struct param_type
{
typedef poisson_distribution<_IntType> distribution_type;
friend class poisson_distribution<_IntType>;
explicit
param_type(double __mean = 1.0)
: _M_mean(__mean)
{
__glibcxx_assert(_M_mean > 0.0);
_M_initialize();
}
double
mean() const
{ return _M_mean; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_mean == __p2._M_mean; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
// Hosts either log(mean) or the threshold of the simple method.
void
_M_initialize();
double _M_mean;
double _M_lm_thr;
#if _GLIBCXX_USE_C99_MATH_TR1
double _M_lfm, _M_sm, _M_d, _M_scx, _M_1cx, _M_c2b, _M_cb;
#endif
};
// constructors and member function
explicit
poisson_distribution(double __mean = 1.0)
: _M_param(__mean), _M_nd()
{ }
explicit
poisson_distribution(const param_type& __p)
: _M_param(__p), _M_nd()
{ }
/**
* @brief Resets the distribution state.
*/
void
reset()
{ _M_nd.reset(); }
/**
* @brief Returns the distribution parameter @p mean.
*/
double
mean() const
{ return _M_param.mean(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return 0; }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two Poisson distributions have the same
* parameters and the sequences that would be generated
* are equal.
*/
friend bool
operator==(const poisson_distribution& __d1,
const poisson_distribution& __d2)
#ifdef _GLIBCXX_USE_C99_MATH_TR1
{ return __d1._M_param == __d2._M_param && __d1._M_nd == __d2._M_nd; }
#else
{ return __d1._M_param == __d2._M_param; }
#endif
/**
* @brief Inserts a %poisson_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %poisson_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _IntType1, typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::poisson_distribution<_IntType1>& __x);
/**
* @brief Extracts a %poisson_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %poisson_distribution random number generator engine.
*
* @returns The input stream with @p __x extracted or in an error
* state.
*/
template<typename _IntType1, typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::poisson_distribution<_IntType1>& __x);
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
// NB: Unused when _GLIBCXX_USE_C99_MATH_TR1 is undefined.
std::normal_distribution<double> _M_nd;
};
/**
* @brief Return true if two Poisson distributions are different.
*/
template<typename _IntType>
inline bool
operator!=(const std::poisson_distribution<_IntType>& __d1,
const std::poisson_distribution<_IntType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief An exponential continuous distribution for random numbers.
*
* The formula for the exponential probability density function is
* @f$p(x|\lambda) = \lambda e^{-\lambda x}@f$.
*
* <table border=1 cellpadding=10 cellspacing=0>
* <caption align=top>Distribution Statistics</caption>
* <tr><td>Mean</td><td>@f$\frac{1}{\lambda}@f$</td></tr>
* <tr><td>Median</td><td>@f$\frac{\ln 2}{\lambda}@f$</td></tr>
* <tr><td>Mode</td><td>@f$zero@f$</td></tr>
* <tr><td>Range</td><td>@f$[0, \infty]@f$</td></tr>
* <tr><td>Standard Deviation</td><td>@f$\frac{1}{\lambda}@f$</td></tr>
* </table>
*/
template<typename _RealType = double>
class exponential_distribution
{
static_assert(std::is_floating_point<_RealType>::value,
"result_type must be a floating point type");
public:
/** The type of the range of the distribution. */
typedef _RealType result_type;
/** Parameter type. */
struct param_type
{
typedef exponential_distribution<_RealType> distribution_type;
explicit
param_type(_RealType __lambda = _RealType(1))
: _M_lambda(__lambda)
{
__glibcxx_assert(_M_lambda > _RealType(0));
}
_RealType
lambda() const
{ return _M_lambda; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_lambda == __p2._M_lambda; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
_RealType _M_lambda;
};
public:
/**
* @brief Constructs an exponential distribution with inverse scale
* parameter @f$\lambda@f$.
*/
explicit
exponential_distribution(const result_type& __lambda = result_type(1))
: _M_param(__lambda)
{ }
explicit
exponential_distribution(const param_type& __p)
: _M_param(__p)
{ }
/**
* @brief Resets the distribution state.
*
* Has no effect on exponential distributions.
*/
void
reset() { }
/**
* @brief Returns the inverse scale parameter of the distribution.
*/
_RealType
lambda() const
{ return _M_param.lambda(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return result_type(0); }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{
__detail::_Adaptor<_UniformRandomNumberGenerator, result_type>
__aurng(__urng);
return -std::log(result_type(1) - __aurng()) / __p.lambda();
}
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two exponential distributions have the same
* parameters.
*/
friend bool
operator==(const exponential_distribution& __d1,
const exponential_distribution& __d2)
{ return __d1._M_param == __d2._M_param; }
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
};
/**
* @brief Return true if two exponential distributions have different
* parameters.
*/
template<typename _RealType>
inline bool
operator!=(const std::exponential_distribution<_RealType>& __d1,
const std::exponential_distribution<_RealType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief Inserts a %exponential_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %exponential_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RealType, typename _CharT, typename _Traits>
std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::exponential_distribution<_RealType>& __x);
/**
* @brief Extracts a %exponential_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %exponential_distribution random number
* generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _RealType, typename _CharT, typename _Traits>
std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::exponential_distribution<_RealType>& __x);
/**
* @brief A weibull_distribution random number distribution.
*
* The formula for the normal probability density function is:
* @f[
* p(x|\alpha,\beta) = \frac{\alpha}{\beta} (\frac{x}{\beta})^{\alpha-1}
* \exp{(-(\frac{x}{\beta})^\alpha)}
* @f]
*/
template<typename _RealType = double>
class weibull_distribution
{
static_assert(std::is_floating_point<_RealType>::value,
"result_type must be a floating point type");
public:
/** The type of the range of the distribution. */
typedef _RealType result_type;
/** Parameter type. */
struct param_type
{
typedef weibull_distribution<_RealType> distribution_type;
explicit
param_type(_RealType __a = _RealType(1),
_RealType __b = _RealType(1))
: _M_a(__a), _M_b(__b)
{ }
_RealType
a() const
{ return _M_a; }
_RealType
b() const
{ return _M_b; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
_RealType _M_a;
_RealType _M_b;
};
explicit
weibull_distribution(_RealType __a = _RealType(1),
_RealType __b = _RealType(1))
: _M_param(__a, __b)
{ }
explicit
weibull_distribution(const param_type& __p)
: _M_param(__p)
{ }
/**
* @brief Resets the distribution state.
*/
void
reset()
{ }
/**
* @brief Return the @f$a@f$ parameter of the distribution.
*/
_RealType
a() const
{ return _M_param.a(); }
/**
* @brief Return the @f$b@f$ parameter of the distribution.
*/
_RealType
b() const
{ return _M_param.b(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return result_type(0); }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two Weibull distributions have the same
* parameters.
*/
friend bool
operator==(const weibull_distribution& __d1,
const weibull_distribution& __d2)
{ return __d1._M_param == __d2._M_param; }
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
};
/**
* @brief Return true if two Weibull distributions have different
* parameters.
*/
template<typename _RealType>
inline bool
operator!=(const std::weibull_distribution<_RealType>& __d1,
const std::weibull_distribution<_RealType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief Inserts a %weibull_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %weibull_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RealType, typename _CharT, typename _Traits>
std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::weibull_distribution<_RealType>& __x);
/**
* @brief Extracts a %weibull_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %weibull_distribution random number
* generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _RealType, typename _CharT, typename _Traits>
std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::weibull_distribution<_RealType>& __x);
/**
* @brief A extreme_value_distribution random number distribution.
*
* The formula for the normal probability mass function is
* @f[
* p(x|a,b) = \frac{1}{b}
* \exp( \frac{a-x}{b} - \exp(\frac{a-x}{b}))
* @f]
*/
template<typename _RealType = double>
class extreme_value_distribution
{
static_assert(std::is_floating_point<_RealType>::value,
"result_type must be a floating point type");
public:
/** The type of the range of the distribution. */
typedef _RealType result_type;
/** Parameter type. */
struct param_type
{
typedef extreme_value_distribution<_RealType> distribution_type;
explicit
param_type(_RealType __a = _RealType(0),
_RealType __b = _RealType(1))
: _M_a(__a), _M_b(__b)
{ }
_RealType
a() const
{ return _M_a; }
_RealType
b() const
{ return _M_b; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_a == __p2._M_a && __p1._M_b == __p2._M_b; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
_RealType _M_a;
_RealType _M_b;
};
explicit
extreme_value_distribution(_RealType __a = _RealType(0),
_RealType __b = _RealType(1))
: _M_param(__a, __b)
{ }
explicit
extreme_value_distribution(const param_type& __p)
: _M_param(__p)
{ }
/**
* @brief Resets the distribution state.
*/
void
reset()
{ }
/**
* @brief Return the @f$a@f$ parameter of the distribution.
*/
_RealType
a() const
{ return _M_param.a(); }
/**
* @brief Return the @f$b@f$ parameter of the distribution.
*/
_RealType
b() const
{ return _M_param.b(); }
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return std::numeric_limits<result_type>::lowest(); }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{ return std::numeric_limits<result_type>::max(); }
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two extreme value distributions have the same
* parameters.
*/
friend bool
operator==(const extreme_value_distribution& __d1,
const extreme_value_distribution& __d2)
{ return __d1._M_param == __d2._M_param; }
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
};
/**
* @brief Return true if two extreme value distributions have different
* parameters.
*/
template<typename _RealType>
inline bool
operator!=(const std::extreme_value_distribution<_RealType>& __d1,
const std::extreme_value_distribution<_RealType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief Inserts a %extreme_value_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %extreme_value_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RealType, typename _CharT, typename _Traits>
std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::extreme_value_distribution<_RealType>& __x);
/**
* @brief Extracts a %extreme_value_distribution random number
* distribution @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %extreme_value_distribution random number
* generator engine.
*
* @returns The input stream with @p __x extracted or in an error state.
*/
template<typename _RealType, typename _CharT, typename _Traits>
std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::extreme_value_distribution<_RealType>& __x);
/**
* @brief A discrete_distribution random number distribution.
*
* The formula for the discrete probability mass function is
*
*/
template<typename _IntType = int>
class discrete_distribution
{
static_assert(std::is_integral<_IntType>::value,
"result_type must be an integral type");
public:
/** The type of the range of the distribution. */
typedef _IntType result_type;
/** Parameter type. */
struct param_type
{
typedef discrete_distribution<_IntType> distribution_type;
friend class discrete_distribution<_IntType>;
param_type()
: _M_prob(), _M_cp()
{ }
template<typename _InputIterator>
param_type(_InputIterator __wbegin,
_InputIterator __wend)
: _M_prob(__wbegin, __wend), _M_cp()
{ _M_initialize(); }
param_type(initializer_list<double> __wil)
: _M_prob(__wil.begin(), __wil.end()), _M_cp()
{ _M_initialize(); }
template<typename _Func>
param_type(size_t __nw, double __xmin, double __xmax,
_Func __fw);
// See: http://cpp-next.com/archive/2010/10/implicit-move-must-go/
param_type(const param_type&) = default;
param_type& operator=(const param_type&) = default;
std::vector<double>
probabilities() const
{ return _M_prob.empty() ? std::vector<double>(1, 1.0) : _M_prob; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_prob == __p2._M_prob; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
void
_M_initialize();
std::vector<double> _M_prob;
std::vector<double> _M_cp;
};
discrete_distribution()
: _M_param()
{ }
template<typename _InputIterator>
discrete_distribution(_InputIterator __wbegin,
_InputIterator __wend)
: _M_param(__wbegin, __wend)
{ }
discrete_distribution(initializer_list<double> __wl)
: _M_param(__wl)
{ }
template<typename _Func>
discrete_distribution(size_t __nw, double __xmin, double __xmax,
_Func __fw)
: _M_param(__nw, __xmin, __xmax, __fw)
{ }
explicit
discrete_distribution(const param_type& __p)
: _M_param(__p)
{ }
/**
* @brief Resets the distribution state.
*/
void
reset()
{ }
/**
* @brief Returns the probabilities of the distribution.
*/
std::vector<double>
probabilities() const
{
return _M_param._M_prob.empty()
? std::vector<double>(1, 1.0) : _M_param._M_prob;
}
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{ return result_type(0); }
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{
return _M_param._M_prob.empty()
? result_type(0) : result_type(_M_param._M_prob.size() - 1);
}
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two discrete distributions have the same
* parameters.
*/
friend bool
operator==(const discrete_distribution& __d1,
const discrete_distribution& __d2)
{ return __d1._M_param == __d2._M_param; }
/**
* @brief Inserts a %discrete_distribution random number distribution
* @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %discrete_distribution random number distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _IntType1, typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::discrete_distribution<_IntType1>& __x);
/**
* @brief Extracts a %discrete_distribution random number distribution
* @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %discrete_distribution random number
* generator engine.
*
* @returns The input stream with @p __x extracted or in an error
* state.
*/
template<typename _IntType1, typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::discrete_distribution<_IntType1>& __x);
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
};
/**
* @brief Return true if two discrete distributions have different
* parameters.
*/
template<typename _IntType>
inline bool
operator!=(const std::discrete_distribution<_IntType>& __d1,
const std::discrete_distribution<_IntType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief A piecewise_constant_distribution random number distribution.
*
* The formula for the piecewise constant probability mass function is
*
*/
template<typename _RealType = double>
class piecewise_constant_distribution
{
static_assert(std::is_floating_point<_RealType>::value,
"result_type must be a floating point type");
public:
/** The type of the range of the distribution. */
typedef _RealType result_type;
/** Parameter type. */
struct param_type
{
typedef piecewise_constant_distribution<_RealType> distribution_type;
friend class piecewise_constant_distribution<_RealType>;
param_type()
: _M_int(), _M_den(), _M_cp()
{ }
template<typename _InputIteratorB, typename _InputIteratorW>
param_type(_InputIteratorB __bfirst,
_InputIteratorB __bend,
_InputIteratorW __wbegin);
template<typename _Func>
param_type(initializer_list<_RealType> __bi, _Func __fw);
template<typename _Func>
param_type(size_t __nw, _RealType __xmin, _RealType __xmax,
_Func __fw);
// See: http://cpp-next.com/archive/2010/10/implicit-move-must-go/
param_type(const param_type&) = default;
param_type& operator=(const param_type&) = default;
std::vector<_RealType>
intervals() const
{
if (_M_int.empty())
{
std::vector<_RealType> __tmp(2);
__tmp[1] = _RealType(1);
return __tmp;
}
else
return _M_int;
}
std::vector<double>
densities() const
{ return _M_den.empty() ? std::vector<double>(1, 1.0) : _M_den; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_int == __p2._M_int && __p1._M_den == __p2._M_den; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
void
_M_initialize();
std::vector<_RealType> _M_int;
std::vector<double> _M_den;
std::vector<double> _M_cp;
};
explicit
piecewise_constant_distribution()
: _M_param()
{ }
template<typename _InputIteratorB, typename _InputIteratorW>
piecewise_constant_distribution(_InputIteratorB __bfirst,
_InputIteratorB __bend,
_InputIteratorW __wbegin)
: _M_param(__bfirst, __bend, __wbegin)
{ }
template<typename _Func>
piecewise_constant_distribution(initializer_list<_RealType> __bl,
_Func __fw)
: _M_param(__bl, __fw)
{ }
template<typename _Func>
piecewise_constant_distribution(size_t __nw,
_RealType __xmin, _RealType __xmax,
_Func __fw)
: _M_param(__nw, __xmin, __xmax, __fw)
{ }
explicit
piecewise_constant_distribution(const param_type& __p)
: _M_param(__p)
{ }
/**
* @brief Resets the distribution state.
*/
void
reset()
{ }
/**
* @brief Returns a vector of the intervals.
*/
std::vector<_RealType>
intervals() const
{
if (_M_param._M_int.empty())
{
std::vector<_RealType> __tmp(2);
__tmp[1] = _RealType(1);
return __tmp;
}
else
return _M_param._M_int;
}
/**
* @brief Returns a vector of the probability densities.
*/
std::vector<double>
densities() const
{
return _M_param._M_den.empty()
? std::vector<double>(1, 1.0) : _M_param._M_den;
}
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{
return _M_param._M_int.empty()
? result_type(0) : _M_param._M_int.front();
}
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{
return _M_param._M_int.empty()
? result_type(1) : _M_param._M_int.back();
}
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two piecewise constant distributions have the
* same parameters.
*/
friend bool
operator==(const piecewise_constant_distribution& __d1,
const piecewise_constant_distribution& __d2)
{ return __d1._M_param == __d2._M_param; }
/**
* @brief Inserts a %piecewise_constant_distribution random
* number distribution @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %piecewise_constant_distribution random number
* distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::piecewise_constant_distribution<_RealType1>& __x);
/**
* @brief Extracts a %piecewise_constant_distribution random
* number distribution @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %piecewise_constant_distribution random number
* generator engine.
*
* @returns The input stream with @p __x extracted or in an error
* state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::piecewise_constant_distribution<_RealType1>& __x);
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
};
/**
* @brief Return true if two piecewise constant distributions have
* different parameters.
*/
template<typename _RealType>
inline bool
operator!=(const std::piecewise_constant_distribution<_RealType>& __d1,
const std::piecewise_constant_distribution<_RealType>& __d2)
{ return !(__d1 == __d2); }
/**
* @brief A piecewise_linear_distribution random number distribution.
*
* The formula for the piecewise linear probability mass function is
*
*/
template<typename _RealType = double>
class piecewise_linear_distribution
{
static_assert(std::is_floating_point<_RealType>::value,
"result_type must be a floating point type");
public:
/** The type of the range of the distribution. */
typedef _RealType result_type;
/** Parameter type. */
struct param_type
{
typedef piecewise_linear_distribution<_RealType> distribution_type;
friend class piecewise_linear_distribution<_RealType>;
param_type()
: _M_int(), _M_den(), _M_cp(), _M_m()
{ }
template<typename _InputIteratorB, typename _InputIteratorW>
param_type(_InputIteratorB __bfirst,
_InputIteratorB __bend,
_InputIteratorW __wbegin);
template<typename _Func>
param_type(initializer_list<_RealType> __bl, _Func __fw);
template<typename _Func>
param_type(size_t __nw, _RealType __xmin, _RealType __xmax,
_Func __fw);
// See: http://cpp-next.com/archive/2010/10/implicit-move-must-go/
param_type(const param_type&) = default;
param_type& operator=(const param_type&) = default;
std::vector<_RealType>
intervals() const
{
if (_M_int.empty())
{
std::vector<_RealType> __tmp(2);
__tmp[1] = _RealType(1);
return __tmp;
}
else
return _M_int;
}
std::vector<double>
densities() const
{ return _M_den.empty() ? std::vector<double>(2, 1.0) : _M_den; }
friend bool
operator==(const param_type& __p1, const param_type& __p2)
{ return __p1._M_int == __p2._M_int && __p1._M_den == __p2._M_den; }
friend bool
operator!=(const param_type& __p1, const param_type& __p2)
{ return !(__p1 == __p2); }
private:
void
_M_initialize();
std::vector<_RealType> _M_int;
std::vector<double> _M_den;
std::vector<double> _M_cp;
std::vector<double> _M_m;
};
explicit
piecewise_linear_distribution()
: _M_param()
{ }
template<typename _InputIteratorB, typename _InputIteratorW>
piecewise_linear_distribution(_InputIteratorB __bfirst,
_InputIteratorB __bend,
_InputIteratorW __wbegin)
: _M_param(__bfirst, __bend, __wbegin)
{ }
template<typename _Func>
piecewise_linear_distribution(initializer_list<_RealType> __bl,
_Func __fw)
: _M_param(__bl, __fw)
{ }
template<typename _Func>
piecewise_linear_distribution(size_t __nw,
_RealType __xmin, _RealType __xmax,
_Func __fw)
: _M_param(__nw, __xmin, __xmax, __fw)
{ }
explicit
piecewise_linear_distribution(const param_type& __p)
: _M_param(__p)
{ }
/**
* Resets the distribution state.
*/
void
reset()
{ }
/**
* @brief Return the intervals of the distribution.
*/
std::vector<_RealType>
intervals() const
{
if (_M_param._M_int.empty())
{
std::vector<_RealType> __tmp(2);
__tmp[1] = _RealType(1);
return __tmp;
}
else
return _M_param._M_int;
}
/**
* @brief Return a vector of the probability densities of the
* distribution.
*/
std::vector<double>
densities() const
{
return _M_param._M_den.empty()
? std::vector<double>(2, 1.0) : _M_param._M_den;
}
/**
* @brief Returns the parameter set of the distribution.
*/
param_type
param() const
{ return _M_param; }
/**
* @brief Sets the parameter set of the distribution.
* @param __param The new parameter set of the distribution.
*/
void
param(const param_type& __param)
{ _M_param = __param; }
/**
* @brief Returns the greatest lower bound value of the distribution.
*/
result_type
min() const
{
return _M_param._M_int.empty()
? result_type(0) : _M_param._M_int.front();
}
/**
* @brief Returns the least upper bound value of the distribution.
*/
result_type
max() const
{
return _M_param._M_int.empty()
? result_type(1) : _M_param._M_int.back();
}
/**
* @brief Generating functions.
*/
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng)
{ return this->operator()(__urng, _M_param); }
template<typename _UniformRandomNumberGenerator>
result_type
operator()(_UniformRandomNumberGenerator& __urng,
const param_type& __p);
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng)
{ this->__generate(__f, __t, __urng, _M_param); }
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
template<typename _UniformRandomNumberGenerator>
void
__generate(result_type* __f, result_type* __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p)
{ this->__generate_impl(__f, __t, __urng, __p); }
/**
* @brief Return true if two piecewise linear distributions have the
* same parameters.
*/
friend bool
operator==(const piecewise_linear_distribution& __d1,
const piecewise_linear_distribution& __d2)
{ return __d1._M_param == __d2._M_param; }
/**
* @brief Inserts a %piecewise_linear_distribution random number
* distribution @p __x into the output stream @p __os.
*
* @param __os An output stream.
* @param __x A %piecewise_linear_distribution random number
* distribution.
*
* @returns The output stream with the state of @p __x inserted or in
* an error state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const std::piecewise_linear_distribution<_RealType1>& __x);
/**
* @brief Extracts a %piecewise_linear_distribution random number
* distribution @p __x from the input stream @p __is.
*
* @param __is An input stream.
* @param __x A %piecewise_linear_distribution random number
* generator engine.
*
* @returns The input stream with @p __x extracted or in an error
* state.
*/
template<typename _RealType1, typename _CharT, typename _Traits>
friend std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is,
std::piecewise_linear_distribution<_RealType1>& __x);
private:
template<typename _ForwardIterator,
typename _UniformRandomNumberGenerator>
void
__generate_impl(_ForwardIterator __f, _ForwardIterator __t,
_UniformRandomNumberGenerator& __urng,
const param_type& __p);
param_type _M_param;
};
/**
* @brief Return true if two piecewise linear distributions have
* different parameters.
*/
template<typename _RealType>
inline bool
operator!=(const std::piecewise_linear_distribution<_RealType>& __d1,
const std::piecewise_linear_distribution<_RealType>& __d2)
{ return !(__d1 == __d2); }
/* @} */ // group random_distributions_poisson
/* @} */ // group random_distributions
/**
* @addtogroup random_utilities Random Number Utilities
* @ingroup random
* @{
*/
/**
* @brief The seed_seq class generates sequences of seeds for random
* number generators.
*/
class seed_seq
{
public:
/** The type of the seed vales. */
typedef uint_least32_t result_type;
/** Default constructor. */
seed_seq() noexcept
: _M_v()
{ }
template<typename _IntType>
seed_seq(std::initializer_list<_IntType> il);
template<typename _InputIterator>
seed_seq(_InputIterator __begin, _InputIterator __end);
// generating functions
template<typename _RandomAccessIterator>
void
generate(_RandomAccessIterator __begin, _RandomAccessIterator __end);
// property functions
size_t size() const noexcept
{ return _M_v.size(); }
template<typename OutputIterator>
void
param(OutputIterator __dest) const
{ std::copy(_M_v.begin(), _M_v.end(), __dest); }
// no copy functions
seed_seq(const seed_seq&) = delete;
seed_seq& operator=(const seed_seq&) = delete;
private:
std::vector<result_type> _M_v;
};
/* @} */ // group random_utilities
/* @} */ // group random
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace std
#endif
| [
"brian.taylor@bolderflight.com"
] | brian.taylor@bolderflight.com |
9f06bc74457dab685b0d69fc19c3850cfa309e68 | 1df4f6ae8a065cacd5aa9880fd869e7f305654c6 | /Character.hpp | 86648e787b2a0b7ac9fecf3e6ef981246b8c31d1 | [] | no_license | MaximePayant/B-CPP-300-LYN-3-1-CPPD09-maxime.payant | fb6e255d6b91bd50612d307e4a4c7c5aaab7c454 | 6d1452cc806fa1823e59461354c0f8d6e8e6fc08 | refs/heads/master | 2023-08-03T18:27:55.590744 | 2021-01-15T17:41:46 | 2021-01-15T17:41:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,128 | hpp | /*
** EPITECH PROJECT, 2021
** CPP_D07M
** File description:
** Character.hpp
*/
#ifndef CHARACTER_HPP
#define CHARACTER_HPP
#include <iostream>
class Character
{
public:
enum AttackRange {CLOSE, RANGE} Range;
Character() = delete;
Character(const Character&) = delete;
Character(Character&&) = delete;
Character(const std::string& name, int level);
const std::string &getName() const { return (m_name); };
int getLvl() const { return (m_level); };
int getPv() const { return (m_hp); };
int getPower() const { return (m_energy); };
const std::string& getClass() const { return (m_class); };
const std::string& getRace() const { return (m_race); };
int getStrength() const { return (m_strength); };
int getStamina() const { return (m_stamina); };
int getIntelligence() const { return (m_intelligence); };
int getSpirit() const { return (m_spirit); };
int getAgility() const { return (m_agility); };
void setPv(int value) { m_hp = (value > 100 ? 100 : value);};
void setPower(int value) { m_energy = (value > 100 ? 100 : value);};
void setStrength(int value) { m_strength = value; };
void setStamina(int value) { m_stamina = value; };
void setIntelligence(int value) { m_intelligence = value; };
void setSpirit(int value) { m_spirit = value; };
void setAgility(int value) { m_agility = value; };
int CloseAttack();
int RangeAttack();
void Heal();
void RestorePower();
void TakeDamage(int damage);
protected:
std::string m_name;
std::size_t m_level;
std::size_t m_hp;
std::size_t m_energy;
std::string m_class;
std::string m_race;
int m_strength;
int m_stamina;
int m_intelligence;
int m_spirit;
int m_agility;
};
#endif // CHARACTER_HPP | [
"maxime@pop-os.localdomain"
] | maxime@pop-os.localdomain |
acc43b80bce5ba9c9e85c0cb71aa708fae2fe05d | 3690d2260131145b15a067ab4bf266c357690a8e | /DAIDALUS/C++/include/SimpleNoPolarProjection.h | 004c11378128754661128791cb623cdffaca93e7 | [
"LicenseRef-scancode-us-govt-public-domain"
] | permissive | nowucme/WellClear | a0919eb21948485ecd8b33c36adcb572613a07ef | 1083d9735d9103f4e0b21502974809011b95f1ee | refs/heads/master | 2021-01-09T06:27:26.783676 | 2016-05-06T21:20:36 | 2016-05-06T21:20:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,686 | h | /*
* SimpleNoPolarProjection.h
*
* Contact: Jeff Maddalon (j.m.maddalon@nasa.gov)
* NASA LaRC
*
* Copyright (c) 2011-2015 United States Government as represented by
* the National Aeronautics and Space Administration. No copyright
* is claimed in the United States under Title 17, U.S.Code. All Other
* Rights Reserved.
*/
#ifndef SIMPLENOPOLARPROJECTION_H_
#define SIMPLENOPOLARPROJECTION_H_
#include "LatLonAlt.h"
#include "Vect3.h"
#include "Velocity.h"
#include "Position.h"
#include "Util.h"
#include "Point.h"
namespace larcfm {
/**
* This class creates a local Euclidean projection around a given point. This projection may be used to
* transform geodesic coordinates (LatLonAlt objects) into this Euclidean frame, using the project() method. Also points
* within this frame, may be found in geodesic coordinates with the inverse() method. As long as the points are
* close to the projection point, the errors will be very small.
*
* This is mimics the original projection function, and does not try to compensate for being near the poles.
*
* Note: projection objects should never be made directly, and instead should be retrieved via Projection.getProjection()
*
*/
class SimpleNoPolarProjection {
private:
double projLat;
double projLon;
double projAlt;
public:
/** Default constructor. */
SimpleNoPolarProjection();
/** Create a projection around the given reference point. */
SimpleNoPolarProjection(const LatLonAlt& lla);
/** Create a projection around the given reference point. */
SimpleNoPolarProjection(double lat, double lon, double alt);
/** Destructor */
~SimpleNoPolarProjection() {}
/** Return a new projection with the given reference point */
SimpleNoPolarProjection makeNew(const LatLonAlt& lla) const;
/** Return a new projection with the given reference point */
SimpleNoPolarProjection makeNew(double lat, double lon, double alt) const;
/**
* Given an ownship latitude and desired accuracy, what is the longest distance to conflict this projection will support? [m]
*/
double conflictRange(double latitude, double accuracy) const;
/**
* What is the maximum effective horizontal range of this projection? [m]
*/
double maxRange() const;
/** Get the projection point for this projection */
LatLonAlt getProjectionPoint() const;
/** Return a projection of a lat/lon(/alt) point in Euclidean 2-space */
Vect2 project2(const LatLonAlt& lla) const;
/** Return a projection of a lat/lon(/alt) point in Euclidean 3-space */
Vect3 project(const LatLonAlt& lla) const;
/** Return a projection of a Position in Euclidean 3-space (if already in Euclidian coordinate, this is the identity function) */
Vect3 project(const Position& sip) const;
Point projectPoint(const Position& sip) const;
/** Return a LatLonAlt value corresponding to the given Euclidean position */
LatLonAlt inverse(const Vect2& xy, double alt) const;
/** Return a LatLonAlt value corresponding to the given Euclidean position */
LatLonAlt inverse(const Vect3& xyz) const;
/** Given a velocity from a point in geodetic coordinates, return a projection of this velocity in Euclidean 3-space */
Velocity projectVelocity(const LatLonAlt& lla, const Velocity& v) const;
/** Given a velocity from a point, return a projection of this velocity in Euclidean 3-space (if already in Euclidian coordinate, this is the identity function) */
Velocity projectVelocity(const Position& ss, const Velocity& v) const;
/** Given a velocity from a point in Euclidean 3-space, return a projection of this velocity. If toLatLon is true, the velocity is projected into the geodetic coordinate space */
Velocity inverseVelocity(const Vect3& s, const Velocity& v, bool toLatLon) const;
/** Given a velocity from a point, return a projection of this velocity and the point in Euclidean 3-space. If the position is already in Euclidean coordinates, this acts as the idenitty function. */
std::pair<Vect3,Velocity> project(const Position& p, const Velocity& v) const;
/** Given a velocity from a point in Euclidean 3-space, return a projection of this velocity and the point. If toLatLon is true, the point/velocity is projected into the geodetic coordinate space */
std::pair<Position,Velocity> inverse(const Vect3& p, const Velocity& v, bool toLatLon) const;
/** String representation */
std::string toString() const { return "SimpleNoPolarProjection "+to_string(projLat)+" "+to_string(projLon)+" "+to_string(projAlt);}
};
}
#endif /* SIMPLENOPOLARPROJECTION_H_ */
| [
"cesaramh@gmail.com"
] | cesaramh@gmail.com |
6217cbf80edc186e07490bb78607aa5cc698eb7f | c07cc5ac787f4029a402f72f56cd9e46f42e359c | /ccc19j5.cpp | f875bb1d98b6d2e6e35c7b55347699cb4e813f5f | [] | no_license | lilweege/dmoj-solutions | 9fbf5ecfa5c5490274ec4bf64dac53cb8cd5751d | 39078fadcb5ed3573ac8253b915a7d1018c72520 | refs/heads/master | 2022-11-06T16:17:58.778724 | 2022-10-04T21:32:19 | 2022-10-04T21:32:19 | 248,377,287 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,093 | cpp | // this solution is not optimal, but is sufficient to pass official tests
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
// too lazy to work out the exact upper bound
// #define MAX 200
#define MAX 64
#define B_LO 'A'
#define B_HI 'B'
// turns out that the gain of using bitset is useless since
// string operations are nothing in comparison to the bfs
struct seq {
size_t n;
bitset<MAX> bs;
seq() = default;
seq(const string& s) : n(size(s)), bs(s, 0, n, B_LO, B_HI) {}
[[nodiscard]] auto to_string() const -> string {
return bs.to_string(B_LO, B_HI).substr(size(bs)-n);
}
auto replace(const seq& x, size_t i, size_t l) -> void {
// insert x into self at position i replacing length l
int grow = int(x.n - l);
if (grow > 0) {
bs <<= grow;
for (size_t b = 0; b < i; ++b)
bs[b] = bs[b+grow];
}
else if (grow < 0) {
for (size_t b = i-1; b+1 > 0; --b)
bs[b-grow] = bs[b];
bs >>= -grow;
}
for (size_t b = i; b < i+x.n; ++b)
bs[b] = x.bs[b-i];
n += grow;
}
[[nodiscard]] auto find_all(const seq& s) const -> vector<size_t> {
vector<size_t> all;
size_t m = s.n;
vector<int> lps(m);
for (size_t i = 1; i < m; ++i) {
size_t j = lps[i-1];
while (j > 0 && s.bs[i] != s.bs[j])
j = lps[j-1];
if (s.bs[i] == s.bs[j])
++j;
lps[i] = int(j);
}
for (size_t i = 0, j = 0; i < n;) {
if (s.bs[j] == bs[i])
++i, ++j;
if (j == m) {
all.push_back(i-j);
j = lps[j-1];
}
else if (i < n && s.bs[j] != bs[i]) {
if (j)
j = lps[j-1];
else
++i;
}
}
return all;
}
auto operator == (const seq& o) const -> bool {
return bs == o.bs && n == o.n;
}
};
struct seq_hash {
auto operator () (const seq &s) const -> size_t {
return hash<bitset<MAX>>()(s.bs) ^ hash<size_t>()(s.n);
// return hash<string>()(s.to_string());
}
};
struct sub {
size_t r, p; // one indexed
seq s;
};
struct rule {
seq fr, to;
};
auto main() -> int {
ios::sync_with_stdio(false);
cin.tie(nullptr);
array<rule, 3> rules;
for (auto& [fr, to] : rules) {
string a, b;
cin >> a >> b;
fr = a, to = b;
}
int N; // steps
string a, b;
cin >> N >> a >> b;
seq S(a), T(b); // start, end
// this approach is sufficient for naive datasets
// for which the breadth size does not blow up
auto half = [&](auto& q, const seq& s, bool fwd) -> void {
size_t n = size(q);
q[0].emplace(s, sub(0, 0, seq(""))); // filler value
for (size_t i = 1; i < n; ++i)
for (auto& [cur, _] : q[i-1])
for (size_t r = 1; r <= size(rules); ++r) {
auto& [fr, to] = rules[r-1];
if (!fwd) swap(fr, to);
for (size_t pos : cur.find_all(fr)) {
seq nxt = cur; nxt.replace(to, pos, fr.n);
q[i].emplace(nxt, sub(r, cur.n-fr.n-pos+1, cur));
}
if (!fwd) swap(fr, to);
}
};
vector<unordered_map<seq, sub, seq_hash>> qf(N/2+1), qb(N-N/2+1);
half(qf, S, true);
half(qb, T, false);
// string cur_check = S.to_string();
// int step_check = 0;
for (auto& [mid, _] : qf.back())
if (qb.back().contains(mid)) {
vector<sub> ans1;
seq cur = mid;
for (auto& x : qf | views::drop(1) | views::reverse) {
auto& nxt = x.find(cur)->second;
ans1.emplace_back(nxt.r, nxt.p, cur);
cur = nxt.s;
}
for (auto& [r, p, s] : ans1 | views::reverse) {
// cur_check = cur_check.substr(0, p-1) + rules[r-1].to.to_string() + cur_check.substr(p-1 + rules[r-1].fr.n);
// assert(cur_check == s.to_string());
// ++step_check;
cout << r << " " << p << " " << s.to_string() << "\n";
}
cur = mid;
for (auto& x : qb | views::drop(1) | views::reverse) {
auto& [r, p, s] = x.find(cur)->second;
// cur_check = cur_check.substr(0, p-1) + rules[r-1].to.to_string() + cur_check.substr(p-1 + rules[r-1].fr.n);
// assert(cur_check == s.to_string());
// ++step_check;
cout << r << " " << p << " " << s.to_string() << "\n";
cur = s;
}
// assert(cur_check == T.to_string());
// assert(step_check == N);
return 0;
}
// something went wrong (queues didn't meet in middle)
assert(false);
}
| [
"lquatt2@gmail.com"
] | lquatt2@gmail.com |
75d28b2bf2b23b57c62716713a85dcbf9bab4c33 | dda3bece634321edb4cfb6483c95eac83ca7cf35 | /ege/CollisionShapeCreator.cpp | 41176f42edf53efb7edb353429fc46d504804973 | [
"Apache-2.0"
] | permissive | BlenderCN-Org/ege | 6a6bf47b5f1b5365f28320ef24541f1f6fdf111d | 73558e63ec485e9e45015bf46ee4302f58fc8ebc | refs/heads/master | 2020-05-23T01:11:27.473726 | 2016-10-23T13:02:20 | 2016-10-26T21:47:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,980 | cpp | /** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license APACHE v2.0 (see license file)
*/
#include <ege/debug.hpp>
#include <ege/CollisionShapeCreator.hpp>
#include <btBulletCollisionCommon.h>
#include <BulletCollision/CollisionShapes/btConvexPolyhedron.h>
#include <BulletCollision/CollisionShapes/btShapeHull.h>
#include <BulletCollision/CollisionDispatch/btCollisionObject.h>
#include <ege/physicsShape/PhysicsShape.hpp>
#include <ege/physicsShape/PhysicsBox.hpp>
#include <ege/physicsShape/PhysicsCapsule.hpp>
#include <ege/physicsShape/PhysicsCone.hpp>
#include <ege/physicsShape/PhysicsConvexHull.hpp>
#include <ege/physicsShape/PhysicsCylinder.hpp>
#include <ege/physicsShape/PhysicsSphere.hpp>
// Documentetion of bullet library :
// http://bulletphysics.org/mediawiki-1.5.8/index.php/Collision_Shapes
btCollisionShape* ege::collision::createShape(const ememory::SharedPtr<ege::resource::Mesh>& _mesh) {
if (_mesh == nullptr) {
EGE_DEBUG("Create empty shape (no mesh)");
return new btEmptyShape();;
}
const std::vector<ememory::SharedPtr<ege::PhysicsShape>>& physiqueProperty = _mesh->getPhysicalProperties();
if (physiqueProperty.size() == 0) {
EGE_DEBUG("Create empty shape (no default shape)");
return new btEmptyShape();;
}
int32_t count = 0;
for (size_t iii=0; iii<physiqueProperty.size(); iii++) {
if (physiqueProperty[iii] == nullptr) {
continue;
}
count++;
}
btCompoundShape* outputShape = nullptr;
if (count>1) {
EGE_DEBUG("Create complexe shape");
outputShape = new btCompoundShape();
} else {
EGE_DEBUG("Create simple shape");
}
for (size_t iii=0; iii<physiqueProperty.size(); iii++) {
if (physiqueProperty[iii] == nullptr) {
continue;
}
switch (physiqueProperty[iii]->getType()) {
case ege::PhysicsShape::box : {
EGE_DEBUG(" Box");
const ege::PhysicsBox* tmpElement = physiqueProperty[iii]->toBox();
if (tmpElement == nullptr) {
// ERROR ...
continue;
}
btCollisionShape* tmpShape = new btBoxShape(tmpElement->getSize());
if (tmpShape != nullptr) {
if (outputShape == nullptr) {
return tmpShape;
} else {
vec4 qqq = tmpElement->getQuaternion();
const btTransform localTransform(btQuaternion(qqq.x(),qqq.y(),qqq.z(),qqq.w()), tmpElement->getOrigin());
outputShape->addChildShape(localTransform, tmpShape);
}
}
break;
}
case ege::PhysicsShape::cylinder : {
EGE_DEBUG(" Cylinder");
const ege::PhysicsCylinder* tmpElement = physiqueProperty[iii]->toCylinder();
if (tmpElement == nullptr) {
// ERROR ...
continue;
}
btCollisionShape* tmpShape = new btCylinderShape(tmpElement->getSize());
if (tmpShape != nullptr) {
if (outputShape == nullptr) {
return tmpShape;
} else {
vec4 qqq = tmpElement->getQuaternion();
const btTransform localTransform(btQuaternion(qqq.x(),qqq.y(),qqq.z(),qqq.w()), tmpElement->getOrigin());
outputShape->addChildShape(localTransform, tmpShape);
}
}
break;
}
case ege::PhysicsShape::capsule : {
EGE_DEBUG(" Capsule");
const ege::PhysicsCapsule* tmpElement = physiqueProperty[iii]->toCapsule();
if (tmpElement == nullptr) {
// ERROR ...
continue;
}
btCollisionShape* tmpShape = new btCapsuleShape(tmpElement->getRadius(), tmpElement->getHeight());
if (tmpShape != nullptr) {
if (outputShape == nullptr) {
return tmpShape;
} else {
vec4 qqq = tmpElement->getQuaternion();
const btTransform localTransform(btQuaternion(qqq.x(),qqq.y(),qqq.z(),qqq.w()), tmpElement->getOrigin());
outputShape->addChildShape(localTransform, tmpShape);
}
}
break;
}
case ege::PhysicsShape::cone : {
EGE_DEBUG(" Cone");
const ege::PhysicsCone* tmpElement = physiqueProperty[iii]->toCone();
if (tmpElement == nullptr) {
// ERROR ...
continue;
}
btCollisionShape* tmpShape = new btConeShape(tmpElement->getRadius(), tmpElement->getHeight());
if (tmpShape != nullptr) {
if (outputShape == nullptr) {
return tmpShape;
} else {
vec4 qqq = tmpElement->getQuaternion();
const btTransform localTransform(btQuaternion(qqq.x(),qqq.y(),qqq.z(),qqq.w()), tmpElement->getOrigin());
outputShape->addChildShape(localTransform, tmpShape);
}
}
break;
}
case ege::PhysicsShape::sphere : {
EGE_DEBUG(" Sphere");
const ege::PhysicsSphere* tmpElement = physiqueProperty[iii]->toSphere();
if (tmpElement == nullptr) {
// ERROR ...
continue;
}
btCollisionShape* tmpShape = new btSphereShape(tmpElement->getRadius());
if (tmpShape != nullptr) {
if (outputShape == nullptr) {
return tmpShape;
} else {
vec4 qqq = tmpElement->getQuaternion();
const btTransform localTransform(btQuaternion(qqq.x(),qqq.y(),qqq.z(),qqq.w()), tmpElement->getOrigin());
outputShape->addChildShape(localTransform, tmpShape);
}
}
break;
}
case ege::PhysicsShape::convexHull : {
EGE_DEBUG(" convexHull");
const ege::PhysicsConvexHull* tmpElement = physiqueProperty[iii]->toConvexHull();
if (tmpElement == nullptr) {
// ERROR ...
continue;
}
btConvexHullShape* tmpShape = new btConvexHullShape(&(tmpElement->getPointList()[0].x()), tmpElement->getPointList().size());
if (tmpShape != nullptr) {
if (outputShape == nullptr) {
return tmpShape;
} else {
vec4 qqq = tmpElement->getQuaternion();
const btTransform localTransform(btQuaternion(qqq.x(),qqq.y(),qqq.z(),qqq.w()), tmpElement->getOrigin());
outputShape->addChildShape(localTransform, tmpShape);
}
}
break;
}
default :
EGE_DEBUG(" ???");
// TODO : UNKNOW type ...
break;
}
}
if (outputShape == nullptr) {
EGE_DEBUG("create empty shape ...");
return new btEmptyShape();
}
return outputShape;
}
| [
"yui.heero@gmail.com"
] | yui.heero@gmail.com |
a967ad01ee8e16a7cb4a08e7b4443784803f2aa0 | 1c74a2e075793e1d35c441518e2e138e14e26ea5 | /bytedance/最长连续递增序列.cpp | ad999af8d02ce1bae19e65a31ed076feb1ea21af | [] | no_license | Dawinia/LeetCode | 1a385bfadbc4869c46dc1e9b8ca7656b77d746a0 | e1dcc71ca657b42eb8eb15116697e852ef4a475a | refs/heads/master | 2021-07-20T00:56:01.058471 | 2020-07-22T14:07:04 | 2020-07-22T14:07:04 | 197,305,126 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 459 | cpp | class Solution {
public:
int findLengthOfLCIS(vector<int>& nums) {
int size = nums.size();
if(size < 2)
return size;
int ans = 0;
int temp = 1;
for(int i = 1; i < size; ++i) {
if(nums[i] > nums[i - 1])
++temp;
else {
ans = max(ans, temp);
temp = 1;
}
}
ans = max(ans, temp);
return ans;
}
}; | [
"dawinialo@163.com"
] | dawinialo@163.com |
a8a452885ac88a31befd41070d49857cdd78860c | 99441588c7d6159064d9ce2b94d3743a37f85d33 | /border_height_detect/pointcloud.cpp | eb3882ac844663e500176b1859c8590bc1136e5f | [] | no_license | YZT1997/robolab_project | 2786f8983c4b02040da316cdd2c8f9bb73e2dd4c | a7edb588d3145356566e9dcc37b03f7429bcb7d6 | refs/heads/master | 2023-09-02T21:28:01.280464 | 2021-10-14T02:06:35 | 2021-10-14T02:06:35 | 369,128,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,790 | cpp | //
// Created by yangzt on 2021/8/26.
//
#include <iostream>
#include <string.h>
#include <pcl/point_types.h>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/PointField.h>
#include <pcl/io/pcd_io.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/sample_consensus/ransac.h>
#include <pcl/sample_consensus/sac_model_plane.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <Eigen/Core>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/surface/mls.h>
#include <message_filters/subscriber.h>
#include <message_filters/time_synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <opencv2/opencv.hpp>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/filters/extract_indices.h>
using namespace std;
using namespace cv;
ros::Publisher pointcloud_pub;
void rgb_depth_sub(const sensor_msgs::ImageConstPtr& rgbimg,const sensor_msgs::ImageConstPtr& depthimg){
//图像预处理,rgb,depth信息
Mat depth_raw;
cv_bridge::CvImageConstPtr cv_ptrdepth;
cv_ptrdepth = cv_bridge::toCvShare(depthimg);
depth_raw = cv_ptrdepth->image;
Mat rgb;
cv_bridge::CvImageConstPtr cv_ptrrgb;
cv_ptrrgb = cv_bridge::toCvShare(rgbimg);
rgb = cv_ptrrgb->image;
Mat depth(depth_raw.size(),CV_16UC1);
for(int row=0;row<rgb.rows;row++){
for(int col=0;col<rgb.cols;col++ ) {
float z = float(depth_raw.at<float>(row, col)) * 1000; //深度图之前是32FC1编码
depth.at<ushort>(row, col) = z; //转成16位编码
Vec3b temp = rgb.at<Vec3b>(row, col);
rgb.at<Vec3b>(row, col)[0] = temp[2];
rgb.at<Vec3b>(row, col)[2] = temp[0];
}
}
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloudin (new pcl::PointCloud<pcl::PointXYZRGB>);
// Transform to point cloud;
cloudin->header.frame_id="/frame";
pcl::PointXYZRGB Point;
for(int row=0;row<rgb.rows;row+=1) {
//row,col这里做了稀疏化,就不用滤波稀疏了
for(int col=0;col<rgb.cols ;col+=1){
float z = float(depth.at<ushort>(row,col))/1000;
float y = (row - 232.171) * z / 615.312;
float x = (col - 323.844) * z / 615.372;
// // For Vzense Camera
// float z = float(depth.at<ushort>(row,col))/1000;
// float y = (row - 245.039) * z / 710.304;
// float x = (col - 330.582) * z / 707.547;
// if(y>0 && z<10) //根据相机坐标系,只选择向下的点云,z方向十米以内的点云;
if(z < 10.0f){
Point.x=x;
Point.y=y;
Point.z=z;
Point.b=rgb.ptr<uchar>(row)[col*3];
Point.g=rgb.ptr<uchar>(row)[col*3+1];
Point.r=rgb.ptr<uchar>(row)[col*3+2];
cloudin->points.push_back(Point);
}
}
}
pointcloud_pub.publish(cloudin);
}
int main(int argc, char** argv){
ros::init(argc, argv, "point_cloud");
ros::NodeHandle nh;
pointcloud_pub = nh.advertise<sensor_msgs::PointCloud2>("/pointcloud", 1000);
//同步接收rgb,depth
message_filters::Subscriber<sensor_msgs::Image> rgb_sub(nh, "/realsense_sr300/ylx/rgb", 1);
message_filters::Subscriber<sensor_msgs::Image> depth_sub(nh, "/realsense_sr300/ylx/depth", 1);
typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image, sensor_msgs::Image> sync_pol;
message_filters::Synchronizer<sync_pol> sync(sync_pol(10), rgb_sub,depth_sub);
sync.registerCallback(boost::bind(&rgb_depth_sub, _1, _2));
ros::spin();
return 0;
}
| [
"yangzt_0943@163.com"
] | yangzt_0943@163.com |
f437c1851df73533968878167546ede2be7bf039 | c1dfcde6d9053726ccf245234ac56f45e0d9e119 | /Point_Ops/HW_gamma.cpp | 96dddccc2e5798d370db8ac1aa50d03d197a0a23 | [] | no_license | baruchshad/Image_Processing | 7664423cff32165f20f2c93c2a15e3b0b1c56bfa | 734a50afcb6a18dfa10a0a474f6f96e5e9e2ce75 | refs/heads/master | 2022-12-12T06:33:04.122811 | 2020-09-03T01:17:06 | 2020-09-03T01:17:06 | 292,396,079 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,402 | cpp | #include "IP.h"
#include <cmath>
using namespace IP;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW_gammaCorrect:
//
// Gamma correct image I1. Output is in I2.
//
void
HW_gammaCorrect(ImagePtr I1, double gamma, ImagePtr I2)
{
// copy image header (width, height) of input image I1 to output image I2
IP_copyImageHeader(I1, I2);
// init vars for width, height, and total number of pixels
int w = I1->width();
int h = I1->height();
int total = w * h;
int i, lut[MXGRAY];
double x, hold;
for (i = 0; i < MaxGray; i++){
x = (double)i / 255; // normalized to 0,255
hold = 255 * pow(x, 1 / gamma); // gamma function to adjust pixels
lut[i] = (int)CLIP(hold, 0, 255); // CLIP just in case for bad rounding errors
}
// declarations for image channel pointers and datatype
ChannelPtr<uchar> p1, p2;
int type;
// Note: IP_getChannel(I, ch, p1, type) gets pointer p1 of channel ch in image I.
// The pixel datatype (e.g., uchar, short, ...) of that channel is returned in type.
// It is ignored here since we assume that our input images consist exclusively of uchars.
// IP_getChannel() returns 1 when channel ch exists, 0 otherwise.
// visit all image channels and evaluate output image
for (int ch = 0; IP_getChannel(I1, ch, p1, type); ch++){
IP_getChannel(I2, ch, p2, type);
for (i = 0; i < total; i++)
*p2++ = lut[*p1++];
}
}
| [
"noreply@github.com"
] | noreply@github.com |
34a02695ecd26e91b99eabc50361629455509d09 | e398a585764f16511a70d0ef33a3b61da0733b69 | /7600.16385.1/src/wpd/WpdServiceSampleDriver/WpdServiceCapabilities.cpp | f000eae6984cd06abf49729b25363d0d28b44ffb | [
"MIT"
] | permissive | MichaelDavidGK/WinDDK | f9e4fc6872741ee742f8eace04b2b3a30b049495 | eea187e357d61569e67292ff705550887c4df908 | refs/heads/master | 2020-05-30T12:26:40.125588 | 2019-06-01T13:28:10 | 2019-06-01T13:28:10 | 189,732,991 | 0 | 0 | null | 2019-06-01T12:58:11 | 2019-06-01T12:58:11 | null | UTF-8 | C++ | false | false | 32,727 | cpp | #include "stdafx.h"
#include "WpdServiceCapabilities.tmh"
WpdServiceCapabilities::WpdServiceCapabilities() : m_pContactsService(NULL)
{
}
WpdServiceCapabilities::~WpdServiceCapabilities()
{
}
HRESULT WpdServiceCapabilities::Initialize(__in FakeContactsService* pContactsService)
{
if (pContactsService == NULL)
{
return E_POINTER;
}
m_pContactsService = pContactsService;
return S_OK;
}
HRESULT WpdServiceCapabilities::DispatchWpdMessage(
REFPROPERTYKEY Command,
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
HRESULT hr = S_OK;
if (Command.fmtid != WPD_CATEGORY_SERVICE_CAPABILITIES)
{
hr = E_INVALIDARG;
CHECK_HR(hr, "This object does not support this command category %ws",CComBSTR(Command.fmtid));
return hr;
}
if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_SUPPORTED_COMMANDS))
{
hr = OnGetSupportedCommands(pParams, pResults);
CHECK_HR(hr, "Failed to get supported commands");
}
else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_COMMAND_OPTIONS))
{
hr = OnGetCommandOptions(pParams, pResults);
CHECK_HR(hr, "Failed to get command options");
}
else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_SUPPORTED_METHODS))
{
hr = OnGetSupportedMethods(pParams, pResults);
CHECK_HR(hr, "Failed to get supported methods");
}
else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_SUPPORTED_METHODS_BY_FORMAT))
{
hr = OnGetSupportedMethodsByFormat(pParams, pResults);
CHECK_HR(hr, "Failed to get supported methods by format");
}
else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_METHOD_ATTRIBUTES))
{
hr = OnGetMethodAttributes(pParams, pResults);
CHECK_HR(hr, "Failed to get method attributes");
}
else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_METHOD_PARAMETER_ATTRIBUTES))
{
hr = OnGetMethodParameterAttributes(pParams, pResults);
CHECK_HR(hr, "Failed to get method parameter attributes");
}
else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_SUPPORTED_FORMATS))
{
hr = OnGetSupportedFormats(pParams, pResults);
CHECK_HR(hr, "Failed to get supported formats");
}
else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_FORMAT_ATTRIBUTES))
{
hr = OnGetFormatAttributes(pParams, pResults);
CHECK_HR(hr, "Failed to get format attributes");
}
else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_SUPPORTED_FORMAT_PROPERTIES))
{
hr = OnGetSupportedFormatProperties(pParams, pResults);
CHECK_HR(hr, "Failed to get supported format properties");
}
else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_FORMAT_PROPERTY_ATTRIBUTES))
{
hr = OnGetFormatPropertyAttributes(pParams, pResults);
CHECK_HR(hr, "Failed to get format property attributes");
}
else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_SUPPORTED_EVENTS))
{
hr = OnGetSupportedEvents(pParams, pResults);
CHECK_HR(hr, "Failed to get supported events");
}
else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_EVENT_ATTRIBUTES))
{
hr = OnGetEventAttributes(pParams, pResults);
CHECK_HR(hr, "Failed to get event attributes");
}
else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_EVENT_PARAMETER_ATTRIBUTES))
{
hr = OnGetEventParameterAttributes(pParams, pResults);
CHECK_HR(hr, "Failed to get event parameter attributes");
}
else if (IsEqualPropertyKey(Command, WPD_COMMAND_SERVICE_CAPABILITIES_GET_INHERITED_SERVICES))
{
hr = OnGetInheritedServices(pParams, pResults);
CHECK_HR(hr, "Failed to get inherited services");
}
else
{
hr = E_NOTIMPL;
CHECK_HR(hr, "This object does not support this command id %d", Command.pid);
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_SUPPORTED_COMMANDS
* command.
*
* The parameters sent to us are:
* - none.
*
* The driver should:
* - Return all commands supported by this service as an
* IPortableDeviceKeyCollection in WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_COMMANDS.
* This includes custom commands, if any.
*/
HRESULT WpdServiceCapabilities::OnGetSupportedCommands(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
UNREFERENCED_PARAMETER(pParams);
HRESULT hr = S_OK;
CComPtr<IPortableDeviceKeyCollection> pCommands;
// CoCreate a collection to store the supported commands.
if (hr == S_OK)
{
hr = CoCreateInstance(CLSID_PortableDeviceKeyCollection,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDeviceKeyCollection,
(VOID**) &pCommands);
CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceKeyCollection");
}
// Add the supported commands to the collection.
if (hr == S_OK)
{
hr = m_pContactsService->GetSupportedCommands(pCommands);
CHECK_HR(hr, "Failed to get the supported commands");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_COMMANDS value in the results.
if (hr == S_OK)
{
hr = pResults->SetIUnknownValue(WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_COMMANDS, pCommands);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_COMMANDS");
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_COMMAND_OPTIONS
* command.
*
* The parameters sent to us are:
* - WPD_PROPERTY_SERVICE_CAPABILITIES_COMMAND: a collection of property keys containing a single value,
* which identifies the specific command options are requested to return.
*
* The driver should:
* - Return an IPortableDeviceValues in WPD_PROPERTY_SERVICE_CAPABILITIES_COMMAND_OPTIONS, containing
* the relevant options. If no options are available for this command, the driver should
* return an IPortableDeviceValues with no elements in it.
*/
HRESULT WpdServiceCapabilities::OnGetCommandOptions(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
HRESULT hr = S_OK;
PROPERTYKEY Command = WPD_PROPERTY_NULL;
CComPtr<IPortableDeviceValues> pOptions;
// Get the command whose options have been requested
if (hr == S_OK)
{
hr = pParams->GetKeyValue(WPD_PROPERTY_SERVICE_CAPABILITIES_COMMAND, &Command);
CHECK_HR(hr, "Missing value for WPD_PROPERTY_SERVICE_CAPABILITIES_COMMAND");
}
// CoCreate a collection to store the command options.
if (hr == S_OK)
{
hr = CoCreateInstance(CLSID_PortableDeviceValues,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDeviceValues,
(VOID**) &pOptions);
CHECK_HR(hr, "Failed to CoCreateInstance CLSID_PortableDeviceValues");
}
// Add command options to the collection
if (hr == S_OK)
{
hr = m_pContactsService->GetCommandOptions(Command, pOptions);
CHECK_HR(hr, "Failed to get the command options");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_COMMAND_OPTIONS value in the results.
if (hr == S_OK)
{
hr = pResults->SetIUnknownValue(WPD_PROPERTY_SERVICE_CAPABILITIES_COMMAND_OPTIONS, pOptions);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_COMMAND_OPTIONS");
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_SUPPORTED_METHODS command.
*
* The parameters sent to us are:
* - none.
*
* The driver should:
* - Return all methods supported by this service as an
* IPortableDevicePropVariantCollection in WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_METHODS.
* If no methods are available for this service, the driver should return an IPortableDevicePropVariantCollection
* with no elements in it.
*/
HRESULT WpdServiceCapabilities::OnGetSupportedMethods(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
UNREFERENCED_PARAMETER(pParams);
CComPtr<IPortableDevicePropVariantCollection> pMethods;
// CoCreate a collection to store the supported methods.
HRESULT hr = CoCreateInstance(CLSID_PortableDevicePropVariantCollection,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDevicePropVariantCollection,
(VOID**) &pMethods);
CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDevicePropVariantCollection");
if (hr == S_OK)
{
hr = m_pContactsService->GetSupportedMethods(pMethods);
CHECK_HR(hr, "Failed to get the supported methods");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_METHODS value in the results.
if (hr == S_OK)
{
hr = pResults->SetIPortableDevicePropVariantCollectionValue(WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_METHODS, pMethods);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_METHODS");
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_SUPPORTED_METHODS_BY_FORMAT command.
*
* The parameters sent to us are:
* - WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT: Identifies the format whose methods are being requested
*
* The driver should:
* - Return an IPortableDevicePropVariantCollection in WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_METHODS,
* containing the supported methods that apply to this format. If no methods are available for this format,
* the driver should return an IPortableDevicePropVariantCollection with no elements in it.
*/
HRESULT WpdServiceCapabilities::OnGetSupportedMethodsByFormat(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
HRESULT hr = S_OK;
GUID Format = GUID_NULL;
CComPtr<IPortableDevicePropVariantCollection> pMethods;
// Get the format parameter
hr = pParams->GetGuidValue(WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT, &Format);
CHECK_HR(hr, "Failed to get WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT");
if (hr == S_OK)
{
// CoCreate a collection to store the supported methods.
hr = CoCreateInstance(CLSID_PortableDevicePropVariantCollection,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDevicePropVariantCollection,
(VOID**) &pMethods);
CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDevicePropVariantCollection");
}
if (hr == S_OK)
{
hr = m_pContactsService->GetSupportedMethodsByFormat(Format, pMethods);
CHECK_HR(hr, "Failed to get the supported methods by format");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_METHODS value in the results.
if (hr == S_OK)
{
hr = pResults->SetIPortableDevicePropVariantCollectionValue(WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_METHODS, pMethods);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_METHODS");
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_METHOD_ATTRIBUTES command.
*
* The parameters sent to us are:
* - WPD_PROPERTY_SERVICE_CAPABILITIES_METHOD: Identifies the method whose attributes are being requested
*
* The driver should:
* - Return an IPortableDeviceValues in WPD_PROPERTY_SERVICE_CAPABILITIES_METHOD_ATTRIBUTES, containing
* the method attributes. If no attributes are available for this method, the driver should
* return an IPortableDeviceValues with no elements in it.
*/
HRESULT WpdServiceCapabilities::OnGetMethodAttributes(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
HRESULT hr = S_OK;
GUID Method = GUID_NULL;
CComPtr<IPortableDeviceValues> pAttributes;
// Get the method
hr = pParams->GetGuidValue(WPD_PROPERTY_SERVICE_CAPABILITIES_METHOD, &Method);
CHECK_HR(hr, "Failed to get WPD_PROPERTY_SERVICE_CAPABILITIES_METHOD");
if (hr == S_OK)
{
// CoCreate a collection to store the method attributes.
hr = CoCreateInstance(CLSID_PortableDeviceValues,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDeviceValues,
(VOID**) &pAttributes);
CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues");
}
if (hr == S_OK)
{
hr = m_pContactsService->GetMethodAttributes(Method, pAttributes);
CHECK_HR(hr, "Failed to add method attributes");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_METHOD_ATTRIBUTES value in the results.
if (hr == S_OK)
{
hr = pResults->SetIPortableDeviceValuesValue(WPD_PROPERTY_SERVICE_CAPABILITIES_METHOD_ATTRIBUTES, pAttributes);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_METHODS");
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_METHOD_PARAMETER_ATTRIBUTES command.
*
* The parameters sent to us are:
* - WPD_PROPERTY_SERVICE_CAPABILITIES_PARAMETER: Identifies the parameter whose attributes are being requested
*
* The driver should:
* - Return an IPortableDeviceValues in WPD_PROPERTY_SERVICE_CAPABILITIES_METHOD_PARAMETER_ATTRIBUTES, containing
* the parameter attributes. If no attributes are available for this parameter, the driver should
* return an IPortableDeviceValues with no elements in it.
*/
HRESULT WpdServiceCapabilities::OnGetMethodParameterAttributes(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
HRESULT hr = S_OK;
PROPERTYKEY Parameter = WPD_PROPERTY_NULL;
CComPtr<IPortableDeviceValues> pAttributes;
// Get the method
hr = pParams->GetKeyValue(WPD_PROPERTY_SERVICE_CAPABILITIES_PARAMETER, &Parameter);
CHECK_HR(hr, "Failed to get WPD_PROPERTY_SERVICE_CAPABILITIES_PARAMETER");
if (hr == S_OK)
{
// CoCreate a collection to store the parameter attributes.
hr = CoCreateInstance(CLSID_PortableDeviceValues,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDeviceValues,
(VOID**) &pAttributes);
CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues");
}
if (hr == S_OK)
{
hr = m_pContactsService->GetMethodParameterAttributes(Parameter, pAttributes);
CHECK_HR(hr, "Failed to get the method parameter attributes");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_PARAMETER_ATTRIBUTES value in the results.
if (hr == S_OK)
{
hr = pResults->SetIPortableDeviceValuesValue(WPD_PROPERTY_SERVICE_CAPABILITIES_PARAMETER_ATTRIBUTES, pAttributes);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_PARAMETER_ATTRIBUTES");
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_SUPPORTED_FORMATS command.
*
* The parameters sent to us are:
* - None
*
* The driver should:
* - Return an IPortableDevicePropVariantCollection in WPD_PROPERTY_SERVICE_CAPABILITIES_FORMATS, containing
* the supported formats for the service. If no formats are supported by this service, the driver should
* return an IPortableDevicePropVariantCollection with no elements in it.
*/
HRESULT WpdServiceCapabilities::OnGetSupportedFormats(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
UNREFERENCED_PARAMETER(pParams);
CComPtr<IPortableDevicePropVariantCollection> pFormats;
// CoCreate a collection to store the formats.
HRESULT hr = CoCreateInstance(CLSID_PortableDevicePropVariantCollection,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDevicePropVariantCollection,
(VOID**) &pFormats);
CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDevicePropVariantCollection");
if (hr == S_OK)
{
hr = m_pContactsService->GetSupportedFormats(pFormats);
CHECK_HR(hr, "Failed to get the supported formats");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_FORMATS value in the results.
if (hr == S_OK)
{
hr = pResults->SetIPortableDevicePropVariantCollectionValue(WPD_PROPERTY_SERVICE_CAPABILITIES_FORMATS, pFormats);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_FORMATS");
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_FORMAT_ATTRIBUTES command.
*
* The parameters sent to us are:
* - WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT: Identifies the format whose attributes are being requested
*
* The driver should:
* - Return an IPortableDeviceValues in WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT_ATTRIBUTES, containing
* the attributes for the format. If no attributes are supported by the format, the driver should
* return an IPortableDeviceValues with no elements in it.
*/
HRESULT WpdServiceCapabilities::OnGetFormatAttributes(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
HRESULT hr = S_OK;
GUID Format = GUID_NULL;
CComPtr<IPortableDeviceValues> pAttributes;
// Get the format
hr = pParams->GetGuidValue(WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT, &Format);
CHECK_HR(hr, "Failed to get WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT");
if (hr == S_OK)
{
// CoCreate a collection to store the attributes.
hr = CoCreateInstance(CLSID_PortableDeviceValues,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDeviceValues,
(VOID**) &pAttributes);
CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues");
}
if (hr == S_OK)
{
hr = m_pContactsService->GetFormatAttributes(Format, pAttributes);
CHECK_HR(hr, "Failed to add format attributes");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT_ATTRIBUTES value in the results.
if (hr == S_OK)
{
hr = pResults->SetIPortableDeviceValuesValue(WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT_ATTRIBUTES, pAttributes);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT_ATTRIBUTES");
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_SUPPORTED_FORMAT_PROPERTIES command.
* This list is the super-set of all properties that will be supported by an object of the given format.
* Individual objects can be queried for their properties using WPD_COMMAND_OBJECT_PROPERTIES_GET_SUPPORTED.
* Note that this method is generally much quicker than calling WPD_COMMAND_OBJECT_PROPERTIES_GET_SUPPORTED,
* since the driver does not have to perform a dynamic lookup based on a specific object.
*
* The parameters sent to us are:
* - WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT: Identifies the format whose attributes are being requested
*
* The driver should:
* - Return an IPortableDeviceKeyCollection in WPD_PROPERTY_SERVICE_CAPABILITIES_PROPERTY_KEYS, containing
* the supported properties for the format. If no properties are supported by the format, the driver should
* return an IPortableDeviceKeyCollection with no elements in it.
*/
HRESULT WpdServiceCapabilities::OnGetSupportedFormatProperties(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
HRESULT hr = S_OK;
GUID Format = GUID_NULL;
CComPtr<IPortableDeviceKeyCollection> pKeys;
// Get the format
hr = pParams->GetGuidValue(WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT, &Format);
CHECK_HR(hr, "Failed to get WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT");
if (hr == S_OK)
{
// CoCreate a collection to store the attributes.
hr = CoCreateInstance(CLSID_PortableDeviceKeyCollection,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDeviceKeyCollection,
(VOID**) &pKeys);
CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceKeyCollection");
}
if (hr == S_OK)
{
hr = m_pContactsService->GetSupportedFormatProperties(Format, pKeys);
CHECK_HR(hr, "Failed to add the supported format properties");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_PROPERTY_KEYS value in the results.
if (hr == S_OK)
{
hr = pResults->SetIPortableDeviceKeyCollectionValue(WPD_PROPERTY_SERVICE_CAPABILITIES_PROPERTY_KEYS, pKeys);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_PROPERTY_KEYS");
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_FORMAT_PROPERTY_ATTRIBUTES command.
* Often, a driver treats objects of a given format the same. Many properties therefore will have attributes
* that are identical across all objects of that format. These can be returned here. There are some attributes
* which may be differ per object instance, which are not returned here. See WPD_COMMAND_OBJECT_PROPERTIES_GET_ATTRIBUTES.
*
* The parameters sent to us are:
* - WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT: Identifies the format whose property attributes are being requested
* - WPD_PROPERTY_SERVICE_CAPABILITIES_PROPERTY_KEYS: An IPortableDeviceKeyCollection containing a single value,
* which is the key identifying the specific property attributes the driver is requested to return.
*
* The driver should:
* - Return an IPortableDeviceValues in WPD_PROPERTY_SERVICE_CAPABILITIES_PROPERTY_ATTRIBUTES, containing
* the attributes for the property. If no attributes are supported by the property, the driver should
* return an IPortableDeviceValues with no elements in it.
*/
HRESULT WpdServiceCapabilities::OnGetFormatPropertyAttributes(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
HRESULT hr = S_OK;
GUID Format = GUID_NULL;
PROPERTYKEY Property = WPD_PROPERTY_NULL;
CComPtr<IPortableDeviceValues> pAttributes;
// Get the format
hr = pParams->GetGuidValue(WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT, &Format);
CHECK_HR(hr, "Failed to get WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT");
if (hr == S_OK)
{
// Get the property
hr = pParams->GetKeyValue(WPD_PROPERTY_SERVICE_CAPABILITIES_PROPERTY_KEYS, &Property);
CHECK_HR(hr, "Failed to get WPD_PROPERTY_SERVICE_CAPABILITIES_FORMAT");
}
if (hr == S_OK)
{
// CoCreate a collection to store the attributes.
hr = CoCreateInstance(CLSID_PortableDeviceValues,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDeviceValues,
(VOID**) &pAttributes);
CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues");
}
if (hr == S_OK)
{
hr = m_pContactsService->GetPropertyAttributes(Format, Property, pAttributes);
CHECK_HR(hr, "Failed to get the supported property attributes");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_PROPERTY_ATTRIBUTES value in the results.
if (hr == S_OK)
{
hr = pResults->SetIPortableDeviceValuesValue(WPD_PROPERTY_SERVICE_CAPABILITIES_PROPERTY_ATTRIBUTES, pAttributes);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_PROPERTY_ATTRIBUTES");
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_SUPPORTED_EVENTS command.
*
* The parameters sent to us are:
* - None
*
* The driver should:
* - Return an IPortableDevicePropVariantCollection in WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_EVENTS, containing
* the events for the service. If no events are supported by the service, the driver should
* return an IPortableDevicePropVariantCollection with no elements in it.
*/
HRESULT WpdServiceCapabilities::OnGetSupportedEvents(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
UNREFERENCED_PARAMETER(pParams);
CComPtr<IPortableDevicePropVariantCollection> pEvents;
// CoCreate a collection to store the supported events.
HRESULT hr = CoCreateInstance(CLSID_PortableDevicePropVariantCollection,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDevicePropVariantCollection,
(VOID**) &pEvents);
CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDevicePropVariantCollection");
// Add the supported events to the collection.
if (hr == S_OK)
{
hr = m_pContactsService->GetSupportedEvents(pEvents);
CHECK_HR(hr, "Failed to get the supported events");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_EVENTS value in the results.
if (hr == S_OK)
{
hr = pResults->SetIPortableDevicePropVariantCollectionValue(WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_EVENTS, pEvents);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_EVENTS");
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_EVENT_ATTRIBUTES command.
*
* The parameters sent to us are:
* - WPD_PROPERTY_SERVICE_CAPABILITIES_EVENT: Indicates the event the caller is interested in
*
* The driver should:
* - Return an IPortableDeviceValues in WPD_PROPERTY_SERVICE_CAPABILITIES_EVENT_ATTRIBUTES, containing
* the event attributes. If there are no attributes for that event, the driver should
* return an IPortableDeviceValues with no elements in it.
*/
HRESULT WpdServiceCapabilities::OnGetEventAttributes(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
HRESULT hr = S_OK;
GUID Event = GUID_NULL;
CComPtr<IPortableDeviceValues> pAttributes;
// Get the format
hr = pParams->GetGuidValue(WPD_PROPERTY_SERVICE_CAPABILITIES_EVENT, &Event);
CHECK_HR(hr, "Failed to get WPD_PROPERTY_SERVICE_CAPABILITIES_EVENT");
if (hr == S_OK)
{
// CoCreate a collection to store the attributes.
hr = CoCreateInstance(CLSID_PortableDeviceValues,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDeviceValues,
(VOID**) &pAttributes);
CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues");
}
if (hr == S_OK)
{
hr = m_pContactsService->GetEventAttributes(Event, pAttributes);
CHECK_HR(hr, "Failed to add event attributes");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_SUPPORTED_EVENTS value in the results.
if (hr == S_OK)
{
hr = pResults->SetIPortableDeviceValuesValue(WPD_PROPERTY_SERVICE_CAPABILITIES_EVENT_ATTRIBUTES, pAttributes);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_EVENT_ATTRIBUTES");
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_EVENT_PARAMETER_ATTRIBUTES command.
*
* The parameters sent to us are:
* - WPD_PROPERTY_SERVICE_CAPABILITIES_PARAMETER: Identifies the parameter whose attributes are being requested
*
* The driver should:
* - Return an IPortableDeviceValues in WPD_PROPERTY_SERVICE_CAPABILITIES_EVENT_PARAMETER_ATTRIBUTES, containing
* the parameter attributes. If no attributes are available for this parameter, the driver should
* return an IPortableDeviceValues with no elements in it.
*/
HRESULT WpdServiceCapabilities::OnGetEventParameterAttributes(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
HRESULT hr = S_OK;
PROPERTYKEY Parameter = WPD_PROPERTY_NULL;
CComPtr<IPortableDeviceValues> pAttributes;
// Get the method
hr = pParams->GetKeyValue(WPD_PROPERTY_SERVICE_CAPABILITIES_PARAMETER, &Parameter);
CHECK_HR(hr, "Failed to get WPD_PROPERTY_SERVICE_CAPABILITIES_PARAMETER");
if (hr == S_OK)
{
// CoCreate a collection to store the parameter attributes.
hr = CoCreateInstance(CLSID_PortableDeviceValues,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDeviceValues,
(VOID**) &pAttributes);
CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDeviceValues");
}
if (hr == S_OK)
{
hr = m_pContactsService->GetEventParameterAttributes(Parameter, pAttributes);
CHECK_HR(hr, "Failed to get the event parameter attributes");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_PARAMETER_ATTRIBUTES value in the results.
if (hr == S_OK)
{
hr = pResults->SetIPortableDeviceValuesValue(WPD_PROPERTY_SERVICE_CAPABILITIES_PARAMETER_ATTRIBUTES, pAttributes);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_PARAMETER_ATTRIBUTES");
}
return hr;
}
/**
* This method is called when we receive a WPD_COMMAND_SERVICE_CAPABILITIES_GET_INHERITED_SERVICES command.
*
* The parameters sent to us are:
* - WPD_PROPERTY_SERVICE_CAPABILITIES_INHERITANCE_TYPE: Indicates the inheritance type the caller is interested in
* Possible values are from the WPD_SERVICE_INHERITANCE_TYPES enumeration
*
* The driver should:
* - Return an IPortableDevicePropVariantCollection in WPD_PROPERTY_SERVICE_CAPABILITIES_INHERITED_SERVICES, containing
* the inherited services. For WPD_SERVICE_INHERITANCE_IMPLEMENTATION, this will be an
* IPortableDevicePropVariantCollection (of type VT_CLSID) containing the inherited service type GUIDs.
* If there are no inherited services, the driver should return an IPortableDevicePropVariantCollection with no elements in it.
*/
HRESULT WpdServiceCapabilities::OnGetInheritedServices(
__in IPortableDeviceValues* pParams,
__out IPortableDeviceValues* pResults)
{
HRESULT hr = S_OK;
DWORD dwInheritanceType = 0;
CComPtr<IPortableDevicePropVariantCollection> pServices;
hr = pParams->GetUnsignedIntegerValue(WPD_PROPERTY_SERVICE_CAPABILITIES_INHERITANCE_TYPE, &dwInheritanceType);
CHECK_HR(hr, "Failed to get WPD_PROPERTY_SERVICE_CAPABILITIES_INHERITANCE_TYPE");
if (hr == S_OK)
{
// CoCreate a collection to store the attributes.
hr = CoCreateInstance(CLSID_PortableDevicePropVariantCollection,
NULL,
CLSCTX_INPROC_SERVER,
IID_IPortableDevicePropVariantCollection,
(VOID**) &pServices);
CHECK_HR(hr, "Failed to CoCreate CLSID_PortableDevicePropVariantCollection");
}
if (hr == S_OK)
{
hr = m_pContactsService->GetInheritedServices(dwInheritanceType, pServices);
CHECK_HR(hr, "Failed to add inherited services");
}
// Set the WPD_PROPERTY_SERVICE_CAPABILITIES_INHERITED_SERVICES value in the results.
if (hr == S_OK)
{
hr = pResults->SetIPortableDevicePropVariantCollectionValue(WPD_PROPERTY_SERVICE_CAPABILITIES_INHERITED_SERVICES, pServices);
CHECK_HR(hr, "Failed to set WPD_PROPERTY_SERVICE_CAPABILITIES_EVENT_ATTRIBUTES");
}
return hr;
}
| [
"blindtiger@foxmail.com"
] | blindtiger@foxmail.com |
cc5f2b81863c1d08dfbbc13999ec3ea7ab3a0cb0 | 4d47c7b9100929452a57e9f9b106062abc1978e4 | /01_generate_pattern/05_1_singleton/ConfigurableRecordFinder.cpp | 084b6e9121291b4f89c16cda0ba5eefb01b75034 | [] | no_license | sy-soons/design_pattern_cpp | 3a32e05395ebce4df6c49ccd2e07fa46c46cf1f2 | 63b5a482f675e15216045cf65cce66125bfc872f | refs/heads/master | 2021-05-20T23:34:19.625200 | 2019-10-27T08:01:15 | 2019-10-27T08:01:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 314 | cpp | #include "ConfigurableRecordFinder.h"
ConfigurableRecordFinder::ConfigurableRecordFinder(Database& db)
:db(db)
{
}
int ConfigurableRecordFinder::total_population(std::vector<std::string>& names)
{
int result = 0;
for(auto& name: names)
result += db.get_population(name);
return result;
}
| [
"soonyoung87@gmail.com"
] | soonyoung87@gmail.com |
ce4efd4b2fc9c0b54ea0b8c6d25094f5d3e2fb70 | d0f37e29d49d76f15773f7d48fe3fa5f426de8f0 | /src/core/environ/ui/GlobalPreferenceForm.cpp | 42fe3bf4b3e6cb03380c66b074e5ec75772fee34 | [
"LicenseRef-scancode-warranty-disclaimer",
"Zlib",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Libpng",
"BSD-2-Clause-Views",
"FTL",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | SakuyaPrs/kirikiroid2lite | 6898334ccceb5c911662e8062101daab73e15887 | ee5890cf5b9714a9348cb6dd8fdbb0a7304c2cbe | refs/heads/master | 2022-12-07T08:54:18.618074 | 2020-09-02T04:17:21 | 2020-09-02T04:17:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,840 | cpp | #include <vector>
#include "GlobalPreferenceForm.h"
#include "ConfigManager/LocaleConfigManager.h"
#include "ui/UIButton.h"
#include "cocos2d/MainScene.h"
#include "ui/UIListView.h"
#include "ConfigManager/GlobalConfigManager.h"
#include "platform/CCFileUtils.h"
#include "Platform.h"
using namespace cocos2d;
using namespace cocos2d::ui;
#define GLOBAL_PREFERENCE
const char * const FileName_NaviBar = "ui/NaviBar.csb";
const char * const FileName_Body = "ui/ListView.csb";
static bool PreferenceGetValueBool(const std::string &name, bool defval) {
return GlobalConfigManager::GetInstance()->GetValue<bool>(name, defval);
}
static void PreferenceSetValueBool(const std::string &name, bool v) {
GlobalConfigManager::GetInstance()->SetValueInt(name, v);
}
static std::string PreferenceGetValueString(const std::string &name, const std::string& defval) {
return GlobalConfigManager::GetInstance()->GetValue<std::string>(name, defval);
}
static void PreferenceSetValueString(const std::string &name, const std::string& v) {
GlobalConfigManager::GetInstance()->SetValue(name, v);
}
static float PreferenceGetValueFloat(const std::string &name, float defval) {
return GlobalConfigManager::GetInstance()->GetValue<float>(name, defval);
}
static void PreferenceSetValueFloat(const std::string &name, float v) {
GlobalConfigManager::GetInstance()->SetValueFloat(name, v);
}
#include "PreferenceConfig.h"
TVPGlobalPreferenceForm * TVPGlobalPreferenceForm::create(const tPreferenceScreen *config) {
Initialize();
if (!config) config = &RootPreference;
TVPGlobalPreferenceForm *ret = new TVPGlobalPreferenceForm();
ret->autorelease();
ret->initFromFile(FileName_NaviBar, FileName_Body, nullptr);
PrefListSize = ret->PrefList->getContentSize();
ret->initPref(config);
ret->setOnExitCallback(std::bind(&GlobalConfigManager::SaveToFile, GlobalConfigManager::GetInstance()));
return ret;
}
static void WalkConfig(tPreferenceScreen* pref) {
//for (iTVPPreferenceInfo* info : pref->Preferences) {
auto& list = pref->Preferences;
for (auto p_info = list.begin(); p_info != list.end(); ++p_info)
{
const auto& info = *p_info;
info->InitDefaultConfig();
tPreferenceScreen* subpref = info->GetSubScreenInfo();
if (subpref) {
WalkConfig(subpref);
}
}
}
void TVPGlobalPreferenceForm::Initialize()
{
static bool Inited = false;
if (!Inited) {
Inited = true;
if (!GlobalConfigManager::GetInstance()->IsValueExist("GL_EXT_shader_framebuffer_fetch")) {
// disable GL_EXT_shader_framebuffer_fetch normally for adreno GPU
if (strstr((const char*)glGetString(GL_RENDERER), "Adreno")) {
GlobalConfigManager::GetInstance()->SetValueInt("GL_EXT_shader_framebuffer_fetch", 0);
}
}
initAllConfig();
WalkConfig(&RootPreference);
WalkConfig(&SoftRendererOptPreference);
WalkConfig(&OpenglOptPreference);
}
}
| [
"weimingtom@163.com"
] | weimingtom@163.com |
6ebb9b8214c5b0873895013f3acc35672636ed55 | 22ac3f7ee206e8d5e2e0cf727958fd5a93d33d67 | /TFM/Device/BleControllerFactory.cpp | 80cf179515eeb95c84761977cb17fb982d42ed7d | [] | no_license | dmmontes/BleDeviceController | 756dfb618561af1c3449daca92e210697ae9285e | 8b116cebb28c0dd80fa38ddf3f58cc3b28a1f048 | refs/heads/main | 2023-02-05T19:23:47.098847 | 2020-12-25T10:39:26 | 2020-12-27T16:10:42 | 308,870,485 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,566 | cpp | #include "BleControllerFactory.h"
#include "DeviceLogger.h"
#include "BleMouseController.h"
#include "BleGamepadController.h"
namespace Ble
{
IBleController *BleControllerFactory::createBleController(BleType type, String name, bool useSecurity)
{
LOG_DEBUG(String("BleControllerFactory::createBleController() BleType: ") + String(static_cast<uint8_t>(type)));
if (bleController_)
{
LOG_WARNING("BleControllerFactory::createBleController() Previouse Ble Controller should be destroyed before");
return nullptr;
}
switch (type)
{
case BleControllerFactory::BleType::MOUSE:
bleController_ = new BleMouseController(name, useSecurity);
break;
case BleControllerFactory::BleType::GAMEPAD:
bleController_ = new BleGamepadController(name, useSecurity);
break;
default:
LOG_WARNING("BleControllerFactory::createBleController() Unknown specified type");
break;
}
return bleController_;
}
void BleControllerFactory::deleteBleController(IBleController *bleController)
{
LOG_DEBUG("BleControllerFactory::deleteBleController()");
if (bleController != bleController_)
{
LOG_WARNING("BleControllerFactory::deleteBleController() Ble Controller different from created previously");
return;
}
// free(bleController_);
delete bleController_;
bleController_ = nullptr;
}
} // namespace Ble
| [
"dmmontes@uoc.com"
] | dmmontes@uoc.com |
ceba2b921c8d0cb31a032a54c5871f1477278655 | 0494c9caa519b27f3ed6390046fde03a313d2868 | /src/chrome/browser/chromeos/enrollment_dialog_view.cc | 31e3762de60d2589edb619769e7d77428256dd11 | [
"BSD-3-Clause"
] | permissive | mhcchang/chromium30 | 9e9649bec6fb19fe0dc2c8b94c27c9d1fa69da2c | 516718f9b7b95c4280257b2d319638d4728a90e1 | refs/heads/master | 2023-03-17T00:33:40.437560 | 2017-08-01T01:13:12 | 2017-08-01T01:13:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,494 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/enrollment_dialog_view.h"
#include "base/bind.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "content/public/common/page_transition_types.h"
#include "extensions/common/constants.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
namespace chromeos {
namespace {
// Default width/height of the dialog.
const int kDefaultWidth = 350;
const int kDefaultHeight = 100;
////////////////////////////////////////////////////////////////////////////////
// Dialog for certificate enrollment. This displays the content from the
// certificate enrollment URI.
class EnrollmentDialogView : public views::DialogDelegateView {
public:
virtual ~EnrollmentDialogView();
static void ShowDialog(gfx::NativeWindow owning_window,
const std::string& network_name,
Profile* profile,
const GURL& target_uri,
const base::Closure& connect);
// views::DialogDelegateView overrides
virtual int GetDialogButtons() const OVERRIDE;
virtual bool Accept() OVERRIDE;
virtual void OnClosed() OVERRIDE;
virtual string16 GetDialogButtonLabel(ui::DialogButton button) const OVERRIDE;
// views::WidgetDelegate overrides
virtual ui::ModalType GetModalType() const OVERRIDE;
virtual string16 GetWindowTitle() const OVERRIDE;
// views::View overrides
virtual gfx::Size GetPreferredSize() OVERRIDE;
private:
EnrollmentDialogView(const std::string& network_name,
Profile* profile,
const GURL& target_uri,
const base::Closure& connect);
void InitDialog();
bool accepted_;
std::string network_name_;
Profile* profile_;
GURL target_uri_;
base::Closure connect_;
bool added_cert_;
};
////////////////////////////////////////////////////////////////////////////////
// EnrollmentDialogView implementation.
EnrollmentDialogView::EnrollmentDialogView(const std::string& network_name,
Profile* profile,
const GURL& target_uri,
const base::Closure& connect)
: accepted_(false),
network_name_(network_name),
profile_(profile),
target_uri_(target_uri),
connect_(connect),
added_cert_(false) {
}
EnrollmentDialogView::~EnrollmentDialogView() {
}
// static
void EnrollmentDialogView::ShowDialog(gfx::NativeWindow owning_window,
const std::string& network_name,
Profile* profile,
const GURL& target_uri,
const base::Closure& connect) {
EnrollmentDialogView* dialog_view =
new EnrollmentDialogView(network_name, profile, target_uri, connect);
views::DialogDelegate::CreateDialogWidget(dialog_view, NULL, owning_window);
dialog_view->InitDialog();
views::Widget* widget = dialog_view->GetWidget();
DCHECK(widget);
widget->Show();
}
int EnrollmentDialogView::GetDialogButtons() const {
return ui::DIALOG_BUTTON_CANCEL | ui::DIALOG_BUTTON_OK;
}
bool EnrollmentDialogView::Accept() {
accepted_ = true;
return true;
}
void EnrollmentDialogView::OnClosed() {
if (!accepted_)
return;
chrome::NavigateParams params(profile_,
GURL(target_uri_),
content::PAGE_TRANSITION_LINK);
params.disposition = NEW_FOREGROUND_TAB;
params.window_action = chrome::NavigateParams::SHOW_WINDOW;
chrome::Navigate(¶ms);
}
string16 EnrollmentDialogView::GetDialogButtonLabel(
ui::DialogButton button) const {
if (button == ui::DIALOG_BUTTON_OK)
return l10n_util::GetStringUTF16(IDS_NETWORK_ENROLLMENT_HANDLER_BUTTON);
return views::DialogDelegateView::GetDialogButtonLabel(button);
}
ui::ModalType EnrollmentDialogView::GetModalType() const {
return ui::MODAL_TYPE_SYSTEM;
}
string16 EnrollmentDialogView::GetWindowTitle() const {
return l10n_util::GetStringUTF16(IDS_NETWORK_ENROLLMENT_HANDLER_TITLE);
}
gfx::Size EnrollmentDialogView::GetPreferredSize() {
return gfx::Size(kDefaultWidth, kDefaultHeight);
}
void EnrollmentDialogView::InitDialog() {
added_cert_ = false;
// Create the views and layout manager and set them up.
views::Label* label = new views::Label(
l10n_util::GetStringFUTF16(IDS_NETWORK_ENROLLMENT_HANDLER_INSTRUCTIONS,
UTF8ToUTF16(network_name_)));
label->SetFont(ui::ResourceBundle::GetSharedInstance().GetFont(
ui::ResourceBundle::BaseFont));
label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
label->SetMultiLine(true);
label->SetAllowCharacterBreak(true);
views::GridLayout* grid_layout = views::GridLayout::CreatePanel(this);
SetLayoutManager(grid_layout);
views::ColumnSet* columns = grid_layout->AddColumnSet(0);
columns->AddColumn(views::GridLayout::FILL, // Horizontal resize.
views::GridLayout::FILL, // Vertical resize.
1, // Resize weight.
views::GridLayout::USE_PREF, // Size type.
0, // Ignored for USE_PREF.
0); // Minimum size.
columns = grid_layout->AddColumnSet(1);
columns->AddPaddingColumn(
0, views::kUnrelatedControlHorizontalSpacing);
columns->AddColumn(views::GridLayout::LEADING, // Horizontal leading.
views::GridLayout::FILL, // Vertical resize.
1, // Resize weight.
views::GridLayout::USE_PREF, // Size type.
0, // Ignored for USE_PREF.
0); // Minimum size.
grid_layout->StartRow(0, 0);
grid_layout->AddView(label);
grid_layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);
grid_layout->Layout(this);
}
////////////////////////////////////////////////////////////////////////////////
// Handler for certificate enrollment.
class DialogEnrollmentDelegate : public EnrollmentDelegate {
public:
// |owning_window| is the window that will own the dialog.
explicit DialogEnrollmentDelegate(gfx::NativeWindow owning_window,
const std::string& network_name,
Profile* profile);
virtual ~DialogEnrollmentDelegate();
// EnrollmentDelegate overrides
virtual void Enroll(const std::vector<std::string>& uri_list,
const base::Closure& connect) OVERRIDE;
private:
gfx::NativeWindow owning_window_;
std::string network_name_;
Profile* profile_;
DISALLOW_COPY_AND_ASSIGN(DialogEnrollmentDelegate);
};
DialogEnrollmentDelegate::DialogEnrollmentDelegate(
gfx::NativeWindow owning_window,
const std::string& network_name,
Profile* profile) : owning_window_(owning_window),
network_name_(network_name),
profile_(profile) {}
DialogEnrollmentDelegate::~DialogEnrollmentDelegate() {}
void DialogEnrollmentDelegate::Enroll(const std::vector<std::string>& uri_list,
const base::Closure& connect) {
// Keep the closure for later activation if we notice that
// a certificate has been added.
// TODO(gspencer): Do something smart with the closure. At the moment it is
// being ignored because we don't know when the enrollment tab is closed.
// http://crosbug.com/30422
for (std::vector<std::string>::const_iterator iter = uri_list.begin();
iter != uri_list.end(); ++iter) {
GURL uri(*iter);
if (uri.IsStandard() || uri.scheme() == extensions::kExtensionScheme) {
// If this is a "standard" scheme, like http, ftp, etc., then open that in
// the enrollment dialog.
EnrollmentDialogView::ShowDialog(owning_window_,
network_name_,
profile_,
uri, connect);
return;
}
}
// If we didn't find a scheme we could handle, then don't continue connecting.
// TODO(gspencer): provide a path to display this failure to the user. (but
// for the most part they won't know what it means, since it's probably coming
// from a policy-pushed ONC file).
VLOG(1) << "Couldn't find usable scheme in enrollment URI(s)";
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// Factory function.
EnrollmentDelegate* CreateEnrollmentDelegate(gfx::NativeWindow owning_window,
const std::string& network_name,
Profile* profile) {
return new DialogEnrollmentDelegate(owning_window, network_name, profile);
}
} // namespace chromeos
| [
"1990zhaoshuang@163.com"
] | 1990zhaoshuang@163.com |
c3cb86201bbe3fbe3d35b576b13493b6a0d0ec57 | b9aefd4a8eee89bdfa0f229f3fcf366f5cfff7c5 | /Math/Point.cpp | 845cfd17f7c2c1b946d1dcd6fce6fcbcf4af6619 | [] | no_license | AlexNewtown/raytrace | 2f201fd5732c86f6537d9ff88c648aa9796762d7 | 36067839fc73679ab02d781b4cd0e98ae52b8e74 | refs/heads/master | 2022-12-24T11:38:45.416393 | 2020-09-14T02:49:33 | 2020-09-14T02:49:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,355 | cpp | #include "Math/Point.hpp"
#include "Math/Vector.hpp"
#include "Math/Transformation.hpp"
namespace Math {
Point::Point()
{
mX = mY = mZ = 0;
}
Point::Point(float x, float y, float z)
{
mX = x;
mY = y;
mZ = z;
}
Point::Point(const Vector &c)
{
mX = c.x();
mY = c.y();
mZ = c.z();
}
float Point::x() const
{
return mX;
}
float Point::y() const
{
return mY;
}
float Point::z() const
{
return mZ;
}
Point Point::operator+(const Vector &b) const
{
return Point(x() + b.x(), y() + b.y(), z() + b.z());
}
Point Point::operator-(const Vector &b) const
{
return Point(x() - b.x(), y() - b.y(), z() - b.z());
}
Vector Point::operator-(const Point &b) const
{
return Vector(x() - b.x(), y() - b.y(), z() - b.z());
}
Point operator*(const BaseTransformation &transformation, const Point &point)
{
return Point(transformation.matrix() * point);
}
Point operator*(const Matrix &matrix, const Point &point)
{
if (matrix.identity()) return point;
float x = matrix(0, 0) * point.x() + matrix(1, 0) * point.y() + matrix(2, 0) * point.z() + matrix(3, 0);
float y = matrix(0, 1) * point.x() + matrix(1, 1) * point.y() + matrix(2, 1) * point.z() + matrix(3, 1);
float z = matrix(0, 2) * point.x() + matrix(1, 2) * point.y() + matrix(2, 2) * point.z() + matrix(3, 2);
return Point(x, y, z);
}
} | [
"mattfischer84@gmail.com"
] | mattfischer84@gmail.com |
97c57914a998c5fd73ee91908b9f3ea8db195c63 | dff9183973f39fef1576cb30646770afaec62ad1 | /VideoRouter(Matrix.Redesigned2016.06.28)/VideoRouter(Matrix.Redesigned)/VideoRouter/InitialManager.h | 01fa241e5e6ccea6898afd6b44f5b5d482935bb8 | [] | no_license | nkjpj/RibbonUIDemo | 07590d60d46c3b1fb4d480ee16e969066b96243b | 9be534f7083600e10339800ef1c57be3ea5c57b1 | refs/heads/master | 2020-09-03T17:52:43.297107 | 2019-03-18T23:20:07 | 2019-03-18T23:20:07 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,026 | h | #pragma once
//******************************************
// CInitialManager
// 初始化事务管理器
//
class CInitialManager : public CObject
{
friend class CGlobalManager;
public:
CInitialManager();
virtual ~CInitialManager();
/* 初始化各管理器{全局事务管理器、通信事务管理器、输入管理器、输出管理器等} */
void InitManagers();
/* 释放内存资源 */
void ReleaseManagers();
/* 设置事务类型 , 在调用事务处理线程之前(BeginTransaction函数),先设置事务类型 */
void SetTransactionType(const emTransaction eTransaction);
/* 特殊事务处理 */
BOOL BeginTransaction(BOOL bShowWaitWnd);
void EndTransacation();
/* 设置初始化标志量,在每次连接初始化完毕后设为TRUE,每次断开连接后设为FALSE */
void SetInitializedFlag(BOOL bInit);
BOOL GetInitializedFlag() const;
private:
emTransaction m_eTransaction;
BOOL m_bInitialized; //程序已通过连接初始化过。
};
extern CInitialManager *pInitManager; | [
"hongyb_1999@163.com"
] | hongyb_1999@163.com |
546b09d0a3274fb6d06ee78fd39a2b3ff9fbaf4e | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/xbmc/2016/4/PeripheralBus.cpp | b58696b87324874c574301360cd934bbdc7419ba | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 10,134 | cpp | /*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* 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, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "PeripheralBus.h"
#include "guilib/LocalizeStrings.h"
#include "peripherals/Peripherals.h"
#include "peripherals/devices/Peripheral.h"
#include "utils/StringUtils.h"
#include "utils/Variant.h"
#include "utils/log.h"
#include "FileItem.h"
using namespace PERIPHERALS;
#define PERIPHERAL_DEFAULT_RESCAN_INTERVAL 5000
CPeripheralBus::CPeripheralBus(const std::string &threadname, CPeripherals *manager, PeripheralBusType type) :
CThread(threadname.c_str()),
m_iRescanTime(PERIPHERAL_DEFAULT_RESCAN_INTERVAL),
m_bInitialised(false),
m_bIsStarted(false),
m_bNeedsPolling(true),
m_manager(manager),
m_type(type),
m_triggerEvent(true)
{
}
void CPeripheralBus::OnDeviceAdded(const std::string &strLocation)
{
ScanForDevices();
}
void CPeripheralBus::OnDeviceChanged(const std::string &strLocation)
{
ScanForDevices();
}
void CPeripheralBus::OnDeviceRemoved(const std::string &strLocation)
{
ScanForDevices();
}
void CPeripheralBus::Clear(void)
{
{
CSingleLock lock(m_critSection);
if (m_bNeedsPolling)
{
m_bStop = true;
lock.Leave();
m_triggerEvent.Set();
StopThread(true);
}
}
CSingleLock lock(m_critSection);
for (unsigned int iPeripheralPtr = 0; iPeripheralPtr < m_peripherals.size(); iPeripheralPtr++)
delete m_peripherals.at(iPeripheralPtr);
m_peripherals.clear();
}
void CPeripheralBus::UnregisterRemovedDevices(const PeripheralScanResults &results)
{
CSingleLock lock(m_critSection);
std::vector<CPeripheral *> removedPeripherals;
for (int iDevicePtr = (int) m_peripherals.size() - 1; iDevicePtr >= 0; iDevicePtr--)
{
CPeripheral *peripheral = m_peripherals.at(iDevicePtr);
PeripheralScanResult updatedDevice(m_type);
if (!results.GetDeviceOnLocation(peripheral->Location(), &updatedDevice) ||
*peripheral != updatedDevice)
{
/* device removed */
removedPeripherals.push_back(peripheral);
m_peripherals.erase(m_peripherals.begin() + iDevicePtr);
}
}
lock.Leave();
for (unsigned int iDevicePtr = 0; iDevicePtr < removedPeripherals.size(); iDevicePtr++)
{
CPeripheral *peripheral = removedPeripherals.at(iDevicePtr);
std::vector<PeripheralFeature> features;
peripheral->GetFeatures(features);
bool peripheralHasFeatures = features.size() > 1 || (features.size() == 1 && features.at(0) != FEATURE_UNKNOWN);
if (peripheral->Type() != PERIPHERAL_UNKNOWN || peripheralHasFeatures)
{
CLog::Log(LOGNOTICE, "%s - device removed from %s/%s: %s (%s:%s)", __FUNCTION__, PeripheralTypeTranslator::TypeToString(peripheral->Type()), peripheral->Location().c_str(), peripheral->DeviceName().c_str(), peripheral->VendorIdAsString(), peripheral->ProductIdAsString());
peripheral->OnDeviceRemoved();
}
m_manager->OnDeviceDeleted(*this, *peripheral);
delete peripheral;
}
}
void CPeripheralBus::RegisterNewDevices(const PeripheralScanResults &results)
{
CSingleLock lock(m_critSection);
for (unsigned int iResultPtr = 0; iResultPtr < results.m_results.size(); iResultPtr++)
{
const PeripheralScanResult& result = results.m_results.at(iResultPtr);
if (!HasPeripheral(result.m_strLocation))
g_peripherals.CreatePeripheral(*this, result);
}
}
bool CPeripheralBus::ScanForDevices(void)
{
bool bReturn(false);
PeripheralScanResults results;
if (PerformDeviceScan(results))
{
UnregisterRemovedDevices(results);
RegisterNewDevices(results);
CPeripherals::GetInstance().NotifyObservers(ObservableMessagePeripheralsChanged);
bReturn = true;
}
CSingleLock lock(m_critSection);
m_bInitialised = true;
return bReturn;
}
bool CPeripheralBus::HasFeature(const PeripheralFeature feature) const
{
bool bReturn(false);
CSingleLock lock(m_critSection);
for (unsigned int iPeripheralPtr = 0; iPeripheralPtr < m_peripherals.size(); iPeripheralPtr++)
{
if (m_peripherals.at(iPeripheralPtr)->HasFeature(feature))
{
bReturn = true;
break;
}
}
return bReturn;
}
void CPeripheralBus::GetFeatures(std::vector<PeripheralFeature> &features) const
{
CSingleLock lock(m_critSection);
for (unsigned int iPeripheralPtr = 0; iPeripheralPtr < m_peripherals.size(); iPeripheralPtr++)
m_peripherals.at(iPeripheralPtr)->GetFeatures(features);
}
CPeripheral *CPeripheralBus::GetPeripheral(const std::string &strLocation) const
{
CPeripheral *peripheral(NULL);
CSingleLock lock(m_critSection);
for (unsigned int iPeripheralPtr = 0; iPeripheralPtr < m_peripherals.size(); iPeripheralPtr++)
{
if (m_peripherals.at(iPeripheralPtr)->Location() == strLocation)
{
peripheral = m_peripherals.at(iPeripheralPtr);
break;
}
}
return peripheral;
}
int CPeripheralBus::GetPeripheralsWithFeature(std::vector<CPeripheral *> &results, const PeripheralFeature feature) const
{
int iReturn(0);
CSingleLock lock(m_critSection);
for (unsigned int iPeripheralPtr = 0; iPeripheralPtr < m_peripherals.size(); iPeripheralPtr++)
{
if (m_peripherals.at(iPeripheralPtr)->HasFeature(feature))
{
results.push_back(m_peripherals.at(iPeripheralPtr));
++iReturn;
}
}
return iReturn;
}
size_t CPeripheralBus::GetNumberOfPeripheralsWithId(const int iVendorId, const int iProductId) const
{
int iReturn(0);
CSingleLock lock(m_critSection);
for (unsigned int iPeripheralPtr = 0; iPeripheralPtr < m_peripherals.size(); iPeripheralPtr++)
{
if (m_peripherals.at(iPeripheralPtr)->VendorId() == iVendorId &&
m_peripherals.at(iPeripheralPtr)->ProductId() == iProductId)
iReturn++;
}
return iReturn;
}
void CPeripheralBus::Process(void)
{
while (!m_bStop)
{
m_triggerEvent.Reset();
if (!ScanForDevices())
break;
// depending on bus implementation
// needsPolling can be set properly
// only after unitial scan.
// if this is the case, bail out.
if (!m_bNeedsPolling)
break;
if (!m_bStop)
m_triggerEvent.WaitMSec(m_iRescanTime);
}
CSingleLock lock(m_critSection);
m_bIsStarted = false;
}
void CPeripheralBus::Initialise(void)
{
CSingleLock lock(m_critSection);
if (m_bIsStarted)
return;
m_bIsStarted = true;
if (m_bNeedsPolling)
{
lock.Leave();
m_triggerEvent.Reset();
Create();
SetPriority(-1);
}
}
void CPeripheralBus::Register(CPeripheral *peripheral)
{
if (!peripheral)
return;
CSingleLock lock(m_critSection);
if (!HasPeripheral(peripheral->Location()))
{
m_peripherals.push_back(peripheral);
CLog::Log(LOGNOTICE, "%s - new %s device registered on %s->%s: %s (%s:%s)", __FUNCTION__, PeripheralTypeTranslator::TypeToString(peripheral->Type()), PeripheralTypeTranslator::BusTypeToString(m_type), peripheral->Location().c_str(), peripheral->DeviceName().c_str(), peripheral->VendorIdAsString(), peripheral->ProductIdAsString());
lock.Leave();
m_manager->OnDeviceAdded(*this, *peripheral);
}
}
void CPeripheralBus::TriggerDeviceScan(void)
{
CSingleLock lock(m_critSection);
if (m_bNeedsPolling)
{
lock.Leave();
m_triggerEvent.Set();
}
else
{
lock.Leave();
ScanForDevices();
}
}
bool CPeripheralBus::HasPeripheral(const std::string &strLocation) const
{
return (GetPeripheral(strLocation) != NULL);
}
void CPeripheralBus::GetDirectory(const std::string &strPath, CFileItemList &items) const
{
std::string strDevPath;
CSingleLock lock(m_critSection);
for (unsigned int iDevicePtr = 0; iDevicePtr < m_peripherals.size(); iDevicePtr++)
{
const CPeripheral *peripheral = m_peripherals.at(iDevicePtr);
if (peripheral->IsHidden())
continue;
CFileItemPtr peripheralFile(new CFileItem(peripheral->DeviceName()));
peripheralFile->SetPath(peripheral->FileLocation());
peripheralFile->SetProperty("vendor", peripheral->VendorIdAsString());
peripheralFile->SetProperty("product", peripheral->ProductIdAsString());
peripheralFile->SetProperty("bus", PeripheralTypeTranslator::BusTypeToString(peripheral->GetBusType()));
peripheralFile->SetProperty("location", peripheral->Location());
peripheralFile->SetProperty("class", PeripheralTypeTranslator::TypeToString(peripheral->Type()));
std::string strVersion(peripheral->GetVersionInfo());
if (strVersion.empty())
strVersion = g_localizeStrings.Get(13205);
std::string strDetails = StringUtils::Format("%s %s", g_localizeStrings.Get(24051).c_str(), strVersion.c_str());
if (peripheral->GetBusType() == PERIPHERAL_BUS_CEC && !peripheral->GetSettingBool("enabled"))
strDetails = StringUtils::Format("%s: %s", g_localizeStrings.Get(126).c_str(), g_localizeStrings.Get(13106).c_str());
peripheralFile->SetProperty("version", strVersion);
peripheralFile->SetLabel2(strDetails);
peripheralFile->SetIconImage("DefaultAddon.png");
items.Add(peripheralFile);
}
}
CPeripheral *CPeripheralBus::GetByPath(const std::string &strPath) const
{
std::string strDevPath;
CSingleLock lock(m_critSection);
for (unsigned int iDevicePtr = 0; iDevicePtr < m_peripherals.size(); iDevicePtr++)
{
if (StringUtils::EqualsNoCase(strPath, m_peripherals.at(iDevicePtr)->FileLocation()))
return m_peripherals.at(iDevicePtr);
}
return NULL;
}
size_t CPeripheralBus::GetNumberOfPeripherals() const
{
CSingleLock lock(m_critSection);
return m_peripherals.size();
}
| [
"rodrigosoaresilva@gmail.com"
] | rodrigosoaresilva@gmail.com |
99dc50dc1099e0ebfb9ee3f669552176393004dd | cea43fb3c76b1b8e3bef3197c662d488017db7f9 | /ffmediaplayer/src/main/cpp/ffplayer/DecodeVideoElement.cpp | 5f256a22d3ae3c24f01580bbe6efe35d201f5e6c | [] | no_license | asdlei99/FFMediaPlayer | 2404336b45ac4913d40b85d3dcc2fe5dbc93633a | da99b7e5b2515478691f661f2868e501cc5015c8 | refs/heads/master | 2023-02-09T03:16:22.846165 | 2020-12-25T08:47:44 | 2020-12-25T08:47:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,242 | cpp | //
// Created by llm on 20-5-16.
//
#include <pthread.h>
#include "DecodeVideoElement.h"
#include "FFLog.h"
#include "macro.h"
extern "C" {
#include <libavutil/time.h>
}
void *video_decode_task_start(void *args) {
ALOGE("enter: %s", __PRETTY_FUNCTION__);
DecodeVideoElement *element = static_cast<DecodeVideoElement *>(args);
element ->_start();
return 0;//一定一定一定要返回0!!!
}
DecodeVideoElement::DecodeVideoElement() {
ALOGE("DecodeVideoElement::DecodeVideoElement()");
elementType = VIDEO_DECODER;
}
DecodeVideoElement::~DecodeVideoElement() {
ALOGE("DecodeVideoElement::~DecodeVideoElement() ");
if (mNotify != 0) {
mNotify = 0;
}
}
int DecodeVideoElement::open(PLAYER_PARAMETERS &avContext, notify_callback_f notifyFunc) {
mNotify = notifyFunc;
if (avContext.videoIndex == -1) {
ALOGE("不包含视频流");
return INVALID_OPERATION;
}
//获取媒体流(
AVStream *stream = avContext.formatContext->streams[avContext.videoIndex];
//获取编解码这段流的参数
AVCodecParameters *codecParameters = stream->codecpar;
ALOGE("解码 id :%d, type: %d", codecParameters->codec_id, codecParameters->codec_type);
//通过参数中的id(编解码的方式),来查找当前流的解码器
AVCodec *codec = avcodec_find_decoder(codecParameters->codec_id);
if (!codec) {
ALOGE("can't find video decoder");
mNotify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, FIND_DECODER_FAIL);
return FIND_DECODER_FAIL;
}
//创建解码器上下文
codecContext = avcodec_alloc_context3(codec);
if (!codecContext) {
ALOGE("创建解码器上下文失败");
mNotify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ALLOC_CODEC_CONTEXT_FAIL);
return ALLOC_CODEC_CONTEXT_FAIL;
}
//7 设置解码器上下文的参数
int ret = avcodec_parameters_to_context(codecContext, codecParameters);
if (ret < 0) {
ALOGE("设置解码器上下文的参数失败:%s", av_err2str(ret));
mNotify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, CODEC_CONTEXT_PARAMETERS_FAIL);
return CODEC_CONTEXT_PARAMETERS_FAIL;
}
//8 打开解码器
ret = avcodec_open2(codecContext, codec, 0);
if (ret) {
ALOGE("打开解码器失败:%s", av_err2str(ret));
mNotify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, OPEN_DECODER_FAIL);
return OPEN_DECODER_FAIL;
}
avContext.videoCodecContext = codecContext;
elementState = ELEMENT_STATE_OPEN;
return STATUS_OK;
}
int DecodeVideoElement::start() {
ALOGE("enter: DecodeVideoElement::start() state %d", elementState);
if (sinkPad == 0 || sourcePad == 0) {
ALOGE("sinkPad is 0");
return INVALID_OPERATION;
}
if (isPlaying == true && elementState == ELEMENT_STATE_PLAYING) {
ALOGE("enter: %s player has already started", __FUNCTION__);
return MEDIA_ALREAD_START;
}
isPlaying = true;
if (elementState != ELEMENT_STATE_PAUSE) {
pthread_create(&pid_start, 0, video_decode_task_start, this);
}
elementState = ELEMENT_STATE_PLAYING;
return STATUS_OK;
}
int DecodeVideoElement::pause() {
ALOGE("enter DecodeVideoElement::pause() state %d", elementState);
if (elementState == ELEMENT_STATE_PAUSE) {
return STATUS_OK;
} else if (elementState == ELEMENT_STATE_PLAYING) {
elementState = ELEMENT_STATE_PAUSE;
return STATUS_OK;
} else {
return INVALID_OPERATION;
}
}
int DecodeVideoElement::stop() {
ALOGE("enter DecodeVideoElement::stop()");
if (isPlaying) {
isPlaying = false;
//防止阻塞
if (sourcePad != 0 && sourcePad->hasObserver()) {
sourcePad->getObserver()->setRecivieData(false);
}
pthread_join(pid_start, 0);
}
//在start线程中会调用, 等线程结束后再删,防止线程冲突
if (sourcePad != 0) {
if (sourcePad->hasObserver()) {
sourcePad->setObserver(0);
}
delete sourcePad;
sourcePad = 0;
}
if (sinkPad != 0) {
delete sinkPad;
sinkPad = 0;
}
// if (codecContext) {
// avcodec_close(codecContext);
// avcodec_free_context(&codecContext);
// codecContext = 0;
// }
return 0;
}
int DecodeVideoElement::release() {
if (sinkPad != 0) {
delete sinkPad;
sinkPad = 0;
}
if (sourcePad != 0) {
delete sourcePad;
sourcePad = 0;
}
return 0;
}
int DecodeVideoElement::reset() {
return stop();
}
void DecodeVideoElement::connectPads(FFPad *sourcePad, FFPad *sinkPad) {
sourcePad->setObserver(sinkPad);
}
void DecodeVideoElement::addPad(FFPad* pad) {
// pads.push_back(pad);
if (pad->getPadType() == PAD_SINK) {
if (sinkPad != 0) {
delete sinkPad;
}
sinkPad = pad;
} else if (pad->getPadType() == PAD_SOURCE) {
if (sourcePad != 0) {
delete sourcePad;
}
sourcePad = pad;
}
}
void DecodeVideoElement::_start() {
ALOGE("enter: %s", __FUNCTION__);
while (isPlaying) {
if (elementState == ELEMENT_STATE_PAUSE) {
av_usleep(10 * 1000);
continue;
}
AVPacket* packet = (AVPacket *)sinkPad -> getData();
if (packet == 0) {
// ALOGE("DecodeVideoElement::_start packet is 0");
av_usleep(10 * 1000);
continue;
}
//拿到了视频数据包(编码压缩了的),需要把数据包给解码器进行解码
int ret = avcodec_send_packet(codecContext, packet);
if (ret != 0) {
//往解码器发送数据包失败,跳出循环
ALOGE("avcodec_send_packet fail %d", ret );
av_packet_free(&packet);//释放packet,后面不需要了
packet = 0;
mNotify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, PASER_PACKETS_FAIL);
break;
}
av_packet_free(&packet);//释放packet,后面不需要了
packet = 0;
AVFrame *frame = av_frame_alloc();
ret = avcodec_receive_frame(codecContext, frame);
if (ret == AVERROR(EAGAIN)) {
// AVERROR(EAGAIN)返回值意味着需要新的输入数据才能返回新的输出。
// 在解码或编码开始时,编解码器可能会接收多个输入帧/数据包而不返回帧,直到其内部缓冲区被填充为止
av_frame_free(&frame);
frame = 0;
continue;
} else if (ret != 0) {
ALOGE("avcodec_receive_frame fail %d", ret);
av_frame_free(&frame);
frame = 0;
mNotify(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, PASER_PACKETS_FAIL);
break;
}
if (sourcePad != 0 && sourcePad->hasObserver()) {
sourcePad->notify(frame);
} else {
av_frame_free(&frame);
frame = 0;
}
}
}
int DecodeVideoElement::setSurface(ANativeWindow *window) {
return INVALID_OPERATION;
}
bool DecodeVideoElement::isDataBufferEmpty() {
return sinkPad->isDataBufferEmpty();
}
| [
"liuliming@iviewdisplays.com"
] | liuliming@iviewdisplays.com |
6faf1d764b4b0985b9efe5c30e3e8b7ecc160141 | 2c958f648b16a64e2790e79d73e5b2847873d6b3 | /chapter3/3.16.cpp | 5425c2f04464af3d13fa4776e0f6e7511cf4a0e4 | [] | no_license | Ashlyn-star/C-primer | 5c65851ff13dbbe3bbc4db5a1da65f6b3865339b | 23577592f9051567567dfe25386e00468271b138 | refs/heads/main | 2023-07-11T09:27:11.861747 | 2021-08-13T07:20:23 | 2021-08-13T07:20:23 | 361,659,770 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 898 | cpp | #include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main() {
vector<int> v1;
vector<int> v2(10);
vector<int> v3(10,42);
vector<int> v4{ 10 };
vector<int> v5{ 10,42 };
vector<string> v6{ 10 };
vector<string> v7{ 10,"hi" };
cout << "v1"<<v1.size() << endl;
for (auto c : v1) {
cout << c << endl;
}
cout << "v2" << v2.size() << endl;
for (auto c : v2) {
cout << c << endl;
}
cout << "v3" << v3.size() << endl;
for (auto c : v3) {
cout << c << endl;
}
cout << "v4" << v4.size() << endl;
for (auto c : v4) {
cout << c << endl;
}
cout << "v5" << v5.size() << endl;
for (auto c : v5) {
cout << c << endl;
}
cout << "v6" << v6.size() << endl;
for (auto c : v6) {
cout << c << endl;
}
cout << "v7" << v7.size() << endl;
for (auto c : v7) {
cout << c << endl;
}
} | [
"214625132@qq.com"
] | 214625132@qq.com |
cf854584aa745b567bfeab82c2ec4125ed816144 | 7222f5f82cff1e39202677b770458527d4cb04ea | /Gui_Core/src/DefaultButton.cpp | 13301fcd9e767a33cacac193ad4007728accaea1 | [] | no_license | EasyToFindName/Gui_Core | 14022f76c2a309d3eef03445fd02109942b1efae | d0786a50913e394a6670d6192d85ac3901100b0c | refs/heads/master | 2020-03-21T20:51:20.399790 | 2018-09-23T12:43:03 | 2018-09-23T12:43:03 | 139,032,706 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,374 | cpp | #include "DefaultButton.h"
#include <iostream>
DefaultButton::DefaultButton(Container* parent)
: GuiActiveElem(parent), m_region(parent), m_text(nullptr) {
m_region.setFillColor(sf::Color(60, 60, 60, 192));
}
DefaultButton::DefaultButton(Container* parent, float width, float height)
: GuiActiveElem(parent), m_region(parent, width, height), m_text(nullptr) {
m_region.setFillColor(sf::Color(60, 60, 60, 192));
}
bool DefaultButton::isPointInside(float x, float y) {
sf::FloatRect bounds(m_region.getPosition(), m_region.getSize());
return bounds.contains(x, y);
}
void DefaultButton::setFillColor(const sf::Color& s) {
m_region.setFillColor(s);
}
void DefaultButton::setText(const std::string& fontPath,
const std::string& text, const sf::Color& c,
int fontSize) {
if (m_text == nullptr) {
m_text = m_region.addElem<TextLabel>(fontPath);
if (m_text == nullptr)
return; // Creating text label failed
}
m_text->setText(text);
m_text->setColor(c);
m_text->setCharacterSize(fontSize);
}
sf::Vector2f DefaultButton::getSize() const { return m_region.getSize(); }
sf::Vector2f DefaultButton::getPosition() const {
return m_region.getPosition();
}
void DefaultButton::setSize(float width, float height) {
m_region.setSize(width, height);
}
void DefaultButton::setPosition(float x, float y) {
m_region.setPosition(x, y);
}
void DefaultButton::onMouseMoved(int x, int y) {
std::cout << "onMouseMoved(" << x << ", " << y << ")\n";
}
void DefaultButton::onMouseOver() {
std::cout << "onMouseOver()\n";
m_region.setFillColor(sf::Color(30, 30, 30, 228));
}
void DefaultButton::onMouseOut() {
std::cout << "onMouseOut()\n";
m_region.setFillColor(sf::Color(60, 60, 60, 192));
}
void DefaultButton::onPressed(sf::Mouse::Button b, int x, int y) {
std::cout << "onPressed()\n";
m_region.setFillColor(sf::Color(192, 192, 192, 255));
if (m_text != nullptr)
m_text->setColor(sf::Color::Black);
}
void DefaultButton::onReleased(sf::Mouse::Button b, int x, int y) {
std::cout << "onReleased()\n";
m_region.setFillColor(sf::Color(30, 30, 30, 228));
if (m_text != nullptr)
m_text->setColor(sf::Color::White);
}
void DefaultButton::draw(sf::RenderTarget& target,
sf::RenderStates states) const {
target.draw(m_region);
}
| [
"golodorov@gmail.com"
] | golodorov@gmail.com |
12fac691d40c70e009c6617fdaac14aa60061aeb | 4799044cec94c502cdd3bac8f7efbd457d44b912 | /HashTable/LongestConsecutiveSubsequence.cpp | 54d0045c6f611c0ad160ec9445a3fc5c2026fa94 | [] | no_license | yogesh019/DataStructures | 669d8b6927df5807904ec3cecd1c8216d21db2f8 | ab369068cab3bb68a84b35deb858cf1aa1472ec5 | refs/heads/master | 2021-01-19T10:56:57.504014 | 2019-06-30T11:08:01 | 2019-06-30T11:08:01 | 82,221,401 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,753 | cpp | /*
Given an array of integers, find the length of the longest sub-sequence such that elements in the subsequence are consecutive
integers, the consecutive numbers can be in any order.
One Solution is to first sort the array and find the longest subarray with consecutive elements. Time complexity of this
solution is O(nLogn). Thanks to Hao.W for suggesting this solution here.
*/
#include<iostream>
#include<unordered_set>
using namespace std;
int findLongestConsecutiveSubsequence(int *arr,int N){
unordered_set<int>check;
for(int i=0;i<N;i++){
check.insert(arr[i]);
}
int res=0;
for(int i=0;i<N;i++){
if(check.find(arr[i]-1)==check.end()){
int j=arr[i];
while(check.find(j)!=check.end()){
j++;
}
res=max(res,j-arr[i]);
}
}
return res;
}
int main(){
int arr[100],N;
cout<<"Enter the array size: ";
cin>>N;
cout<<"Enter the array elements: ";
for(int i=0;i<N;i++){
cin>>arr[i];
}
cout<<"length of longest Consecutive Subsequence is: "<<findLongestConsecutiveSubsequence(arr,N)<<endl<<endl;
return 0;
}
/*Note
Time Complexity: At first look, time complexity looks more than O(n). If we take a closer look, we can notice that it is O(n)
under the assumption that hash insert and search take O(1) time. The function S.find() inside the while loop is called at
most twice for every element. For example, consider the case when all array elements are consecutive.
In this case, the outer find is called for every element, but we go inside the if condition only
for the smallest element. Once we are inside the if condition, we call find() one more time for every other element.*/
| [
"sharmay376@gmail.com"
] | sharmay376@gmail.com |
ef59f85b3e5e977182d1e00fcef0568f225e6a33 | f81749de4aad3955433ef183dba9813cd54af57f | /instance/problem/continuous/global/CEC2015/F15_global_composition7.h | aaf28187d482b017ae5c1443e7b5c87f731ee2f2 | [] | no_license | Strawberry9583/OFEC_Alpha | bc27208143647e91f5acd7cfc86b666c8a59aac4 | f251f02d8d63544f49d832efa8acb06da5cd028a | refs/heads/master | 2021-08-22T11:00:32.068132 | 2017-11-28T02:04:36 | 2017-11-28T02:04:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,571 | h | /*************************************************************************
* Project:Open Frameworks for Evolutionary Computation (OFEC)
*************************************************************************
* Author: Changhe Li and Li Zhou
* Email: changhe.lw@gmail.com, 441837060@qq.com
* Language: C++
*************************************************************************
* This file is part of OFEC. This library 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, or (at your option) any later version.
*************************************************************************
* Paper : Problem Definitions and Evaluation Criteria for the CEC2015
* Competition on Learning-based Real-Parameter Single Objective
* Optimization.
************************************************************************/
#ifndef OFEC_F15_GLOBAL_COMPOSITION7_H
#define OFEC_F15_GLOBAL_COMPOSITION7_H
#include "../../expensive/CEC2015/composition_2015.h"
namespace OFEC {
namespace CEC2015 {
class F15_global_composition7 final : public composition_2015
{
public:
F15_global_composition7(param_map &v);
F15_global_composition7(const std::string &name, size_t size_var, size_t size_obj);
protected:
void initialize();
void evaluate__(real *x, std::vector<real>& obj);
void set_function();
protected:
};
}
using CEC2015_GOP_F15 = CEC2015::F15_global_composition7;
}
#endif // !OFEC_F15_GLOBAL_COMPOSITION7_H
| [
"changhe.lw@gmail.com"
] | changhe.lw@gmail.com |
8d399843e02f62e46503b126d76742f9ce040dd1 | cc7661edca4d5fb2fc226bd6605a533f50a2fb63 | /Ionic.Zip.Reduced/__StaticArrayInitTypeSize=12.h | c7b0fb8f7793f1be0afdc3e9ff1132d67f7a4c59 | [
"MIT"
] | permissive | g91/Rust-C-SDK | 698e5b573285d5793250099b59f5453c3c4599eb | d1cce1133191263cba5583c43a8d42d8d65c21b0 | refs/heads/master | 2020-03-27T05:49:01.747456 | 2017-08-23T09:07:35 | 2017-08-23T09:07:35 | 146,053,940 | 1 | 0 | null | 2018-08-25T01:13:44 | 2018-08-25T01:13:44 | null | UTF-8 | C++ | false | false | 126 | h | #pragma once
namespace rust
{
class __StaticArrayInitTypeSize=12 : public ValueType // 0x0
{
public:
}; // size = 0x0
}
| [
"info@cvm-solutions.co.uk"
] | info@cvm-solutions.co.uk |
9dd65d1bc8df3e6c2499e48de0f211ee513cecf6 | 60b640d669dda37704a6ecc3890f25beed07c81b | /package/src/server/server.h | c873ec199a776b4ae407f46f8cbcba9530f15a5d | [] | no_license | LTU-Actor/AdapParameter | 08caacbff7c3cadcfb27d79f470720aa0d397eda | 8e46ca94037f40c85847e09c9a3622a5158a8fb3 | refs/heads/master | 2020-03-29T22:57:07.594738 | 2019-08-08T01:20:55 | 2019-08-08T01:20:55 | 150,449,365 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,285 | h | #pragma once
#include "client.h"
#include <adap_parameter/Feedback.h>
#include <adap_parameter/Register.h>
#include <memory>
#include <ros/ros.h>
#include <string>
#include <unordered_map>
/*
* Main class for server. It has a few jobs:
* - Handle registrations
* - Keep a map of client names to Client objects
* - Forward feedback to the correct Client object
*
* We take a node handle in the constructor so make it easier to change the
* node's namespace (in main.cpp)
*/
class Server {
public:
Server(const ros::NodeHandle &);
/*
* Does not exit until ros::spin() would exit
*/
void run();
private:
bool
registrationCB(ros::ServiceEvent<adap_parameter::Register::Request,
adap_parameter::Register::Response> &);
bool feedbackCB(ros::ServiceEvent<adap_parameter::Feedback::Request,
adap_parameter::Feedback::Response> &);
/*
* When called, checks every Client in the map and deletes it if the
* corisponding node has died.
*/
void pruneDeadClients();
ros::NodeHandle nh;
ros::ServiceServer registration_server;
ros::ServiceServer feedback_server;
std::unordered_map<std::string, std::shared_ptr<Client>> clients;
};
| [
"mitchpleune@gmail.com"
] | mitchpleune@gmail.com |
dcd3f2d5aa3f2a73fcbe828096b6472aea7cca71 | 1b661259b97244ab41a63aca3e179e0f51cad7a9 | /source/unity.build.resynth.cpp | 93128da79b91c928b03b00f328d7d8e986548dbb | [] | no_license | OlivierSohn/cpp.audio | 5a041b826972531b7a1b38ae586be815738b2481 | 46de4303f8e37bbb4556d1f2f85a6e076e35168b | refs/heads/master | 2022-12-20T23:26:10.102074 | 2022-12-04T14:42:56 | 2022-12-04T14:42:56 | 130,727,889 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 71 | cpp |
#include <iostream>
#include "public.h"
#include "main.resynth.cpp"
| [
"olivier.sohn@gmail.com"
] | olivier.sohn@gmail.com |
6679ad28fb98bde7077e92d36494c278a5557341 | e5cbcf9efcd3848e9621a9c5ed2029f492a6c084 | /DNP3/SlaveConfig.h | 023877ed23753f640fe9054435562e83c0597a17 | [] | no_license | prakashnsm/DNP3-Modified | af3f4e7f4bee141ef1dd085dffe65bce0584ffaa | b23f0d744b6cd87b8cf740e27922ecf1a7393664 | refs/heads/master | 2021-01-10T01:52:07.454711 | 2013-02-04T13:35:41 | 2013-02-04T13:35:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,997 | h | //
// Licensed to Green Energy Corp (www.greenenergycorp.com) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Green Enery Corp licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
#ifndef __SLAVE_CONFIG_H_
#define __SLAVE_CONFIG_H_
#include <assert.h>
#include <APL/Exception.h>
#include "ClassMask.h"
#include "ObjectInterfaces.h"
namespace apl
{
namespace dnp
{
class IStackObserver;
// Group/Variation pair
struct GrpVar {
GrpVar() : Grp(-1), Var(-1) {}
GrpVar(int aGrp, int aVar) : Grp(aGrp), Var(aVar) {}
int Grp;
int Var;
};
struct EventMaxConfig {
EventMaxConfig();
EventMaxConfig(size_t, size_t, size_t, size_t);
/** The number of binary events the slave will buffer before overflowing */
size_t mMaxBinaryEvents;
/** The number of analog events the slave will buffer before overflowing */
size_t mMaxAnalogEvents;
/** The number of counter events the slave will buffer before overflowing */
size_t mMaxCounterEvents;
/** The number of vto events the slave will buffer before overflowing */
size_t mMaxVtoEvents;
};
/** Configuration information for a dnp3 slave (outstation)
Used as both input describing the startup configuration of the slave, and as configuration state of mutable properties (i.e. unsolicited responses).
Major feature areas are unsolicited responses, time synchronization requests, event buffer limits, and the DNP3 object/variations to use by default
when the master requests class data or variation 0.
*/
struct SlaveConfig {
SlaveConfig();
// The maximum number of controls the slave will attempt to process from a single APDU
size_t mMaxControls;
// if true, fully disables unsolicited mode as if the slave didn't support it
bool mDisableUnsol;
// controls what unsol classes are enabled
ClassMask mUnsolMask;
// if true, the slave will request time synchronization on an interval
bool mAllowTimeSync;
// The period of time sync interval in milliseconds
millis_t mTimeSyncPeriod;
// The amount of time the slave will wait before sending new unsolicited data ( <= 0 == immediate)
millis_t mUnsolPackDelay;
// How long the slave will wait before retrying an unsuccessful unsol response
millis_t mUnsolRetryDelay;
// The maximum fragment size the slave will use for data it sends
size_t mMaxFragSize;
// The number of objects to store in the VtoWriter queue.
size_t mVtoWriterQueueSize;
// Structure that defines the maximum number of events to buffer
EventMaxConfig mEventMaxConfig;
// default static response types
// The default group/variation to use for static binary responses
GrpVar mStaticBinary;
// The default group/variation to use for static analog responses
GrpVar mStaticAnalog;
// The default group/variation to use for static counter responses
GrpVar mStaticCounter;
// The default group/variation to use for static setpoint status responses
GrpVar mStaticSetpointStatus;
// default event response types
// The default group/variation to use for binary event responses
GrpVar mEventBinary;
// The default group/variation to use for analog event responses
GrpVar mEventAnalog;
// The default group/variation to use for counter event responses
GrpVar mEventCounter;
// The default group/variation to use for VTO event responses
GrpVar mEventVto;
IStackObserver* mpObserver;
};
}
}
/* vim: set ts=4 sw=4: */
#endif
| [
"prakash.nsm@gmail.com"
] | prakash.nsm@gmail.com |
d26cf78d9b816f5bdf6a12a1baa369bc52412dc2 | 4b9b8f43f492ed4e48fd015c1fa793ae950e87cb | /ButtonAndLCDDemo/Button.h | 93192879d6813050c59cb716b193053ff72e18c2 | [] | no_license | hvietnguyen/GlassHouseArduino | 18110d262868e4086d0603dbb37f6c15707cb0a3 | 120bc5558d0ce47a80c754036da316eb9456ff94 | refs/heads/master | 2020-05-21T15:59:50.519409 | 2017-03-11T07:46:11 | 2017-03-11T07:46:11 | 84,633,209 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 309 | h | // Button.h
#ifndef _BUTTON_h
#define _BUTTON_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#else
#include "WProgram.h"
#endif
class Button {
private:
boolean previousState = HIGH;
boolean currentState = HIGH;
byte pin;
public:
//Constructor
Button(byte p=0);
boolean de
};
#endif
| [
"h.viet0384@gmail.com"
] | h.viet0384@gmail.com |
2f0d979c2ccaf662ca12797f46b23989154b502e | 29a4c1e436bc90deaaf7711e468154597fc379b7 | /modules/cephes/bench/simd/k1e.cpp | 7ea9ee5488f9db7ffc89cfa7921ad055279840ee | [
"BSL-1.0"
] | permissive | brycelelbach/nt2 | 31bdde2338ebcaa24bb76f542bd0778a620f8e7c | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | refs/heads/master | 2021-01-17T12:41:35.021457 | 2011-04-03T17:37:15 | 2011-04-03T17:37:15 | 1,263,345 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,104 | cpp | //////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#include <nt2/toolbox/cephes/include/k1e.hpp>
#include <nt2/sdk/unit/benchmark.hpp>
//////////////////////////////////////////////////////////////////////////////
// Runtime benchmark for functor<k1e_> from cephes
//////////////////////////////////////////////////////////////////////////////
using nt2::cephes::tag::k1e_;
//////////////////////////////////////////////////////////////////////////////
// bench/simd
// E.G:
// NT2_TIMING( k1e_ , ((nt2::simd::native<float,nt2::tag::sse_>, -10, 10)) )
// )
//////////////////////////////////////////////////////////////////////////////
| [
"jtlapreste@gmail.com"
] | jtlapreste@gmail.com |
e3506ad98263d001e51a6bc41d9c0ccc46c0a14d | d82e56817a7da1d85da546370975ea0a7bd79314 | /CppSource/Source/Services/Misc/title_callable_ui.cpp | 866eb6cf83fcd277b24a80e91cdd2e35df6acc08 | [
"MIT"
] | permissive | aablackm/xbox-live-unity-plugin | 9cae50700c211715cc67be97ec2f1c1c6aeb9dca | ca19dec99a43a44c46b6eba75e689327d431c7b4 | refs/heads/master | 2021-08-28T10:42:21.717030 | 2017-12-11T21:41:17 | 2017-12-11T21:41:17 | 113,923,793 | 1 | 0 | null | 2017-12-12T00:30:33 | 2017-12-12T00:30:33 | null | UTF-8 | C++ | false | false | 4,779 | cpp | // Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pch.h"
#include "xsapi/title_callable_ui_c.h"
#include "taskargs.h"
using namespace xbox::services::system;
struct show_profile_card_taskargs : public taskargs
{
string_t targetXboxUserId;
};
struct check_gaming_privilege_taskargs : public taskargs_with_payload<bool>
{
XSAPI_GAMING_PRIVILEGE privilege;
string_t friendlyMessage;
};
HC_RESULT TCUIShowProfileCardUIExecute(
_In_opt_ void* executionRoutineContext,
_In_ HC_TASK_HANDLE taskHandle
)
{
auto args = reinterpret_cast<show_profile_card_taskargs*>(executionRoutineContext);
auto result = title_callable_ui::show_profile_card_ui(args->targetXboxUserId).get();
args->copy_xbox_live_result(result);
return HCTaskSetCompleted(taskHandle);
}
XSAPI_DLLEXPORT XSAPI_RESULT XBL_CALLING_CONV
TCUIShowProfileCardUI(
_In_ PCSTR targetXboxUserId,
_In_ XSAPI_SHOW_PROFILE_CARD_UI_COMPLETION_ROUTINE completionRoutine,
_In_opt_ void* completionRoutineContext,
_In_ uint64_t taskGroupId
) XSAPI_NOEXCEPT
try
{
verify_global_init();
auto args = new show_profile_card_taskargs();
args->targetXboxUserId = utils::to_utf16string(targetXboxUserId);
return utils::xsapi_result_from_hc_result(
HCTaskCreate(
taskGroupId,
TCUIShowProfileCardUIExecute,
static_cast<void*>(args),
utils::execute_completion_routine<show_profile_card_taskargs, XSAPI_SHOW_PROFILE_CARD_UI_COMPLETION_ROUTINE>,
static_cast<void*>(args),
static_cast<void*>(completionRoutine),
completionRoutineContext,
nullptr
));
}
CATCH_RETURN()
HC_RESULT TCUICheckGamingPrivilegeSilentlyExecute(
_In_opt_ void* executionRoutineContext,
_In_ HC_TASK_HANDLE taskHandle
)
{
auto args = reinterpret_cast<check_gaming_privilege_taskargs*>(executionRoutineContext);
auto result = title_callable_ui::check_gaming_privilege_silently((gaming_privilege)args->privilege);
args->copy_xbox_live_result(result);
args->completionRoutinePayload = result.payload();
return HCTaskSetCompleted(taskHandle);
}
XSAPI_DLLEXPORT XSAPI_RESULT XBL_CALLING_CONV
TCUICheckGamingPrivilegeSilently(
_In_ XSAPI_GAMING_PRIVILEGE privilege,
_In_ XSAPI_CHECK_GAMING_PRIVILEGE_COMPLETION_ROUTINE completionRoutine,
_In_opt_ void* completionRoutineContext,
_In_ uint64_t taskGroupId
) XSAPI_NOEXCEPT
try
{
verify_global_init();
auto tcuiArgs = new check_gaming_privilege_taskargs();
tcuiArgs->privilege = privilege;
return utils::xsapi_result_from_hc_result(
HCTaskCreate(
taskGroupId,
TCUICheckGamingPrivilegeSilentlyExecute,
static_cast<void*>(tcuiArgs),
utils::execute_completion_routine_with_payload<check_gaming_privilege_taskargs, XSAPI_CHECK_GAMING_PRIVILEGE_COMPLETION_ROUTINE>,
static_cast<void*>(tcuiArgs),
static_cast<void*>(completionRoutine),
completionRoutineContext,
nullptr
));
}
CATCH_RETURN()
HC_RESULT TCUICheckGamingPrivilegeWithUIExecute(
_In_opt_ void* executionRoutineContext,
_In_ HC_TASK_HANDLE taskHandle
)
{
auto args = reinterpret_cast<check_gaming_privilege_taskargs*>(executionRoutineContext);
auto result = title_callable_ui::check_gaming_privilege_with_ui(
(gaming_privilege)args->privilege,
args->friendlyMessage
).get();
args->copy_xbox_live_result(result);
args->completionRoutinePayload = result.payload();
return HCTaskSetCompleted(taskHandle);
}
XSAPI_DLLEXPORT XSAPI_RESULT XBL_CALLING_CONV
TCUICheckGamingPrivilegeWithUI(
_In_ XSAPI_GAMING_PRIVILEGE privilege,
_In_ PCSTR friendlyMessage,
_In_ XSAPI_CHECK_GAMING_PRIVILEGE_COMPLETION_ROUTINE completionRoutine,
_In_opt_ void* completionRoutineContext,
_In_ uint64_t taskGroupId
) XSAPI_NOEXCEPT
try
{
verify_global_init();
auto tcuiArgs = new check_gaming_privilege_taskargs();
tcuiArgs->privilege = privilege;
tcuiArgs->friendlyMessage = utils::to_utf16string(friendlyMessage);
return utils::xsapi_result_from_hc_result(
HCTaskCreate(
taskGroupId,
TCUICheckGamingPrivilegeWithUIExecute,
static_cast<void*>(tcuiArgs),
utils::execute_completion_routine_with_payload<check_gaming_privilege_taskargs, XSAPI_CHECK_GAMING_PRIVILEGE_COMPLETION_ROUTINE>,
static_cast<void*>(tcuiArgs),
static_cast<void*>(completionRoutine),
completionRoutineContext,
nullptr
));
}
CATCH_RETURN()
| [
"noreply@github.com"
] | noreply@github.com |
f7aa1de5e1130e030b0b9fc1475b7706f66bf3d1 | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.0025/NEOC5H12 | bf0873708214849f45acc58a42f75d4d96d5d478 | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 841 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.0025";
object NEOC5H12;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 1.77998e-07;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"jfeatherstone123@gmail.com"
] | jfeatherstone123@gmail.com | |
67b929939d701fb98373dbb91460f1eefbe2ccab | 11d1aae2d410563972ae7dcfb13cb632b7c83975 | /view.h | 0db0ae12fc4d3a3d0eb5e951d51be6a55362b0f0 | [] | no_license | werton14/Simulink | c101b250578034b35ae106fd59bd7cca307d452a | e7833c258d48684c62ce43be9cec955c21c58866 | refs/heads/master | 2020-06-12T19:00:34.671916 | 2017-05-23T20:11:39 | 2017-05-23T20:11:39 | 75,216,793 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | h | #ifndef VIEW_H
#define VIEW_H
#include <QGraphicsView>
#include <QMimeData>
#include "Scene.h"
#include <item.h>
class View: public QGraphicsView
{
public:
View(Scene * scene);
protected:
virtual void dragEnterEvent ( QDragEnterEvent * event );
virtual void dragLeaveEvent ( QDragLeaveEvent * event );
virtual void dragMoveEvent ( QDragMoveEvent * event );
virtual void dropEvent ( QDropEvent * event );
virtual void resizeEvent(QResizeEvent * event);
};
#endif
| [
"qwerty191498@gmail.com"
] | qwerty191498@gmail.com |
2945120c6200d161575122541eb2846fc800e32c | 76a033d0bf3003927d543924f95fcd8dc66015e5 | /OrderReader/orderreader.cpp | fec25918e177aef4fb67a95c0c149b44b442c176 | [
"WTFPL"
] | permissive | sonnd9x/lol-clientless-bot | 48547b5ade02c68da590619d4ea1fae8b1e65a20 | d1d013e1b6056ec2c06267096dd63ae380993ed3 | refs/heads/master | 2020-09-30T15:50:12.295690 | 2017-08-24T10:47:03 | 2017-08-24T10:47:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,740 | cpp | #include "orderreader.h"
OrderReader::OrderReader(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
setAcceptDrops(true);
orderTableModel = new QStandardItemModel();
ui.orderTable->setModel(orderTableModel);
}
OrderReader::~OrderReader()
{
saveOrderDb();
}
void OrderReader::dragEnterEvent(QDragEnterEvent *e)
{
e->acceptProposedAction();
}
void OrderReader::dropEvent(QDropEvent *e)
{
auto urlList = e->mimeData()->urls();
orderTableModel->clear();
loadOrder(urlList[0].toLocalFile());
}
void OrderReader::loadOrder(QString fileName)
{
//Load db file
QFile db(fileName);
if (db.open(QIODevice::ReadOnly))
{
QDataStream stream(&db);
qint32 rowCount, columnCount;
stream >> rowCount >> columnCount;
orderTableModel->setRowCount(rowCount);
orderTableModel->setColumnCount(columnCount);
for (int i = 0; i < rowCount; ++i)
{
for (int j = 0; j < columnCount; ++j)
{
QStandardItem *item = new QStandardItem();
item->read(stream);
item->setBackground(QColor(255, 255, 255));
orderTableModel->setItem(i, j, item);
}
}
}
db.close();
}
void OrderReader::saveOrderDb()
{
//Safe db file
QFile db("orderData.db");
if (db.open(QIODevice::WriteOnly))
{
QDataStream stream(&db);
qint32 rowCount = orderTableModel->rowCount();
qint32 columnCount = orderTableModel->columnCount();
stream << rowCount << columnCount;
if (rowCount && columnCount)
{
for (int i = 0; i < rowCount; ++i)
{
for (int j = 0; j < columnCount; ++j)
{
auto itm = orderTableModel->item(i, j);
if (itm != nullptr)
itm->write(stream);
}
}
}
db.close();
}
} | [
"noreply@github.com"
] | noreply@github.com |
2d3c2642749a4139b892dfe3722e0eb642ed63c4 | ee830c48b6cf531a862287186ccf89345866b5ef | /Algorithm/baekjoon/c++/7785_회사에있는사람.cpp | 4303a42a74e6fa9190ad8a9bdd9bfca19d64b19c | [] | no_license | huisam/JinLearnedList | 6afa7fb16638042b037f8a3425eb341739ef515e | 018d3e8f200b272c0323d6d946842234bc969fdc | refs/heads/master | 2023-03-12T16:55:45.404646 | 2021-03-06T11:38:34 | 2021-03-06T11:38:34 | 118,875,274 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,697 | cpp | #include<iostream>
#define MAX_LENGTH 6
#define MAX_NODE 1000000
#define MAX_TABLE (MAX_NODE >> 1) + 7
using namespace std;
unsigned long mhash(const char *str)
{
unsigned long hash = 5381;
int c;
while (c = *str++)
{
hash = (((hash << 5) + hash) + c) % MAX_TABLE;
}
return hash % MAX_TABLE;
}
void mstrcpy(char *dst, const char *src) {
int pos = 0;
while (src[pos]) {
dst[pos] = src[pos];
pos++;
}
dst[pos] = '\0';
}
int mstrcmp(const char *str1, const char *str2) {
int pos = 0;
while (str2[pos]) {
if (str1[pos] != str2[pos])
break;
pos++;
}
return str1[pos] - str2[pos];
}
struct Node {
char name[MAX_LENGTH];
bool isIn;
bool operator<(const Node &node) {
return mstrcmp(name, node.name) > 0;
}
};
Node nodePool[MAX_NODE];
Node *arr[MAX_NODE];
Node *temp[MAX_NODE];
int nCnt;
Node *newNode(const char *name) {
Node *n = &nodePool[nCnt];
mstrcpy(n->name, name);
n->isIn = true;
arr[nCnt] = &nodePool[nCnt];
nCnt++;
return n;
}
struct Table {
Node *node;
Table *prev;
Table *next;
};
Table tablePool[MAX_NODE];
int tCnt;
Table hashTable[MAX_TABLE];
Table *newTable(Node *node) {
Table* t = &tablePool[tCnt++];
t->node = node;
t->prev = 0;
t->next = 0;
return t;
}
void addHashTable(Node *node) {
int key = mhash(node->name);
Table *head = hashTable[key].next;
Table *entity = newTable(node);
entity->prev = &hashTable[key];
entity->next = head;
if (head != 0) head->prev = entity;
hashTable[key].next = entity;
}
Node* findHashTable(const char *str) {
int key = mhash(str);
Table *head = hashTable[key].next;
while (head) {
if (mstrcmp(str, head->node->name) == 0)
return head->node;
head = head->next;
}
return 0;
}
void mergeSort(Node **arr, int len) {
if (len < 2)
return;
int mid = len / 2;
mergeSort(arr, mid);
mergeSort(arr + mid, len - mid);
int i = 0, j = mid, k = 0;
while (i < mid && j < len) {
if (*arr[i] < *arr[j])
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
while (i < mid) {
temp[k++] = arr[i++];
}
while (j < len) {
temp[k++] = arr[j++];
}
for (register int a = 0; a < len; ++a)
arr[a] = temp[a];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
while (n--) {
char name[MAX_LENGTH];
char status[MAX_LENGTH];
cin >> name >> status;
if (mstrcmp(status, "enter") == 0) {
Node *node = findHashTable(name);
if (node != 0)
node->isIn = true;
else
addHashTable(newNode(name));
}
else {
Node *node = findHashTable(name);
if(node)
node->isIn = false;
}
}
mergeSort(arr, nCnt);
for (register int i = 0; i < nCnt; ++i) {
if (arr[i]->isIn)
cout << arr[i]->name << '\n';
}
} | [
"huisam@naver.com"
] | huisam@naver.com |
b419e1ca418fc57fc8c745b26930e741188f2d16 | 41b4adb10cc86338d85db6636900168f55e7ff18 | /aws-cpp-sdk-rds/include/aws/rds/model/CopyDBSnapshotRequest.h | f3dd9dc75eab6f64ae9ecd763b4e725d1b978db6 | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | totalkyos/AWS | 1c9ac30206ef6cf8ca38d2c3d1496fa9c15e5e80 | 7cb444814e938f3df59530ea4ebe8e19b9418793 | refs/heads/master | 2021-01-20T20:42:09.978428 | 2016-07-16T00:03:49 | 2016-07-16T00:03:49 | 63,465,708 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 21,647 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/rds/RDS_EXPORTS.h>
#include <aws/rds/RDSRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/rds/model/Tag.h>
namespace Aws
{
namespace RDS
{
namespace Model
{
/**
* <p/>
*/
class AWS_RDS_API CopyDBSnapshotRequest : public RDSRequest
{
public:
CopyDBSnapshotRequest();
Aws::String SerializePayload() const override;
/**
* <p>The identifier for the source DB snapshot.</p> <p>If you are copying from a
* shared manual DB snapshot, this must be the ARN of the shared DB snapshot.</p>
* <p>Constraints:</p> <ul> <li> <p>Must specify a valid system snapshot in the
* "available" state.</p> </li> <li> <p>If the source snapshot is in the same
* region as the copy, specify a valid DB snapshot identifier.</p> </li> <li> <p>If
* the source snapshot is in a different region than the copy, specify a valid DB
* snapshot ARN. For more information, go to <a
* href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html">
* Copying a DB Snapshot</a>.</p> </li> </ul> <p>Example:
* <code>rds:mydb-2012-04-02-00-01</code> </p> <p>Example:
* <code>arn:aws:rds:rr-regn-1:123456789012:snapshot:mysql-instance1-snapshot-20130805</code>
* </p>
*/
inline const Aws::String& GetSourceDBSnapshotIdentifier() const{ return m_sourceDBSnapshotIdentifier; }
/**
* <p>The identifier for the source DB snapshot.</p> <p>If you are copying from a
* shared manual DB snapshot, this must be the ARN of the shared DB snapshot.</p>
* <p>Constraints:</p> <ul> <li> <p>Must specify a valid system snapshot in the
* "available" state.</p> </li> <li> <p>If the source snapshot is in the same
* region as the copy, specify a valid DB snapshot identifier.</p> </li> <li> <p>If
* the source snapshot is in a different region than the copy, specify a valid DB
* snapshot ARN. For more information, go to <a
* href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html">
* Copying a DB Snapshot</a>.</p> </li> </ul> <p>Example:
* <code>rds:mydb-2012-04-02-00-01</code> </p> <p>Example:
* <code>arn:aws:rds:rr-regn-1:123456789012:snapshot:mysql-instance1-snapshot-20130805</code>
* </p>
*/
inline void SetSourceDBSnapshotIdentifier(const Aws::String& value) { m_sourceDBSnapshotIdentifierHasBeenSet = true; m_sourceDBSnapshotIdentifier = value; }
/**
* <p>The identifier for the source DB snapshot.</p> <p>If you are copying from a
* shared manual DB snapshot, this must be the ARN of the shared DB snapshot.</p>
* <p>Constraints:</p> <ul> <li> <p>Must specify a valid system snapshot in the
* "available" state.</p> </li> <li> <p>If the source snapshot is in the same
* region as the copy, specify a valid DB snapshot identifier.</p> </li> <li> <p>If
* the source snapshot is in a different region than the copy, specify a valid DB
* snapshot ARN. For more information, go to <a
* href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html">
* Copying a DB Snapshot</a>.</p> </li> </ul> <p>Example:
* <code>rds:mydb-2012-04-02-00-01</code> </p> <p>Example:
* <code>arn:aws:rds:rr-regn-1:123456789012:snapshot:mysql-instance1-snapshot-20130805</code>
* </p>
*/
inline void SetSourceDBSnapshotIdentifier(Aws::String&& value) { m_sourceDBSnapshotIdentifierHasBeenSet = true; m_sourceDBSnapshotIdentifier = value; }
/**
* <p>The identifier for the source DB snapshot.</p> <p>If you are copying from a
* shared manual DB snapshot, this must be the ARN of the shared DB snapshot.</p>
* <p>Constraints:</p> <ul> <li> <p>Must specify a valid system snapshot in the
* "available" state.</p> </li> <li> <p>If the source snapshot is in the same
* region as the copy, specify a valid DB snapshot identifier.</p> </li> <li> <p>If
* the source snapshot is in a different region than the copy, specify a valid DB
* snapshot ARN. For more information, go to <a
* href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html">
* Copying a DB Snapshot</a>.</p> </li> </ul> <p>Example:
* <code>rds:mydb-2012-04-02-00-01</code> </p> <p>Example:
* <code>arn:aws:rds:rr-regn-1:123456789012:snapshot:mysql-instance1-snapshot-20130805</code>
* </p>
*/
inline void SetSourceDBSnapshotIdentifier(const char* value) { m_sourceDBSnapshotIdentifierHasBeenSet = true; m_sourceDBSnapshotIdentifier.assign(value); }
/**
* <p>The identifier for the source DB snapshot.</p> <p>If you are copying from a
* shared manual DB snapshot, this must be the ARN of the shared DB snapshot.</p>
* <p>Constraints:</p> <ul> <li> <p>Must specify a valid system snapshot in the
* "available" state.</p> </li> <li> <p>If the source snapshot is in the same
* region as the copy, specify a valid DB snapshot identifier.</p> </li> <li> <p>If
* the source snapshot is in a different region than the copy, specify a valid DB
* snapshot ARN. For more information, go to <a
* href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html">
* Copying a DB Snapshot</a>.</p> </li> </ul> <p>Example:
* <code>rds:mydb-2012-04-02-00-01</code> </p> <p>Example:
* <code>arn:aws:rds:rr-regn-1:123456789012:snapshot:mysql-instance1-snapshot-20130805</code>
* </p>
*/
inline CopyDBSnapshotRequest& WithSourceDBSnapshotIdentifier(const Aws::String& value) { SetSourceDBSnapshotIdentifier(value); return *this;}
/**
* <p>The identifier for the source DB snapshot.</p> <p>If you are copying from a
* shared manual DB snapshot, this must be the ARN of the shared DB snapshot.</p>
* <p>Constraints:</p> <ul> <li> <p>Must specify a valid system snapshot in the
* "available" state.</p> </li> <li> <p>If the source snapshot is in the same
* region as the copy, specify a valid DB snapshot identifier.</p> </li> <li> <p>If
* the source snapshot is in a different region than the copy, specify a valid DB
* snapshot ARN. For more information, go to <a
* href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html">
* Copying a DB Snapshot</a>.</p> </li> </ul> <p>Example:
* <code>rds:mydb-2012-04-02-00-01</code> </p> <p>Example:
* <code>arn:aws:rds:rr-regn-1:123456789012:snapshot:mysql-instance1-snapshot-20130805</code>
* </p>
*/
inline CopyDBSnapshotRequest& WithSourceDBSnapshotIdentifier(Aws::String&& value) { SetSourceDBSnapshotIdentifier(value); return *this;}
/**
* <p>The identifier for the source DB snapshot.</p> <p>If you are copying from a
* shared manual DB snapshot, this must be the ARN of the shared DB snapshot.</p>
* <p>Constraints:</p> <ul> <li> <p>Must specify a valid system snapshot in the
* "available" state.</p> </li> <li> <p>If the source snapshot is in the same
* region as the copy, specify a valid DB snapshot identifier.</p> </li> <li> <p>If
* the source snapshot is in a different region than the copy, specify a valid DB
* snapshot ARN. For more information, go to <a
* href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html">
* Copying a DB Snapshot</a>.</p> </li> </ul> <p>Example:
* <code>rds:mydb-2012-04-02-00-01</code> </p> <p>Example:
* <code>arn:aws:rds:rr-regn-1:123456789012:snapshot:mysql-instance1-snapshot-20130805</code>
* </p>
*/
inline CopyDBSnapshotRequest& WithSourceDBSnapshotIdentifier(const char* value) { SetSourceDBSnapshotIdentifier(value); return *this;}
/**
* <p>The identifier for the copied snapshot.</p> <p>Constraints:</p> <ul> <li>
* <p>Cannot be null, empty, or blank</p> </li> <li> <p>Must contain from 1 to 255
* alphanumeric characters or hyphens</p> </li> <li> <p>First character must be a
* letter</p> </li> <li> <p>Cannot end with a hyphen or contain two consecutive
* hyphens</p> </li> </ul> <p>Example: <code>my-db-snapshot</code> </p>
*/
inline const Aws::String& GetTargetDBSnapshotIdentifier() const{ return m_targetDBSnapshotIdentifier; }
/**
* <p>The identifier for the copied snapshot.</p> <p>Constraints:</p> <ul> <li>
* <p>Cannot be null, empty, or blank</p> </li> <li> <p>Must contain from 1 to 255
* alphanumeric characters or hyphens</p> </li> <li> <p>First character must be a
* letter</p> </li> <li> <p>Cannot end with a hyphen or contain two consecutive
* hyphens</p> </li> </ul> <p>Example: <code>my-db-snapshot</code> </p>
*/
inline void SetTargetDBSnapshotIdentifier(const Aws::String& value) { m_targetDBSnapshotIdentifierHasBeenSet = true; m_targetDBSnapshotIdentifier = value; }
/**
* <p>The identifier for the copied snapshot.</p> <p>Constraints:</p> <ul> <li>
* <p>Cannot be null, empty, or blank</p> </li> <li> <p>Must contain from 1 to 255
* alphanumeric characters or hyphens</p> </li> <li> <p>First character must be a
* letter</p> </li> <li> <p>Cannot end with a hyphen or contain two consecutive
* hyphens</p> </li> </ul> <p>Example: <code>my-db-snapshot</code> </p>
*/
inline void SetTargetDBSnapshotIdentifier(Aws::String&& value) { m_targetDBSnapshotIdentifierHasBeenSet = true; m_targetDBSnapshotIdentifier = value; }
/**
* <p>The identifier for the copied snapshot.</p> <p>Constraints:</p> <ul> <li>
* <p>Cannot be null, empty, or blank</p> </li> <li> <p>Must contain from 1 to 255
* alphanumeric characters or hyphens</p> </li> <li> <p>First character must be a
* letter</p> </li> <li> <p>Cannot end with a hyphen or contain two consecutive
* hyphens</p> </li> </ul> <p>Example: <code>my-db-snapshot</code> </p>
*/
inline void SetTargetDBSnapshotIdentifier(const char* value) { m_targetDBSnapshotIdentifierHasBeenSet = true; m_targetDBSnapshotIdentifier.assign(value); }
/**
* <p>The identifier for the copied snapshot.</p> <p>Constraints:</p> <ul> <li>
* <p>Cannot be null, empty, or blank</p> </li> <li> <p>Must contain from 1 to 255
* alphanumeric characters or hyphens</p> </li> <li> <p>First character must be a
* letter</p> </li> <li> <p>Cannot end with a hyphen or contain two consecutive
* hyphens</p> </li> </ul> <p>Example: <code>my-db-snapshot</code> </p>
*/
inline CopyDBSnapshotRequest& WithTargetDBSnapshotIdentifier(const Aws::String& value) { SetTargetDBSnapshotIdentifier(value); return *this;}
/**
* <p>The identifier for the copied snapshot.</p> <p>Constraints:</p> <ul> <li>
* <p>Cannot be null, empty, or blank</p> </li> <li> <p>Must contain from 1 to 255
* alphanumeric characters or hyphens</p> </li> <li> <p>First character must be a
* letter</p> </li> <li> <p>Cannot end with a hyphen or contain two consecutive
* hyphens</p> </li> </ul> <p>Example: <code>my-db-snapshot</code> </p>
*/
inline CopyDBSnapshotRequest& WithTargetDBSnapshotIdentifier(Aws::String&& value) { SetTargetDBSnapshotIdentifier(value); return *this;}
/**
* <p>The identifier for the copied snapshot.</p> <p>Constraints:</p> <ul> <li>
* <p>Cannot be null, empty, or blank</p> </li> <li> <p>Must contain from 1 to 255
* alphanumeric characters or hyphens</p> </li> <li> <p>First character must be a
* letter</p> </li> <li> <p>Cannot end with a hyphen or contain two consecutive
* hyphens</p> </li> </ul> <p>Example: <code>my-db-snapshot</code> </p>
*/
inline CopyDBSnapshotRequest& WithTargetDBSnapshotIdentifier(const char* value) { SetTargetDBSnapshotIdentifier(value); return *this;}
/**
* <p>The AWS Key Management Service (AWS KMS) key identifier for an encrypted DB
* snapshot. The KMS key identifier is the Amazon Resource Name (ARN) or the KMS
* key alias for the KMS encryption key.</p> <p>If you copy an unencrypted DB
* snapshot and specify a value for the <code>KmsKeyId</code> parameter, Amazon RDS
* encrypts the target DB snapshot using the specified KMS encryption key.</p>
* <p>If you copy an encrypted DB snapshot from your AWS account, you can specify a
* value for <code>KmsKeyId</code> to encrypt the copy with a new KMS encryption
* key. If you don't specify a value for <code>KmsKeyId</code> then the copy of the
* DB snapshot is encrypted with the same KMS key as the source DB snapshot. </p>
* <p>If you copy an encrypted DB snapshot that is shared from another AWS account,
* then you must specify a value for <code>KmsKeyId</code>.</p>
*/
inline const Aws::String& GetKmsKeyId() const{ return m_kmsKeyId; }
/**
* <p>The AWS Key Management Service (AWS KMS) key identifier for an encrypted DB
* snapshot. The KMS key identifier is the Amazon Resource Name (ARN) or the KMS
* key alias for the KMS encryption key.</p> <p>If you copy an unencrypted DB
* snapshot and specify a value for the <code>KmsKeyId</code> parameter, Amazon RDS
* encrypts the target DB snapshot using the specified KMS encryption key.</p>
* <p>If you copy an encrypted DB snapshot from your AWS account, you can specify a
* value for <code>KmsKeyId</code> to encrypt the copy with a new KMS encryption
* key. If you don't specify a value for <code>KmsKeyId</code> then the copy of the
* DB snapshot is encrypted with the same KMS key as the source DB snapshot. </p>
* <p>If you copy an encrypted DB snapshot that is shared from another AWS account,
* then you must specify a value for <code>KmsKeyId</code>.</p>
*/
inline void SetKmsKeyId(const Aws::String& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = value; }
/**
* <p>The AWS Key Management Service (AWS KMS) key identifier for an encrypted DB
* snapshot. The KMS key identifier is the Amazon Resource Name (ARN) or the KMS
* key alias for the KMS encryption key.</p> <p>If you copy an unencrypted DB
* snapshot and specify a value for the <code>KmsKeyId</code> parameter, Amazon RDS
* encrypts the target DB snapshot using the specified KMS encryption key.</p>
* <p>If you copy an encrypted DB snapshot from your AWS account, you can specify a
* value for <code>KmsKeyId</code> to encrypt the copy with a new KMS encryption
* key. If you don't specify a value for <code>KmsKeyId</code> then the copy of the
* DB snapshot is encrypted with the same KMS key as the source DB snapshot. </p>
* <p>If you copy an encrypted DB snapshot that is shared from another AWS account,
* then you must specify a value for <code>KmsKeyId</code>.</p>
*/
inline void SetKmsKeyId(Aws::String&& value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId = value; }
/**
* <p>The AWS Key Management Service (AWS KMS) key identifier for an encrypted DB
* snapshot. The KMS key identifier is the Amazon Resource Name (ARN) or the KMS
* key alias for the KMS encryption key.</p> <p>If you copy an unencrypted DB
* snapshot and specify a value for the <code>KmsKeyId</code> parameter, Amazon RDS
* encrypts the target DB snapshot using the specified KMS encryption key.</p>
* <p>If you copy an encrypted DB snapshot from your AWS account, you can specify a
* value for <code>KmsKeyId</code> to encrypt the copy with a new KMS encryption
* key. If you don't specify a value for <code>KmsKeyId</code> then the copy of the
* DB snapshot is encrypted with the same KMS key as the source DB snapshot. </p>
* <p>If you copy an encrypted DB snapshot that is shared from another AWS account,
* then you must specify a value for <code>KmsKeyId</code>.</p>
*/
inline void SetKmsKeyId(const char* value) { m_kmsKeyIdHasBeenSet = true; m_kmsKeyId.assign(value); }
/**
* <p>The AWS Key Management Service (AWS KMS) key identifier for an encrypted DB
* snapshot. The KMS key identifier is the Amazon Resource Name (ARN) or the KMS
* key alias for the KMS encryption key.</p> <p>If you copy an unencrypted DB
* snapshot and specify a value for the <code>KmsKeyId</code> parameter, Amazon RDS
* encrypts the target DB snapshot using the specified KMS encryption key.</p>
* <p>If you copy an encrypted DB snapshot from your AWS account, you can specify a
* value for <code>KmsKeyId</code> to encrypt the copy with a new KMS encryption
* key. If you don't specify a value for <code>KmsKeyId</code> then the copy of the
* DB snapshot is encrypted with the same KMS key as the source DB snapshot. </p>
* <p>If you copy an encrypted DB snapshot that is shared from another AWS account,
* then you must specify a value for <code>KmsKeyId</code>.</p>
*/
inline CopyDBSnapshotRequest& WithKmsKeyId(const Aws::String& value) { SetKmsKeyId(value); return *this;}
/**
* <p>The AWS Key Management Service (AWS KMS) key identifier for an encrypted DB
* snapshot. The KMS key identifier is the Amazon Resource Name (ARN) or the KMS
* key alias for the KMS encryption key.</p> <p>If you copy an unencrypted DB
* snapshot and specify a value for the <code>KmsKeyId</code> parameter, Amazon RDS
* encrypts the target DB snapshot using the specified KMS encryption key.</p>
* <p>If you copy an encrypted DB snapshot from your AWS account, you can specify a
* value for <code>KmsKeyId</code> to encrypt the copy with a new KMS encryption
* key. If you don't specify a value for <code>KmsKeyId</code> then the copy of the
* DB snapshot is encrypted with the same KMS key as the source DB snapshot. </p>
* <p>If you copy an encrypted DB snapshot that is shared from another AWS account,
* then you must specify a value for <code>KmsKeyId</code>.</p>
*/
inline CopyDBSnapshotRequest& WithKmsKeyId(Aws::String&& value) { SetKmsKeyId(value); return *this;}
/**
* <p>The AWS Key Management Service (AWS KMS) key identifier for an encrypted DB
* snapshot. The KMS key identifier is the Amazon Resource Name (ARN) or the KMS
* key alias for the KMS encryption key.</p> <p>If you copy an unencrypted DB
* snapshot and specify a value for the <code>KmsKeyId</code> parameter, Amazon RDS
* encrypts the target DB snapshot using the specified KMS encryption key.</p>
* <p>If you copy an encrypted DB snapshot from your AWS account, you can specify a
* value for <code>KmsKeyId</code> to encrypt the copy with a new KMS encryption
* key. If you don't specify a value for <code>KmsKeyId</code> then the copy of the
* DB snapshot is encrypted with the same KMS key as the source DB snapshot. </p>
* <p>If you copy an encrypted DB snapshot that is shared from another AWS account,
* then you must specify a value for <code>KmsKeyId</code>.</p>
*/
inline CopyDBSnapshotRequest& WithKmsKeyId(const char* value) { SetKmsKeyId(value); return *this;}
inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }
inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; }
inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = value; }
inline CopyDBSnapshotRequest& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}
inline CopyDBSnapshotRequest& WithTags(Aws::Vector<Tag>&& value) { SetTags(value); return *this;}
inline CopyDBSnapshotRequest& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }
inline CopyDBSnapshotRequest& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }
/**
* <p>True to copy all tags from the source DB snapshot to the target DB snapshot;
* otherwise false. The default is false.</p>
*/
inline bool GetCopyTags() const{ return m_copyTags; }
/**
* <p>True to copy all tags from the source DB snapshot to the target DB snapshot;
* otherwise false. The default is false.</p>
*/
inline void SetCopyTags(bool value) { m_copyTagsHasBeenSet = true; m_copyTags = value; }
/**
* <p>True to copy all tags from the source DB snapshot to the target DB snapshot;
* otherwise false. The default is false.</p>
*/
inline CopyDBSnapshotRequest& WithCopyTags(bool value) { SetCopyTags(value); return *this;}
private:
Aws::String m_sourceDBSnapshotIdentifier;
bool m_sourceDBSnapshotIdentifierHasBeenSet;
Aws::String m_targetDBSnapshotIdentifier;
bool m_targetDBSnapshotIdentifierHasBeenSet;
Aws::String m_kmsKeyId;
bool m_kmsKeyIdHasBeenSet;
Aws::Vector<Tag> m_tags;
bool m_tagsHasBeenSet;
bool m_copyTags;
bool m_copyTagsHasBeenSet;
};
} // namespace Model
} // namespace RDS
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
a916ecee3da93b017f83f7812c4b3608057746c3 | 8a42f7246f6df21dd810d80aa52cc7dbd95f598c | /components/gta-core-five/src/CustomText.cpp | be659c9a9e882054b79ba14f1206a9aaba4d34f5 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | calibercheats/client | c7da5b3783efc730249e5b223cb234c7175e748f | f69c0fcb5612e42231c48c181122909c5c57f47a | refs/heads/portability-five | 2021-01-24T15:43:37.294191 | 2016-07-24T20:07:09 | 2016-07-24T20:07:20 | 64,492,887 | 10 | 6 | null | 2016-07-29T15:57:29 | 2016-07-29T15:57:29 | null | UTF-8 | C++ | false | false | 1,233 | cpp | /*
* This file is part of the CitizenFX project - http://citizen.re/
*
* See LICENSE and MENTIONS in the root of the source tree for information
* regarding licensing.
*/
#include "StdInc.h"
#include "Hooking.h"
#include <mutex>
static const char*(*g_origGetText)(void* theText, uint32_t hash);
static std::mutex g_textMutex;
static std::unordered_map<uint32_t, std::string> g_textMap;
static const char* GetText(void* theText, uint32_t hash)
{
{
std::unique_lock<std::mutex> lock(g_textMutex);
auto it = g_textMap.find(hash);
if (it != g_textMap.end())
{
return it->second.c_str();
}
}
return g_origGetText(theText, hash);
}
void AddCustomText(const char* key, const char* value)
{
std::unique_lock<std::mutex> lock(g_textMutex);
g_textMap[HashString(key)] = value;
}
static HookFunction hookFunction([] ()
{
g_textMap[HashString("PM_PANE_LEAVE")] = "Disconnect";
void* getTextPtr = hook::pattern("48 8B CB 8B D0 E8 ? ? ? ? 48 85 C0 0F 95 C0").count(1).get(0).get<void>(5);
hook::set_call(&g_origGetText, getTextPtr);
hook::call(getTextPtr, GetText);
hook::call(hook::pattern("48 85 C0 75 34 8B 0D").count(1).get(0).get<void>(-5), GetText);
}); | [
"bas@dotbas.net"
] | bas@dotbas.net |
4169879e8abb15aee438e42d44df68d63ea81fba | 79927e3d89f99ea730c4f5652a5f8cc4c9cf66be | /src/TetrisPieceDwg.cpp | 6dbdc87f0b0a2288e6a3dfc11485fe9c6cd9d7af | [] | no_license | bazaneli/TetrisSFML | 771e63cac2424b454033abda38448c80448dbda3 | 5ed19396b5b966b0b08d63ed48310db5897b8505 | refs/heads/main | 2023-05-08T02:25:16.843613 | 2021-05-30T13:20:42 | 2021-05-30T13:20:42 | 366,070,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,057 | cpp | #include "TetrisPieceDwg.h"
void TetrisPieceDwg::LoadSprites()
{
pieceTexture.loadFromFile("assets/square2.png");
pieceSprite = sf::Sprite(pieceTexture);
}
void TetrisPieceDwg::Draw()
{
pieceSprite.setTextureRect(sf::IntRect(this->engine.currentPiece.GetPieceID() *32, 0, 32, 32));
for (int line = 0; line < engine.currentPiece.GetSize(); line++)
for (int column = 0; column < engine.currentPiece.GetSize(); column++)
{
if (engine.currentPiece.GetCurrentLayout()[line][column] == TileType::pieceOnBoard)
{
pieceSprite.setPosition(
static_cast<float>((engine.GetCurrentDx() + column) * settings.basePixelSize),
static_cast<float>((engine.GetCurrentDy() + line) * settings.basePixelSize)
);
pieceSprite.setScale(settings.spriteScale, settings.spriteScale);
window.draw(pieceSprite);
}
}
}
TetrisPieceDwg::~TetrisPieceDwg()
{
}
| [
"joseluiz.bazaneli@gmail.com"
] | joseluiz.bazaneli@gmail.com |
31b436da8a04c9c66935e858bfb7e065d26c809e | 3f4e7dfa972a4d5975afa57c5901e14ae7965ebd | /RayCastingCUDA_SDL2/source/Mesh.cpp | 2ded7b61a0ac74d002e1d42f5de7bb51853b74b8 | [] | no_license | HelliceSaouli/Simple_RayTracing_Cuda | a2341674d1f92201f4a0cc80d7f7ca1ce100394d | f08acfcdfb29a1283c6a882ec481c63bc0977618 | refs/heads/master | 2022-04-22T18:50:18.238713 | 2020-04-24T11:08:45 | 2020-04-24T11:09:28 | 258,480,680 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,388 | cpp | /*
* Mesh.cpp
*
* Created on: Jun 13, 2015
* Author: hakosoft
*/
#include "Mesh.h"
//for mesh that we extracted from
Mesh::Mesh(std::vector< glm::vec3 > vertices,std::vector< glm::vec3 > colors, unsigned int numVertices, GLint *Attribut)
{
this->_drawCount = numVertices;
glGenVertexArrays(1,&this->_vao);
glBindVertexArray(this->_vao);
//Vertices
glGenBuffers(NUM_BUFFER-1,this->_vbo);
glBindBuffer(GL_ARRAY_BUFFER,this->_vbo[POSITION_VB]);
glBufferData(GL_ARRAY_BUFFER,vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);//it's look like cudaMemCopy xD
glEnableVertexAttribArray(Attribut[0]); // there is only one attribute for now
glVertexAttribPointer(Attribut[0], 3, GL_FLOAT, GL_FALSE,0,0); // how to read our data
//colors
glBindBuffer(GL_ARRAY_BUFFER,this->_vbo[COLOR_VB]);
glBufferData(GL_ARRAY_BUFFER,colors.size() * sizeof(glm::vec3), &colors[0], GL_STATIC_DRAW);//it's look like cudaMemCopy xD
glEnableVertexAttribArray(Attribut[1]); // there is only one attribute for now
glVertexAttribPointer(Attribut[1], 3, GL_FLOAT, GL_FALSE,0,0); // how to read our data
glBindVertexArray(0); // stop the binding after this instruction
}
//for the quard that we are gonna draw on it i know 2 constructor is ugly but hey what i can do XD
Mesh::Mesh(Vertex* vertices, unsigned int numVertices, GLint *Attribut)
{
this->_drawCount = numVertices;
glGenVertexArrays(1,&this->_vao);
glBindVertexArray(this->_vao);
std::vector<glm::vec3> position;
std::vector<glm::vec2> TexCoord;
std::vector<glm::vec3> colors;
position.reserve(numVertices);
TexCoord.reserve(numVertices);
colors.reserve(numVertices);
for(int i = 0; i < numVertices; i++)
{
position.push_back(vertices[i].getVertexPos());
TexCoord.push_back(vertices[i].getTexCoords());
colors.push_back(vertices[i].getColors());
}
// position
glGenBuffers(NUM_BUFFER,this->_vbo);
glBindBuffer(GL_ARRAY_BUFFER,this->_vbo[POSITION_VB]);
glBufferData(GL_ARRAY_BUFFER,position.size() * sizeof(glm::vec3), &position[0], GL_STATIC_DRAW);//it's look like cudaMemCopy xD
glEnableVertexAttribArray(Attribut[0]); // there is only one attribute for now
glVertexAttribPointer(Attribut[0], 3, GL_FLOAT, GL_FALSE,0,0); // how to read our data
//colors
glBindBuffer(GL_ARRAY_BUFFER,this->_vbo[COLOR_VB]);
glBufferData(GL_ARRAY_BUFFER,colors.size() * sizeof(glm::vec3), &colors[0], GL_STATIC_DRAW);//it's look like cudaMemCopy xD
glEnableVertexAttribArray(Attribut[1]); // there is only one attribute for now
glVertexAttribPointer(Attribut[1], 3, GL_FLOAT, GL_FALSE,0,0); // how to read our data
//UV
glBindBuffer(GL_ARRAY_BUFFER,this->_vbo[TEXCOORD_VB]);
glBufferData(GL_ARRAY_BUFFER,TexCoord.size() * sizeof(glm::vec2), &TexCoord[0], GL_STATIC_DRAW);//it's look like cudaMemCopy xD
glEnableVertexAttribArray(Attribut[2]); // there is only one attribute for now
glVertexAttribPointer(Attribut[2], 2, GL_FLOAT, GL_FALSE,0,0); // how to read our data
glBindVertexArray(0); // stop the binding after this instruction
}
Mesh::~Mesh()
{
glDeleteVertexArrays(1,&this->_vao);
}
void Mesh::Draw()
{
glBindVertexArray(this->_vao);
// the drawing
glDrawArrays(GL_POINTS, 0,this->_drawCount);
glBindVertexArray(0);
}
void Mesh::DrawQuad()
{
glBindVertexArray(this->_vao);
// the drawing
glDrawArrays(GL_TRIANGLES, 0,this->_drawCount);
glBindVertexArray(0);
}
| [
"saouli-abdelhak@hotmail.com"
] | saouli-abdelhak@hotmail.com |
c5261e3d7d2c221fc03c72d8feedcbdaa86b6c79 | a2206795a05877f83ac561e482e7b41772b22da8 | /Source/PV/build/Qt/Components/ui_pqEmptyView.h | 5ec8d79647c7223e0f3892a5e6937511b96ee152 | [] | no_license | supreethms1809/mpas-insitu | 5578d465602feb4d6b239a22912c33918c7bb1c3 | 701644bcdae771e6878736cb6f49ccd2eb38b36e | refs/heads/master | 2020-03-25T16:47:29.316814 | 2018-08-08T02:00:13 | 2018-08-08T02:00:13 | 143,947,446 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,449 | h | /********************************************************************************
** Form generated from reading UI file 'pqEmptyView.ui'
**
** Created by: Qt User Interface Compiler version 4.8.6
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_PQEMPTYVIEW_H
#define UI_PQEMPTYVIEW_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QFrame>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QScrollArea>
#include <QtGui/QSpacerItem>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_EmptyView
{
public:
QGridLayout *gridLayout;
QScrollArea *scrollArea;
QWidget *widgetFoo;
QGridLayout *gridLayout_2;
QSpacerItem *verticalSpacer;
QSpacerItem *horizontalSpacer;
QFrame *ConvertActionsFrame;
QVBoxLayout *verticalLayout;
QLabel *label;
QSpacerItem *horizontalSpacer_2;
QSpacerItem *verticalSpacer_2;
void setupUi(QWidget *EmptyView)
{
if (EmptyView->objectName().isEmpty())
EmptyView->setObjectName(QString::fromUtf8("EmptyView"));
EmptyView->resize(319, 306);
gridLayout = new QGridLayout(EmptyView);
gridLayout->setContentsMargins(0, 0, 0, 0);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
scrollArea = new QScrollArea(EmptyView);
scrollArea->setObjectName(QString::fromUtf8("scrollArea"));
scrollArea->setWidgetResizable(true);
widgetFoo = new QWidget();
widgetFoo->setObjectName(QString::fromUtf8("widgetFoo"));
widgetFoo->setGeometry(QRect(0, 0, 315, 302));
gridLayout_2 = new QGridLayout(widgetFoo);
gridLayout_2->setObjectName(QString::fromUtf8("gridLayout_2"));
verticalSpacer = new QSpacerItem(20, 109, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout_2->addItem(verticalSpacer, 0, 1, 1, 1);
horizontalSpacer = new QSpacerItem(88, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
gridLayout_2->addItem(horizontalSpacer, 1, 0, 1, 1);
ConvertActionsFrame = new QFrame(widgetFoo);
ConvertActionsFrame->setObjectName(QString::fromUtf8("ConvertActionsFrame"));
ConvertActionsFrame->setFrameShape(QFrame::NoFrame);
ConvertActionsFrame->setFrameShadow(QFrame::Raised);
verticalLayout = new QVBoxLayout(ConvertActionsFrame);
verticalLayout->setSpacing(2);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
label = new QLabel(ConvertActionsFrame);
label->setObjectName(QString::fromUtf8("label"));
label->setAlignment(Qt::AlignCenter);
verticalLayout->addWidget(label);
gridLayout_2->addWidget(ConvertActionsFrame, 1, 1, 1, 1);
horizontalSpacer_2 = new QSpacerItem(88, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
gridLayout_2->addItem(horizontalSpacer_2, 1, 2, 1, 1);
verticalSpacer_2 = new QSpacerItem(20, 109, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout_2->addItem(verticalSpacer_2, 2, 1, 1, 1);
scrollArea->setWidget(widgetFoo);
gridLayout->addWidget(scrollArea, 0, 0, 1, 1);
retranslateUi(EmptyView);
QMetaObject::connectSlotsByName(EmptyView);
} // setupUi
void retranslateUi(QWidget *EmptyView)
{
EmptyView->setWindowTitle(QApplication::translate("EmptyView", "Form", 0, QApplication::UnicodeUTF8));
label->setText(QApplication::translate("EmptyView", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:'Helvetica'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-weight:600;\">Create View</span></p></body></html>", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class EmptyView: public Ui_EmptyView {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_PQEMPTYVIEW_H
| [
"mpasVM@localhost.org"
] | mpasVM@localhost.org |
60c5c387383aa35c6607e24daaf9b95a562eedb1 | f2d123e540bac9164323740ec9ed98eb5d97067e | /smartCudaTest/smartCudaTest/smartCuda_lib/smartCuda_v013/smartCuda_v013.h | 8364627ba578801d5aed6e3340c6825ff250535f | [] | no_license | markamo/Smart-Cuda | 768b84de013c17bf8d13670b84cffcc0958502d9 | 3d29fff0275c6e4116faf65b246f16afd7f155f1 | refs/heads/master | 2016-09-05T23:17:53.755159 | 2014-02-06T07:54:24 | 2014-02-06T07:54:24 | 15,227,718 | 1 | 1 | null | null | null | null | WINDOWS-1258 | C++ | false | false | 94,068 | h | /*
* SMART CUDA 0.1.2 (18th December, 2013) - Initial Release
*
*
* Copyright 2013 by Mark Amo-Boateng (smartcuda@outlook.com)
*
* For tutorials and more information, go to:
* http://markamo.github.io/Smart-Cuda/
*
*
*/
#pragma once
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
#include <math.h>
////memory allocations
#define smartHost 0
#define smartDevice 1
#define smartPinnedHost 2
#define smartKernel 11
////memory lifespan
#define scopeLocal false
#define scopeGlobal true
////deallocating global wrapper memories////
#define ON true;
#define OFF false;
////memory initialization /////
#define _MEMSET_INIT_VAL_ 0
__device__
extern bool __clean_globals = false;
//bool smartGlobalFree = false;
__device__
extern int __device_id = 0;
#define CUDA_ERR(x) do { if((x) != cudaSuccess) { \
printf("Error at %s:%d\n",__FILE__,__LINE__); \
return EXIT_FAILURE;}} while(0)
template <typename T>
__host__ __device__ void smartFill(T *dev_Array, const int size, const T init)
{
int i = 0;
for (i = 0; i < size; i++)
{
dev_Array[i] = init;
//i += 1;
}
}
template <typename T>
__host__ __device__ void smartSequence(T *dev_Array, const int size, const T init, T step = 1)
{
int i = 0;
for (i = 0; i < size; i++)
{
dev_Array[i] = init + i * step;
//i += 1;
}
}
template <typename T>
__global__ void smartFillAsync_core(T *dev_Array, const int size, const T init)
{
int i = threadIdx.x + blockIdx.x * blockDim.x;
while(i < size)
{
dev_Array[i] = init;
i += blockDim.x * gridDim.x;
}
}
template <typename T>
__global__ void smartSequenceAsync_core(T *dev_Array, const int size, const T init, T step = 1)
{
int i = threadIdx.x + blockIdx.x * blockDim.x;
while(i < size)
{
dev_Array[i] = init + i * step;
i += blockDim.x * gridDim.x;
}
}
template <typename T>
__host__ __device__ cudaError_t smartFillAsync35(T *dev_Array, const int size, const T init)
{
cudaError_t cudaStatus;
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
////check for launch errors
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Memory initialization launch failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
template <typename T>
__host__ __device__ cudaError_t smartSequenceAsync35(T *dev_Array, const int size, const T init, T step = 1)
{
cudaError_t cudaStatus;
smartSequenceAsync_core<<<128, 128>>>(dev_Array, size, init,step);
////check for launch errors
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Memory initialization launch failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
template <typename T>
__host__ cudaError_t smartFillAsync(T *dev_Array, const int size, const T init)
{
cudaError_t cudaStatus;
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
////check for launch errors
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Memory initialization launch failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
template <typename T>
__host__ cudaError_t smartSequenceAsync(T *dev_Array, const int size, const T init, T step = 1)
{
cudaError_t cudaStatus;
smartSequenceAsync_core<<<128, 128>>>(dev_Array, size, init,step);
////check for launch errors
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Memory initialization launch failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
template <typename T>
inline T* seq_allocSmartDeviceArrayAsync( int size, T init = 0, bool setINI = false, T step=1) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(1D) failed!\n");
//////goto Error;
}
/*if (setINI)
{
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
cudaDeviceSynchronize();
}*/
if (setINI)
{
smartSequenceAsync_core<<<128, 128>>>(dev_Array, size, init,step);
////check for launch errors
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Memory initialization launch failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
cudaDeviceSynchronize();
////check for sync errors
cudaStatus = cudaDeviceSynchronize();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching Memory Initialization!\n", cudaStatus);
////goto Error;
}
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* allocSmartDeviceArrayAsync( int size, T init = 0, bool setINI = false)////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(1D) failed\n!");
//////goto Error;
}
/*if (setINI)
{
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
cudaDeviceSynchronize();
}*/
if (setINI)
{
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
////check for launch errors
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Memory initialization launch failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
cudaDeviceSynchronize();
////check for sync errors
cudaStatus = cudaDeviceSynchronize();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching Memory Initialization!\n", cudaStatus);
////goto Error;
}
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* seq_allocSmartDeviceArray( int size, T init = 0, bool setINI = false, T step=1) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(1D) failed!\n");
//////goto Error;
}
if (setINI)
{
smartSequence(dev_Array, size, init,step);
}
//////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* allocSmartDeviceArray( int size, T init = 0, bool setINI = false) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(1D) failed\n!");
//////goto Error;
}
if (setINI)
{
smartFill(dev_Array, size, init);
}
//////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* allocSmartDeviceArrayAsync( int sizeX, int sizeY, T init = 0, bool setINI = false) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(2D) failed!\n");
//////goto Error;
}
/*if (setINI)
{
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
cudaDeviceSynchronize();
}*/
if (setINI)
{
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
////check for launch errors
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Memory initialization launch failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
cudaDeviceSynchronize();
////check for sync errors
cudaStatus = cudaDeviceSynchronize();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching Memory Initialization!\n", cudaStatus);
////goto Error;
}
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* seq_allocSmartDeviceArrayAsync( int sizeX, int sizeY, T init = 0, bool setINI = false, T step = 1) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(2D) failed!\n");
//////goto Error;
}
/*if (setINI)
{
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
cudaDeviceSynchronize();
}*/
if (setINI)
{
smartSequenceAsync_core<<<128, 128>>>(dev_Array, size, init);
////check for launch errors
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Memory initialization launch failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
cudaDeviceSynchronize();
////check for sync errors
cudaStatus = cudaDeviceSynchronize();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching Memory Initialization!\n", cudaStatus);
////goto Error;
}
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* allocSmartDeviceArray( int sizeX, int sizeY, T init = 0, bool setINI = false) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(2D) failed!\n");
//////goto Error;
}
if (setINI)
{
smartFill(dev_Array, size, init);
}
//////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* seq_allocSmartDeviceArray( int sizeX, int sizeY, T init = 0, bool setINI = false, T step =1) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(2D) failed!\n");
//////goto Error;
}
if (setINI)
{
smartFill(dev_Array, size, init,step);
}
//////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* allocSmartDeviceArrayAsync( int sizeX, int sizeY, int sizeZ, T init = 0, bool setINI = false) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY * sizeZ;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(3D) failed!\n");
//////goto Error;
}
/*if (setINI)
{
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
cudaDeviceSynchronize();
}*/
if (setINI)
{
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
////check for launch errors
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Memory initialization launch failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
cudaDeviceSynchronize();
////check for sync errors
cudaStatus = cudaDeviceSynchronize();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching Memory Initialization!\n", cudaStatus);
////goto Error;
}
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* seq_allocSmartDeviceArrayAsync( int sizeX, int sizeY, int sizeZ, T init = 0, bool setINI = false, T step =1) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY * sizeZ;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(3D) failed!\n");
//////goto Error;
}
/*if (setINI)
{
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
cudaDeviceSynchronize();
}*/
if (setINI)
{
smartSequenceAsync_core<<<128, 128>>>(dev_Array, size, init, step);
////check for launch errors
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Memory initialization launch failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
cudaDeviceSynchronize();
////check for sync errors
cudaStatus = cudaDeviceSynchronize();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching Memory Initialization!\n", cudaStatus);
////goto Error;
}
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* allocSmartDeviceArray( int sizeX, int sizeY, int sizeZ, T init = 0, bool setINI = false) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY * sizeZ;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(3D) failed!\n");
//////goto Error;
}
if (setINI)
{
smartFill(dev_Array, size, init);
}
//////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* seq_allocSmartDeviceArray( int sizeX, int sizeY, int sizeZ,T init = 0, bool setINI = false, T step =1) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY * sizeZ;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(3D) failed!\n");
//////goto Error;
}
if (setINI)
{
smartFill(dev_Array, size, init,step);
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* allocSmartDeviceArrayAsync( int sizeX, int sizeY, int sizeZ, int sizeW, T init = 0, bool setINI = false) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY * sizeZ * sizeW;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(4D) failed!\n");
//////goto Error;
}
/*if (setINI)
{
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
cudaDeviceSynchronize();
}*/
if (setINI)
{
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
////check for launch errors
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Memory initialization launch failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
cudaDeviceSynchronize();
////check for sync errors
cudaStatus = cudaDeviceSynchronize();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching Memory Initialization!\n", cudaStatus);
////goto Error;
}
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* seq_allocSmartDeviceArrayAsync( int sizeX, int sizeY, int sizeZ, int sizeW, T init = 0, T step=1, bool setINI = false) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY * sizeZ * sizeW;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(4D) failed!\n");
//////goto Error;
}
/*if (setINI)
{
smartFillAsync_core<<<128, 128>>>(dev_Array, size, init);
cudaDeviceSynchronize();
}*/
if (setINI)
{
smartSequenceAsync_core<<<128, 128>>>(dev_Array, size, init, step);
////check for launch errors
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Memory initialization launch failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
cudaDeviceSynchronize();
////check for sync errors
cudaStatus = cudaDeviceSynchronize();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching Memory Initialization!\n", cudaStatus);
////goto Error;
}
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* allocSmartDeviceArray( int sizeX, int sizeY, int sizeZ, int sizeW, T init = 0, bool setINI = false) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY * sizeZ * sizeW;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(4D) failed!\n");
//////goto Error;
}
if (setINI)
{
smartFill(dev_Array, size, init,step);
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline T* seq_allocSmartDeviceArray( int sizeX, int sizeY, int sizeZ, int sizeW, T init = 0, T step=1, bool setINI = false) ////, cudaError_t cudaStatus = cudaSuccess)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY * sizeZ * sizeW;
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "CUDA Memory Allocation(4D) failed!\n");
//////goto Error;
}
if (setINI)
{
smartFill(dev_Array, size, init,step);
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline cudaError_t smartDeviceFree(T* dev_mem)
{
cudaError_t cudaStatus;
cudaFree(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
template <typename T>
inline cudaError_t smartDeviceFree(T* dev_mem, cudaError_t &cudaStatus)
{
////cudaError_t cudaStatus;
cudaFree(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
template <typename T>
inline cudaError_t smartHostFree(T* dev_mem)
{
cudaError_t cudaStatus;
free(dev_mem);
dev_mem = NULL;
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
template <typename T>
inline cudaError_t smartHostFree(T* dev_mem, cudaError_t &cudaStatus)
{
////cudaError_t cudaStatus;
free(dev_mem);
dev_mem = NULL;
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
template <typename T>
inline cudaError_t smartPinnedHostFree(T* dev_mem)
{
cudaError_t cudaStatus;
cudaFreeHost(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
template <typename T>
inline cudaError_t smartPinnedHostFree(T* dev_mem, cudaError_t &cudaStatus)
{
////cudaError_t cudaStatus;
cudaFreeHost(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
template <typename T>
__device__
inline cudaError_t smartKernelFree(T* dev_mem)
{
cudaError_t cudaStatus;
free(dev_mem);
dev_mem = NULL;
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
template <typename T>
__device__
inline cudaError_t smartKernelFree(T* dev_mem, cudaError_t &cudaStatus)
{
////cudaError_t cudaStatus;
free(dev_mem);
dev_mem = NULL;
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
template <typename T>
inline cudaError_t freeSmartDeviceArray(T* dev_mem, int array_type)
{
cudaError_t cudaStatus;
if (array_type == 0)
{
free(dev_mem);
dev_mem = NULL;
cudaStatus = cudaSuccess;
}
else if (array_type == 1)
{
cudaFree(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Device Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else if (array_type == 2)
{
cudaFreeHost(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else
{
cudaStatus = cudaErrorMemoryAllocation;
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
return cudaStatus;
}
return cudaStatus;
}
template <typename T>
inline cudaError_t freeSmartDeviceArray(T* dev_mem, int array_type, cudaError_t &cudaStatus)
{
////cudaError_t cudaStatus;
if (array_type == smartHost)
{
free(dev_mem);
dev_mem = NULL;
cudaStatus = cudaSuccess;
}
else if (array_type == smartDevice)
{
cudaFree(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Device Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else if (array_type == smartPinnedHost)
{
cudaFreeHost(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else
{
cudaStatus = cudaErrorMemoryAllocation;
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
return cudaStatus;
}
return cudaStatus;
}
template <typename T>
cudaError_t smartCopyHost2Device(T* dev_mem, const T* host_mem, unsigned int size, cudaError_t cudaStatus = cudaSuccess)
{
cudaStatus = cudaMemcpy(dev_mem, host_mem, size * sizeof(T), cudaMemcpyHostToDevice);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy Host to Device failed!\n");
//////goto Error;
}
return cudaStatus;
}
template <typename T>
cudaError_t smartCopyDevice2Host(T* host_mem, T* dev_mem, unsigned int size, cudaError_t cudaStatus = cudaSuccess)
{
cudaStatus = cudaMemcpy(host_mem, dev_mem, size * sizeof(T), cudaMemcpyDeviceToHost);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy Device to Host failed!\n");
//////goto Error;
}
return cudaStatus;
}
template <typename T>
cudaError_t smartCopyDevice2DevicePeer(T* host_mem, int host_id, T* dev_mem, int src_id, unsigned int size, cudaError_t cudaStatus = cudaSuccess)
{
cudaStatus = cudaMemcpyPeer(host_mem, host_id, dev_mem, src_id, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy Device to Device failed!\n");
//////goto Error;
}
return cudaStatus;
}
template <typename T>
cudaError_t smartCopyDevice2Device(T* host_mem, T* dev_mem, unsigned int size, cudaError_t cudaStatus = cudaSuccess)
{
cudaStatus = cudaMemcpy(host_mem, dev_mem, size * sizeof(T), cudaMemcpyDeviceToDevice);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy Device to Device failed!\n");
//////goto Error;
}
return cudaStatus;
}
template <typename T>
cudaError_t smartCopyHost2Host(T* host_mem, T* dev_mem, unsigned int size, cudaError_t cudaStatus = cudaSuccess)
{
cudaStatus = cudaMemcpy(host_mem, dev_mem, size * sizeof(T), cudaMemcpyHostToHost);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy Host to Host failed!\n");
//////goto Error;
}
return cudaStatus;
}
//template<int X, int Y, int Z, int W>
class smartIndex
{
private:
int dimX; int dimY; int dimZ; int dimW;
public:
__device__ __host__ smartIndex()
{
}
__device__ __host__ smartIndex(int i,int j=1, int k=1, int w=1)
{
if((i < 0 || j < 0 || k < 0) || (w < 0))
{
// Take appropriate action here. This is just a placeholder response.
fprintf(stderr, "Array Dimensions [%d][%d][%d][%d] of smart Array is out of bounds\n",i,j,k,w);
//exit(1);
}
dimX = i;dimY = j; dimZ = k; dimW = w;
}
__device__ __host__ int operator()(int i=1,int j=1, int k=1, int w=1)
{
if((i < 0 || j < 0 || k < 0) || (w < 0))
{
// Take appropriate action here. This is just a placeholder response.
fprintf(stderr, "Array Dimensions [%d][%d][%d][%d] of smart Array is out of bounds\n",i,j,k,w);
//exit(1);
}
dimX = i;dimY = j; dimZ = k; dimW = w;
return dimX * dimY * dimZ * dimW;
}
__device__ __host__
int getDimX() { return dimX; }
__device__ __host__
int getDimY() { return dimY; }
__device__ __host__
int getDimZ() { return dimZ; }
__device__ __host__
int getDimW() { return dimW; }
};
template <typename T, int mem_loc>
inline T* smartArray( int sizeX) ////, cudaError_t &cudaStatus)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX;
if (mem_loc == smartHost)
{
////allocate pageable host memory
dev_Array = (T*)malloc(size * sizeof(T));
if (NULL == dev_Array) {
/* Handle error… */
fprintf(stderr, "Dynamic Memory Allocation on Device failed!\n");
cudaStatus = cudaErrorMemoryAllocation;
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else if (mem_loc == smartDevice)
{
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Dynamic Memory Allocation on Device failed!\n");
//////goto Error;
}
cudaMemset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else if (mem_loc == smartPinnedHost) {
cudaStatus = cudaMallocHost((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Dynamic Pinned Memory Allocation on Host failed!\n");
//////goto Error;
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else if (mem_loc == smartKernel)
{
////allocate pageable host memory
dev_Array = (T*)malloc(size * sizeof(T));
if (NULL == dev_Array) {
/* Handle error… */
printf( "Dynamic Memory Allocation in Global Kernel failed!\n");
cudaStatus = cudaErrorMemoryAllocation;
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else
{
fprintf(stderr, "Cannot allocate unsupported memory\n");
cudaStatus = cudaErrorMemoryAllocation;
//return cudaStatus;
}
//////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T, int mem_loc>
inline T* smartArray( int sizeX, int sizeY) ////, cudaError_t &cudaStatus)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY;
if (mem_loc == smartHost)
{
////allocate pageable host memory
dev_Array = (T*)malloc(size * sizeof(T));
if (NULL == dev_Array) {
/* Handle error… */
fprintf(stderr, "Dynamic Memory Allocation on Device failed!\n");
cudaStatus = cudaErrorMemoryAllocation;
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else if (mem_loc == smartDevice)
{
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Dynamic Memory Allocation on Device failed!\n");
//////goto Error;
}
cudaMemset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else if (mem_loc == smartPinnedHost) {
cudaStatus = cudaMallocHost((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Dynamic Pinned Memory Allocation on Host failed!\n");
//////goto Error;
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else if (mem_loc == smartKernel)
{
////allocate pageable host memory
dev_Array = (T*)malloc(size * sizeof(T));
if (NULL == dev_Array) {
/* Handle error… */
printf( "Dynamic Memory Allocation in Global Kernel failed!\n");
cudaStatus = cudaErrorMemoryAllocation;
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else
{
fprintf(stderr, "Cannot allocate unsupported memory\n");
cudaStatus = cudaErrorMemoryAllocation;
//return cudaStatus;
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T, int mem_loc>
inline T* smartArray( int sizeX, int sizeY, int sizeZ) ////, cudaError_t &cudaStatus)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY * sizeZ;
if (mem_loc == smartHost)
{
////allocate pageable host memory
dev_Array = (T*)malloc(size * sizeof(T));
if (NULL == dev_Array) {
/* Handle error… */
fprintf(stderr, "Dynamic Memory Allocation on Device failed!\n");
cudaStatus = cudaErrorMemoryAllocation;
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else if (mem_loc == smartDevice)
{
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Dynamic Memory Allocation on Device failed!\n");
//////goto Error;
}
cudaMemset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else if (mem_loc == smartPinnedHost) {
cudaStatus = cudaMallocHost((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Dynamic Pinned Memory Allocation on Host failed!\n");
//////goto Error;
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else if (mem_loc == smartKernel)
{
////allocate pageable host memory
dev_Array = (T*)malloc(size * sizeof(T));
if (NULL == dev_Array) {
/* Handle error… */
printf( "Dynamic Memory Allocation in Global Kernel failed!\n");
cudaStatus = cudaErrorMemoryAllocation;
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else
{
fprintf(stderr, "Cannot allocate unsupported memory\n");
cudaStatus = cudaErrorMemoryAllocation;
//return cudaStatus;
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T, int mem_loc>
inline T* smartArray( int sizeX, int sizeY, int sizeZ, int sizeW) ////, cudaError_t &cudaStatus)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY * sizeZ * sizeW;
if (mem_loc == smartHost)
{
////allocate pageable host memory
dev_Array = (T*)malloc(size * sizeof(T));
if (NULL == dev_Array) {
/* Handle error… */
fprintf(stderr, "Dynamic Memory Allocation on Device failed!\n");
cudaStatus = cudaErrorMemoryAllocation;
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else if (mem_loc == smartDevice)
{
cudaStatus = cudaMalloc((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Dynamic Memory Allocation on Device failed!\n");
//////goto Error;
}
cudaMemset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else if (mem_loc == smartPinnedHost) {
cudaStatus = cudaMallocHost((void**)&dev_Array, size * sizeof(T));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Dynamic Pinned Memory Allocation on Host failed!\n");
//////goto Error;
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else if (mem_loc == smartKernel)
{
////allocate pageable host memory
dev_Array = (T*)malloc(size * sizeof(T));
if (NULL == dev_Array) {
/* Handle error… */
printf( "Dynamic Memory Allocation in Global Kernel failed!\n");
cudaStatus = cudaErrorMemoryAllocation;
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
}
else
{
fprintf(stderr, "Cannot allocate unsupported memory\n");
cudaStatus = cudaErrorMemoryAllocation;
//return cudaStatus;
}
////Error:
// cudaFree(dev_Array);
return dev_Array;
}
template <typename T>
inline __device__ T* smartKernelArray(int sizeX)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX;
{
////allocatekernel global memory
dev_Array = (T*)malloc(size * sizeof(T));
if (NULL == dev_Array) {
/* Handle error… */
printf( "Dynamic Memory Allocation in Global Kernel failed!\n");
cudaStatus = cudaErrorMemoryAllocation;
}
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
return dev_Array;
}
template <typename T>
inline __device__ T* smartKernelArray( int sizeX, int sizeY) ////, cudaError_t &cudaStatus)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY;
{
////allocatekernel global memory
dev_Array = (T*)malloc(size * sizeof(T));
if (NULL == dev_Array) {
/* Handle error… */
printf( "Dynamic Memory Allocation in Global Kernel failed!\n");
cudaStatus = cudaErrorMemoryAllocation;
}
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
return dev_Array;
}
template <typename T>
inline __device__ T* smartKernelArray( int sizeX, int sizeY, int sizeZ) ////, cudaError_t &cudaStatus)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY * sizeZ;
{
////allocatekernel global memory
dev_Array = (T*)malloc(size * sizeof(T));
if (NULL == dev_Array) {
/* Handle error… */
printf( "Dynamic Memory Allocation in Global Kernel failed!\n");
cudaStatus = cudaErrorMemoryAllocation;
}
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
return dev_Array;
}
template <typename T>
inline __device__ T* smartKernelArray( int sizeX, int sizeY, int sizeZ, int sizeW) ////, cudaError_t &cudaStatus)
{
cudaError_t cudaStatus;
T* dev_Array = 0;
int size = sizeX * sizeY * sizeZ * sizeW;
{
////allocatekernel global memory
dev_Array = (T*)malloc(size * sizeof(T));
if (NULL == dev_Array) {
/* Handle error… */
printf( "Dynamic Memory Allocation in Global Kernel failed!\n");
cudaStatus = cudaErrorMemoryAllocation;
}
}
memset(dev_Array, _MEMSET_INIT_VAL_, size * sizeof(T));
return dev_Array;
}
template <typename T>
inline cudaError_t smartFree(T* dev_mem, int array_type)
{
cudaError_t cudaStatus;
if (array_type == smartHost)
{
free(dev_mem);
dev_mem = NULL;
cudaStatus = cudaSuccess;
}
else if (array_type == smartDevice)
{
cudaFree(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Device Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else if (array_type == smartPinnedHost)
{
cudaFreeHost(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else
{
cudaStatus = cudaErrorMemoryAllocation;
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
return cudaStatus;
}
return cudaStatus;
}
template <typename T>
inline cudaError_t smartFree(T* dev_mem, int array_type, cudaError_t &cudaStatus)
{
if (array_type == smartHost)
{
free(dev_mem);
dev_mem = NULL;
cudaStatus = cudaSuccess;
}
else if (array_type == smartDevice)
{
cudaFree(dev_mem);
dev_mem = NULL;
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Device Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else if (array_type == smartPinnedHost)
{
cudaFreeHost(dev_mem);
dev_mem = NULL;
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else
{
cudaStatus = cudaErrorMemoryAllocation;
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
return cudaStatus;
}
return cudaStatus;
}
template <typename T, int mem_loc>
class smartArrayWrapper
{
private:
////pointer to array
T* dev_arr;
////array dimensions
int lengthX;
int lengthY;
int lengthZ;
int lengthW;
////specialize views
int vX,vY,vZ,vW;
////array wrapper type ////0= host, 1 = device
////useful for copies
int array_type;
////destructor behaviour //// 0 leave array, 1 destroy on scope exit
bool _global_scope; ////destroy_array_on_scope_exit;
//bool _is_copy; /////used to control destructor on copy assignment///
bool _is_cleaned;
////increment and decrement operators for navigation of the data array
unsigned int idx; /////current location
unsigned int vidx; /////current specialized view location
unsigned int ix,iy,iz,iw;
//// keeping track of device id for peer to peer memory copy
int device_id;
__device__ __host__
void initializeArray(T* dev=NULL, int lenX=1,int lenY=1,int lenZ=1,int lenW=1, bool global_scope = true )
{
dev_arr = dev;
lengthX = lenX;
lengthY = lenY;
lengthZ = lenZ;
lengthW = lenW;
////initialize views to default dimensions
vX = 1; vY = 1; vZ = 1; vW = 1;
////set location type
array_type = mem_loc;
////destructor behaviour //// 0 leave array, 1 destroy on scope exit
_global_scope = global_scope;
_is_cleaned = false;
//_is_copy = true;
////increment operators for navigation
idx = 0; vidx = 0;
ix = 0; iy =0; iz = 0; iw = 0;
////device id
device_id = __device_id;
}
__device__ __host__
int getIndex(int i)
{
int j = 0; int k = 0; int w = 0;
//if((((i < 0 || i > lengthX-1) || (j < 0 || j > lengthY-1) || (k < 0 || k > lengthZ-1)) ||(w < 0 || w > lengthW-1))|| dev_arr==NULL)
//{
// // Take appropriate action here. This is just a placeholder response.
// fprintf(stderr, "Array not INITIALIZED or Index [%d][%d][%d][%d] of smart Array is out of bounds\n",i,j,k,w);
// exit(1);
//}
int _idx = i + j * lengthX + k * lengthX * lengthY + w * lengthX * lengthY * lengthZ;
return _idx;
}
__device__ __host__
int getIndex(int i, int j)
{
int k = 0; int w = 0;
//if((((i < 0 || i > lengthX-1) || (j < 0 || j > lengthY-1) || (k < 0 || k > lengthZ-1)) ||(w < 0 || w > lengthW-1))|| dev_arr==NULL)
//{
// // Take appropriate action here. This is just a placeholder response.
// fprintf(stderr, "Array not INITIALIZED or Index [%d][%d][%d][%d] of smart Array is out of bounds\n",i,j,k,w);
// exit(1);
//}
int _idx = i + j * lengthX + k * lengthX * lengthY + w * lengthX * lengthY * lengthZ;
return _idx;
}
__device__ __host__
int getIndex(int i, int j, int k)
{
int w = 0;
//if((((i < 0 || i > lengthX-1) || (j < 0 || j > lengthY-1) || (k < 0 || k > lengthZ-1)) ||(w < 0 || w > lengthW-1))|| dev_arr==NULL)
//{
// // Take appropriate action here. This is just a placeholder response.
// fprintf(stderr, "Array not INITIALIZED or Index [%d][%d][%d][%d] of smart Array is out of bounds\n",i,j,k,w);
// exit(1);
//}
int _idx = i + j * lengthX + k * lengthX * lengthY + w * lengthX * lengthY * lengthZ;
return _idx;
}
__device__ __host__
int getIndex(int i, int j, int k, int w)
{
//if((((i < 0 || i > lengthX-1) || (j < 0 || j > lengthY-1) || (k < 0 || k > lengthZ-1)) ||(w < 0 || w > lengthW-1))|| dev_arr==NULL)
//{
// // Take appropriate action here. This is just a placeholder response.
// fprintf(stderr, "Array not INITIALIZED or Index [%d][%d][%d][%d] of smart Array is out of bounds\n",i,j,k,w);
// exit(1);
//}
int _idx = i + j * lengthX + k * lengthX * lengthY + w * lengthX * lengthY * lengthZ;
return _idx;
}
__device__ __host__
int getViewIndex(int i, int j=0, int k=0, int w=0)
{
//if(((i < 0 || i > vX-1) || (j < 0 || j > vY-1) || (k < 0 || k > vZ-1)) ||(w < 0 || w > vW-1))
//{
// // Take appropriate action here. This is just a placeholder response.
// fprintf(stderr, "View Index [%d][%d][%d][%d] of smart Array is out of bounds\n",i,j,k,w);
// exit(1);
//}
int _idx = i + j * vX + k * vX * vY + w * vX * vY * vZ;
return dev_arr[_idx];
}
__device__ __host__
cudaError_t inner_copy(T* src_array, int src_type, int src_size, int src_device_id)
{
cudaError_t cudaStatus;
//// size of data to copy, using the least of the 2 to avoid errors
unsigned int copySize = (getlen() > src_size) ? getlen() : src_size;
if(array_type == smartHost || array_type == smartPinnedHost) ////host -> host/device copies
{
if(src_type == smartHost || src_type == smartPinnedHost)
{
cudaStatus = smartCopyHost2Host<T>(dev_arr,src_array,copySize);
}
else if (src_type == smartDevice)
{
cudaStatus = smartCopyDevice2Host<T>(dev_arr,src_array,copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else if (array_type == smartDevice || array_type == smartKernel) ////device -> host/device copies
{
if(src_type == smartHost || src_type == smartPinnedHost)
{
cudaStatus = smartCopyHost2Device<T>(dev_arr,src_array,copySize);
}
else if (src_type == smartDevice|| src_type == smartKernel)
{
if (device_id == src_device_id)
{
cudaStatus = smartCopyDevice2Device<T>(dev_arr,src_array,copySize);
}
else
{
cudaStatus = smartCopyDevice2DevicePeer<T>(dev_arr,device_id, src_array,scr_device_id, copySize);
}
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else ////unsupported copy types
{
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
return cudaStatus;
}
public:
__device__ __host__
smartArrayWrapper()
{
initializeArray();
}
__device__ __host__
smartArrayWrapper(bool global_scope)
{
initializeArray(NULL,1,1,1,1,global_scope);
//dev_arr = NULL;
//lengthX = 1;
//lengthY = 1;
//lengthZ = 1;
//lengthW = 1;
//////initialize views to default dimensions
//vX = 1; vY = 1; vZ = 1; vW = 1;
//////set location type
//array_type = mem_loc;
//////destructor behaviour //// 0 leave array, 1 destroy on scope exit
//_global_scope = global_scope;
//_is_copy = true;
}
__device__ __host__
smartArrayWrapper(T* dev, int lenX, bool global_scope = true )
{
initializeArray(dev,lenX,1,1,1,global_scope);
//dev_arr = dev;
//lengthX = lenX;
//lengthY = 1;
//lengthZ = 1;
//lengthW = 1;
//////initialize views to default dimensions
//vX = 1; vY = 1; vZ = 1; vW = 1;
//////set location type
//array_type = mem_loc;
//////destructor behaviour //// 0 leave array, 1 destroy on scope exit
//_global_scope = global_scope;
//_is_copy = true;
}
__device__ __host__
smartArrayWrapper(T* dev, int lenX,int lenY, bool global_scope = true )
{
initializeArray(dev,lenX,lenY,1,1,global_scope);
//dev_arr = dev;
//lengthX = lenX;
//lengthY = lenY;
//lengthZ = 1;
//lengthW = 1;
//////initialize views to default dimensions
//vX = 1; vY = 1; vZ = 1; vW = 1;
//////set location type
//array_type = mem_loc;
//////destructor behaviour //// 0 leave array, 1 destroy on scope exit
//_global_scope = global_scope;
//_is_copy = true;
}
__device__ __host__
smartArrayWrapper(T* dev, int lenX,int lenY,int lenZ, bool global_scope = true )
{
initializeArray(dev,lenX,lenY,lenZ,1,global_scope);
//dev_arr = dev;
//lengthX = lenX;
//lengthY = lenY;
//lengthZ = lenZ;
//lengthW = 1;
//////initialize views to default dimensions
//vX = 1; vY = 1; vZ = 1; vW = 1;
//////set location type
//array_type = mem_loc;
//////destructor behaviour //// 0 leave array, 1 destroy on scope exit
//_global_scope = global_scope;
//_is_copy = true;
}
__device__ __host__
smartArrayWrapper(T* dev, int lenX,int lenY,int lenZ,int lenW, bool global_scope = true )
{
initializeArray(dev,lenX,lenY,lenZ,lenW,global_scope);
//dev_arr = dev;
//lengthX = lenX;
//lengthY = lenY;
//lengthZ = lenZ;
//lengthW = lenW;
//////initialize views to default dimensions
//vX = 1; vY = 1; vZ = 1; vW = 1;
//////set location type
//array_type = mem_loc;
//////destructor behaviour //// 0 leave array, 1 destroy on scope exit
//_global_scope = global_scope;
//_is_copy = true;
}
__device__ __host__
~smartArrayWrapper()
{
if(!_is_cleaned)
{
if(!_global_scope )
{
_is_cleaned = true;
//smartFree<T>(*this);
smartFree<T>(inner_ptr(),array_type);
}
else if(_global_scope && __clean_globals)
{
_is_cleaned = true;
//smartFree<T>(*this);
smartFree<T>(inner_ptr(),array_type);
}
//_is_copy = false;
}
}
__device__ __host__
void wrap(smartArrayWrapper<T,mem_loc> dev )
{
initializeArray(dev.inner_ptr(),dev.getlenX(),dev.getlenY(),dev.getlenZ(),dev.getlenW(),mem_loc);
}
__device__ __host__
void wrapView(smartArrayWrapper<T,mem_loc> dev )
{
initializeArray(dev.inner_ptr(),dev.getViewDimX(),dev.getViewDimX(),dev.getViewDimX(),dev.getViewDimX(),mem_loc);
}
/*
__device__ __host__
void wrap(smartArrayWrapper<T,smartHost> dev )
{
initializeArray(dev.inner_ptr(),dev.getlenX(),.getlenX(),.getlenX(),.getlenX(),dev.getType());
}
__device__ __host__
void wrap(smartArrayWrapper<T,smartPinnedHost> dev )
{
initializeArray(dev.inner_ptr(),dev.getlenX(),.getlenX(),.getlenX(),.getlenX(),dev.getType());
}
__device__ __host__
void wrap(smartArrayWrapper<T,smartDevice> dev )
{
initializeArray(dev.inner_ptr(),dev.getlenX(),.getlenX(),.getlenX(),.getlenX(),dev.getType());
}
*/
__device__ __host__
void wrap(T* dev, int lenX, bool global_scope = true )
{
initializeArray(dev,lenX,1,1,1,global_scope);
}
__device__ __host__
void wrap(T* dev, int lenX,int lenY, bool global_scope = true )
{
initializeArray(dev,lenX,lenY,1,1,global_scope);
}
__device__ __host__
void wrap(T* dev, int lenX,int lenY,int lenZ, bool global_scope = true )
{
initializeArray(dev,lenX,lenY,lenZ,1,global_scope);
}
__device__ __host__
void wrap(T* dev, int lenX,int lenY,int lenZ,int lenW, bool global_scope = true )
{
initializeArray(dev,lenX,lenY,lenZ,lenW,global_scope);
}
template<typename custom>
__device__ __host__
void wrapCustom( custom other, bool global_scope = true )
{
T* dev = other.inner_ptr();
int lenX = other.size();
initializeArray(dev,lenX,1,1,1,global_scope);
}
template<typename custom>
__device__ __host__
void wrapSTL( custom other, bool global_scope = true )
{
T* dev = &other[0];
int lenX = other.size();
initializeArray(dev,lenX,1,1,1,global_scope);
}
__device__ __host__
T &operator()(int i)
{
if((i < 0 || i > lengthX-1) || dev_arr==NULL)
{
// Take appropriate action here. This is just a placeholder response.
fprintf(stderr, "Array not INITIALIZED or Index [%d] of smart Array is out of bounds\n",i);
exit(1);
}
//T temp = dev_arr[i];
idx = i;
return dev_arr[i];
}
__device__ __host__
T &operator()(int i, int j)
{
if(((i < 0 || i > lengthX-1) || (j < 0 || j > lengthY-1))|| dev_arr==NULL)
{
// Take appropriate action here. This is just a placeholder response.
fprintf(stderr, "Array not INITIALIZED or Index [%d][%d] of smart Array is out of bounds\n",i,j);
exit(1);
}
int _idx = i + j * lengthX;
idx = _idx;
return dev_arr[_idx];
}
__device__ __host__
T &operator()(int i, int j, int k)
{
if(((i < 0 || i > lengthX-1) || (j < 0 || j > lengthY-1) || (k < 0 || k > lengthZ-1))|| dev_arr==NULL)
{
// Take appropriate action here. This is just a placeholder response.
fprintf(stderr, "Array not INITIALIZED or Index [%d][%d][%d] of smart Array is out of bounds\n",i,j,k);
exit(1);
}
int _idx = i + j * lengthX + k * lengthX * lengthY;
idx = _idx;
return dev_arr[_idx];
}
__device__ __host__
T &operator()(int i, int j, int k, int w)
{
if((((i < 0 || i > lengthX-1) || (j < 0 || j > lengthY-1) || (k < 0 || k > lengthZ-1)) ||(w < 0 || w > lengthW-1))|| dev_arr==NULL)
{
// Take appropriate action here. This is just a placeholder response.
fprintf(stderr, "Array not INITIALIZED or Index [%d][%d][%d][%d] of smart Array is out of bounds\n",i,j,k,w);
exit(1);
}
int _idx = i + j * lengthX + k * lengthX * lengthY + w * lengthX * lengthY * lengthZ;
idx = _idx;
return dev_arr[_idx];
}
__device__ __host__
T &operator[](int _idx)
{
if((idx < 0 || idx > lengthX * lengthY * lengthZ * lengthW -1) || dev_arr==NULL)
{
// Take appropriate action here. This is just a placeholder response.
fprintf(stderr, "Array not INITIALIZED or Index [%d] of smart Array is out of bounds\n",idx);
exit(1);
}
idx = _idx;
return dev_arr[_idx];
}
__device__ __host__
cudaError_t &operator=(smartArrayWrapper<T,smartDevice> &other)
{
cudaError_t cudaStatus;
//other._is_copy = true; ////prevent destructor from deleting array pointer
//if (this == &other)////check for self assignment
//{
// fprintf(stderr, "Cannot self assign\n");
// cudaStatus = cudaErrorMemoryAllocation;
// return cudaStatus;
// //exit(1);
//}
//if(dev_arr == NULL) ////allocate memory if it does not exist
//{
// dev_arr = smartArray<T,mem_loc>(other.getlen(), cudaStatus);
// lengthX = other.getlenX();
// lengthY = other.getlenY();
// lengthZ = other.getlenZ();
// lengthW = other.getlenW();
//}
//// size of data to copy, using the least of the 2 to avoid errors
unsigned int copySize = (getlen() > other.getlen()) ? getlen() : other.getlen();
if(array_type == smartHost || array_type == smartPinnedHost) ////host -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
cudaStatus = smartCopyDevice2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else if (array_type == smartDevice || array_type == smartKernel) ////device -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
if (device_id == other.deviceID())
{
cudaStatus = smartCopyDevice2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
cudaStatus = smartCopyDevice2DevicePeer<T>(dev_arr,device_id, other.inner_ptr(),other.deviceID(), copySize);
}
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else ////unsupported copy types
{
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
return cudaStatus;
}
__device__ __host__
cudaError_t &operator=(smartArrayWrapper<T,smartHost> &other)
{
cudaError_t cudaStatus;
//other._is_copy = true; ////prevent destructor from deleting array pointer
//if (this == &other)////check for self assignment
//{
// fprintf(stderr, "Cannot self assign\n");
// cudaStatus = cudaErrorMemoryAllocation;
// return cudaStatus;
// //exit(1);
//}
//if(dev_arr == NULL) ////allocate memory if it does not exist
//{
// dev_arr = smartArray<T,mem_loc>(other.getlen(), cudaStatus);
// lengthX = other.getlenX();
// lengthY = other.getlenY();
// lengthZ = other.getlenZ();
// lengthW = other.getlenW();
//}
//// size of data to copy, using the least of the 2 to avoid errors
unsigned int copySize = (getlen() > other.getlen()) ? getlen() : other.getlen();
if(array_type == smartHost || array_type == smartPinnedHost) ////host -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
cudaStatus = smartCopyDevice2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else if (array_type == smartDevice || array_type == smartKernel) ////device -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
if (device_id == other.deviceID())
{
cudaStatus = smartCopyDevice2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
cudaStatus = smartCopyDevice2DevicePeer<T>(dev_arr,device_id, other.inner_ptr(),other.deviceID(), copySize);
}
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else ////unsupported copy types
{
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
return cudaStatus;
}
__device__ __host__
cudaError_t &operator=(smartArrayWrapper<T,smartPinnedHost> &other)
{
cudaError_t cudaStatus;
//other._is_copy = true; ////prevent destructor from deleting array pointer
//if (this == &other)////check for self assignment
//{
// fprintf(stderr, "Cannot self assign\n");
// cudaStatus = cudaErrorMemoryAllocation;
// return cudaStatus;
// //exit(1);
//}
//if(dev_arr == NULL) ////allocate memory if it does not exist
//{
// dev_arr = smartArray<T,mem_loc>(other.getlen(), cudaStatus);
// lengthX = other.getlenX();
// lengthY = other.getlenY();
// lengthZ = other.getlenZ();
// lengthW = other.getlenW();
//}
//// size of data to copy, using the least of the 2 to avoid errors
unsigned int copySize = (getlen() > other.getlen()) ? getlen() : other.getlen();
if(array_type == smartHost || array_type == smartPinnedHost) ////host -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
cudaStatus = smartCopyDevice2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else if (array_type == smartDevice || array_type == smartKernel) ////device -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
if (device_id == other.deviceID())
{
cudaStatus = smartCopyDevice2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
cudaStatus = smartCopyDevice2DevicePeer<T>(dev_arr,device_id, other.inner_ptr(),other.deviceID(), copySize);
}
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else ////unsupported copy types
{
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
return cudaStatus;
}
__device__ __host__
cudaError_t &operator=(smartArrayWrapper<T,smartKernel> &other)
{
cudaError_t cudaStatus;
//other._is_copy = true; ////prevent destructor from deleting array pointer
//if (this == &other)////check for self assignment
//{
// fprintf(stderr, "Cannot self assign\n");
// cudaStatus = cudaErrorMemoryAllocation;
// return cudaStatus;
// //exit(1);
//}
//if(dev_arr == NULL) ////allocate memory if it does not exist
//{
// dev_arr = smartArray<T,mem_loc>(other.getlen(), cudaStatus);
// lengthX = other.getlenX();
// lengthY = other.getlenY();
// lengthZ = other.getlenZ();
// lengthW = other.getlenW();
//}
//// size of data to copy, using the least of the 2 to avoid errors
unsigned int copySize = (getlen() > other.getlen()) ? getlen() : other.getlen();
if(array_type == smartHost || array_type == smartPinnedHost) ////host -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
cudaStatus = smartCopyDevice2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else if (array_type == smartDevice || array_type == smartKernel) ////device -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
if (device_id == other.deviceID())
{
cudaStatus = smartCopyDevice2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
cudaStatus = smartCopyDevice2DevicePeer<T>(dev_arr,device_id, other.inner_ptr(),other.deviceID(), copySize);
}
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else ////unsupported copy types
{
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
return cudaStatus;
}
template <typename custom>
__device__ __host__
cudaError_t &operator=(custom other)
{
cudaError_t cudaStatus;
//// size of data to copy, using the least of the 2 to avoid errors
T* arr = &other[0];
int size = other.size();
int type = smartHost;
int dev_id = 0; //// __device_id; //// global device id
unsigned int copySize = (getlen() > size) ? getlen() : size;
if(array_type == smartHost || array_type == smartPinnedHost) ////host -> host/device copies
{
if(type == smartHost || array_type == smartPinnedHost)
{
cudaStatus = smartCopyHost2Host<T>(dev_arr,arr,copySize);
}
else if (type == smartDevice || type == smartKernel)
{
if (device_id == dev_id)
{
cudaStatus = smartCopyDevice2Device<T>(dev_arr,arr,copySize);
}
else
{
cudaStatus = smartCopyDevice2DevicePeer<T>(dev_arr,device_id, arr,dev_id, copySize);
}
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else if (array_type == smartDevice || array_type == smartKernel) ////device -> host/device copies
{
if(type == smartHost || array_type == smartPinnedHost)
{
cudaStatus = smartCopyHost2Device<T>(dev_arr,arr,copySize);
}
else if (type == smartDevice || type == smartKernel)
{
if (device_id == dev_id)
{
cudaStatus = smartCopyDevice2Device<T>(dev_arr,arr,copySize);
}
else
{
cudaStatus = smartCopyDevice2DevicePeer<T>(dev_arr,device_id, arr, dev_id, copySize);
}
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else ////unsupported copy types
{
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
return cudaStatus;
}
//////NAVIGATION ///////
////increment and decrement operators
__device__ __host__
T &operator++()
{
idx++;
////if (idx > getlen() -1) {idx = getlen() -1;}
return dev_arr[idx];
}
__device__ __host__
T operator++(int)
{
idx++;
int temp = dev_arr[idx];
return temp;
}
__device__ __host__
T &operator--()
{
idx--;
////if (idx > getlen() -1) {idx = getlen() -1;}
return dev_arr[idx];
}
__device__ __host__
T operator--(int)
{
idx--;
int temp = dev_arr[idx];
return temp;
}
////PEEK, ADVANCE, SEEK
__device__ __host__
T peek(int adv = 1) ////view data from advance without moving current index position
{
unsigned int temp = idx + adv;
return dev_arr[temp];
}
__device__ __host__
T adv(int adv = 1) //// advance adv steps from current index position////
{
idx = idx + adv;
return dev_arr[idx];
}
__device__ __host__
T seek(int adv = 1) //// move current index position////
{
idx = adv;
return dev_arr[idx];
}
/////4 DIMENSIONAL SEEK,PEEK, ADVANCE
__device__ __host__
T seek4(int i) //// move current index position////
{
idx = getIndex(i);
return dev_arr[idx];
}
__device__ __host__
T seek4(int i, int j) //// move current index position////
{
idx = getIndex(i, j);
return dev_arr[idx];
}
__device__ __host__
T seek4(int i, int j, int k) //// move current index position////
{
idx = getIndex(i, j, k);
return dev_arr[idx];
}
__device__ __host__
T seek4(int i, int j, int k, int w) //// move current index position////
{
idx = getIndex(i, j, k, w);
return dev_arr[idx];
}
////4D advance
__device__ __host__
T adv4(int i) //// move current index position////
{
idx += getIndex(i);
return dev_arr[idx];
}
__device__ __host__
T adv4(int i, int j) //// move current index position////
{
idx += getIndex(i, j);
return dev_arr[idx];
}
__device__ __host__
T adv4(int i, int j, int k) //// move current index position////
{
idx += getIndex(i, j, k);
return dev_arr[idx];
}
__device__ __host__
T adv4(int i, int j, int k, int w) //// move current index position////
{
idx += getIndex(i, j, k, w);
return dev_arr[idx];
}
////4D Peek
__device__ __host__
T peek4(int i) //// move current index position////
{
int _idx = idx + getIndex(i);
return dev_arr[_idx];
}
__device__ __host__
T peek4(int i, int j) //// move current index position////
{
int _idx = idx + getIndex(i, j);
return dev_arr[_idx];
}
__device__ __host__
T peek4(int i, int j, int k) //// move current index position////
{
int _idx = idx + getIndex(i, j, k);
return dev_arr[_idx];
}
__device__ __host__
T peek4(int i, int j, int k, int w) //// move current index position////
{
int _idx = idx + getIndex(i, j, k, w);
return dev_arr[_idx];
}
////return current index position
__device__ __host__
int pos()
{
return idx;
}
/////specialized views section for navigation
__device__ __host__
int vpos()
{
return vidx;
}
__device__ __host__
T vpeek(int adv = 1) ////view data from advance without moving current index position
{
unsigned int temp = vidx + adv;
return dev_arr[temp];
}
__device__ __host__
T vadv(int adv = 1) //// advance adv steps from current index position////
{
vidx = idx + adv;
return dev_arr[vidx];
}
__device__ __host__
T vseek(int adv = 1) //// move current index position////
{
vidx = adv;
return dev_arr[vidx];
}
__device__ __host__
T vadv4(int i, int j=0, int k=0, int w=0) //// move current index position////
{
vidx += getViewIndex(i, j, k, w);
return dev_arr[vidx];
}
__device__ __host__
T vseek4(int i, int j, int k, int w) //// move current index position////
{
vidx = getViewIndex(i, j, k, w);
return dev_arr[vidx];
}
__device__ __host__
T vpeek4(int i, int j=0, int k=0, int w=0) //// move current index position////
{
int _idx = vidx + getViewIndex(i, j, k, w);
return dev_arr[_idx];
}
//__device__ __host__ ////original copy engine
//cudaError_t copy(smartArrayWrapper other)
//{
// cudaError_t cudaStatus;
// if (this == &other) ////check for self assignment
// {
// fprintf(stderr, "Cannot self assign\n");
// cudaStatus = cudaErrorMemoryAllocation;
// return cudaStatus;
// //exit(1);
// }
//
// //// size of data to copy, using the least of the 2 to avoid errors
// unsigned int copySize = (getlen() > other.getlen()) ? getlen() : other.getlen();
// if(array_type == smartHost) ////host -> host/device copies
// {
// if(other.getType() == smartHost)
// {
// cudaStatus = smartCopyHost2Host<T>(dev_arr,other.inner_ptr(),copySize);
// }
// else if (other.getType() == smartDevice)
// {
// cudaStatus = smartCopyHost2Device<T>(dev_arr,other.inner_ptr(),copySize);
// }
// else
// {
// ////unsupported copy types
// fprintf(stderr, "Cannot copy unsupported type\n");
// cudaStatus = cudaErrorMemoryAllocation;
// return cudaStatus;
// }
// }
// else if (array_type == smartDevice) ////device -> host/device copies
// {
// if(other.getType() == smartHost)
// {
// cudaStatus = smartCopyDevice2Host<T>(dev_arr,other.inner_ptr(),copySize);
// }
// else if (other.getType() == smartDevice)
// {
// cudaStatus = smartCopyDevice2Device<T>(dev_arr,other.inner_ptr(),copySize);
// }
// else
// {
// ////unsupported copy types
// fprintf(stderr, "Cannot copy unsupported type\n");
// cudaStatus = cudaErrorMemoryAllocation;
// return cudaStatus;
// }
// }
// else ////unsupported copy types
// {
// fprintf(stderr, "Cannot copy unsupported type\n");
// cudaStatus = cudaErrorMemoryAllocation;
// return cudaStatus;
// }
//
//
// return cudaStatus;
//}
__device__ __host__
cudaError_t copy(smartArrayWrapper<T,smartDevice> &other)
{
cudaError_t cudaStatus;
//other._is_copy = true; ////prevent destructor from deleting array pointer
//if (this == &other)////check for self assignment
//{
// fprintf(stderr, "Cannot self assign\n");
// cudaStatus = cudaErrorMemoryAllocation;
// return cudaStatus;
// //exit(1);
//}
//if(dev_arr == NULL) ////allocate memory if it does not exist
//{
// dev_arr = smartArray<T,mem_loc>(other.getlen(), cudaStatus);
// lengthX = other.getlenX();
// lengthY = other.getlenY();
// lengthZ = other.getlenZ();
// lengthW = other.getlenW();
//}
//// size of data to copy, using the least of the 2 to avoid errors
unsigned int copySize = (getlen() > other.getlen()) ? getlen() : other.getlen();
if(array_type == smartHost || array_type == smartPinnedHost) ////host -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
cudaStatus = smartCopyDevice2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else if (array_type == smartDevice || array_type == smartKernel) ////device -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
cudaStatus = smartCopyDevice2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else ////unsupported copy types
{
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
return cudaStatus;
}
__device__ __host__
cudaError_t copy(smartArrayWrapper<T,smartHost> &other)
{
cudaError_t cudaStatus;
//other._is_copy = true; ////prevent destructor from deleting array pointer
//if (this == &other)////check for self assignment
//{
// fprintf(stderr, "Cannot self assign\n");
// cudaStatus = cudaErrorMemoryAllocation;
// return cudaStatus;
// //exit(1);
//}
//if(dev_arr == NULL) ////allocate memory if it does not exist
//{
// dev_arr = smartArray<T,mem_loc>(other.getlen(), cudaStatus);
// lengthX = other.getlenX();
// lengthY = other.getlenY();
// lengthZ = other.getlenZ();
// lengthW = other.getlenW();
//}
//// size of data to copy, using the least of the 2 to avoid errors
unsigned int copySize = (getlen() > other.getlen()) ? getlen() : other.getlen();
if(array_type == smartHost || array_type == smartPinnedHost) ////host -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
cudaStatus = smartCopyDevice2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else if (array_type == smartDevice || array_type == smartKernel) ////device -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
cudaStatus = smartCopyDevice2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else ////unsupported copy types
{
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
return cudaStatus;
}
__device__ __host__
cudaError_t copy(smartArrayWrapper<T,smartPinnedHost> &other)
{
cudaError_t cudaStatus;
//other._is_copy = true; ////prevent destructor from deleting array pointer
//if (this == &other)////check for self assignment
//{
// fprintf(stderr, "Cannot self assign\n");
// cudaStatus = cudaErrorMemoryAllocation;
// return cudaStatus;
// //exit(1);
//}
//if(dev_arr == NULL) ////allocate memory if it does not exist
//{
// dev_arr = smartArray<T,mem_loc>(other.getlen(), cudaStatus);
// lengthX = other.getlenX();
// lengthY = other.getlenY();
// lengthZ = other.getlenZ();
// lengthW = other.getlenW();
//}
//// size of data to copy, using the least of the 2 to avoid errors
unsigned int copySize = (getlen() > other.getlen()) ? getlen() : other.getlen();
if(array_type == smartHost || array_type == smartPinnedHost) ////host -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
cudaStatus = smartCopyDevice2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else if (array_type == smartDevice || array_type == smartKernel) ////device -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
cudaStatus = smartCopyDevice2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else ////unsupported copy types
{
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
return cudaStatus;
}
__device__ __host__
cudaError_t copy(smartArrayWrapper<T,smartKernel> &other)
{
cudaError_t cudaStatus;
//other._is_copy = true; ////prevent destructor from deleting array pointer
//if (this == &other)////check for self assignment
//{
// fprintf(stderr, "Cannot self assign\n");
// cudaStatus = cudaErrorMemoryAllocation;
// return cudaStatus;
// //exit(1);
//}
//if(dev_arr == NULL) ////allocate memory if it does not exist
//{
// dev_arr = smartArray<T,mem_loc>(other.getlen(), cudaStatus);
// lengthX = other.getlenX();
// lengthY = other.getlenY();
// lengthZ = other.getlenZ();
// lengthW = other.getlenW();
//}
//// size of data to copy, using the least of the 2 to avoid errors
unsigned int copySize = (getlen() > other.getlen()) ? getlen() : other.getlen();
if(array_type == smartHost || array_type == smartPinnedHost) ////host -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
cudaStatus = smartCopyDevice2Host<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else if (array_type == smartDevice || array_type == smartKernel) ////device -> host/device copies
{
if(other.getType() == smartHost || other.getType() == smartPinnedHost)
{
cudaStatus = smartCopyHost2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else if (other.getType() == smartDevice || other.getType() == smartKernel)
{
cudaStatus = smartCopyDevice2Device<T>(dev_arr,other.inner_ptr(),copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else ////unsupported copy types
{
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
return cudaStatus;
}
__device__ __host__
cudaError_t copy(T* other, unsigned int other_size, int other_array_type = 1)
{
cudaError_t cudaStatus;
//if (this != &other)
//{
// fprintf(stderr, "Cannot copy unsupported type\n");
// cudaStatus != cudaSuccess;
// return cudaStatus;
// //exit(1);
//}
//// size of data to copy, using the least of the 2 to avoid errors
int copySize = (getlen() > other_size) ? getlen() : other_size;
if(array_type == smartHost || array_type == smartPinnedHost) ////host -> host/device copies
{
if(other_array_type == smartHost || other_array_type == smartPinnedHost)
{
cudaStatus = smartCopyHost2Host<T>(dev_arr,other,copySize);
}
else if (other_array_type == smartDevice || other_array_type == smartKernel)
{
cudaStatus = smartCopyDevice2Host<T>(dev_arr,other,copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else if (array_type == smartDevice || array_type == smartKernel) ////device -> host/device copies
{
if(other_array_type == smartHost || other_array_type == smartPinnedHost)
{
cudaStatus = smartCopyHost2Device<T>(dev_arr,other,copySize);
}
else if (other_array_type == smartDevice || other_array_type == smartKernel)
{
cudaStatus = smartCopyDevice2Device<T>(dev_arr,other,copySize);
}
else
{
////unsupported copy types
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
}
else ////unsupported copy types
{
fprintf(stderr, "Cannot copy unsupported type\n");
cudaStatus = cudaErrorMemoryAllocation;
return cudaStatus;
}
return cudaStatus;
}
__device__ __host__
cudaError_t destroy()
{
cudaError_t cudaStatus;
//cudaStatus = smartFree<T>(*this);
cudaStatus = smartFree<T>(inner_ptr(),array_type);
initializeArray();
return cudaStatus;
}
// Return the pointer to the array.
__device__ __host__
T* inner_ptr() { return dev_arr; }
__device__ __host__
T* &inner_ptr_ref() { return dev_arr; }
// Return the location of the array.
__device__ __host__
int getType() { return array_type; }
// Return the length of the array.
__device__ __host__
int size() { return lengthX * lengthY * lengthZ * lengthW; }
__device__ __host__
int getlen() { return lengthX * lengthY * lengthZ * lengthW; }
__device__ __host__
int getlenX() { return lengthX; }
__device__ __host__
int getlenY() { return lengthY; }
__device__ __host__
int getlenZ() { return lengthZ; }
__device__ __host__
int getlenW() { return lengthW; }
__device__ __host__
int deviceID() { return device_id; }
// Specialized views of the array.
__device__ __host__
int getViewDimX() { return vX; }
__device__ __host__
int getViewDimY() { return vY; }
__device__ __host__
int getViewDimZ() { return vZ; }
__device__ __host__
int getViewDimW() { return vW; }
__device__ __host__
bool setViewDim(int X = 1, int Y = 1, int Z = 1, int W = 1, bool setSuccess = true)
{
if (X < 0) {setSuccess = false; return setSuccess;}
if (Y < 0) {setSuccess = false; return setSuccess;}
if (Z < 0) {setSuccess = false; return setSuccess;}
if (W < 0) {setSuccess = false; return setSuccess;}
if((X * Y * Z * W >= 0) && (X * Y * Z * W <= lengthX * lengthY * lengthZ * lengthW))
{
vX = X; vY = Y; vZ = Z; vW = W;
setSuccess = true;
}
else
{
setSuccess = false; ////set view failed
}
return setSuccess;
}
__device__ __host__
T viewAt_1D(int i)
{
if(i < 0 || i > vX * vY * vZ * vW -1)
{
// Take appropriate action here. This is just a placeholder response.
fprintf(stderr, "View Index [%d] of smart Array is out of bounds\n",i);
exit(1);
}
vidx = 1;
return dev_arr[i];
}
__device__ __host__
T viewAt_2D(int i, int j)
{
if((i < 0 || i > vX-1) || (j < 0 || j > vY-1))
{
// Take appropriate action here. This is just a placeholder response.
fprintf(stderr, "View Index [%d][%d] of smart Array is out of bounds\n",i,j);
exit(1);
}
int _idx = i + j * vX;
vidx = _idx;
return dev_arr[_idx];
}
__device__ __host__
T viewAt_3D(int i, int j, int k)
{
if((i < 0 || i > vX-1) || (j < 0 || j > vY-1) || (k < 0 || k > vZ-1))
{
// Take appropriate action here. This is just a placeholder response.
fprintf(stderr, "View Index [%d][%d][%d] of smart Array is out of bounds\n",i,j,k);
exit(1);
}
int _idx = i + j * vX + k * vX * vY;
vidx = _idx;
return dev_arr[_idx];
}
__device__ __host__
T viewAt_4D(int i, int j, int k, int w)
{
if(((i < 0 || i > vX-1) || (j < 0 || j > vY-1) || (k < 0 || k > vZ-1)) ||(w < 0 || w > vW-1))
{
// Take appropriate action here. This is just a placeholder response.
fprintf(stderr, "View Index [%d][%d][%d][%d] of smart Array is out of bounds\n",i,j,k,w);
exit(1);
}
int _idx = i + j * vX + k * vX * vY + w * vX * vY * vZ;
vidx = _idx;
return dev_arr[_idx];
}
__device__ __host__
T viewAt(int i, int j=0, int k=0, int w=0)
{
if(((i < 0 || i > vX-1) || (j < 0 || j > vY-1) || (k < 0 || k > vZ-1)) ||(w < 0 || w > vW-1))
{
// Take appropriate action here. This is just a placeholder response.
fprintf(stderr, "View Index [%d][%d][%d][%d] of smart Array is out of bounds\n",i,j,k,w);
exit(1);
}
int _idx = i + j * vX + k * vX * vY + w * vX * vY * vZ;
vidx = _idx;
return dev_arr[_idx];
}
};
template <typename T>
inline __device__ __host__
cudaError_t smartFree(smartArrayWrapper<T,smartHost> other)
{
cudaError_t cudaStatus;
int array_type = other.getType();
T* dev_mem = other.inner_ptr();
if (array_type == smartHost)
{
free(dev_mem);
dev_mem = NULL;
cudaStatus = cudaSuccess;
}
else if (array_type == smartDevice)
{
cudaFree(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Device Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else if (array_type == smartPinnedHost)
{
cudaFreeHost(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else
{
cudaStatus = cudaErrorMemoryAllocation;
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
return cudaStatus;
}
return cudaStatus;
}
template <typename T>
inline __device__ __host__ cudaError_t smartFree(smartArrayWrapper<T,smartPinnedHost> other)
{
cudaError_t cudaStatus;
int array_type = other.getType();
T* dev_mem = other.inner_ptr();
if (array_type == smartHost)
{
free(dev_mem);
dev_mem = NULL;
cudaStatus = cudaSuccess;
}
else if (array_type == smartDevice)
{
cudaFree(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Device Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else if (array_type == smartPinnedHost)
{
cudaFreeHost(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else
{
cudaStatus = cudaErrorMemoryAllocation;
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
return cudaStatus;
}
return cudaStatus;
}
template <typename T>
inline __device__ __host__ cudaError_t smartFree(smartArrayWrapper<T,smartDevice> other)
{
cudaError_t cudaStatus;
int array_type = other.getType();
T* dev_mem = other.inner_ptr();
if (array_type == smartHost)
{
free(dev_mem);
dev_mem = NULL;
cudaStatus = cudaSuccess;
}
else if (array_type == smartDevice)
{
cudaFree(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Device Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else if (array_type == smartPinnedHost)
{
cudaFreeHost(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else
{
cudaStatus = cudaErrorMemoryAllocation;
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
return cudaStatus;
}
return cudaStatus;
}
template <typename T>
inline __device__ __host__
cudaError_t smartFree(smartArrayWrapper<T,smartKernel> other)
{
cudaError_t cudaStatus;
int array_type = other.getType();
T* dev_mem = other.inner_ptr();
if (array_type == smartHost)
{
free(dev_mem);
dev_mem = NULL;
cudaStatus = cudaSuccess;
}
else if (array_type == smartDevice)
{
cudaFree(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Device Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else if (array_type == smartPinnedHost)
{
cudaFreeHost(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
return cudaStatus;
}
else if (array_type == smartKernel)
{
free(dev_mem);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
//////goto Error;
}
dev_mem = NULL;
return cudaStatus;
}
else
{
cudaStatus = cudaErrorMemoryAllocation;
fprintf(stderr, "Cuda Host Memory Release failed: %s\n", cudaGetErrorString(cudaStatus));
return cudaStatus;
}
return cudaStatus;
}
////miscellanous wrappers
class smartDeviceManager
{
////beta////
private:
int device_id; //// device id
bool reset_on_exit; ///used to check if automatic reset of device is called
bool _is_mapped_device; ///// check if a device has been wrapped
public:
smartDeviceManager()
{
device_id = -1;
reset_on_exit = false;
_is_mapped_device = false;
}
smartDeviceManager(int dev_id)
{
device_id = dev_id;
reset_on_exit = false;
_is_mapped_device = true;
}
smartDeviceManager(int dev_id, bool _reset_on_exit)
{
device_id = dev_id;
reset_on_exit = _reset_on_exit;
_is_mapped_device = true;
}
~smartDeviceManager()
{
if(reset_on_exit)
{
//initializeDevice();
if (_is_mapped_device)
{
resetDevice();
}
}
}
cudaError_t chooseDevice(cudaDeviceProp deviceProp)
{
int device;
cudaError_t cudaStatus;
cudaStatus = cudaChooseDevice(&device, &deviceProp);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Choose Device failed! Do you have a CUDA-capable GPU installed?");
}
device_id = device;
return cudaStatus;
}
void mapDevice(int dev_id = 0)
{
device_id = dev_id;
_is_mapped_device = true;
}
void removeDeviceMap()
{
device_id = -1;
_is_mapped_device = false;
}
cudaError_t setDevice()
{
///keeping track of device ////
//int t_device_id = __device_id;
//cudaStatus = cudaSetDevice(__device_id); ////retore original device
cudaError_t cudaStatus;
cudaStatus = cudaSetDevice(device_id);
//cudaStatus = cudaSetDevice(__device_id); ////retore original device
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Set Device failed! Do you have a CUDA-capable GPU installed?\n");
}
return cudaStatus;
}
cudaError_t initializeDevice(int dev_id=0)
{
device_id = dev_id;
cudaError_t cudaStatus;
cudaStatus = cudaSetDevice(device_id);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Initialization failed! Do you have a CUDA-capable GPU installed?\n");
return cudaStatus;
}
_is_mapped_device = true;
return cudaStatus;
}
cudaError_t resetDevice(bool clean_global_state = false)
{
cudaError_t cudaStatus;
int t_device_id = __device_id; //// store current device
setDevice();
cudaStatus = cudaDeviceReset();
cudaStatus = cudaSetDevice(t_device_id); ////retore original device
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Device Reset failed!\n");
return cudaStatus;
}
__clean_globals = clean_global_state;
return cudaStatus;
}
cudaError_t synchronize()
{
cudaError_t cudaStatus;
int t_device_id = __device_id; //// store current device
setDevice();
cudaStatus = cudaDeviceSynchronize();
cudaStatus = cudaSetDevice(t_device_id); ////retore original device
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching Kernel!\n", cudaStatus);
}
return cudaStatus;
}
////set limits - default in bytes
cudaError_t setDeviceLimit(int memory_size)
{
cudaError_t cudaStatus;
int t_device_id = __device_id; //// store current device
setDevice();
cudaStatus = cudaDeviceSetLimit(cudaLimitMallocHeapSize, memory_size);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSetLimit returned error code %d!\n", cudaStatus);
}
cudaStatus = cudaSetDevice(t_device_id); ////retore original device
return cudaStatus;
}
////set limits - default in KB
cudaError_t setDeviceLimitKB(int memory_size)
{
cudaError_t cudaStatus;
int t_device_id = __device_id; //// store current device
setDevice();
cudaStatus = cudaDeviceSetLimit(cudaLimitMallocHeapSize, memory_size*1024);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSetLimit returned error code %d!\n", cudaStatus);
}
cudaStatus = cudaSetDevice(t_device_id); ////retore original device
return cudaStatus;
}
////set limits - default in MB
cudaError_t setDeviceLimitMB(int memory_size)
{
cudaError_t cudaStatus;
int t_device_id = __device_id; //// store current device
setDevice();
cudaStatus = cudaDeviceSetLimit(cudaLimitMallocHeapSize, memory_size*1024*1024);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSetLimit returned error code %d!\n", cudaStatus);
}
cudaStatus = cudaSetDevice(t_device_id); ////retore original device
return cudaStatus;
}
int getDeviceID()
{
return device_id;
}
cudaDeviceProp getDeviceProperties()
{
cudaError_t cudaStatus;
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, device_id);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Device selection and properties failed!\n", cudaStatus);
}
return deviceProp;
}
cudaDeviceProp printDeviceProperties()
{
cudaError_t cudaStatus;
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, device_id);
cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "Device selection and properties failed!\n", cudaStatus);
}
printf("Device %d has compute capability %d.%d.\n",
device_id, deviceProp.major, deviceProp.minor);
return deviceProp;
}
};
class smartEvent
{
private:
cudaEvent_t start, stop;
bool _stoped;
public:
smartEvent()
{
cudaEventCreate(&start);
cudaEventCreate(&stop);
initialize();
}
~smartEvent()
{
cudaEventDestroy(start);
cudaEventDestroy(stop);
}
void initialize()
{
cudaEventRecord(start, 0);
cudaEventRecord(stop, 0);
_stoped = false;
}
inline
void recStart()
{
initialize();
cudaEventRecord(start, 0);
}
inline
void recStop()
{
cudaEventRecord(stop, 0);
_stoped = true;
}
float elapsedTime()
{
float elapsedTime = 0;
if(_stoped)
{
cudaEventSynchronize(stop);
cudaEventElapsedTime(&elapsedTime, start, stop);
}
return elapsedTime;
}
float printElapsedTime()
{
float elapsedTime;
cudaEventElapsedTime(&elapsedTime, start, stop);
printf("Elapsed time is %fms\n",elapsedTime);
return elapsedTime;
}
};
class smartConfig
{
////beta testing/////
private:
int device_id;
int problem_size;
cudaDeviceProp deviceProp;
int configRank; //// rank of the config //// 1, 2, 3 for 1,2,3 dimensions. like x,y,z dimensions
///return params
int threads_per_block;
int num_blocks;
void _initialize(int data_size, int dev_id, int threads, int blocks)
{
device_id = dev_id;
problem_size = data_size;
cudaGetDeviceProperties(&deviceProp, device_id);
threads_per_block = threads;
num_blocks = blocks;
}
void _calcConfig(int dim_size)
{
int launch_thread_size = problem_size + problem_size % 32;
int launch_block_size = (launch_thread_size / deviceProp.maxThreadsPerBlock) + ((launch_thread_size%deviceProp.maxThreadsPerBlock)?1:0);
num_blocks = (launch_block_size % 128) + launch_block_size;
int maxBlockDimX = deviceProp.maxThreadsDim[0];
if (num_blocks > maxBlockDimX ) num_blocks = maxBlockDimX;
}
public:
smartConfig()
{
_initialize(0,0,-1,-1);
}
smartConfig(int data_size)
{
_initialize(data_size,0,-1,-1);
}
smartConfig(int data_size, int dev_id)
{
_initialize(data_size,dev_id,-1,-1);
}
smartConfig(int data_size, int dev_id, int threads, int blocks)
{
_initialize(data_size,dev_id, threads, blocks);
}
~smartConfig()
{
}
void setDataSize(int data_size)
{
problem_size = data_size;
}
void config(int threads, int blocks)
{
threads_per_block = threads;
num_blocks = blocks;
}
void setDeviceId(int dev_id)
{
device_id = dev_id;
}
int getDataSize()
{
return problem_size;
}
int getDeviceId()
{
return device_id;
}
int getBlockSize()
{
if (num_blocks <= 0)
{
_calcConfig(problem_size);
}
return num_blocks;
}
int getThreadSize()
{
if (threads_per_block <=0)
{
return deviceProp.maxThreadsPerBlock;
}
return threads_per_block;
}
}; | [
"smartcuda@outlook.com"
] | smartcuda@outlook.com |
839011b2b9adedf652c052fb1dee6de877cff210 | be13a930b4fb3ac40e8d6bb91dba67972a53e861 | /С++/Цикл While/Цикл While.cpp | 2e7d13127f0b3362b84f2fb89f069b2c8240cd55 | [] | no_license | Motenka/C- | 01c903c2083980347bb3466724ac6f61e2986b03 | 06a7a265541a82e157258f8784b14e52e34df8f8 | refs/heads/master | 2021-05-03T19:47:54.230187 | 2018-02-06T08:34:13 | 2018-02-06T08:34:13 | 120,422,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177 | cpp | #include <iostream>
using namespace std;
int main()
{
int i = 1;
while (i <= 100)
{
cout << i << " ";
i = i + 1;
}
return 0;
}
| [
"olimptrade7320@gmail.com"
] | olimptrade7320@gmail.com |
762af186406d9f557ed562506503ec4166f51394 | 681aa52928afa7ca6d86d77aa3d66530f0aee786 | /chapter-03/ex3_17.cpp | e24eca9ade61ff2004b40a56b2005e502e302a25 | [] | no_license | iBreaker/cpp-primer | d2797d50b6cd77ff903dafd42465ff296c8947d2 | dd165319e632b44f1e0f878bdd81ecf6a459d3bf | refs/heads/master | 2021-01-17T17:03:31.538347 | 2016-07-21T03:32:21 | 2016-07-21T03:32:21 | 62,540,417 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 335 | cpp |
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<string> str;
string temp;
while(cin >> temp)
{
str.push_back(temp);
}
cout << endl;
for(string s:str)
{
for(char &c:s)
{
c = toupper(c);
}
cout << s << endl;
}
}
| [
"791628659@qq.com"
] | 791628659@qq.com |
24377c99b6b484483bef5f91780ae7b3468cd118 | d85dc311f6d9668c2d425bb1395e8099c833d334 | /src/dumpkey/stdafx.cpp | 132b07cb7eab7a1376a51ef415039dba1643cc27 | [
"BSD-3-Clause",
"LicenseRef-scancode-unicode-mappings"
] | permissive | yedaoq/google-breakpad_msvc | 594bff6c38f340872d92489c5b4765680e9b55ec | ce09f9eafb8227a99c92ff261090a1d882ec0626 | refs/heads/master | 2021-01-19T09:31:08.502500 | 2015-04-29T03:09:42 | 2015-04-29T03:09:42 | 34,309,571 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 259 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// dumpkey.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
| [
"yedaoq@gmail.com"
] | yedaoq@gmail.com |
0015b1fd3d17abf943642bb50d336d145a39ac90 | 2b6ed44e1a81b7538c68416a94f39c67827e9244 | /Card.cpp | 686e087efa86c2b8e2fb6ab232a42f5757e03bd7 | [] | no_license | rock4on/Atm | 1965218521f246ecac362b53474f8adc696ad7d0 | e0175fbba3fd32be66c956be1eb4b24195b4f069 | refs/heads/main | 2022-12-26T01:38:18.237283 | 2020-10-12T16:29:27 | 2020-10-12T16:29:27 | 303,450,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 266 | cpp | #include "Card.h"
Card::Card(const Card& c):pin(c.pin),sold(c.sold)
{}
float const Card::GetSold()
{
return sold;
}
void Card::SetSold(float s)
{
sold = s;
}
Card* Card::valueOf(Card& c)
{
Card* ca=new Card(c.pin,c.sold);
return ca;
} | [
"noreply@github.com"
] | noreply@github.com |
61a7444b90dec2f341d50b00d0d93dce870cdcc1 | d7e1a4539b56252e76e1e817706dc3de6ce0e979 | /factorial.cpp | 188cbe7860d4404e707d04b1af8baef84cb527fd | [] | no_license | sultanularefin/CPPworks | 0b90481184ff678b501ec5892e75f4641b5dbb2b | 7dcac693646af77acf7d0b5c85a400b19b8b614d | refs/heads/master | 2021-09-21T01:45:33.519523 | 2018-08-18T17:50:51 | 2018-08-18T17:50:51 | 112,120,652 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | cpp | #include"stdafx.h"
#include<stdio.h>
long factorial(int);
int main()
{
int n;
long f;
printf("Enter an integer to find factorial\n");
scanf("%d", &n);
if (n < 0)
printf("Negative integers are not allowed.\n");
else
{
f = factorial(n);
printf("%d! = %ld\n", n, f);
}
return 0;
}
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n - 1));
} | [
"arefin.nordecode@gmail.com"
] | arefin.nordecode@gmail.com |
b97922ce24edae3facc23d70ab8aebea42faa64b | 45d300db6d241ecc7ee0bda2d73afd011e97cf28 | /OTCDerivativesCalculatorModule/Project_Cpp/lib_static/FpmlSerialized/GenClass/fpml-dividend-swaps-5-4/DividendPeriodPayment.hpp | 127521ff1eceb3d33d577b7fb87f98728b6c696d | [] | no_license | fagan2888/OTCDerivativesCalculatorModule | 50076076f5634ffc3b88c52ef68329415725e22d | e698e12660c0c2c0d6899eae55204d618d315532 | refs/heads/master | 2021-05-30T03:52:28.667409 | 2015-11-27T06:57:45 | 2015-11-27T06:57:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,488 | hpp | // DividendPeriodPayment.hpp
#ifndef FpmlSerialized_DividendPeriodPayment_hpp
#define FpmlSerialized_DividendPeriodPayment_hpp
#include <fpml-eq-shared-5-4/DividendPeriod.hpp>
#include <fpml-shared-5-4/PositiveDecimal.hpp>
#include <fpml-shared-5-4/AdjustableOrRelativeDate.hpp>
namespace FpmlSerialized {
class DividendPeriodPayment : public DividendPeriod {
public:
DividendPeriodPayment(TiXmlNode* xmlNode);
bool isFixedStrike(){return this->fixedStrikeIsNull_;}
boost::shared_ptr<PositiveDecimal> getFixedStrike();
std::string getFixedStrikeIDRef(){return fixedStrikeIDRef_;}
bool isPaymentDate(){return this->paymentDateIsNull_;}
boost::shared_ptr<AdjustableOrRelativeDate> getPaymentDate();
std::string getPaymentDateIDRef(){return paymentDateIDRef_;}
bool isValuationDate(){return this->valuationDateIsNull_;}
boost::shared_ptr<AdjustableOrRelativeDate> getValuationDate();
std::string getValuationDateIDRef(){return valuationDateIDRef_;}
protected:
boost::shared_ptr<PositiveDecimal> fixedStrike_;
std::string fixedStrikeIDRef_;
bool fixedStrikeIsNull_;
boost::shared_ptr<AdjustableOrRelativeDate> paymentDate_;
std::string paymentDateIDRef_;
bool paymentDateIsNull_;
boost::shared_ptr<AdjustableOrRelativeDate> valuationDate_;
std::string valuationDateIDRef_;
bool valuationDateIsNull_;
};
} //namespaceFpmlSerialized end
#endif
| [
"math.ansang@gmail.com"
] | math.ansang@gmail.com |
18cce9fd243d56a0eaa0a683f3e88681fdf922b2 | 565e85570d42a599351e513040e1bda8d05d3948 | /tool/zamba/src/view/modules/changechannel.cpp | 8a6725c9a26cd259fa59489a1f57e0ac72f5ac04 | [] | no_license | Hanun11/tvd | 95a74b8ee8a939ba06b4d15dce99bdc548e1be7b | 0d113c46014d738d87cb4db93b566d07fcbc031f | refs/heads/master | 2021-12-14T19:41:15.800531 | 2017-05-20T19:54:40 | 2017-05-20T19:54:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,016 | cpp | /*******************************************************************************
Copyright (C) 2010, 2013 LIFIA - Facultad de Informatica - Univ. Nacional de La Plata
********************************************************************************
This file is part of DTV-luaz implementation.
DTV-luaz is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 2 of the License.
DTV-luaz is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
********************************************************************************
Este archivo es parte de la implementación de DTV-luaz.
DTV-luaz es Software Libre: Ud. puede redistribuirlo y/o modificarlo
bajo los términos de la Licencia Pública General Reducida GNU como es publicada por la
Free Software Foundation, según la versión 2 de la licencia.
DTV-luaz se distribuye esperando que resulte de utilidad, pero SIN NINGUNA
GARANTÍA; ni siquiera la garantía implícita de COMERCIALIZACIÓN o ADECUACIÓN
PARA ALGÚN PROPÓSITO PARTICULAR. Para más detalles, revise la Licencia Pública
General Reducida GNU.
Ud. debería haber recibido una copia de la Licencia Pública General Reducida GNU
junto a este programa. Si no, puede verla en <http://www.gnu.org/licenses/>.
*******************************************************************************/
/*
* changechannel.cpp
*
* Created on: Jun 17, 2011
* Author: gonzalo
*/
#include "luawgt.h"
#include "wgt.h"
#include "../widget/changechannelbydigit.h"
#include <boost/make_shared.hpp>
namespace wgt {
namespace changechannel {
std::map<WidgetId, ChangeChannelByDigitPtr> _widgets;
int create(lua_State* L)
{
int narg = 2;
const colorMap_t colorMap = parseColorTable( L, narg++ );
ChangeChannelByDigitPtr w = boost::make_shared<ChangeChannelByDigit>( colorMap );
WidgetId id = Wgt::view()->addWidget(w);
_widgets[id] = w;
lua_pushnumber(L, id);
return 1;
}
int getValueStr(lua_State* L)
{
int narg = 2;
const WidgetId id = luaL_checkint(L, narg++);
ChangeChannelByDigitPtr widget = _widgets[id];
lua_pushstring(L, widget->getValueStr().c_str());
return 1;
}
int reset(lua_State* L)
{
int narg = 2;
const WidgetId id = luaL_checkint(L, narg++);
ChangeChannelByDigitPtr widget = _widgets[id];
widget->reset();
return 0;
}
void init(lua_State *L){
const struct luaL_Reg methods[] = {
{"new", create},
{"getValueStr", getValueStr},
{"reset", reset},
{NULL, NULL}
};
luaL_register(L, "changechannel", methods);
}
} // changechannel
} // wgt
| [
"jbucar@gmail.com"
] | jbucar@gmail.com |
6be97ddd1b1e15ef3fed30abd7190b7008b5960e | c3744c8c230573a4bcdb76bf49493a1ea61c72d1 | /test/benchmarktest/ability_manager_test/ability_manager_test.cpp | 472d2bdcd76b922df1111880dcc2066a696f0bc9 | [
"Apache-2.0"
] | permissive | openharmony/aafwk_standard | 31d1f9d2c19067b804f1236d73df744586bbe7f7 | 834a566b1372268c7bbb0c40362322f812ca6efc | refs/heads/master | 2022-07-22T02:08:02.526908 | 2022-05-27T02:39:48 | 2022-05-27T02:39:48 | 400,083,557 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,859 | cpp | /*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <benchmark/benchmark.h>
#include <unistd.h>
#include <vector>
#include "ability_manager_client.h"
#include "hilog_wrapper.h"
using namespace std;
using namespace OHOS;
using namespace OHOS::AAFwk;
namespace {
class AbilityManagerTest : public benchmark::Fixture {
public:
AbilityManagerTest()
{
Iterations(iterations);
Repetitions(repetitions);
ReportAggregatesOnly();
}
~AbilityManagerTest() override = default;
void SetUp(const ::benchmark::State &state) override
{
AbilityManagerClient::GetInstance()->CleanAllMissions();
usleep(usleepTime);
}
void TearDown(const ::benchmark::State &state) override
{
AbilityManagerClient::GetInstance()->CleanAllMissions();
usleep(usleepTime);
}
protected:
const int32_t repetitions = 3;
const int32_t iterations = 1000;
const int32_t upperLimit = 32;
// sleep 100ms
const int32_t usleepTime = 1000 * 100;
};
BENCHMARK_F(AbilityManagerTest, GetProcessRunningInfosTestCase)(
benchmark::State &state)
{
while (state.KeepRunning()) {
std::vector<AppExecFwk::RunningProcessInfo> info {};
ErrCode errCode = AbilityManagerClient::GetInstance()->GetProcessRunningInfos(info);
if (errCode != ERR_OK) {
state.SkipWithError("GetProcessRunningInfosTestCase failed.");
}
}
}
BENCHMARK_F(AbilityManagerTest, GetAbilityRunningInfosTestCase)(
benchmark::State &state)
{
while (state.KeepRunning()) {
std::vector<AbilityRunningInfo> info {};
ErrCode errCode = AbilityManagerClient::GetInstance()->GetAbilityRunningInfos(info);
if (errCode != ERR_OK) {
state.SkipWithError("GetAbilityRunningInfosTestCase failed.");
}
}
}
BENCHMARK_F(AbilityManagerTest, GetExtensionRunningInfosTestCase)(
benchmark::State &state)
{
while (state.KeepRunning()) {
std::vector<ExtensionRunningInfo> info {};
ErrCode errCode = AbilityManagerClient::GetInstance()->GetExtensionRunningInfos(upperLimit, info);
if (errCode != ERR_OK) {
state.SkipWithError("GetExtensionRunningInfosTestCase failed.");
}
}
}
}
// Run the benchmark
BENCHMARK_MAIN();
| [
"yangzhongkai@huawei.com"
] | yangzhongkai@huawei.com |
a81ea7b2988b894cfb8b7783fe3ea6c6663973b4 | 362d2b1a4f4967cd8a20a6340e662a85800ca315 | /include/mpc_local_planner/shadow_casting.h | b2c79ea43ca536552dea4cc5cf98011542ef63de | [] | no_license | project-TARIV/mpc_local_planner | 57c92dcb2925a57a317a451a319a83913dc57284 | a4824c4450a69c42bd807e629fad94b632812583 | refs/heads/master | 2023-05-02T00:11:37.620180 | 2021-05-24T13:46:26 | 2021-05-24T13:46:26 | 275,569,148 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 361 | h | #ifndef MPC_LOCAL_PLANNER_SHADOW_CASTING_H
#define MPC_LOCAL_PLANNER_SHADOW_CASTING_H
#include <functional>
using IsBlocked = std::function<bool(int, int)>;
using AddPoint = std::function<void(int, int)>;
void shadow_cast(const IsBlocked &is_blocked, const AddPoint &add_point, int max_index, double del = 1e-5);
#endif //MPC_LOCAL_PLANNER_SHADOW_CASTING_H
| [
"suraj.rathi00@gmail.com"
] | suraj.rathi00@gmail.com |
a85029f8457e7a644e10a1a27ff79dc9e642d856 | 81b370d8b975b36834800390254f92fb67fb9328 | /Leetcode/31.cc | 9e5c4c34b193be1aa59954b6a87440fa6ed99def | [
"MIT"
] | permissive | Superdanby/YEE | b58c198486ffb45d5c162958d232441d9ac56ed4 | 3dfb71033455772dac9a6c09a025fdfd0307182e | refs/heads/master | 2022-08-29T05:11:24.816963 | 2022-07-10T08:50:02 | 2022-07-10T08:50:02 | 53,384,232 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 465 | cc | class Solution {
public:
void nextPermutation(vector<int>& nums) {
int prev = nums.back();
auto it = nums.rbegin();
for (; it != nums.rend(); ++it) {
if (prev > *it) break;
prev = *it;
}
if (it == nums.rend()) {
sort(nums.begin(), nums.end());
return;
}
auto replacement = std::lower_bound(nums.rbegin(), it, *it + 1);
std::swap(*it, *replacement);
std::sort(nums.rbegin(), it, std::greater());
}
};
| [
"dannymrt1@gmail.com"
] | dannymrt1@gmail.com |
969564e65943b9d6619d0e2f895dcf67faeab4dd | 50696432296e7603bf6e1eebd0b5a343f3c878d5 | /opp_gui/include/opp_gui/widgets/polygon_area_selection_widget.h | 46238f3d3cb4b56965336dbb9bc2d3fedc65d833 | [] | no_license | mpowelson/Toolpath-Offline-Planning | b56ab8c473313086d0fe691dfb7723cc0896c15d | 2fff173666c0fb8e191b0c2a4d01d353f819a34b | refs/heads/master | 2020-12-12T08:59:28.513411 | 2020-01-07T19:24:48 | 2020-01-07T19:24:48 | 234,094,685 | 0 | 0 | null | 2020-01-15T14:10:22 | 2020-01-15T14:10:21 | null | UTF-8 | C++ | false | false | 1,779 | h | /*
* Copyright 2019 Southwest Research Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OPP_GUI_WIDGETS_POLYGON_AREA_SELECTION_WIDGET_H
#define OPP_GUI_WIDGETS_POLYGON_AREA_SELECTION_WIDGET_H
#include <QWidget>
#include <ros/ros.h>
#include <shape_msgs/Mesh.h>
#include <opp_area_selection/selection_artist.h>
#include "opp_gui/register_ros_msgs_for_qt.h"
namespace Ui {
class PolygonAreaSelectionWidget;
}
namespace opp_gui
{
class PolygonAreaSelectionWidget : public QWidget
{
Q_OBJECT
public:
explicit PolygonAreaSelectionWidget(
ros::NodeHandle& nh,
const std::string& selection_world_frame,
const std::string& selection_sensor_frame,
QWidget *parent = nullptr);
~PolygonAreaSelectionWidget();
public Q_SLOTS:
void init(const shape_msgs::Mesh& mesh);
Q_SIGNALS:
void selectedSubmesh(const shape_msgs::Mesh::Ptr& selected_submesh);
private Q_SLOTS:
void clearROISelection();
void applySelection();
private:
Ui::PolygonAreaSelectionWidget *ui_;
shape_msgs::Mesh::Ptr mesh_;
shape_msgs::Mesh::Ptr submesh_;
opp_area_selection::SelectionArtist selector_;
}; // end class PolygonAreaSelectionWidget
} // end namespace opp_gui
#endif // OPP_GUI_WIDGETS_POLYGON_AREA_SELECTION_WIDGET_H
| [
"david.merz@swri.org"
] | david.merz@swri.org |
433d248c4ff5c28125f00a416277763662cb9fbc | cc992e6414ceb7734cf36e6e09d5ae0555e2b759 | /activefunctional_test.h | bd74a5c8e929456569728542fb8c571398b5588e | [] | no_license | sitr0n/testinginterface | 95d0d4370a2a0468e9e6cd34f8935b21d15b6888 | b540445bc52a90b226ef2afae89672d31c008d19 | refs/heads/master | 2020-07-29T13:08:36.706412 | 2019-11-14T16:24:11 | 2019-11-14T16:24:11 | 209,815,381 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,234 | h | #pragma once
#include "testingtask.h"
#include "wingchargeblock.h"
#include <QTime>
#include <vector>
class ActiveFunctionalTest : public TestingTask
{
public:
ActiveFunctionalTest(WingChargeBlock &unit);
struct Margins {
float inputCurrent = 180.0;
float inductiveCurrent = 180.0;
float wingLQI = 60.0;
float slotLQI = 60.0;
float wingLoss = 1.0;
float slotLoss = 1.0;
float chargeCurrent = 48.0;
};
struct Parameters {
int measuringDuration = 15000;
Margins margin;
};
static Parameters getParameters();
static void setParameters(Parameters param);
private:
WingChargeBlock &m_unit;
bool m_pairDelayStarted;
bool m_measuringStarted;
QTime m_pairDelayWatch;
QTime m_measuringWatch;
std::vector<float> m_iSupplySamples;
std::vector<float> m_iSupplyWingSamples;
std::vector<float> m_wingLossSamples;
std::vector<float> m_wingLQISamples;
std::vector<float> m_slotLQISamples;
static Parameters s_param;
const int PAIRING_DELAY = 2000;
const int STABILIZING_INERTIA = 22500; // wingLoss seems to stabilize after ~22.5 seconds [= 22500 ms]
const int TIMEOUT_MARGIN = 5000;
};
| [
"a@a.com"
] | a@a.com |
e45a1b3f5582e8cda0c278f46297093a3bffac29 | 08fae5bd7f16809b84cf6463693732f2308ab4da | /MarketDataAdapters/include/$Activ/ActivMiddleware/ActivIp/Windows/TcpSocket.h | af0a706ad3f99883330c420afd6c1effdde5097b | [] | no_license | psallandre/IVRM | a7738c31534e1bbff32ded5cfc7330c52b378f19 | 5a674d10caba23b126e9bcea982dee30eee72ee1 | refs/heads/master | 2021-01-21T03:22:33.658311 | 2014-09-24T11:47:10 | 2014-09-24T11:47:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,446 | h | /**
* @file Windows/TcpSocket.h
*
* @brief Header file for tcp socket class.
*
* $Log: $
*/
#if !defined (ACTIV_IP_WINDOWS_TCP_SOCKET_H)
#define ACTIV_IP_WINDOWS_TCP_SOCKET_H
#include "ActivMiddleware/ActivIp/IpSocket.h"
#include <mswsock.h>
/**
* @brief List of socket states.
*/
#define ACTIV_IP_SOCKET_STATE_LIST(d) \
d(STATE_INITIALIZED) \
d(STATE_W4_CONNECT) \
d(STATE_W4_ACCEPT) \
d(STATE_CONNECTED) \
d(STATE_W4_DISCONNECT)
namespace Activ
{
class TcpListener;
/**
* @brief TCP socket class.
*/
class TcpSocket : public IpSocket
{
public:
/**
* @brief Connection states.
*/
enum State
{
ACTIV_IP_SOCKET_STATE_LIST(ACTIV_DECLARE_VALUE_WITH_COMMA)
};
/**
* @brief Stats.
*/
class Stats : public IpSocket::Stats
{
public:
/**
* @brief Constructor.
*
* Note if constructing a Stats object directly, you the socket's mutex must be locked (this isn't
* done by the Stats constructor). Alternatively, use the helper function IpSocket::Stats::Get() which will
* lock the mutex for you before gathering the stats.
*
* @param socket to get stats from.
*/
ACTIV_IP_API Stats(const TcpSocket &socket);
State m_state; ///< Connection state
bool m_connectPosted; ///< Connect posted
bool m_acceptPosted; ///< Accept posted
};
/**
* @brief Constructor.
*
* @param manager the IpManager that owns the socket.
*
* @throw Exception.
*/
ACTIV_IP_API TcpSocket(IpManager &manager);
/**
* @brief Destructor.
*/
ACTIV_IP_API ~TcpSocket();
/**
* @brief Initiate connection.
*
* @param remoteAddress the remote address to connect to.
* @param remotePort the remote port to connect to (local endian).
* @param localAddress the optional local address to bind to.
* @param localPort the optional local port number to bind to (local endian).
*
* @throw Exception.
*/
ACTIV_IP_API void Connect(const char *remoteAddress, const uint16_t remotePort, const char *localAddress = 0, const uint16_t localPort = 0);
/**
* @brief Initiate connection.
*
* @param remoteAddress the remote address to connect to.
* @param localAddress the local address to bind to.
*
* @throw Exception.
*/
ACTIV_IP_API void Connect(const IpAddress &remoteAddress, const IpAddress &localAddress);
/**
* @brief Post a connect to an already set up address.
*
* @throw Exception.
*/
ACTIV_IP_API void PostConnect();
/**
* @brief Post an accept.
*
* @param listener the server to accept from.
*
* @throw Exception.
*/
ACTIV_IP_API void Accept(TcpListener &listener);
/**
* @brief Close a connection.
*
* @param gracefully true to only close the socket once any outstanding tx has completed,
* false to force the socket closed immediately.
*
* @retval true the socket is fully closed.
* @retval false a close event will be fired when the socket is fully closed (OnDisconnect()).
*/
ACTIV_IP_API bool Disconnect(const bool gracefully = false);
/**
* @brief Forcably initiate a connection break. If the socket was connected, OnBreak() will be fired.
*/
ACTIV_IP_API void Break();
/**
* @brief Get the state of the socket.
*/
ACTIV_IP_API State GetState() const;
/**
* @brief Return state as string.
*
* @return Socket state in string form.
*/
ACTIV_IP_API static std::string StateToString(const State state);
protected:
// IpSocket overrides
ACTIV_IP_API virtual CompletionResult OnRxBuffers(const size_t dataLength);
ACTIV_IP_API virtual CompletionResult OnTxBuffers(const size_t dataLength);
/**
* @brief Connection has closed at the user's request.
*/
ACTIV_IP_API virtual void OnDisconnect();
/**
* @brief Connection has broken (the user didn't initiate).
*/
ACTIV_IP_API virtual void OnBreak();
/**
* @brief Connect has succeeded.
*/
ACTIV_IP_API virtual void OnConnect();
/**
* @brief Connect has been aborted (with a Disconnect()) before it completed either successfully or unsuccessfully.
*/
ACTIV_IP_API virtual void OnConnectAborted();
/**
* @brief Connect has failed.
*
* @param errorCode Win32 error code.
*/
ACTIV_IP_API virtual void OnConnectFailed(const uint32_t errorCode);
/**
* @brief Accept has succeeded.
*/
ACTIV_IP_API virtual void OnAccept();
/**
* @brief Accept has been aborted. Calling Disconnect() before an accept has completed will cause this event.
*/
ACTIV_IP_API virtual void OnAcceptAborted();
/**
* @brief Accept has failed. Stopping the listener will cause this event on an accepting connection.
*
* @param errorCode Win32 error code.
*/
ACTIV_IP_API virtual void OnAcceptFailed(const uint32_t errorCode);
private:
/**
* @brief Set up a client side socket.
*
* @param socket reference to a SocketWrapper object to receive the socket handle.
*
* @throw Exception.
*/
void CreateClientSocket(SocketWrapper &socket);
/**
* @brief Set up an accepting socket.
*
* @param socket reference to a SocketWrapper object to receive the socket handle.
*
* @throw Exception.
*/
void CreateAcceptSocket(SocketWrapper &socket);
/**
* @brief Do final cleanup on the connection, including firing disconnection events.
*/
void Cleanup();
ACTIV_IP_API virtual void HandleIoFailure(const bool gracefully);
ACTIV_IP_API virtual bool OnIoCompletion(Overlapped *pOverlapped);
/**
* @brief Process connect completion.
*/
void OnConnectCompletion();
/**
* @brief Process successful connect completion.
*/
void OnSuccessfulConnectCompletion();
/**
* @brief Process accept completion.
*/
void OnAcceptCompletion();
/**
* @brief Process successful accept completion.
*/
void OnSuccessfulAcceptCompletion();
/**
* @brief Sync bsd connect thread info.
*/
class ConnectThreadInfo
{
public:
/**
* @brief Constructor.
*
* @param tcpSocket TcpSocket object initiating the connect.
* @param socket socket to connect on.
* @param remoteAddress address to connect to.
*/
ConnectThreadInfo(TcpSocket &tcpSocket, const SOCKET socket, const IpAddress &remoteAddress);
TcpSocket & m_tcpSocket;
SOCKET m_socket;
IpAddress m_remoteAddress;
};
/**
* @brief Initiate a bsd sync connect.
*
* @param pConnectThreadInfo info for the connect.
*/
void BsdConnect(ConnectThreadInfo * const pConnectThreadInfo);
/**
* @brief Thread function to invoke bsd connect.
*/
static unsigned WINAPI BsdConnectThread(void *p);
State m_state; ///< The state of the connection
// client side members
Overlapped m_connectOverlapped; ///< Overlapped info for async connect
LPFN_CONNECTEX m_pConnectEx; ///< Pointer to ConnectEx() function
IpAddress m_providedLocalAddress; ///< Provided local address
// server side members
static const size_t PADDED_ADDRESS_SIZE = sizeof(SOCKADDR_IN6) + 16;
static const size_t ACCEPT_BUFFER_SIZE = 2 * PADDED_ADDRESS_SIZE;
Overlapped m_acceptOverlapped; ///< Overlapped info for async accept
SOCKET m_listeningSocket; ///< The server socket that will accept
byte_t m_acceptBuffer[ACCEPT_BUFFER_SIZE]; ///< Buffer for addresses
LPFN_ACCEPTEX m_pAcceptEx; ///< Pointer to AcceptEx() function
LPFN_GETACCEPTEXSOCKADDRS m_pGetAcceptExSockAddrs; ///< Pointer to GetAcceptExSockAddrs() function
};
} // namespace Activ
#endif // !defined (ACTIV_IP_WINDOWS_TCP_SOCKET_H)
| [
"alex2172@gmail.com"
] | alex2172@gmail.com |
9d27f8e9ecab801678666e1bdef50ac5bfeb138f | f5d2816aef1b26222c780dc2de428c2c4e50575a | /div.hpp | 091c41639cc3f6dfb29a66e814306322217152a5 | [] | no_license | Kirby-Vong/Lab6 | bb810114e01a3afc3d042b4ea59b9e5e146c6b9d | 7bd3b31f6f3b4ac6044d638908707ef2850f163a | refs/heads/master | 2023-02-03T07:55:29.295849 | 2020-11-18T01:31:11 | 2020-11-18T01:31:11 | 322,998,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 637 | hpp | #ifndef __DIV_HPP__
#define __DIV_HPP__
#include "base.hpp"
#include <string>
using namespace std;
class Div : public Base {
public:
string str;
//Div() : Base(){ };
Base* leftChild;
Base* rightChild;
Div(Base* left, Base* right){
leftChild = left;
rightChild = right;
}
virtual double evaluate() {
if(rightChild->evaluate() == 0) return -1;
return leftChild->evaluate() / rightChild->evaluate();
}
virtual string stringify() {
str = leftChild->stringify() + " / " + rightChild->stringify();
return str;
}
};
#endif //__DIV_HPP__
| [
"kirbyvong@gmail.com"
] | kirbyvong@gmail.com |
b2d4632c1f333cbb71b11b23fd64f76c02bb01a0 | fc2dc1ed6446e7354f2425e5c8294c41a4033c9e | /src/catsim/Logger.h | 60e02815c19d4ed9d2dce2a7d1a860e1f4c11691 | [] | no_license | IsuraManchanayake/cat-simulator-cpp | bb51d3c60cb646a98595d3666b60b0dab9284b1f | 4f62b98537300da7d1d63435a4fb77a776747e99 | refs/heads/main | 2023-08-12T19:16:42.716176 | 2021-10-14T16:49:23 | 2021-10-14T16:49:23 | 417,211,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 766 | h | //
// Created by isura on 10/13/2021.
//
#ifndef CAT_SIMULATOR_CPP_LOGGER_H
#define CAT_SIMULATOR_CPP_LOGGER_H
#include "Enums.h"
#include <functional>
#include <memory>
#include <ostream>
struct LoggerHelper {
using type = std::ostream;
LogMethod method;
LoggerHelper::type *file;
bool dynamic;
LoggerHelper(LogMethod method, const std::string &file);
LoggerHelper(LoggerHelper &&other) noexcept ;
LoggerHelper &operator=(LoggerHelper other);
~LoggerHelper();
};
struct Logger {
static LoggerHelper helper;
static void setup(LogMethod method, const std::string &file="simulation.log");
static LoggerHelper::type &log();
static void sep();
static bool first_time;
};
#endif //CAT_SIMULATOR_CPP_LOGGER_H
| [
"isura.14@cse.mrt.ac.lk"
] | isura.14@cse.mrt.ac.lk |
fb95e30caf882aba632cd8a9d65513c44f12b5cf | 819c0f614ad59e17dfc04c3649189a70a03c342d | /C++/Tasks/IPClassEmpty.cpp | 325d817be55849ce4cf365cf87a72fdae984d08d | [] | no_license | harshjoshi02/Hacktoberfest2020 | 79e81a093c92d1203043aa4c2f69635b77a0f1f9 | 785a25acf8dfd8ad0737451f7b6b630960dd4c86 | refs/heads/master | 2023-01-06T22:35:01.986679 | 2020-10-31T18:06:01 | 2020-10-31T18:06:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,550 | cpp | //find class of an IP Address through C programming
#include <stdio.h>
#include <string.h>
/*
Function : extractIpAddress
Arguments :
1) sourceString - String pointer that contains ip address
2) ipAddress - Target variable short type array pointer that will store ip address octets
*/
void extractIpAddress(unsigned char *sourceString,short *ipAddress)
{
unsigned short len=0;
unsigned char oct[4]={0},cnt=0,cnt1=0,i,buf[5];
len=strlen(sourceString);
for(i=0;i<len;i++)
{
if(sourceString[i]!='.'){
buf[cnt++] =sourceString[i];
}
if(sourceString[i]=='.' || i==len-1){
buf[cnt]='\0';
cnt=0;
oct[cnt1++]=atoi(buf);
}
}
ipAddress[0]=oct[0];
ipAddress[1]=oct[1];
ipAddress[2]=oct[2];
ipAddress[3]=oct[3];
}
int main()
{
unsigned char ip[20]={0};
short ipAddress[4];
printf("Enter IP Address (xxx.xxx.xxx.xxx format): ");
scanf("%s",ip);
extractIpAddress(ip,&ipAddress[0]);
printf("\nIp Address: %03d. %03d. %03d. %03d\n",ipAddress[0],ipAddress[1],ipAddress[2],ipAddress[3]);
if(ipAddress[0]>=0 && ipAddress[0]<=127)
printf("Class A Ip Address.\n");
if(ipAddress[0]>127 && ipAddress[0]<191)
printf("Class B Ip Address.\n");
if(ipAddress[0]>191 && ipAddress[0]<224)
printf("Class C Ip Address.\n");
if(ipAddress[0]>224 && ipAddress[0]<=239)
printf("Class D Ip Address.\n");
if(ipAddress[0]>239)
printf("Class E Ip Address.\n");
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
9244b600948a2c7f3ee678d1785a476f89f86eaa | b1aef802c0561f2a730ac3125c55325d9c480e45 | /src/ripple/unity/app_consensus.cpp | 4212e64fea56976c38cb16a1535dc6e7f3a6d7c0 | [] | no_license | sgy-official/sgy | d3f388cefed7cf20513c14a2a333c839aa0d66c6 | 8c5c356c81b24180d8763d3bbc0763f1046871ac | refs/heads/master | 2021-05-19T07:08:54.121998 | 2020-03-31T11:08:16 | 2020-03-31T11:08:16 | 251,577,856 | 6 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 176 | cpp |
#include <ripple/app/consensus/RCLConsensus.cpp>
#include <ripple/app/consensus/RCLCxPeerPos.cpp>
#include <ripple/app/consensus/RCLValidations.cpp>
| [
"sgy-official@hotmail.com"
] | sgy-official@hotmail.com |
4e8d2b4d258df54fdb04da146dcb1d3bb9064c96 | 83b8df63f639ad6d29b35bff2c5ef32f928ba053 | /Project7.2/copyP7.2.cpp | 696764a9787ee6a334c9d941fabe1d8e7e362db3 | [] | no_license | JonathanVasquez0620/Project7.2 | a0c4495d47d4af3e66030cc05e21c5cc7c03eadb | c0b264216f1eea16e068c13f9438668c61ec6175 | refs/heads/master | 2020-05-01T06:00:57.649851 | 2019-05-11T22:52:49 | 2019-05-11T22:52:49 | 177,318,518 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,809 | cpp | /*
Jonathan Vasquez
Main menu U)ser, A)dministrator or Q)uit
User asks for userID and number of copies and increment the appropriate account. Return to Main Menu
Administrator brings up menu B)alance, M)aster or P)roject
Balance shows copy total of all accounts, Master and Project input user and link to appropriate account.
*/
#include<iostream>
using namespace std;
int main()
{
int* user[100] = { nullptr };
int masterAccount = 0, projectAccount[10] = { 0 };
for (int i = 0; i < 100; i++)
{
user[i] = &masterAccount;
}
int id, copies;
bool quit = false;
char menuChoice;
do
{
cout << "Enter choice from the following Menu.\n";
cout << "U)ser A)dministrator or Q)uit:" << endl;
cin >> menuChoice;
switch (menuChoice)
{
case 'U':
cout << "Enter user ID followed by number of copies: ";
cin >> id >> copies;
*user[id] = *user[id] + copies;
break;
case 'A':
char adMenu;
cout << "Enter choice from the following menu:\n";
cout << "B)alance M)aster or P)roject:" << endl;
cin >> adMenu;
switch (adMenu)
{
case 'B':
cout << masterAccount << endl;
for (int i = 0; i < 9; i++)
{
cout << projectAccount[i] << endl;
}
break;
case 'M':
cout << "Enter user id to be placed into Master Account (0-99):" << endl;
cin >> id;
user[id] = &masterAccount;
break;
case 'P':
int projAccount;
cout << "Enter user id (0 - 99) and Project Account (0-9) to be placed into:" << endl;
cin >> id >> projAccount ;
user[id] = &projectAccount[projAccount];
break;
default:
break;
}
break;
case 'Q':
cout << "Have a nice day.";
quit = true;
break;
default:
cout << "Your choice was not valid. Please try again: " << endl;
break;
}
}
while (quit == false);
return 0;
} | [
"jvasquezaj@gmail.com"
] | jvasquezaj@gmail.com |
8d99a1882d31d3ea3f9e754c4adb17668905107a | ed5926ae512e238af0f14655a3187d7e7fbf7ef7 | /chromium2/chrome/browser/ash/policy/login/signin_profile_extensions_policy_browsertest.cc | 9a442d404756949eb4ee38297aa65739eb401caf | [
"BSD-3-Clause"
] | permissive | slimsag/mega | 82595cd443d466f39836e24e28fc86d3f2f1aefd | 37ef02d1818ae263956b7c8bc702b85cdbc83d20 | refs/heads/master | 2023-08-16T22:36:25.860917 | 2023-08-15T23:40:31 | 2023-08-15T23:40:31 | 41,717,977 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 25,901 | cc | // Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <string>
#include "ash/constants/ash_paths.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/threading/thread_restrictions.h"
#include "base/version.h"
#include "chrome/browser/ash/policy/login/signin_profile_extensions_policy_test_base.h"
#include "chrome/browser/extensions/crx_installer.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/policy/extension_force_install_mixin.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_paths.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_launcher.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/extension_host_test_helper.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extension_util.h"
#include "extensions/browser/notification_types.h"
#include "extensions/browser/test_extension_registry_observer.h"
#include "extensions/browser/update_observer.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_id.h"
#include "extensions/common/extension_set.h"
#include "extensions/common/features/feature_channel.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "extensions/common/switches.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace content {
class StoragePartition;
}
namespace policy {
namespace {
// Parameters for the several extensions and apps that are used by the tests in
// this file (note that the paths are given relative to the src/chrome/test/data
// directory):
// * The manual testing app which is allowlisted for running in the sign-in
// profile:
const char kAllowlistedAppId[] = "bjaiihebfngildkcjkjckolinodhliff";
const char kAllowlistedAppCrxPath[] =
"extensions/signin_screen_manual_test_app/app_signed_by_webstore.crx";
// * A trivial test app which is NOT allowlisted for running in the sign-in
// profile:
const char kNotAllowlistedAppId[] = "mockapnacjbcdncmpkjngjalkhphojek";
const char kNotAllowlistedAppPath[] = "extensions/trivial_platform_app/app/";
const char kNotAllowlistedAppPemPath[] =
"extensions/trivial_platform_app/app.pem";
// * A trivial test extension which is allowlisted for running in the sign-in
// profile:
const char kAllowlistedExtensionId[] = "ngjobkbdodapjbbncmagbccommkggmnj";
const char kAllowlistedExtensionCrxPath[] =
"extensions/signin_screen_manual_test_extension/"
"extension_signed_by_webstore.crx";
// * A trivial test extension which is NOT allowlisted for running in the
// sign-in profile:
const char kNotAllowlistedExtensionId[] = "mockepjebcnmhmhcahfddgfcdgkdifnc";
const char kNotAllowlistedExtensionPath[] =
"extensions/trivial_extension/extension/";
const char kNotAllowlistedExtensionPemPath[] =
"extensions/trivial_extension/extension.pem";
// * An extension which is NOT allowlisted for running in the sign-in profile
// and that suppresses its immediate auto updates:
const char kNoImmediateUpdateExtensionId[] = "noidlplbgmdmbccnafgibfgokggdpncj";
const char kNoImmediateUpdateExtensionPathTemplate[] =
"extensions/no_immediate_update_extension/src-%s";
const char kNoImmediateUpdateExtensionPemPath[] =
"extensions/no_immediate_update_extension/key.pem";
const char kNoImmediateUpdateExtensionLatestVersion[] = "2.0";
const char kNoImmediateUpdateExtensionOlderVersion[] = "1.0";
// Returns the path to the no_immediate_update_extension with the given version.
base::FilePath GetNoImmediateUpdateExtensionPath(const std::string& version) {
return base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(base::StringPrintf(kNoImmediateUpdateExtensionPathTemplate,
version.c_str()));
}
// Observer that allows waiting for an installation failure of a specific
// extension/app.
// TODO(emaxx): Extract this into a more generic helper class for using in other
// tests.
class ExtensionInstallErrorObserver final {
public:
ExtensionInstallErrorObserver(const Profile* profile,
const std::string& extension_id)
: profile_(profile),
extension_id_(extension_id),
notification_observer_(
extensions::NOTIFICATION_EXTENSION_INSTALL_ERROR,
base::BindRepeating(
&ExtensionInstallErrorObserver::IsNotificationRelevant,
base::Unretained(this))) {}
ExtensionInstallErrorObserver(const ExtensionInstallErrorObserver&) = delete;
ExtensionInstallErrorObserver& operator=(
const ExtensionInstallErrorObserver&) = delete;
void Wait() { notification_observer_.Wait(); }
private:
// Callback which is used for |WindowedNotificationObserver| for checking
// whether the condition being awaited is met.
bool IsNotificationRelevant(
const content::NotificationSource& source,
const content::NotificationDetails& details) const {
extensions::CrxInstaller* const crx_installer =
content::Source<extensions::CrxInstaller>(source).ptr();
return crx_installer->profile() == profile_ &&
crx_installer->extension()->id() == extension_id_;
}
const raw_ptr<const Profile, ExperimentalAsh> profile_;
const extensions::ExtensionId extension_id_;
content::WindowedNotificationObserver notification_observer_;
};
// Observer that allows waiting until the specified version of the given
// extension/app gets available for an update.
class ExtensionUpdateAvailabilityObserver final
: public extensions::UpdateObserver {
public:
ExtensionUpdateAvailabilityObserver(Profile* profile,
const std::string& extension_id,
const base::Version& awaited_version)
: profile_(profile),
extension_id_(extension_id),
awaited_version_(awaited_version) {
extensions::ExtensionSystem::Get(profile_)
->extension_service()
->AddUpdateObserver(this);
}
ExtensionUpdateAvailabilityObserver(
const ExtensionUpdateAvailabilityObserver&) = delete;
ExtensionUpdateAvailabilityObserver& operator=(
const ExtensionUpdateAvailabilityObserver&) = delete;
~ExtensionUpdateAvailabilityObserver() override {
extensions::ExtensionSystem::Get(profile_)
->extension_service()
->RemoveUpdateObserver(this);
}
// Should be called no more than once.
void Wait() {
// Note that the expected event could have already been observed before this
// point, in which case the run loop will exit immediately.
run_loop_.Run();
}
void OnAppUpdateAvailable(const extensions::Extension* extension) override {
if (extension->id() == extension_id_ &&
extension->version() == awaited_version_) {
run_loop_.Quit();
}
}
void OnChromeUpdateAvailable() override {}
private:
const raw_ptr<Profile, ExperimentalAsh> profile_;
const extensions::ExtensionId extension_id_;
const base::Version awaited_version_;
base::RunLoop run_loop_;
};
// Class for testing sign-in profile apps/extensions.
class SigninProfileExtensionsPolicyTest
: public SigninProfileExtensionsPolicyTestBase {
public:
SigninProfileExtensionsPolicyTest(const SigninProfileExtensionsPolicyTest&) =
delete;
SigninProfileExtensionsPolicyTest& operator=(
const SigninProfileExtensionsPolicyTest&) = delete;
protected:
SigninProfileExtensionsPolicyTest()
: SigninProfileExtensionsPolicyTestBase(version_info::Channel::STABLE) {}
void SetUpOnMainThread() override {
SigninProfileExtensionsPolicyTestBase::SetUpOnMainThread();
extension_force_install_mixin_.InitWithDevicePolicyCrosTestHelper(
GetInitialProfile(), policy_helper());
}
ExtensionForceInstallMixin extension_force_install_mixin_{&mixin_host_};
};
} // namespace
// Tests that a allowlisted app gets installed.
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsPolicyTest,
AllowlistedAppInstallation) {
EXPECT_TRUE(extension_force_install_mixin_.ForceInstallFromCrx(
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kAllowlistedAppCrxPath),
ExtensionForceInstallMixin::WaitMode::kLoad));
const extensions::Extension* extension =
extension_force_install_mixin_.GetEnabledExtension(kAllowlistedAppId);
ASSERT_TRUE(extension);
EXPECT_TRUE(extension->is_platform_app());
}
// Tests that a non-allowlisted app is forbidden from installation.
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsPolicyTest,
NotAllowlistedAppInstallation) {
Profile* profile = GetInitialProfile();
ExtensionInstallErrorObserver install_error_observer(profile,
kNotAllowlistedAppId);
EXPECT_TRUE(extension_force_install_mixin_.ForceInstallFromSourceDir(
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kNotAllowlistedAppPath),
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kNotAllowlistedAppPemPath),
ExtensionForceInstallMixin::WaitMode::kNone));
install_error_observer.Wait();
EXPECT_FALSE(extension_force_install_mixin_.GetInstalledExtension(
kNotAllowlistedAppId));
}
// Tests that a allowlisted extension is installed. Force-installed extensions
// on the sign-in screen should also automatically have the
// |login_screen_extension| type.
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsPolicyTest,
AllowlistedExtensionInstallation) {
EXPECT_TRUE(extension_force_install_mixin_.ForceInstallFromCrx(
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kAllowlistedExtensionCrxPath),
ExtensionForceInstallMixin::WaitMode::kLoad));
const extensions::Extension* extension =
extension_force_install_mixin_.GetEnabledExtension(
kAllowlistedExtensionId);
ASSERT_TRUE(extension);
EXPECT_TRUE(extension->is_login_screen_extension());
}
// Tests that a non-allowlisted extension is forbidden from installation.
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsPolicyTest,
NotAllowlistedExtensionInstallation) {
Profile* profile = GetInitialProfile();
ExtensionInstallErrorObserver install_error_observer(
profile, kNotAllowlistedExtensionId);
EXPECT_TRUE(extension_force_install_mixin_.ForceInstallFromSourceDir(
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kNotAllowlistedExtensionPath),
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kNotAllowlistedExtensionPemPath),
ExtensionForceInstallMixin::WaitMode::kNone));
install_error_observer.Wait();
EXPECT_FALSE(extension_force_install_mixin_.GetInstalledExtension(
kNotAllowlistedExtensionId));
}
// Tests that the extension system enables non-standard extensions in the
// sign-in profile.
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsPolicyTest, ExtensionsEnabled) {
EXPECT_TRUE(extensions::ExtensionSystem::Get(GetInitialProfile())
->extension_service()
->extensions_enabled());
}
// Tests that a background page is created for the installed sign-in profile
// app.
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsPolicyTest, BackgroundPage) {
EXPECT_TRUE(extension_force_install_mixin_.ForceInstallFromCrx(
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kAllowlistedAppCrxPath),
ExtensionForceInstallMixin::WaitMode::kBackgroundPageFirstLoad));
}
// Tests installation of multiple sign-in profile apps/extensions.
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsPolicyTest,
MultipleAppsOrExtensions) {
EXPECT_TRUE(extension_force_install_mixin_.ForceInstallFromCrx(
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kAllowlistedAppCrxPath),
ExtensionForceInstallMixin::WaitMode::kLoad));
EXPECT_TRUE(extension_force_install_mixin_.ForceInstallFromCrx(
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kAllowlistedExtensionCrxPath),
ExtensionForceInstallMixin::WaitMode::kLoad));
EXPECT_TRUE(
extension_force_install_mixin_.GetEnabledExtension(kAllowlistedAppId));
EXPECT_TRUE(extension_force_install_mixin_.GetEnabledExtension(
kAllowlistedExtensionId));
}
// Tests that a sign-in profile app or a sign-in profile extension has isolated
// storage, i.e. that it does not reuse the Profile's default StoragePartition.
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsPolicyTest,
IsolatedStoragePartition) {
Profile* profile = GetInitialProfile();
EXPECT_TRUE(extension_force_install_mixin_.ForceInstallFromCrx(
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kAllowlistedAppCrxPath),
ExtensionForceInstallMixin::WaitMode::kBackgroundPageFirstLoad));
EXPECT_TRUE(extension_force_install_mixin_.ForceInstallFromCrx(
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kAllowlistedExtensionCrxPath),
ExtensionForceInstallMixin::WaitMode::kBackgroundPageFirstLoad));
content::StoragePartition* storage_partition_for_app =
extensions::util::GetStoragePartitionForExtensionId(
kAllowlistedAppId, profile, /*can_create=*/false);
content::StoragePartition* storage_partition_for_extension =
extensions::util::GetStoragePartitionForExtensionId(
kAllowlistedExtensionId, profile, /*can_create=*/false);
content::StoragePartition* default_storage_partition =
profile->GetDefaultStoragePartition();
ASSERT_TRUE(storage_partition_for_app);
ASSERT_TRUE(storage_partition_for_extension);
ASSERT_TRUE(default_storage_partition);
EXPECT_NE(default_storage_partition, storage_partition_for_app);
EXPECT_NE(default_storage_partition, storage_partition_for_extension);
EXPECT_NE(storage_partition_for_app, storage_partition_for_extension);
}
// Class for testing the sign-in profile extensions with the simulated absence
// of network connectivity.
class SigninProfileExtensionsPolicyOfflineLaunchTest
: public SigninProfileExtensionsPolicyTest {
protected:
SigninProfileExtensionsPolicyOfflineLaunchTest() {
// In the non-PRE test, this simulates inability to make network requests
// for fetching the extension update manifest and CRX files. In the PRE test
// the server is not hung, allowing the initial installation of the
// extension.
if (!content::IsPreTest()) {
extension_force_install_mixin_.SetServerErrorMode(
ExtensionForceInstallMixin::ServerErrorMode::kHung);
}
}
void SetUpOnMainThread() override {
SigninProfileExtensionsPolicyTest::SetUpOnMainThread();
test_extension_registry_observer_ =
std::make_unique<extensions::TestExtensionRegistryObserver>(
extensions::ExtensionRegistry::Get(GetInitialProfile()),
kAllowlistedAppId);
EXPECT_TRUE(extension_force_install_mixin_.ForceInstallFromCrx(
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kAllowlistedAppCrxPath),
ExtensionForceInstallMixin::WaitMode::kNone));
}
void TearDownOnMainThread() override {
test_extension_registry_observer_.reset();
SigninProfileExtensionsPolicyTest::TearDownOnMainThread();
}
void WaitForTestExtensionLoaded() {
test_extension_registry_observer_->WaitForExtensionLoaded();
}
private:
std::unique_ptr<extensions::TestExtensionRegistryObserver>
test_extension_registry_observer_;
};
// This is the preparation step for the actual test. Here the allowlisted app
// gets installed into the sign-in profile.
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsPolicyOfflineLaunchTest,
PRE_Test) {
WaitForTestExtensionLoaded();
}
// Tests that the allowlisted app gets launched using the cached version even
// when there's no network connection (i.e., neither the extension update
// manifest nor the CRX file can be fetched during this browser execution).
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsPolicyOfflineLaunchTest, Test) {
WaitForTestExtensionLoaded();
}
// Class for testing the sign-in profile extensions with a corrupt cache file.
class SigninProfileExtensionsPolicyCorruptCacheTest
: public SigninProfileExtensionsPolicyTest {
protected:
void SetUpOnMainThread() override {
SigninProfileExtensionsPolicyTest::SetUpOnMainThread();
test_extension_registry_observer_ =
std::make_unique<extensions::TestExtensionRegistryObserver>(
extensions::ExtensionRegistry::Get(GetInitialProfile()),
kAllowlistedAppId);
EXPECT_TRUE(extension_force_install_mixin_.ForceInstallFromCrx(
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kAllowlistedAppCrxPath),
ExtensionForceInstallMixin::WaitMode::kNone, &installed_extension_id_,
&installed_extension_version_));
}
void TearDownOnMainThread() override {
test_extension_registry_observer_.reset();
SigninProfileExtensionsPolicyTest::TearDownOnMainThread();
}
void WaitForTestExtensionLoaded() {
test_extension_registry_observer_->WaitForExtensionLoaded();
}
base::FilePath GetCachedCrxFilePath() const {
const base::FilePath cache_file_path =
base::PathService::CheckedGet(ash::DIR_SIGNIN_PROFILE_EXTENSIONS);
const std::string file_name =
base::StringPrintf("%s-%s.crx", installed_extension_id_.c_str(),
installed_extension_version_.GetString().c_str());
return cache_file_path.AppendASCII(file_name);
}
private:
std::unique_ptr<extensions::TestExtensionRegistryObserver>
test_extension_registry_observer_;
extensions::ExtensionId installed_extension_id_;
base::Version installed_extension_version_;
};
// This is the preparation step for the actual test. Here the allowlisted app
// gets installed into the sign-in profile and then the cached .crx file get
// corrupted.
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsPolicyCorruptCacheTest,
PRE_ExtensionIsInstalledAfterCorruption) {
WaitForTestExtensionLoaded();
// Manually corrupt file. The directory for cached extensions
// (|DIR_SIGNIN_PROFILE_EXTENSIONS|) is overridden with a new temp directory
// for every test run (see RegisterStubPathOverrides()) so this does not
// affect any other tests.
base::ScopedAllowBlockingForTesting scoped_allowed_blocking_for_testing;
const base::FilePath cached_crx_file_path = GetCachedCrxFilePath();
ASSERT_TRUE(PathExists(cached_crx_file_path));
ASSERT_TRUE(base::WriteFile(cached_crx_file_path, "random-data"));
}
// Tests that the allowlisted app still gets installed correctly, even if the
// existing file in cache is corrupted.
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsPolicyCorruptCacheTest,
ExtensionIsInstalledAfterCorruption) {
WaitForTestExtensionLoaded();
}
// Class for testing the auto update of the sign-in profile extensions.
class SigninProfileExtensionsAutoUpdatePolicyTest
: public SigninProfileExtensionsPolicyTest {
public:
SigninProfileExtensionsAutoUpdatePolicyTest() {
// Initially block the server that hosts the extension. This is to let the
// test bodies simulate the offline scenario or to let them make the updated
// manifest seen by the extension system quickly (background: once it
// fetches a manifest for the first time, the next check will happen after a
// very long delay, which would make the test time out).
extension_force_install_mixin_.SetServerErrorMode(
ExtensionForceInstallMixin::ServerErrorMode::kInternalError);
}
void SetUpCommandLine(base::CommandLine* command_line) override {
SigninProfileExtensionsPolicyTest::SetUpCommandLine(command_line);
// Allow the test extension to be run on the login screen despite not being
// conformant to the "signin_screen" behavior feature.
command_line->AppendSwitchASCII(
extensions::switches::kAllowlistedExtensionID,
kNoImmediateUpdateExtensionId);
}
void SetUpOnMainThread() override {
SigninProfileExtensionsPolicyTest::SetUpOnMainThread();
test_extension_registry_observer_ =
std::make_unique<extensions::TestExtensionRegistryObserver>(
extensions::ExtensionRegistry::Get(GetInitialProfile()),
kNoImmediateUpdateExtensionId);
test_extension_latest_version_update_available_observer_ =
std::make_unique<ExtensionUpdateAvailabilityObserver>(
GetInitialProfile(), kNoImmediateUpdateExtensionId,
base::Version(kNoImmediateUpdateExtensionLatestVersion));
const std::string version = content::IsPreTest()
? kNoImmediateUpdateExtensionOlderVersion
: kNoImmediateUpdateExtensionLatestVersion;
EXPECT_TRUE(extension_force_install_mixin_.ForceInstallFromSourceDir(
GetNoImmediateUpdateExtensionPath(version),
base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
.AppendASCII(kNoImmediateUpdateExtensionPemPath),
ExtensionForceInstallMixin::WaitMode::kNone));
}
void TearDownOnMainThread() override {
test_extension_latest_version_update_available_observer_.reset();
test_extension_registry_observer_.reset();
SigninProfileExtensionsPolicyTest::TearDownOnMainThread();
}
void WaitForTestExtensionLoaded() {
test_extension_registry_observer_->WaitForExtensionLoaded();
}
void WaitForTestExtensionLatestVersionUpdateAvailable() {
test_extension_latest_version_update_available_observer_->Wait();
}
base::Version GetTestExtensionVersion() const {
const extensions::Extension* const extension =
extension_force_install_mixin_.GetEnabledExtension(
kNoImmediateUpdateExtensionId);
if (!extension)
return base::Version();
return extension->version();
}
private:
std::unique_ptr<extensions::TestExtensionRegistryObserver>
test_extension_registry_observer_;
std::unique_ptr<ExtensionUpdateAvailabilityObserver>
test_extension_latest_version_update_available_observer_;
};
// This is the first preparation step for the actual test. Here the old version
// of the extension is served, and it gets installed into the sign-in profile.
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsAutoUpdatePolicyTest,
PRE_PRE_Test) {
// Unblock the server hosting the extension immediately.
extension_force_install_mixin_.SetServerErrorMode(
ExtensionForceInstallMixin::ServerErrorMode::kNone);
WaitForTestExtensionLoaded();
EXPECT_EQ(GetTestExtensionVersion(),
base::Version(kNoImmediateUpdateExtensionOlderVersion));
}
// This is the second preparation step for the actual test. Here the new version
// of the extension is served, and it gets fetched and cached.
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsAutoUpdatePolicyTest, PRE_Test) {
// Let the extensions system load the previously fetched version before
// starting to serve the newer version, to avoid hitting flaky DCHECKs in the
// extensions system internals (see https://crbug.com/810799).
WaitForTestExtensionLoaded();
EXPECT_EQ(GetTestExtensionVersion(),
base::Version(kNoImmediateUpdateExtensionOlderVersion));
// Start serving the newer version. The extensions system should eventually
// fetch this version due to the retry mechanism when the fetch request to the
// update servers was failing. We verify that the new version eventually gets
// fetched and becomes available for an update.
EXPECT_TRUE(extension_force_install_mixin_.UpdateFromSourceDir(
GetNoImmediateUpdateExtensionPath(
kNoImmediateUpdateExtensionLatestVersion),
kNoImmediateUpdateExtensionId,
ExtensionForceInstallMixin::UpdateWaitMode::kNone));
extension_force_install_mixin_.SetServerErrorMode(
ExtensionForceInstallMixin::ServerErrorMode::kNone);
WaitForTestExtensionLatestVersionUpdateAvailable();
// The running extension should stay at the older version, since it ignores
// update notifications and never idles, and also the browser is expected to
// not force immediate updates.
// Note: There's no reliable way to test that the preliminary autoupdate
// doesn't happen, but doing RunUntilIdle() at this point should make the test
// at least flaky in case a bug is introduced somewhere.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(GetTestExtensionVersion(),
base::Version(kNoImmediateUpdateExtensionOlderVersion));
}
// This is the actual test. Here we verify that the new version of the
// extension, as fetched in the PRE_Test, gets launched even in the "offline"
// mode (since the server hosting the extension stays in the error mode
// throughout this part).
IN_PROC_BROWSER_TEST_F(SigninProfileExtensionsAutoUpdatePolicyTest, Test) {
WaitForTestExtensionLoaded();
EXPECT_EQ(GetTestExtensionVersion(),
base::Version(kNoImmediateUpdateExtensionLatestVersion));
}
} // namespace policy
| [
"stephen@sourcegraph.com"
] | stephen@sourcegraph.com |
14d6e0fe47217c3a29ee00d7376c7c8d2b816691 | 1b30ac483e5bceb592d45b297c0c5caf2bfb785b | /9095.cpp | 63a0d0325d16099595def3dcc9b50b901a44bf77 | [] | no_license | GreJangre/algorithm_C | b1bdb9d9963e38d84e1c0724ce9caa4af5a2221c | c0199479dfe672d79b7e394265d620254b6014f3 | refs/heads/master | 2020-04-29T16:09:51.975141 | 2019-03-18T09:44:52 | 2019-03-18T09:44:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 373 | cpp | #include <cstdio>
int t, n, arr[12] = {0, 1, 2, 4};
int fib(int value) {
if (value < 1) return 0;
if (arr[value] != 0) return arr[value];
return arr[value] = fib(value - 1) + fib(value - 2) + fib(value - 3);
}
int main() {
scanf("%d", &t);
for(int i = 0; i < t; i++) {
scanf("%d", &n);
printf("%d\n", fib(n));
}
return 0;
} | [
"dlatjdwn8824@naver.com"
] | dlatjdwn8824@naver.com |
e9e367aeff7fb5d92b5d445ace6de9aa53211c75 | 1b9ff615cef2ad9edf1114c4c33afd38e4430571 | /ui/mainwindow.h | 5113eb4a8dd26193082d50a5b6caab040b08dcac | [] | no_license | cuvidk/interactive-character-recognition | 0f6881cccfc76451ad2bdb36ff88ba45db00d1cf | f822c56f98907cb333eb62ecd9c5b82b07b0295f | refs/heads/master | 2021-01-21T14:11:39.498402 | 2017-09-15T10:12:12 | 2017-09-15T10:12:12 | 59,768,175 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,266 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QSpinBox>
#include <QMessageBox>
class ScribbleArea;
class OcrAppManager;
class MainWindow : public QMainWindow
{
friend class OcrAppManager;
Q_OBJECT
signals:
void startLearning();
void learnDataSignal(QImage image, int label);
public slots:
void updatePredictionLabel(int pred);
void updateActualLabel(int label);
void disableWhenDemoRunning();
void enableWhenDemoDone();
void learnWarningBox();
void emitLearnData(QImage image);
void toggleUi();
void setDoneLearning();
public:
explicit MainWindow(ScribbleArea* scribbleArea, QWidget *parent = 0);
~MainWindow();
private:
QWidget *centerWidget;
QHBoxLayout *hbox;
QHBoxLayout *actual_hbox;
QVBoxLayout *vbox_left;
QVBoxLayout *vbox_right;
ScribbleArea *scribbleArea;
QLabel *predictedLabel;
QLabel *actualLabel;
QLabel *doneLabel;
QSpinBox *actualLabelBox;
QPushButton *predictButton;
QPushButton *clearButton;
QPushButton *mnistDemoButton;
QPushButton *learnButton;
void setupUiElements();
};
#endif // MAINWINDOW_H
| [
"cuvidk@yahoo.ro"
] | cuvidk@yahoo.ro |
f2c198dfc1f860edc6710c2067b7f541f45ff40a | 7e8f38691c3816d7e39b454b1900c85b5c5b0f17 | /Vertical-Farming/utils.hpp | d95c6664d9ea3691d200b7588751836129b6c521 | [] | no_license | nicjacks315/PLC-Projects | 8a72165bae42f30e477c99b442e9fa73da86e886 | 95fdcfec0fbe7502ce53b7526c833f56d83df1f3 | refs/heads/main | 2023-04-23T09:49:45.137697 | 2021-04-23T02:13:32 | 2021-04-23T02:13:32 | 347,445,033 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 771 | hpp | #ifndef UTILS_HPP
#define UTILS_HPP
static String leadingZero( uint8_t n ) {
if( (n-(n%10))/10 == 0 ) {
return "0" + String(n);
} else {
return String(n);
}
}
static void overlayStr( char* arr, String str ) {
for( uint8_t i = 0; i < 16; i++ ) {
if( i >= str.length() ) {
arr[i]=' ';
} else {
arr[i]=str.charAt(i);
}
}
}
static void tokenize( char* array, const char* delimiters, char* strings[] ) {
//char* strings[10];
char* ptr = NULL;
byte index = 0;
ptr = strtok(array, delimiters); // takes a list of delimiters
while(ptr != NULL) {
strings[index] = ptr;
index++;
ptr = strtok(NULL, delimiters); // takes a list of delimiters
}
return strings;
}
#endif
| [
"noreply@github.com"
] | noreply@github.com |
998e34a8235dc5cd1ee2c37397273d150ec0f944 | 81294afc727ac72b9342630c014ea7fb02886bd2 | /src/shader.cpp | 2f7c4377169c6644bf993c1b7f0114c29c4c7ab1 | [
"MIT"
] | permissive | TheKK/3DPop | aa838be5d46143d2f7bab2b91bf914b7d243ba76 | 3cb3f3eb557239e734c0b2d4cae96115959f114e | refs/heads/master | 2020-04-05T23:09:27.587653 | 2014-01-13T15:29:50 | 2014-01-13T15:29:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,162 | cpp | /*
* Author: KK <thumbd03803@gmail.com>
*
* shader.cpp
*
*/
#include "shader.h"
Shader::Shader ()
{
//Initialze view matrix
for( int i = 0; i < 4; i++ )
for( int j = 0; j < 4; j++ ){
if( i == j )
m_ViewMatrix[ i ][ j ] = 1;
else
m_ViewMatrix[ i ][ j ] = 0;
}
CameraRotateX( m_ViewMatrix, -1 * 3.14 / 2 );
//Initialze projection matrix
for( int i = 0; i < 4; i++ )
for( int j = 0; j < 4; j++ )
m_ProjectMatrix[ i ][ j ] = 0;
SetPerspective( 5, 5, 1, 100 );
m_ViewScale = 0.1;
m_ViewAngle = 0.03;
//Initialize move status
m_MovingRight = false;
m_MovingLeft = false;
m_MovingFront = false;
m_MovingBack = false;
//Initialize move speed
m_MovingSpeed = 0.3;
}
Shader::~Shader ()
{
glDeleteProgram( m_ShaderProgram );
glDeleteShader( m_VertexShader );
glDeleteShader( m_FragmentShader );
}
bool
Shader::BuildShaderProgram ( string vertexShaderPath, string fragmentShaderPath )
{
string source;
GLint errorStatus;
//Load, create and compile vertex shader
source = LoadString( vertexShaderPath );
if( source == "" )
return false;
m_VertexShader = glCreateShader( GL_VERTEX_SHADER );
glShaderSource( m_VertexShader, //Shader for used
1, //Number of array to load
(const GLchar**)&source,//Path of array
NULL //When loaded "NULL", terminate loading array
);
glCompileShader( m_VertexShader );
//Check error after compiling vertex shader
glGetShaderiv( m_VertexShader, GL_COMPILE_STATUS, &errorStatus );
if( errorStatus != GL_TRUE ){
char errorLog[ 512 ];
glGetShaderInfoLog( m_VertexShader, 512, NULL, errorLog );
fprintf( stderr, "Vertex Shader Compile Error: %s\n", errorLog );
return false;
}
//Load, create and compile fragment shader
source = LoadString( fragmentShaderPath );
if( source == "" )
return false;
m_FragmentShader = glCreateShader( GL_FRAGMENT_SHADER );
glShaderSource( m_FragmentShader, //Shader for used
1, //Number of array to load
(const GLchar**)&source,//Path of array
NULL //When loaded "NULL, terminate loading array
);
glCompileShader( m_FragmentShader );
//Check error after compiling fragment shader
glGetShaderiv( m_FragmentShader, GL_COMPILE_STATUS, &errorStatus );
if( errorStatus != GL_TRUE ){
char errorLog[ 512 ];
glGetShaderInfoLog( m_FragmentShader, 512, NULL, errorLog );
fprintf( stderr, "Fragment Shader Compile Error: %s\n", errorLog );
return false;
}
//Create a shader program and bind our vertex and fragment shader into it
m_ShaderProgram = glCreateProgram();
glAttachShader( m_ShaderProgram, m_VertexShader );
glAttachShader( m_ShaderProgram, m_FragmentShader );
glBindFragDataLocation( m_ShaderProgram, 0, "outColor" );
glLinkProgram( m_ShaderProgram );
glUseProgram( m_ShaderProgram );
//Get uniform loaction in GLSL
m_UniViewMatrix = glGetUniformLocation( m_ShaderProgram, "V" );
m_UniProjectMatrix = glGetUniformLocation( m_ShaderProgram, "P" );
//Enable depth test
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LESS );
return true;
}
void
Shader::Update ()
{
if( m_MovingFront == true )
CameraMove( 0, 0, m_MovingSpeed );
if( m_MovingBack == true )
CameraMove( 0, 0, -1 * m_MovingSpeed );
if( m_MovingLeft == true )
CameraMove( m_MovingSpeed, 0, 0 );
if( m_MovingRight == true )
CameraMove( -1 * m_MovingSpeed, 0, 0 );
glUniformMatrix4fv( m_UniViewMatrix, 1, GL_TRUE, ( GLfloat* )m_ViewMatrix );
glUniformMatrix4fv( m_UniProjectMatrix, 1, GL_TRUE, ( GLfloat* )m_ProjectMatrix );
}
void
Shader::Event ( SDL_Event* event )
{
switch( event->type ){
case SDL_KEYDOWN:
if( event->key.keysym.sym == SDLK_w )
m_MovingFront = true;
if( event->key.keysym.sym == SDLK_s )
m_MovingBack = true;
if( event->key.keysym.sym == SDLK_a )
m_MovingLeft = true;
if( event->key.keysym.sym == SDLK_d )
m_MovingRight = true;
if( event->key.keysym.sym == SDLK_KP_1 )
m_ViewScale = 0.1;
if( event->key.keysym.sym == SDLK_KP_2 )
m_ViewScale = 0.2;
if( event->key.keysym.sym == SDLK_KP_3 )
m_ViewScale = 0.3;
if( event->key.keysym.sym == SDLK_KP_4 )
m_ViewScale = 0.4;
if( event->key.keysym.sym == SDLK_KP_5 )
m_ViewScale = 0.5;
break;
case SDL_KEYUP:
if( event->key.keysym.sym == SDLK_w )
m_MovingFront = false;
if( event->key.keysym.sym == SDLK_s )
m_MovingBack = false;
if( event->key.keysym.sym == SDLK_a )
m_MovingLeft = false;
if( event->key.keysym.sym == SDLK_d )
m_MovingRight = false;
break;
case SDL_MOUSEMOTION:
if( event->motion.xrel != 0 )
CameraRotateZ( m_ViewMatrix, event->motion.xrel / 200.0 );
if( event->motion.yrel != 0 )
CameraRotateX( m_ViewMatrix, event->motion.yrel / 200.0 );
break;
case SDL_MOUSEWHEEL:
if( event->wheel.y > 0 )
m_ViewAngle += 0.005;
else if( event->wheel.y < 0 && m_ViewAngle - 0.005 > 0 )
m_ViewAngle -= 0.005;
else
m_ViewAngle = 0;
break;
}
}
void
Shader::CameraMove ( float x = 0, float y = 0, float z = 0 )
{
m_ViewMatrix[ 0 ][ 3 ] += x;
m_ViewMatrix[ 1 ][ 3 ] += y;
m_ViewMatrix[ 2 ][ 3 ] += z;
}
void
Shader::CameraRotateZ( float matrix[ 4 ][ 4 ], float degree )
{
//Tmp use to recored the result of operation
float tmp[ 4 ][ 4 ];
float rotateMatrix[ 4 ][ 4 ] = {
{ cos( degree ), 0, sin( degree ), 0 },
{ 0, 1, 0, 0 },
{-1 * sin( degree ), 0, cos( degree ), 0 },
{ 0, 0, 0, 1 }
};
//Matrix multiplication
for( int i = 0; i < 4; i++ )
for( int j = 0; j < 4; j++ ){
float sum = 0;
for( int k = 0; k < 4; k++ )
sum += rotateMatrix[ i ][ k ] * m_ViewMatrix[ k ][ j ];
tmp[ i ][ j ] = sum;
}
//Read back the result
for( int i = 0; i < 4; i++ )
for( int j = 0; j < 4; j++ )
m_ViewMatrix[ i ][ j ] = tmp[ i ][ j ];
}
void
Shader::CameraRotateX( float matrix[ 4 ][ 4 ], float degree )
{
//Tmp use to recored the result of operation
float tmp[ 4 ][ 4 ];
float rotateMatrix[ 4 ][ 4 ] = {
{ 1, 0, 0, 0 },
{ 0, cos( degree ),-1 * sin( degree ), 0 },
{ 0, sin( degree ), cos( degree ), 0 },
{ 0, 0, 0, 1 }
};
//Matrix multiplication
for( int i = 0; i < 4; i++ )
for( int j = 0; j < 4; j++ ){
float sum = 0;
for( int k = 0; k < 4; k++ )
sum += rotateMatrix[ i ][ k ] * matrix[ k ][ j ];
tmp[ i ][ j ] = sum;
}
//Read back the result
for( int i = 0; i < 4; i++ )
for( int j = 0; j < 4; j++ )
matrix[ i ][ j ] = tmp[ i ][ j ];
}
string
Shader::LoadString ( string filePath )
{
//Create file stream and check error
ifstream source( filePath.c_str(), ios::in );
if( !source.good() ){
fprintf( stderr, "File open failed: %s\n", filePath.c_str() );
return "";
}
//Stream the file data into string
stringstream buffer;
buffer << source.rdbuf();
source.close();
//Return the string pointer
return buffer.str();
}
GLuint
Shader::GetShaderProgram ()
{
return m_ShaderProgram;
}
void
Shader::SetColorMask ( bool r, bool g, bool b, bool a )
{
glColorMask( r, g, b, a );
}
void
Shader::SetPerspective ( float width, float height, float near, float far )
{
m_ProjectMatrix[ 0 ][ 0 ] = width; //Width of projection plane
m_ProjectMatrix[ 1 ][ 1 ] = height; //Height of projection plane
m_ProjectMatrix[ 2 ][ 2 ] = ( far + near ) / ( near - far );
m_ProjectMatrix[ 2 ][ 3 ] =-1.0;
m_ProjectMatrix[ 3 ][ 2 ] = ( 2.0 * far * near ) / ( near - far );
}
void
Shader::SetRight ()
{
float rightView[ 4 ][ 4 ];
for( int i = 0; i < 4; i++ )
for( int j = 0; j < 4; j++ )
rightView[ i ][ j ] = m_ViewMatrix[ i ][ j ];
rightView[ 0 ][ 3 ] += m_ViewScale;
CameraRotateZ( rightView, m_ViewAngle );
glUniformMatrix4fv( m_UniViewMatrix, 1, GL_TRUE, ( GLfloat* )rightView );
}
void
Shader::SetLeft ()
{
float leftView[ 4 ][ 4 ];
for( int i = 0; i < 4; i++ )
for( int j = 0; j < 4; j++ )
leftView[ i ][ j ] = m_ViewMatrix[ i ][ j ];
leftView[ 0 ][ 3 ] -= m_ViewScale;
CameraRotateZ( leftView, -1 * m_ViewAngle );
glUniformMatrix4fv( m_UniViewMatrix, 1, GL_TRUE, ( GLfloat* )leftView );
}
| [
"thumbd03803@gmail.com"
] | thumbd03803@gmail.com |
e96751d965d545b74b233c6ed980e4c4728f2dea | 634120df190b6262fccf699ac02538360fd9012d | /Develop/Game/DummyClient/XDummyBot_Echo.cpp | 64359b6055b2a21f45655212595159219763f6d1 | [] | no_license | ktj007/Raiderz_Public | c906830cca5c644be384e68da205ee8abeb31369 | a71421614ef5711740d154c961cbb3ba2a03f266 | refs/heads/master | 2021-06-08T03:37:10.065320 | 2016-11-28T07:50:57 | 2016-11-28T07:50:57 | 74,959,309 | 6 | 4 | null | 2016-11-28T09:53:49 | 2016-11-28T09:53:49 | null | UTF-8 | C++ | false | false | 1,694 | cpp | #include "stdafx.h"
#include "XDummyBot_Echo.h"
#include "XDummyMaster.h"
#include "XNPCInfo.h"
#include "XPost_GM.h"
XDummyBot_Echo::XDummyBot_Echo(XBirdDummyAgent* pAgent, XDummyAgentInfo* pAgentInfo)
: XDummyBot_Roam(pAgent, pAgentInfo)
{
wstring strEchoTickTime = pAgentInfo->GetValue(L"echo_tick");
m_fEchoTickTime = (float)_wtoi(strEchoTickTime.c_str());
wstring strDataSize = pAgentInfo->GetValue(L"data_size");
m_nDataSize = _wtoi(strDataSize.c_str());
wstring strRouteType = pAgentInfo->GetValue(L"route_type");
m_nRouteType = _wtoi(strRouteType.c_str());
}
XDummyBot_Echo::~XDummyBot_Echo()
{
}
void XDummyBot_Echo::OnRun(float fDelta)
{
m_fElapsedPostTime += fDelta;
if (m_fElapsedPostTime >= m_fEchoTickTime)
{
vector<int> vecData;
vecData.resize(m_nDataSize);
for (int i = 0; i < m_nDataSize; i++)
{
vecData[i] = i;
}
XBIRDPOSTCMD3(m_pAgent->GetClient(), MC_DEBUG_ECHO_REQ, MCommandParameterInt(m_nRouteType), MCommandParameterInt(m_nDataSize), MCommandParameterBlob(vecData));
m_fElapsedPostTime = 0.0f;
}
}
minet::MCommandResult XDummyBot_Echo::OnCommand( XBirdDummyAgent* pAgent, MCommand* pCommand )
{
XDummyBot::OnCommand(pAgent, pCommand);
XBirdClient* pClient = pAgent->GetClient();
switch(pCommand->GetID())
{
case MC_FIELD_START_GAME:
{
m_fElapsedPostTime = 0.0f;
}
break;
case MC_FIELD_CHANGE_FIELD:
{
XBIRDPOSTCMD1(pClient, MC_GM_REBIRTH_REQ, MCommandParameterVector(m_vPosition));
XBIRDPOSTCMD2(pClient, MC_GM_SET_ME_REQ, MCommandParameterWideString(L"grade"), MCommandParameterWideString(L"3"));
XBIRDPOSTCMD0(pClient, MC_GM_GOD_REQ);
}
break;
default:
{
}
break;
}
return CR_FALSE;
}
| [
"espause0703@gmail.com"
] | espause0703@gmail.com |
3dcd9561a50b5fcacbf08bc96cc843ea8c175526 | 6cdad6305c04eca4ff954204ca1aeaa1d7cb58fc | /shell/platform/windows/flutter_windows_view.cc | baf9389e541f53ceac4184c468bed5722b4b9fd3 | [
"BSD-3-Clause"
] | permissive | nshahan/engine | 2cffef1480b1f9eba67165d268cab0ca361cafb9 | c90e46300488a1335e455b999962e960c9fb1540 | refs/heads/master | 2023-03-02T23:41:58.962661 | 2022-05-19T17:18:04 | 2022-05-19T17:18:04 | 198,472,659 | 0 | 0 | BSD-3-Clause | 2023-09-12T05:11:42 | 2019-07-23T16:53:04 | C++ | UTF-8 | C++ | false | false | 20,083 | cc | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/windows/flutter_windows_view.h"
#include <chrono>
#include "flutter/shell/platform/common/accessibility_bridge.h"
#include "flutter/shell/platform/windows/keyboard_key_channel_handler.h"
#include "flutter/shell/platform/windows/keyboard_key_embedder_handler.h"
#include "flutter/shell/platform/windows/text_input_plugin.h"
namespace flutter {
namespace {
// The maximum duration to block the platform thread for while waiting
// for a window resize operation to complete.
constexpr std::chrono::milliseconds kWindowResizeTimeout{100};
/// Returns true if the surface will be updated as part of the resize process.
///
/// This is called on window resize to determine if the platform thread needs
/// to be blocked until the frame with the right size has been rendered. It
/// should be kept in-sync with how the engine deals with a new surface request
/// as seen in `CreateOrUpdateSurface` in `GPUSurfaceGL`.
bool SurfaceWillUpdate(size_t cur_width,
size_t cur_height,
size_t target_width,
size_t target_height) {
// TODO (https://github.com/flutter/flutter/issues/65061) : Avoid special
// handling for zero dimensions.
bool non_zero_target_dims = target_height > 0 && target_width > 0;
bool not_same_size =
(cur_height != target_height) || (cur_width != target_width);
return non_zero_target_dims && not_same_size;
}
} // namespace
FlutterWindowsView::FlutterWindowsView(
std::unique_ptr<WindowBindingHandler> window_binding) {
// Take the binding handler, and give it a pointer back to self.
binding_handler_ = std::move(window_binding);
binding_handler_->SetView(this);
render_target_ = std::make_unique<WindowsRenderTarget>(
binding_handler_->GetRenderTarget());
}
FlutterWindowsView::~FlutterWindowsView() {
DestroyRenderSurface();
}
void FlutterWindowsView::SetEngine(
std::unique_ptr<FlutterWindowsEngine> engine) {
engine_ = std::move(engine);
engine_->SetView(this);
internal_plugin_registrar_ =
std::make_unique<PluginRegistrar>(engine_->GetRegistrar());
// Set up the system channel handlers.
auto internal_plugin_messenger = internal_plugin_registrar_->messenger();
InitializeKeyboard();
platform_handler_ = PlatformHandler::Create(internal_plugin_messenger, this);
cursor_handler_ = std::make_unique<CursorHandler>(internal_plugin_messenger,
binding_handler_.get());
PhysicalWindowBounds bounds = binding_handler_->GetPhysicalWindowBounds();
SendWindowMetrics(bounds.width, bounds.height,
binding_handler_->GetDpiScale());
}
std::unique_ptr<KeyboardHandlerBase>
FlutterWindowsView::CreateKeyboardKeyHandler(
BinaryMessenger* messenger,
KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state,
KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan) {
auto keyboard_key_handler = std::make_unique<KeyboardKeyHandler>();
keyboard_key_handler->AddDelegate(
std::make_unique<KeyboardKeyEmbedderHandler>(
[this](const FlutterKeyEvent& event, FlutterKeyEventCallback callback,
void* user_data) {
return engine_->SendKeyEvent(event, callback, user_data);
},
get_key_state, map_vk_to_scan));
keyboard_key_handler->AddDelegate(
std::make_unique<KeyboardKeyChannelHandler>(messenger));
return keyboard_key_handler;
}
std::unique_ptr<TextInputPlugin> FlutterWindowsView::CreateTextInputPlugin(
BinaryMessenger* messenger) {
return std::make_unique<TextInputPlugin>(messenger, this);
}
uint32_t FlutterWindowsView::GetFrameBufferId(size_t width, size_t height) {
// Called on an engine-controlled (non-platform) thread.
std::unique_lock<std::mutex> lock(resize_mutex_);
if (resize_status_ != ResizeState::kResizeStarted) {
return kWindowFrameBufferID;
}
if (resize_target_width_ == width && resize_target_height_ == height) {
// Platform thread is blocked for the entire duration until the
// resize_status_ is set to kDone.
engine_->surface_manager()->ResizeSurface(GetRenderTarget(), width, height);
engine_->surface_manager()->MakeCurrent();
resize_status_ = ResizeState::kFrameGenerated;
}
return kWindowFrameBufferID;
}
void FlutterWindowsView::ForceRedraw() {
if (resize_status_ == ResizeState::kDone) {
// Request new frame
// TODO(knopp): Replace with more specific call once there is API for it
// https://github.com/flutter/flutter/issues/69716
SendWindowMetrics(resize_target_width_, resize_target_height_,
binding_handler_->GetDpiScale());
}
}
void FlutterWindowsView::OnPreEngineRestart() {
InitializeKeyboard();
}
void FlutterWindowsView::OnWindowSizeChanged(size_t width, size_t height) {
// Called on the platform thread.
std::unique_lock<std::mutex> lock(resize_mutex_);
if (!engine_->surface_manager()) {
SendWindowMetrics(width, height, binding_handler_->GetDpiScale());
return;
}
EGLint surface_width, surface_height;
engine_->surface_manager()->GetSurfaceDimensions(&surface_width,
&surface_height);
bool surface_will_update =
SurfaceWillUpdate(surface_width, surface_height, width, height);
if (surface_will_update) {
resize_status_ = ResizeState::kResizeStarted;
resize_target_width_ = width;
resize_target_height_ = height;
}
SendWindowMetrics(width, height, binding_handler_->GetDpiScale());
if (surface_will_update) {
// Block the platform thread until:
// 1. GetFrameBufferId is called with the right frame size.
// 2. Any pending SwapBuffers calls have been invoked.
resize_cv_.wait_for(lock, kWindowResizeTimeout,
[&resize_status = resize_status_] {
return resize_status == ResizeState::kDone;
});
}
}
void FlutterWindowsView::OnPointerMove(double x,
double y,
FlutterPointerDeviceKind device_kind,
int32_t device_id) {
SendPointerMove(x, y, GetOrCreatePointerState(device_kind, device_id));
}
void FlutterWindowsView::OnPointerDown(
double x,
double y,
FlutterPointerDeviceKind device_kind,
int32_t device_id,
FlutterPointerMouseButtons flutter_button) {
if (flutter_button != 0) {
auto state = GetOrCreatePointerState(device_kind, device_id);
state->buttons |= flutter_button;
SendPointerDown(x, y, state);
}
}
void FlutterWindowsView::OnPointerUp(
double x,
double y,
FlutterPointerDeviceKind device_kind,
int32_t device_id,
FlutterPointerMouseButtons flutter_button) {
if (flutter_button != 0) {
auto state = GetOrCreatePointerState(device_kind, device_id);
state->buttons &= ~flutter_button;
SendPointerUp(x, y, state);
}
}
void FlutterWindowsView::OnPointerLeave(double x,
double y,
FlutterPointerDeviceKind device_kind,
int32_t device_id) {
SendPointerLeave(x, y, GetOrCreatePointerState(device_kind, device_id));
}
void FlutterWindowsView::OnText(const std::u16string& text) {
SendText(text);
}
void FlutterWindowsView::OnKey(int key,
int scancode,
int action,
char32_t character,
bool extended,
bool was_down,
KeyEventCallback callback) {
SendKey(key, scancode, action, character, extended, was_down, callback);
}
void FlutterWindowsView::OnComposeBegin() {
SendComposeBegin();
}
void FlutterWindowsView::OnComposeCommit() {
SendComposeCommit();
}
void FlutterWindowsView::OnComposeEnd() {
SendComposeEnd();
}
void FlutterWindowsView::OnComposeChange(const std::u16string& text,
int cursor_pos) {
SendComposeChange(text, cursor_pos);
}
void FlutterWindowsView::OnScroll(double x,
double y,
double delta_x,
double delta_y,
int scroll_offset_multiplier,
FlutterPointerDeviceKind device_kind,
int32_t device_id) {
SendScroll(x, y, delta_x, delta_y, scroll_offset_multiplier, device_kind,
device_id);
}
void FlutterWindowsView::OnUpdateSemanticsEnabled(bool enabled) {
engine_->UpdateSemanticsEnabled(enabled);
}
gfx::NativeViewAccessible FlutterWindowsView::GetNativeViewAccessible() {
return engine_->GetNativeAccessibleFromId(AccessibilityBridge::kRootNodeId);
}
void FlutterWindowsView::OnCursorRectUpdated(const Rect& rect) {
binding_handler_->OnCursorRectUpdated(rect);
}
void FlutterWindowsView::OnResetImeComposing() {
binding_handler_->OnResetImeComposing();
}
void FlutterWindowsView::InitializeKeyboard() {
auto internal_plugin_messenger = internal_plugin_registrar_->messenger();
// TODO(cbracken): This can be inlined into KeyboardKeyEmedderHandler once
// UWP code is removed. https://github.com/flutter/flutter/issues/102172.
KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state = GetKeyState;
KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan =
[](UINT virtual_key, bool extended) {
return MapVirtualKey(virtual_key,
extended ? MAPVK_VK_TO_VSC_EX : MAPVK_VK_TO_VSC);
};
keyboard_key_handler_ = std::move(CreateKeyboardKeyHandler(
internal_plugin_messenger, get_key_state, map_vk_to_scan));
text_input_plugin_ =
std::move(CreateTextInputPlugin(internal_plugin_messenger));
}
// Sends new size information to FlutterEngine.
void FlutterWindowsView::SendWindowMetrics(size_t width,
size_t height,
double dpiScale) const {
FlutterWindowMetricsEvent event = {};
event.struct_size = sizeof(event);
event.width = width;
event.height = height;
event.pixel_ratio = dpiScale;
engine_->SendWindowMetricsEvent(event);
}
void FlutterWindowsView::SendInitialBounds() {
PhysicalWindowBounds bounds = binding_handler_->GetPhysicalWindowBounds();
SendWindowMetrics(bounds.width, bounds.height,
binding_handler_->GetDpiScale());
}
FlutterWindowsView::PointerState* FlutterWindowsView::GetOrCreatePointerState(
FlutterPointerDeviceKind device_kind,
int32_t device_id) {
// Create a virtual pointer ID that is unique across all device types
// to prevent pointers from clashing in the engine's converter
// (lib/ui/window/pointer_data_packet_converter.cc)
int32_t pointer_id = (static_cast<int32_t>(device_kind) << 28) | device_id;
auto [it, added] = pointer_states_.try_emplace(pointer_id, nullptr);
if (added) {
auto state = std::make_unique<PointerState>();
state->device_kind = device_kind;
state->pointer_id = pointer_id;
it->second = std::move(state);
}
return it->second.get();
}
// Set's |event_data|'s phase to either kMove or kHover depending on the current
// primary mouse button state.
void FlutterWindowsView::SetEventPhaseFromCursorButtonState(
FlutterPointerEvent* event_data,
const PointerState* state) const {
// For details about this logic, see FlutterPointerPhase in the embedder.h
// file.
if (state->buttons == 0) {
event_data->phase = state->flutter_state_is_down
? FlutterPointerPhase::kUp
: FlutterPointerPhase::kHover;
} else {
event_data->phase = state->flutter_state_is_down
? FlutterPointerPhase::kMove
: FlutterPointerPhase::kDown;
}
}
void FlutterWindowsView::SendPointerMove(double x,
double y,
PointerState* state) {
FlutterPointerEvent event = {};
event.x = x;
event.y = y;
SetEventPhaseFromCursorButtonState(&event, state);
SendPointerEventWithData(event, state);
}
void FlutterWindowsView::SendPointerDown(double x,
double y,
PointerState* state) {
FlutterPointerEvent event = {};
event.x = x;
event.y = y;
SetEventPhaseFromCursorButtonState(&event, state);
SendPointerEventWithData(event, state);
state->flutter_state_is_down = true;
}
void FlutterWindowsView::SendPointerUp(double x,
double y,
PointerState* state) {
FlutterPointerEvent event = {};
event.x = x;
event.y = y;
SetEventPhaseFromCursorButtonState(&event, state);
SendPointerEventWithData(event, state);
if (event.phase == FlutterPointerPhase::kUp) {
state->flutter_state_is_down = false;
}
}
void FlutterWindowsView::SendPointerLeave(double x,
double y,
PointerState* state) {
FlutterPointerEvent event = {};
event.x = x;
event.y = y;
event.phase = FlutterPointerPhase::kRemove;
SendPointerEventWithData(event, state);
}
void FlutterWindowsView::SendText(const std::u16string& text) {
text_input_plugin_->TextHook(text);
}
void FlutterWindowsView::SendKey(int key,
int scancode,
int action,
char32_t character,
bool extended,
bool was_down,
KeyEventCallback callback) {
keyboard_key_handler_->KeyboardHook(
key, scancode, action, character, extended, was_down,
[=, callback = std::move(callback)](bool handled) {
if (!handled) {
text_input_plugin_->KeyboardHook(key, scancode, action, character,
extended, was_down);
}
callback(handled);
});
}
void FlutterWindowsView::SendComposeBegin() {
text_input_plugin_->ComposeBeginHook();
}
void FlutterWindowsView::SendComposeCommit() {
text_input_plugin_->ComposeCommitHook();
}
void FlutterWindowsView::SendComposeEnd() {
text_input_plugin_->ComposeEndHook();
}
void FlutterWindowsView::SendComposeChange(const std::u16string& text,
int cursor_pos) {
text_input_plugin_->ComposeChangeHook(text, cursor_pos);
}
void FlutterWindowsView::SendScroll(double x,
double y,
double delta_x,
double delta_y,
int scroll_offset_multiplier,
FlutterPointerDeviceKind device_kind,
int32_t device_id) {
auto state = GetOrCreatePointerState(device_kind, device_id);
FlutterPointerEvent event = {};
event.x = x;
event.y = y;
event.signal_kind = FlutterPointerSignalKind::kFlutterPointerSignalKindScroll;
event.scroll_delta_x = delta_x * scroll_offset_multiplier;
event.scroll_delta_y = delta_y * scroll_offset_multiplier;
SetEventPhaseFromCursorButtonState(&event, state);
SendPointerEventWithData(event, state);
}
void FlutterWindowsView::SendPointerEventWithData(
const FlutterPointerEvent& event_data,
PointerState* state) {
// If sending anything other than an add, and the pointer isn't already added,
// synthesize an add to satisfy Flutter's expectations about events.
if (!state->flutter_state_is_added &&
event_data.phase != FlutterPointerPhase::kAdd) {
FlutterPointerEvent event = {};
event.phase = FlutterPointerPhase::kAdd;
event.x = event_data.x;
event.y = event_data.y;
event.buttons = 0;
SendPointerEventWithData(event, state);
}
// Don't double-add (e.g., if events are delivered out of order, so an add has
// already been synthesized).
if (state->flutter_state_is_added &&
event_data.phase == FlutterPointerPhase::kAdd) {
return;
}
FlutterPointerEvent event = event_data;
event.device_kind = state->device_kind;
event.device = state->pointer_id;
event.buttons = state->buttons;
// Set metadata that's always the same regardless of the event.
event.struct_size = sizeof(event);
event.timestamp =
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch())
.count();
engine_->SendPointerEvent(event);
if (event_data.phase == FlutterPointerPhase::kAdd) {
state->flutter_state_is_added = true;
} else if (event_data.phase == FlutterPointerPhase::kRemove) {
auto it = pointer_states_.find(state->pointer_id);
if (it != pointer_states_.end()) {
pointer_states_.erase(it);
}
}
}
bool FlutterWindowsView::MakeCurrent() {
return engine_->surface_manager()->MakeCurrent();
}
bool FlutterWindowsView::MakeResourceCurrent() {
return engine_->surface_manager()->MakeResourceCurrent();
}
bool FlutterWindowsView::ClearContext() {
return engine_->surface_manager()->ClearContext();
}
bool FlutterWindowsView::SwapBuffers() {
// Called on an engine-controlled (non-platform) thread.
std::unique_lock<std::mutex> lock(resize_mutex_);
switch (resize_status_) {
// SwapBuffer requests during resize are ignored until the frame with the
// right dimensions has been generated. This is marked with
// kFrameGenerated resize status.
case ResizeState::kResizeStarted:
return false;
case ResizeState::kFrameGenerated: {
bool visible = binding_handler_->IsVisible();
bool swap_buffers_result;
// For visible windows swap the buffers while resize handler is waiting.
// For invisible windows unblock the handler first and then swap buffers.
// SwapBuffers waits for vsync and there's no point doing that for
// invisible windows.
if (visible) {
swap_buffers_result = engine_->surface_manager()->SwapBuffers();
}
resize_status_ = ResizeState::kDone;
lock.unlock();
resize_cv_.notify_all();
binding_handler_->OnWindowResized();
if (!visible) {
swap_buffers_result = engine_->surface_manager()->SwapBuffers();
}
return swap_buffers_result;
}
case ResizeState::kDone:
default:
return engine_->surface_manager()->SwapBuffers();
}
}
bool FlutterWindowsView::PresentSoftwareBitmap(const void* allocation,
size_t row_bytes,
size_t height) {
return binding_handler_->OnBitmapSurfaceUpdated(allocation, row_bytes,
height);
}
void FlutterWindowsView::CreateRenderSurface() {
if (engine_ && engine_->surface_manager()) {
PhysicalWindowBounds bounds = binding_handler_->GetPhysicalWindowBounds();
engine_->surface_manager()->CreateSurface(GetRenderTarget(), bounds.width,
bounds.height);
}
}
void FlutterWindowsView::DestroyRenderSurface() {
if (engine_ && engine_->surface_manager()) {
engine_->surface_manager()->DestroySurface();
}
}
WindowsRenderTarget* FlutterWindowsView::GetRenderTarget() const {
return render_target_.get();
}
PlatformWindow FlutterWindowsView::GetPlatformWindow() const {
return binding_handler_->GetPlatformWindow();
}
FlutterWindowsEngine* FlutterWindowsView::GetEngine() {
return engine_.get();
}
} // namespace flutter
| [
"noreply@github.com"
] | noreply@github.com |
93e62a1605565f6c9c33a47f3c08a1179007ac88 | 12af37ff9e15da5e773d8ecccb8040c931d36c43 | /source code/FarmingRush/Player.h | dcc0bebff79b3570456dc0bd5d7ec6f2aa5787d3 | [] | no_license | MsrdMai/Project-ComProG | 6394b28bbdf6911b3c5c539346ebb6d8d6e2d1ed | 066f0df61066b9e88c6b570271fa9f94505ea8e6 | refs/heads/master | 2020-04-28T22:20:31.438781 | 2019-05-02T16:41:20 | 2019-05-02T16:41:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,730 | h | #pragma once
#include <SFML\Graphics.hpp>
#include "Animation.h"
#include "TextDisplay.h"
class Player
{
public:
Player(sf::Texture* texture, sf::Texture* colliderTexture,sf::Texture* farColliderTexture, sf::Texture* UITexture, sf::Vector2u imageCount, float switchTime, float speed);
~Player();
void setCollider(bool lc, bool rc, bool tc, bool bc, bool pc, bool lfc, bool rfc, bool tfc, bool bfc);
void Update(float deltaTime);
void Draw(sf::RenderWindow& window);
sf::Vector2f getPosition() { return body.getPosition(); }
sf::Sprite getSprite() { return body; }
sf::Sprite getLeft() { return left; }
sf::Sprite getRight() { return right; }
sf::Sprite getTop() { return top; }
sf::Sprite getBottom() { return bottom; }
sf::Sprite getLeftfar() { return leftfar; }
sf::Sprite getRightfar() { return rightfar; }
sf::Sprite getTopfar() { return topfar; }
sf::Sprite getBottomfar() { return bottomfar; }
bool checkLeft() { return lc; }
bool checkRight() { return rc; }
bool checkTop() { return tc; }
bool checkBottom() { return bc; }
bool checkLeftfar() { return lfc; }
bool checkRightfar() { return rfc; }
bool checkTopfar() { return tfc; }
bool checkBottomfar() { return bfc; }
char getFace() { return faceTo; }
private:
bool rc = false, lc = false, tc = false, bc = false, pc = false;
bool rfc = false, lfc = false, tfc = false, bfc = false, pfc = false;
sf::Sprite body;
sf::Sprite left, right, top, bottom;
sf::Sprite leftfar, rightfar, topfar, bottomfar;
sf::Sprite UI;
sf::Text text;
sf::Font font;
TextDisplay text_dm;
std::vector<TextDisplay>::const_iterator iter_text;
std::vector<TextDisplay> textArray;
Animation animation;
unsigned int row;
float speed;
char faceTo;
};
| [
"35396908+Tearrockster@users.noreply.github.com"
] | 35396908+Tearrockster@users.noreply.github.com |
7d839e0d703dcdc8a3a99fecf8e2b057ae1ad296 | a580ce506d15c589c631001f5e31990d02f0572e | /ePC-8801MA/vm/i8255.cpp | e78f3cf5d864f77b02d482c0400239c3a51cf56e | [] | no_license | yoshisuga/xm8-ios | 2725759b194db7d885ada542071187bab298a295 | ed4e23343190e44357c0df188786afaa19b85122 | refs/heads/master | 2021-01-12T10:14:43.534303 | 2018-02-12T17:19:29 | 2018-02-12T17:19:29 | 76,394,958 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,306 | cpp | /*
Skelton for retropc emulator
Author : Takeda.Toshiya
Date : 2006.06.01-
[ i8255 ]
*/
#include "i8255.h"
// mode1 input
#define BIT_IBF_A 0x20 // PC5
#define BIT_STB_A 0x10 // PC4
#define BIT_STB_B 0x04 // PC2
#define BIT_IBF_B 0x02 // PC1
#define BIT_OBF_A 0x80 // PC7
#define BIT_ACK_A 0x40 // PC6
#define BIT_ACK_B 0x04 // PC2
#define BIT_OBF_B 0x02 // PC1
#define BIT_INTR_A 0x08 // PC3
#define BIT_INTR_B 0x01 // PC0
void I8255::reset()
{
for(int i = 0; i < 3; i++) {
port[i].rmask = 0xff;
port[i].first = true;
port[i].mode = 0;
}
}
void I8255::write_io8(uint32 addr, uint32 data)
{
int ch = addr & 3;
switch(ch) {
case 0:
case 1:
case 2:
if(port[ch].wreg != data || port[ch].first) {
write_signals(&port[ch].outputs, port[ch].wreg = data);
port[ch].first = false;
}
#ifndef I8255_AUTO_HAND_SHAKE
if(ch == 0) {
if(port[0].mode == 1 || port[0].mode == 2) {
uint32 val = port[2].wreg & ~BIT_OBF_A;
if(port[2].wreg & BIT_ACK_A) {
val &= ~BIT_INTR_A;
}
write_io8(2, val);
}
} else if(ch == 1) {
if(port[1].mode == 1) {
uint32 val = port[2].wreg & ~BIT_OBF_B;
if(port[2].wreg & BIT_ACK_B) {
val &= ~BIT_INTR_B;
}
write_io8(2, val);
}
}
#endif
break;
case 3:
if(data & 0x80) {
port[0].mode = (data & 0x40) ? 2 : ((data >> 5) & 1);
port[0].rmask = (port[0].mode == 2) ? 0xff : (data & 0x10) ? 0xff : 0;
port[1].mode = (data >> 2) & 1;
port[1].rmask = (data & 2) ? 0xff : 0;
port[2].rmask = ((data & 8) ? 0xf0 : 0) | ((data & 1) ? 0xf : 0);
// clear ports
if(clear_ports_by_cmdreg) {
write_io8(0, 0);
write_io8(1, 0);
write_io8(2, 0);
}
// setup control signals
if(port[0].mode != 0 || port[1].mode != 0) {
uint32 val = port[2].wreg;
if(port[0].mode == 1 || port[0].mode == 2) {
val &= ~BIT_IBF_A;
val |= BIT_OBF_A;
val &= ~BIT_INTR_A;
}
if(port[1].mode == 1) {
if(port[1].mode == 0xff) {
val &= ~BIT_IBF_B;
} else {
val |= BIT_OBF_B;
}
val &= ~BIT_INTR_B;
}
write_io8(2, val);
}
} else {
uint32 val = port[2].wreg;
int bit = (data >> 1) & 7;
if(data & 1) {
val |= 1 << bit;
} else {
val &= ~(1 << bit);
}
write_io8(2, val);
}
break;
}
}
uint32 I8255::read_io8(uint32 addr)
{
int ch = addr & 3;
switch(ch) {
case 0:
case 1:
case 2:
if(ch == 0) {
if(port[0].mode == 1 || port[0].mode == 2) {
uint32 val = port[2].wreg & ~BIT_IBF_A;
if(port[2].wreg & BIT_STB_A) {
val &= ~BIT_INTR_A;
}
write_io8(2, val);
}
} else if(ch == 1) {
if(port[1].mode == 1) {
uint32 val = port[2].wreg & ~BIT_IBF_B;
if(port[2].wreg & BIT_STB_B) {
val &= ~BIT_INTR_B;
}
write_io8(2, val);
}
}
return (port[ch].rreg & port[ch].rmask) | (port[ch].wreg & ~port[ch].rmask);
}
return 0xff;
}
void I8255::write_signal(int id, uint32 data, uint32 mask)
{
switch(id) {
case SIG_I8255_PORT_A:
port[0].rreg = (port[0].rreg & ~mask) | (data & mask);
#ifdef I8255_AUTO_HAND_SHAKE
if(port[0].mode == 1 || port[0].mode == 2) {
uint32 val = port[2].wreg | BIT_IBF_A;
if(port[2].wreg & BIT_STB_A) {
val |= BIT_INTR_A;
}
write_io8(2, val);
}
#endif
break;
case SIG_I8255_PORT_B:
port[1].rreg = (port[1].rreg & ~mask) | (data & mask);
#ifdef I8255_AUTO_HAND_SHAKE
if(port[1].mode == 1) {
uint32 val = port[2].wreg | BIT_IBF_B;
if(port[2].wreg & BIT_STB_B) {
val |= BIT_INTR_B;
}
write_io8(2, val);
}
#endif
break;
case SIG_I8255_PORT_C:
#ifndef I8255_AUTO_HAND_SHAKE
if(port[0].mode == 1 || port[0].mode == 2) {
if(mask & BIT_STB_A) {
if((port[2].rreg & BIT_STB_A) && !(data & BIT_STB_A)) {
write_io8(2, port[2].wreg | BIT_IBF_A);
} else if(!(port[2].rreg & BIT_STB_A) && (data & BIT_STB_A)) {
if(port[2].wreg & BIT_STB_A) {
write_io8(2, port[2].wreg | BIT_INTR_A);
}
}
}
if(mask & BIT_ACK_A) {
if((port[2].rreg & BIT_ACK_A) && !(data & BIT_ACK_A)) {
write_io8(2, port[2].wreg | BIT_OBF_A);
} else if(!(port[2].rreg & BIT_ACK_A) && (data & BIT_ACK_A)) {
if(port[2].wreg & BIT_ACK_A) {
write_io8(2, port[2].wreg | BIT_INTR_A);
}
}
}
}
if(port[1].mode == 1) {
if(port[0].rmask == 0xff) {
if(mask & BIT_STB_B) {
if((port[2].rreg & BIT_STB_B) && !(data & BIT_STB_B)) {
write_io8(2, port[2].wreg | BIT_IBF_B);
} else if(!(port[2].rreg & BIT_STB_B) && (data & BIT_STB_B)) {
if(port[2].wreg & BIT_STB_B) {
write_io8(2, port[2].wreg | BIT_INTR_B);
}
}
}
} else {
if(mask & BIT_ACK_B) {
if((port[2].rreg & BIT_ACK_B) && !(data & BIT_ACK_B)) {
write_io8(2, port[2].wreg | BIT_OBF_B);
} else if(!(port[2].rreg & BIT_ACK_B) && (data & BIT_ACK_B)) {
if(port[2].wreg & BIT_ACK_B) {
write_io8(2, port[2].wreg | BIT_INTR_B);
}
}
}
}
}
#endif
port[2].rreg = (port[2].rreg & ~mask) | (data & mask);
break;
}
}
uint32 I8255::read_signal(int id)
{
switch(id) {
case SIG_I8255_PORT_A:
return port[0].wreg;
case SIG_I8255_PORT_B:
return port[1].wreg;
case SIG_I8255_PORT_C:
return port[2].wreg;
}
return 0;
}
#define STATE_VERSION 1
void I8255::save_state(FILEIO* state_fio)
{
state_fio->FputUint32(STATE_VERSION);
state_fio->FputInt32(this_device_id);
for(int i = 0; i < 3; i++) {
state_fio->FputUint8(port[i].wreg);
state_fio->FputUint8(port[i].rreg);
state_fio->FputUint8(port[i].rmask);
state_fio->FputUint8(port[i].mode);
state_fio->FputBool(port[i].first);
}
}
bool I8255::load_state(FILEIO* state_fio)
{
if(state_fio->FgetUint32() != STATE_VERSION) {
return false;
}
if(state_fio->FgetInt32() != this_device_id) {
return false;
}
for(int i = 0; i < 3; i++) {
port[i].wreg = state_fio->FgetUint8();
port[i].rreg = state_fio->FgetUint8();
port[i].rmask = state_fio->FgetUint8();
port[i].mode = state_fio->FgetUint8();
port[i].first = state_fio->FgetBool();
}
return true;
}
| [
"yoshi@transfix.io"
] | yoshi@transfix.io |
122aa2615ca6aea487555614149492f0a0b34b92 | e7394c35e8587092aeee5dda051c879b447ac0e8 | /lalafell_player/src/main/cpp/extractor/rtmp_extractor.h | 18711482ebf708ef4de714b0ed3e0632bd13db1b | [
"MIT"
] | permissive | retamia/lalafell | cc11c9d9c79099b237e7ec274411dce9701679ba | 83e7fb8804b64c077bc24c8ec75046f349d5631c | refs/heads/master | 2020-04-03T02:00:54.324036 | 2019-06-06T08:10:42 | 2019-06-06T08:10:42 | 154,944,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 900 | h | //
// Created by retamia on 2018/10/23.
//
#ifndef LIVEPLAYER_RTMP_EXTRACTOR_H
#define LIVEPLAYER_RTMP_EXTRACTOR_H
#include <string>
#include "util/thread.h"
#include "util/linked_blocking_queue.h"
struct RRtmpPacket;
struct RTMP;
class RTMPExtractor : public RThread {
public:
explicit RTMPExtractor();
virtual ~RTMPExtractor();
void setUrl(const std::string &url);
void setVideoPacketQueue(LinkedBlockingQueue<RRtmpPacket *> *packetQueue) { this->videoPacketQueue = packetQueue; }
void setAudioPacketQueue(LinkedBlockingQueue<RRtmpPacket *> *packetQueue) { this->audioPacketQueue = packetQueue; }
protected:
void run() override;
private:
bool openRTMP();
private:
RTMP *rtmp;
std::string url;
LinkedBlockingQueue<RRtmpPacket *> *videoPacketQueue;
LinkedBlockingQueue<RRtmpPacket *> *audioPacketQueue;
};
#endif //LIVEPLAYER_RTMP_EXTRACTOR_H
| [
"retamia@gmail.com"
] | retamia@gmail.com |
e24fa3fcb3a83fdfe6105a78d643147d51c969ec | 01d6feb157226d01ffd19d52fe3927cc80bbf718 | /packages/plugin_library/MotomanRobotDriver/src/CobotMotomanComm.cpp | 26282b2ebe1de303d8996accfa11c94c2f0e2060 | [] | no_license | jackros1022/UrRobotControllerInTCP | 3dda2d17d4bbc120bcd5b29bdc753f3df084790c | 3dd388c58b21d909b6c69c4d6160e631ab306a7a | refs/heads/master | 2020-03-25T16:52:10.601581 | 2018-02-13T12:30:26 | 2018-02-13T12:30:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,710 | cpp | //
// Created by 杨帆 on 17-5-2.
// Copyright (c) 2017 Wuhan Collaborative Robot Technology Co.,Ltd. All rights reserved.
//
#include "CobotMotoman.h"
#include "CobotMotomanComm.h"
CobotMotomanComm::CobotMotomanComm(std::condition_variable& udp_msg_cond,
std::condition_variable& tcp_msg_cond,
const QString& robotAddr,
QObject* parent) : QObject(parent){
m_motomanTCPCommCtrl = new CobotMotomanTCPCommCtrl(tcp_msg_cond, robotAddr, this);
m_motomanUDPCommCtrl = new CobotMotomanUDPCommCtrl(udp_msg_cond, robotAddr, this);
connect(m_motomanTCPCommCtrl->motoman, &CobotMotomanTCPComm::connected, this, &CobotMotomanComm::handleTCPConnected);
connect(m_motomanUDPCommCtrl->motoman, &CobotMotomanUDPComm::connected, this, &CobotMotomanComm::handleUDPConnected);
connect(m_motomanTCPCommCtrl->motoman, &CobotMotomanTCPComm::disconnected, this, &CobotMotomanComm::handleTCPDisconnected);
connect(m_motomanUDPCommCtrl->motoman, &CobotMotomanUDPComm::disconnected, this, &CobotMotomanComm::handleUDPDisconnected);
connect(m_motomanTCPCommCtrl->motoman, &CobotMotomanTCPComm::connectFail, this, &CobotMotomanComm::handleTCPDisconnected);
connect(m_motomanUDPCommCtrl->motoman, &CobotMotomanUDPComm::connectFail, this, &CobotMotomanComm::handleUDPDisconnected);
m_noDisconnectedAccept = false;
servoj_gain_ = 300;
servoj_lookahead_time_ = 0.05;
servoj_time_ = 0.016;
m_connectTime = 0;
m_isConnected = false;
}
CobotMotomanComm::~CobotMotomanComm(){
stopDriver();
}
void CobotMotomanComm::handleTCPConnected(){
onConnectSuccess();
}
void CobotMotomanComm::handleTCPDisconnected(){
m_connectTime = 0;
m_isConnected = false;
m_disconnectCount++;
if (m_noDisconnectedAccept) {
Q_EMIT driverStartFailed();
}
if (m_disconnectCount >= 2) {
Q_EMIT driverStopped();
}
}
void CobotMotomanComm::handleUDPConnected(){
}
void CobotMotomanComm::handleUDPDisconnected(){
if (m_isConnected) {
Q_EMIT driverStopped();
}
}
void CobotMotomanComm::startDriver(){
m_noDisconnectedAccept = true;
m_disconnectCount = 0;
m_connectTime = 0;
m_isConnected = false;
m_motomanTCPCommCtrl->startComm();
m_motomanUDPCommCtrl->startComm();
}
void CobotMotomanComm::stopDriver(){
m_noDisconnectedAccept = false;
m_motomanTCPCommCtrl->motoman->executeCmd(CobotMotomanTCPComm::CMD_SERVO_OFF);
}
void CobotMotomanComm::setServojTime(double t){
if (t > 0.004) {
servoj_time_ = t;
} else {
servoj_time_ = 0.004;
}
}
void CobotMotomanComm::setServojLookahead(double t){
if (t > 0.03) {
if (t < 0.2) {
servoj_lookahead_time_ = t;
} else {
servoj_lookahead_time_ = 0.2;
}
} else {
servoj_lookahead_time_ = 0.03;
}
}
void CobotMotomanComm::setServojGain(double g){
if (g > 100) {
if (g < 2000) {
servoj_gain_ = g;
} else {
servoj_gain_ = 2000;
}
} else {
servoj_gain_ = 100;
}
}
void CobotMotomanComm::onConnectSuccess(){
m_isConnected = true;
ip_addr_ = m_motomanTCPCommCtrl->motoman->getLocalIp();
COBOT_LOG.info() << "Local Ip: " << ip_addr_;
m_motomanTCPCommCtrl->motoman->executeCmd(CobotMotomanTCPComm::CMD_SERVO_ON);
m_motomanTCPCommCtrl->motoman->executeCmd(CobotMotomanTCPComm::CMD_START_UDP);
Q_EMIT driverStartSuccess();
}
void CobotMotomanComm::servoj(const std::vector<double>& positions){
if (m_motomanTCPCommCtrl) {
m_motomanTCPCommCtrl->motoman->asyncServoj(positions);
}
} | [
"sailcpu@gmail.com"
] | sailcpu@gmail.com |
d063a4bdfdd90497be44bd9008490a925de883f9 | 87929efca3d762486e086f222efef55b29256eca | /contracts/test_api/test_checktime.cpp | 1d589bfbc77b10bc64f714a14c4f95fe3e1aed9d | [
"MIT"
] | permissive | ProbeChain/cubetrain | d4650865ae1a821d78aaf6712d7bdf8937e562ab | f02f9b67ef0d3e6d46d3aa96e6f9974ae72b13ff | refs/heads/master | 2022-12-13T12:12:41.137518 | 2019-11-30T10:09:02 | 2019-11-30T10:09:02 | 224,988,171 | 1 | 0 | MIT | 2022-12-11T18:49:23 | 2019-11-30T09:24:26 | C++ | UTF-8 | C++ | false | false | 1,754 | cpp | /**
* @file
* @copyright defined in seat/LICENSE.txt
*/
#include <cubetrainlib/cubetrain.hpp>
#include <cubetrainlib/crypto.h>
#include <cubetrainlib/print.h>
#include "test_api.hpp"
#include <vector>
void test_checktime::checktime_pass() {
int p = 0;
for ( int i = 0; i < 10000; i++ )
p += i;
cubetrain::print(p);
}
void test_checktime::checktime_failure() {
int p = 0;
for ( unsigned long long i = 0; i < 10000000000000000000ULL; i++ )
for ( unsigned long long j = 0; i < 10000000000000000000ULL; i++ )
p += i+j;
cubetrain::print(p);
}
constexpr size_t size = 20000000;
void test_checktime::checktime_sha1_failure() {
char* ptr = new char[size];
checksum160 res;
sha1( ptr, size, &res );
}
void test_checktime::checktime_assert_sha1_failure() {
char* ptr = new char[size];
checksum160 res;
assert_sha1( ptr, size, &res );
}
void test_checktime::checktime_sha256_failure() {
char* ptr = new char[size];
checksum256 res;
sha256( ptr, size, &res );
}
void test_checktime::checktime_assert_sha256_failure() {
char* ptr = new char[size];
checksum256 res;
assert_sha256( ptr, size, &res );
}
void test_checktime::checktime_sha512_failure() {
char* ptr = new char[size];
checksum512 res;
sha512( ptr, size, &res );
}
void test_checktime::checktime_assert_sha512_failure() {
char* ptr = new char[size];
checksum512 res;
assert_sha512( ptr, size, &res );
}
void test_checktime::checktime_ripemd160_failure() {
char* ptr = new char[size];
checksum160 res;
ripemd160( ptr, size, &res );
}
void test_checktime::checktime_assert_ripemd160_failure() {
char* ptr = new char[size];
checksum160 res;
assert_ripemd160( ptr, size, &res );
}
| [
"qf_wu@shanchain.com"
] | qf_wu@shanchain.com |
a6f6befcb06ce61c737e528da6849ec2e87cb694 | 087cbbd3099ff8fd8d2051c60461a0458333dbac | /practice/DP/CF477D2.cpp | 7de856da5f111f3e503b68f1d286a7ff31b687e2 | [] | no_license | 1998factorial/Codeforces | 1046ffb2dbee582191fa59e7290c53e902c0af5c | f5b8139810e0724828e6ce7e26f3f8228589b00a | refs/heads/master | 2021-07-05T21:34:45.053171 | 2021-04-10T06:21:33 | 2021-04-10T06:21:33 | 228,158,437 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,845 | cpp | #include <bits/stdc++.h>
#define ID if(1)
#define MOD 1000000007
using namespace std;
const int INF = 1e9;
int N , way[5005][5005] , sum[5005][5005] , ones[5005][5005] , MIN[5005][5005];
int LCP[5005][5005] , p[5005];
// LCP[i][j] = longest common prefix of a[j...] and a[i...]
// j < i
char a[5005];
int main(){
scanf("%s" , a + 1);
N = strlen(a + 1);
p[0] = 1;for(int i = 1; i <= N; ++i)p[i] = p[i - 1] * 2 % MOD;
for(int i = N; i >= 1; --i){
for(int j = i - 1; j >= 1; --j){
LCP[i][j] = a[i] == a[j] ? 1 + LCP[i + 1][j + 1] : 0;
}
}
way[0][1] = 1;
for(int i = 1; i <= N; ++i){
sum[0][i] = sum[0][i - 1] + way[0][i];
if(sum[0][i] >= MOD)sum[0][i] -= MOD;
}
for(int i = 0; i <= N; ++i){
for(int j = 0; j <= N; ++j){
ones[i][j] = MIN[i][j] = INF;
}
}
ones[0][1] = 0;
for(int i = 1; i <= N; ++i)MIN[0][i] = min(MIN[0][i - 1] , ones[0][i]);
// way[i][j] = # ways st segment ends with a[i] has length j
// ones[i][j] = minimal number of "1" operations used if we have last segment ending with a[i] , length being j
for(int i = 1; i <= N; ++i){
for(int j = 1; j <= i; ++j){
if(j > 1 && a[i - j + 1] == '0')continue;
if(i - j - j + 1 >= 1){
int longest = LCP[i - j + 1][i - j - j + 1];
int k = (longest >= j || a[i - j + longest + 1] >= a[i - j - j + longest + 1]) ? j : j - 1;
way[i][j] = sum[i - j][k];
ones[i][j] = min(MIN[i - j][k] + 1 , ones[i][j]);
}
else{
way[i][j] = sum[i - j][j];
ones[i][j] = min(MIN[i - j][j] + 1 , ones[i][j]);
}
}
for(int j = 1; j <= N; ++j){
sum[i][j] = sum[i][j - 1] + way[i][j];
if(sum[i][j] >= MOD)sum[i][j] -= MOD;
MIN[i][j] = min(MIN[i][j - 1] , ones[i][j]);
}
}
printf("%d\n" , sum[N][N]);
// find minimal length of operations
// we want the number 2 + number 1 as small as possible
int val = 0;
int min_len = INF;
for(int j = 1; j <= N; ++j){
int i = N - j + 1;
if(a[i] == '1'){
val += p[j - 1];
if(val >= MOD)val -= MOD;
}
//printf("val = %d\n" , val);
if(ones[N][j] >= INF)continue;
//printf("ones[%d][%d] = %d\n" , N , j , ones[N][j]);
if(j < 25){
min_len = min(min_len , ones[N][j] + val);
//printf("for length = %d , val = %d\n" , j , ones[N][j] + val);
}
else{
if(min_len == INF){
min_len = (val + ones[N][j]) % MOD;
//printf("for length = %d , val = %d\n" , j , min_len);
break;
}
}
}
printf("%d\n" , min_len);
} | [
"edward19980505@gmail.com"
] | edward19980505@gmail.com |
1fbf7fb5de2e11f3203021eed56fe13662d9181a | 4fdc9e8bd08da2313ab10498da0229b16c94ca4d | /product_inventory_project/src/Product.cpp | 956deb69ab02a29001ba3be9246502b1d9cbd258 | [] | no_license | atsyro/miniprojects | 9c51c2f475e1049c57193f9ee201a08df334809f | 928497f2a210b8964b2b65a9fb3d2a1b7a778b24 | refs/heads/master | 2021-01-21T05:05:44.776360 | 2017-02-25T11:01:54 | 2017-02-25T11:01:54 | 83,133,369 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 73 | cpp |
#include "Product.h"
namespace mini
{
} /* namespace mini */
| [
"arsenytsyro96@gmail.com"
] | arsenytsyro96@gmail.com |
f7ec81a07e089f4ca5027f688040b22a8b8f45ce | f04aa8af3717d20540e5d00e0f5e011497b4ddf0 | /cpp/corner_detection_cpp.cpp | 059dd2395b983398f5be0a28b8cd957048bc521b | [] | no_license | Codermay/opencvjp-sample | fa7a73b205fa1ca1b4c7362e11256764e265a73e | 511d957517f500835cb7678a7f17c76778c523fa | refs/heads/master | 2021-01-17T21:27:06.266019 | 2012-02-29T09:56:34 | 2012-02-29T09:56:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,135 | cpp | #include <cvaux.h>
#include <highgui.h>
using namespace cv;
int
main (int argc, char **argv)
{
// (1)load a specified file as a 3-channel color image
const char *imagename = argc > 1 ? argv[1] : "../image/library.png";
Mat eigen_img = imread(imagename);
if(!eigen_img.data)
return -1;
Mat harris_img = eigen_img.clone();
Mat fast_img = eigen_img.clone();
// (2)convert to a grayscale image and normalize it
Mat gray_img;
cvtColor(eigen_img, gray_img, CV_BGR2GRAY);
normalize(gray_img, gray_img, 0, 255, NORM_MINMAX);
// (3)detect and draw strong corners on the image based on Eigen Value
vector<Point2f> corners;
goodFeaturesToTrack(gray_img, corners, 80, 0.01, 5);
vector<Point2f>::iterator it_corner = corners.begin();
for(; it_corner!=corners.end(); ++it_corner) {
circle(eigen_img, Point(it_corner->x, it_corner->y), 1, Scalar(0,200,255), -1);
circle(eigen_img, Point(it_corner->x, it_corner->y), 8, Scalar(0,200,255));
}
// (4)detect and draw strong corners on the image using Harris detector
goodFeaturesToTrack(gray_img, corners, 80, 0.01, 3, Mat(), 3, true);
it_corner = corners.begin();
for(; it_corner!=corners.end(); ++it_corner) {
circle(harris_img, Point(it_corner->x, it_corner->y), 1, Scalar(0,255,0), -1);
circle(harris_img, Point(it_corner->x, it_corner->y), 8, Scalar(0,255,0 ));
}
// (5)detect corners using high-speed corner detection; FAST
int threshold = 100;
bool nonmax = true;
vector<KeyPoint> keypoints;
FAST(gray_img, keypoints, threshold, nonmax);
vector<KeyPoint>::iterator it_kp = keypoints.begin();
for(; it_kp!=keypoints.end(); ++it_kp) {
circle(fast_img, Point(it_kp->pt.x, it_kp->pt.y), 1, Scalar(50,0,255), -1);
circle(fast_img, Point(it_kp->pt.x, it_kp->pt.y), 8, Scalar(50,0,255));
}
// (6)show destination images, and quit when any key pressed
namedWindow("EigenValue",CV_WINDOW_AUTOSIZE);
namedWindow("Harris",CV_WINDOW_AUTOSIZE);
namedWindow("Fast",CV_WINDOW_AUTOSIZE);
imshow("EigenValue", eigen_img);
imshow("Harris", harris_img);
imshow("Fast", fast_img);
waitKey(0);
return 0;
}
| [
"idojun@18163362-01b4-11df-b4af-25c34a55dae2"
] | idojun@18163362-01b4-11df-b4af-25c34a55dae2 |
25901caf96b3378f566cfab70b8c588e7cba558f | 7b0bed7a8f1a8d2856c82aa9d5ed9e2cecaeeb71 | /The Bintr Bunk/Player.h | a71e48cf34a72c890503bf3d85e2301c9e739ba6 | [] | no_license | TheBrenten/The-Bintr-Bunk | ec0e965d815528fee682a4bc591c8c398d066253 | 1e674d3ab3dc42e4eba820296f3347916b73e54e | refs/heads/master | 2021-04-26T11:53:15.585684 | 2018-07-05T04:49:57 | 2018-07-05T04:49:57 | 60,561,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,842 | h | #pragma once
#include "GameObject.h"
#include "LoadResources.h"
#include "BintrImage.h"
#include "PhysicsStuff.h"
#include "ImageObj.h"
extern int showHealthBar;
class Player;
extern vector<Player*> players;
/*
multiplayer process:
-player creates 3 imageobjs (body + 2 arms)
-packet updates pos/angle/dir/hand pos
-player.setImages() runs and sets imageobjs layer/pos/angle/dir accordingly
*/
extern Weapon* mainItem;
extern Weapon* lItem;
extern Weapon* rItem;
extern ImageObj* mainItemObj;
class Player
{
public:
// possibly remove
//vec lItemPos;
//float lItemAng;
//vec rItemPos;
//float rItemAng;
//vec mainItemPos;
//float mainItemAng;
//vec lHandPos;
//vec rHandPos;
//vec lShoulderPos, rShoulderPos;
// definitely needed
float health, maxHealth;
vec pos;
vec posLast;
// angle is smoothed
float angle;
float idealAngle = 0;
vector<ImageData> crouchWalk;
vector<ImageData> jumpToFall;
vector<ImageData> run;
vector<ImageData> standToCrouch;
ImageObj body;
ImageObj lArm;
ImageObj rArm;
bool leftHanded = false;
// animation
bool dir = true;
bool dirLast = true;
int animState = animStanding;
int animStateLast = animStanding;
int runFrame = 0;
int fallFrame = 0;
int crouchWalkFrame = 0;
int standToCrouchFrame = 0;
map<int, ArmData> arms;
ArmData* rArmData;
ArmData* lArmData;
int invincibilitySteps = 0;
int regenerate = 0;
sf::Shader* shader = nullptr;
ImageData stand;
ImageData crouch;
ImageData jump;
ImageData fall;
ImageData* imageData; // active image
Player();
~Player();
void move();
void setImages();
void setLeftItem(Weapon* item);
void setRightItem(Weapon* item);
void hurt(float damage);
};
| [
"bintrmagmorganorts@gmail.com"
] | bintrmagmorganorts@gmail.com |
40d7be76f63d9293718aa0a41dd2afeff1da9d10 | 7f08b096a26c5a12e18cbed4c041ba08d3c4029d | /tempSensor.ino | 1b523a29cfdd7e78b0446762944d16fa6676dbb6 | [] | no_license | souravsharm/SIT210-Task3.1P-WebHook | dade9f8d4a4b46a3b71c72ef4a0c7372b4fab9b6 | 9461a649e82d17bbd5e3c00c5d57c1ac85c7890f | refs/heads/main | 2023-04-14T22:43:46.929432 | 2021-05-04T15:30:27 | 2021-05-04T15:30:27 | 364,302,402 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 913 | ino | #include <Grove_Temperature_And_Humidity_Sensor.h>
#include <JsonParserGeneratorRK.h>
#define DELAY_TIME 30000
#define DHT_PIN D4
DHT dht(DHT_PIN);
double temp;
double hum;
void postEventPayload(double temp,double humidity){
JsonWriterStatic<256> jw;
{
JsonWriterAutoObject obj(&jw);
jw.insertKeyValue("temp",temp);
jw.insertKeyValue("hum",hum);
}
Particle.publish("Temperature",jw.getBuffer(),PRIVATE);
}
// ------------
//setting the pin D4 as an input pin
void setup() {
dht.begin();
pinMode(DHT_PIN,INPUT);
}
//looping the code with a 30 second delay
//values are inserted into a json file
//time is delayed for 30 seconds
void loop() {
// To blink the LED, first we'll turn it on...
temp=dht.getTempCelcius();
hum=dht.getHumidity();
postEventPayload(temp,hum);
delay(DELAY_TIME);
// And repeat!
}
| [
"noreply@github.com"
] | noreply@github.com |
6ebb2141a57657a4734eae7987ba8a664b43a23d | d2fe80fba383f3debee17d8c360b411498069d81 | /cpp/osh_eval_stubs.h | cc7c4a53b558acb8b882965ab72c282e66a47c08 | [] | no_license | stevenworthington/oil | 7c6bfb20f5dc9485da28c6285e0f909a644316b9 | 721e5da392a8ae02e1af4acf03cb76900946ec29 | refs/heads/master | 2022-11-07T16:34:54.883277 | 2020-06-15T17:03:02 | 2020-06-15T17:29:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,917 | h | // osh_eval_stubs.h
#ifndef OSH_EVAL_STUBS_H
#define OSH_EVAL_STUBS_H
// Hacky stubs
#include "id_kind_asdl.h"
#include "runtime_asdl.h"
#include "syntax_asdl.h"
namespace vm {
class _Executor;
}
namespace word_eval {
class AbstractWordEvaluator;
}
namespace expr_eval {
class OilEvaluator {
public:
// TODO: Should return value_t
void* EvalExpr(syntax_asdl::expr_t* node) {
assert(0);
}
void CheckCircularDeps() {
assert(0);
}
vm::_Executor* shell_ex;
word_eval::AbstractWordEvaluator* word_ev;
};
} // namespace expr_eval
// problem: incomplete type
#if 0
namespace cmd_exec {
class Executor {
public:
Str* RunCommandSub(syntax_asdl::command_t* node) {
assert(0);
}
Str* RunProcessSub(syntax_asdl::command_t* node, Id_t id) {
assert(0);
}
};
}
#endif
// stub for cmd_eval.py
#if 0
namespace args {
class UsageError {
public:
Str* msg;
int span_id;
};
} // namespace args
#endif
namespace util {
inline Str* BackslashEscape(Str* s, Str* meta_chars) {
int upper_bound = s->len_ * 2;
char* buf = static_cast<char*>(malloc(upper_bound));
char* p = buf;
for (int i = 0; i < s->len_; ++i) {
char c = s->data_[i];
if (memchr(meta_chars->data_, c, meta_chars->len_)) {
*p++ = '\\';
}
*p++ = c;
}
int len = p - buf;
return new Str(buf, len);
}
class UserExit {
public:
UserExit(int arg) {
}
};
} // namespace util
// TODO: Should these have their own file?
namespace pyutil {
inline Str* strerror_IO(IOError* e) {
assert(0);
}
inline Str* strerror_OS(OSError* e) {
assert(0);
}
} // namespace pyutil
//
// Stubs added for osh/cmd_exec.py
//
namespace builtin_misc {
class _Builtin {
public:
int Run(runtime_asdl::cmd_value_t* cmd_val) {
assert(0);
}
};
} // namespace builtin_misc
namespace builtin_process {
class _TrapHandler {
public:
syntax_asdl::command_t* node;
};
} // namespace builtin_process
namespace util {
class DebugFile {
public:
DebugFile(mylib::Writer* writer) {
}
};
} // namespace util
namespace executor {
class ShellExecutor {
public:
// overload
int RunSimpleCommand(runtime_asdl::cmd_value__Argv* cmd_val, bool do_fork) {
assert(0);
}
int RunSimpleCommand(runtime_asdl::cmd_value__Argv* cmd_val, bool do_fork,
bool call_procs) {
assert(0);
}
int RunBackgroundJob(syntax_asdl::command_t* node) {
assert(0);
}
int RunPipeline(syntax_asdl::command__Pipeline* node) {
assert(0);
}
int RunSubshell(syntax_asdl::command__Subshell* node) {
assert(0);
}
bool PushRedirects(List<runtime_asdl::redirect*>* redirects) {
assert(0);
}
void PopRedirects() {
assert(0);
}
Str* RunCommandSub(syntax_asdl::command_t* node) {
assert(0);
}
Str* RunProcessSub(syntax_asdl::command_t* node, Id_t op_id) {
assert(0);
}
};
} // namespace executor
#endif // OSH_EVAL_STUBS_H
| [
"andy@oilshell.org"
] | andy@oilshell.org |
21a705ab5ea7c9d8c72d92d9249c1c743b8bc132 | aaa60b19f500fc49dbaac1ec87e9c535a66b4ff5 | /0-OJ/bd3.cc | 3519d93e470cf18adebe295048271def59fc787c | [] | no_license | younger-1/leetcode-younger | c24e4a2a77c2f226c064c4eaf61e7f47d7e98d74 | a6dc92bbb90c5a095ac405476aeae6690e204b6b | refs/heads/master | 2023-07-25T02:31:42.430740 | 2021-09-09T08:06:05 | 2021-09-09T08:06:05 | 334,441,040 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 247 | cc | #include <iostream>
#include <string>
#include <vector>
using namespace std;
class A {
int a[100][1000];
};
int main() {
auto aa = new A();
int N, Q;
string s;
scanf("%d", &N);
scanf("%d", &Q);
while (Q--) {
}
}
| [
"45989017+younger-1@users.noreply.github.com"
] | 45989017+younger-1@users.noreply.github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.