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
e2634b5e58e56a38850df01ae54711ff7c5b72e1
2107f0f09213ab2e014232c8865a4c9a3ed4c9f8
/jk_0_0_2/jk_0_0_2.ino
8de99138b01ef3bcc0ac5a292cdd70e92f8e9b77
[]
no_license
benoit-artefactlabs/arduinoSketches
3bdd1eea73f428818cda452e2d7899fe49a37c09
3af964e9460b9cf39c970e0efbcc73af346b5173
refs/heads/master
2021-01-02T08:31:55.065025
2014-08-05T13:02:08
2014-08-05T13:02:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,658
ino
// include libraries begin -------------------------------- #include "parameters.h" #include <IRremote.h> #include <SPI.h> #include <Ethernet.h> #include <TextFinder.h> #include <MemoryFree.h> // include libraries end ---------------------------------- // configuration begin ------------------------------------ // 90.A2.DA.0F.15.0E // wired // 90.A2.DA.0E.B5.A1 // wifi byte mac[] = {0x90, 0xA2, 0xDA, 0x0F, 0x15, 0x0E}; EthernetClient client; //byte ip[] = {192, 168, 1, 44}; // set the IP address to an unused address on your network //char ESServer[] = paramESServer; IPAddress ESServer(paramESServer); int ESServerPort = paramESServerPort; int DHCPStatus = 0; int ESClientWait = paramESClientWait; boolean ESClientLastConnected = false; int currentJobIndex = 0; TextFinder finder(client); int LED_PIN = paramLed; IRsend irsend; char* jobs[] = {paramJobs}; unsigned long pM = 0; boolean httpResponseSearchStatus = false; // configuration end -------------------------------------- // helper functions begin --------------------------------- void setupSerial() { Serial.begin(9600); while (!Serial) { ; } delay(1000); } void setupEthernet() { if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); //Ethernet.begin(mac, ip); DHCPStatus = 0; } else { Serial.println("Configured Ethernet using DHCP"); DHCPStatus = 1; } } void setupHardware() { // init IR digitalWrite(LED_PIN, LOW); // AMP 1 Serial.println("sending ON F7C03F"); irsend.sendNEC(0xF7C03F, 32); Serial.println("sending WHITE F7E01F"); irsend.sendNEC(0xF7E01F, 32); // TODO, amp n ... in a loop } void printFreeMemory() { Serial.print("freeMemory : "); Serial.print(freeMemory()); Serial.println(" B"); } void jobAction() { sendHttpRequest(String(jobs[currentJobIndex])); if (currentJobIndex+1 < paramJobsLength) { currentJobIndex++; } else { currentJobIndex = 0; } } void sendHttpRequest(String jobname) { if (client.connected()) { return; } String ESClientPath = paramESClientPath; ESClientPath.replace(String("JOBNAME"), jobname); /* Serial.println(ESServer+String(":")+ESServerPort); Serial.print("GET "); Serial.print(ESClientPath); Serial.println(" HTTP/1.1"); Serial.print("Host: "); Serial.println(ESServer); Serial.print("Authorization: Basic "); Serial.println(paramESClientAuthRealm); Serial.print("User-Agent: "); Serial.println(paramESClientUA); Serial.println("Connection: close"); Serial.println(); */ Serial.println(F("Sending http request to server")); if (client.connect(ESServer, ESServerPort)) { client.print("GET "); client.print(ESClientPath); client.println(" HTTP/1.1"); client.print("Host: "); client.println(ESServer); //client.print("Authorization: Basic "); //client.println(paramESClientAuthRealm); client.print("User-Agent: "); client.println(paramESClientUA); client.println("Connection: close"); client.println(); Serial.println("connection success"); } else { Serial.println("connection failed"); Serial.println("disconnecting."); client.flush(); client.stop(); } } void resetHttpResponse() { Serial.println("disconnecting."); client.stop(); client.flush(); httpResponseSearchStatus = false; } void readHttpResponse() { if (client.available() && !httpResponseSearchStatus) { httpResponseSearchStatus = true; int jobNameBufferLength = 32; char jobName[jobNameBufferLength]; char jobNamePre[] = paramJobNamePre; char jobNamePost[] = paramJobNamePost; int jobNameLength = 0; int jobStatusBufferLength = 10; char jobStatus[jobStatusBufferLength]; char jobStatusPre[] = paramJobStatusPre; char jobStatusPost[] = paramJobStatusPost; int jobStatusLength = 0; if( finder.find(paramHttpResponseOk) ) { Serial.println("http response OK"); jobNameLength = finder.getString(jobNamePre, jobNamePost, jobName, jobNameBufferLength); jobStatusLength = finder.getString(jobStatusPre, jobStatusPost, jobStatus, jobStatusBufferLength); if (jobNameLength && jobStatusLength) { Serial.println("http response format OK"); actionLedGroupToggle(decodeJobStatus(String(jobStatus)), decodeJobName(String(jobName))); } else { Serial.println("http response format KO"); } } else { Serial.println("http response KO"); } resetHttpResponse(); } if (!client.connected() && ESClientLastConnected) { resetHttpResponse(); } } void actionLedGroupToggle(int state, int pin) { Serial.println(String("state: ")+String(state)+String(", pin: ")+String(pin)); /*boolean authorizedPin = false; for (int k = 0; k < paramLedsGroupsLength; k++) { if (pin == leds[k]) { authorizedPin = true; break; } }*/ // TODO pin is ignored for the moment // should find hex IR codes to send from pin number // in order to work with several jobs monitoring boolean authorizedPin = true; if (authorizedPin) { if (state == 2) { Serial.println("sending RED F720DF"); irsend.sendNEC(0xF720DF, 32); } else if (state == 1) { Serial.println("sending GREEN F7A05F"); irsend.sendNEC(0xF7A05F, 32); } else { Serial.println("sending SMOOTH F7E817"); irsend.sendNEC(0xF7E817, 32); } } } int decodeJobName(String jobName) { Serial.println(String("jobName: [")+jobName+String("]")); for (int k = 0; k < paramJobsLength; k++) { String _jobName = jobs[k]; if (jobName.startsWith(_jobName)) { //return leds[k]; return k; } } } int decodeJobStatus(String jobStatus) { Serial.println(String("jobStatus: [")+jobStatus+String("]")); if (jobStatus == "FAILURE") { return 2; } else if (jobStatus == "SUCCESS") { return 1; } return 0; } // helper functions end ----------------------------------- // main program setup begin ------------------------------- void setup() { setupSerial(); setupHardware(); setupEthernet(); delay(1000); } // main program setup end --------------------------------- // main program loop begin -------------------------------- void loop() { if (DHCPStatus > 0) { unsigned long cM = millis(); readHttpResponse(); if (cM-pM > ESClientWait*1000) { pM = cM; //String jobname = "artefactlabs"; //sendHttpRequest(jobname); jobAction(); } else { // wait //Serial.print("Wait"); //Serial.println(cM-pM); } ESClientLastConnected = client.connected(); } } // main program loop end ----------------------------------
[ "bencom@artefactlabs.net" ]
bencom@artefactlabs.net
c67bf7144d5de4ea49e78ee40beb6a331a8a7b55
02bf7298924574d1336540c53d70471b7625a8ae
/tasks/TiledAcquisition.cpp
90c10156607226e86e0e4de06b75f94f9739a6e0
[ "BSD-3-Clause" ]
permissive
davidackerman/fetchUpgrades
c1d2d671756a7d31d37f21b31db45b4a460ba8ed
c32e892b13a3da22f8d04f6f982dc2d4d9f638b1
refs/heads/master
2020-04-12T01:21:53.770051
2020-03-11T14:51:50
2020-03-11T14:51:50
65,045,666
0
0
null
null
null
null
UTF-8
C++
false
false
6,915
cpp
/** \file Microscope task. Acquire stacks for each marked tile in a plane. \author Nathan Clack <clackn@janelia.hhmi.org> \copyright Copyright 2010 Howard Hughes Medical Institute. All rights reserved. Use is subject to Janelia Farm Research Campus Software Copyright 1.1 license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html). */ #include "common.h" #include "TiledAcquisition.h" #include "StackAcquisition.h" #include "Video.h" #include "frame.h" #include "devices\digitizer.h" #include "devices\Microscope.h" #include "devices\tiling.h" #if 1 // PROFILING #define TS_OPEN(name) timestream_t ts__=timestream_open(name) #define TS_TIC timestream_tic(ts__) #define TS_TOC timestream_toc(ts__) #define TS_CLOSE timestream_close(ts__) #else #define TS_OPEN(name) #define TS_TIC #define TS_TOC #define TS_CLOSE #endif #define CHKJMP(expr) if(!(expr)) {warning("%s(%d)"ENDL"\tExpression indicated failure:"ENDL"\t%s"ENDL,__FILE__,__LINE__,#expr); goto Error;} namespace fetch { namespace task { // // TiledAcquisition - microscope task // namespace microscope { //Upcasting unsigned int TiledAcquisition::config(IDevice *d) {return config(dynamic_cast<device::Microscope*>(d));} unsigned int TiledAcquisition::run (IDevice *d) {return run (dynamic_cast<device::Microscope*>(d));} unsigned int TiledAcquisition::config(device::Microscope *d) { static task::scanner::ScanStack<u16> grabstack; std::string filename; Guarded_Assert(d); //Assemble pipeline here IDevice *cur; cur = d->configPipeline(); CHKJMP(d->file_series.ensurePathExists()); d->file_series.inc(); filename = d->stack_filename(); IDevice::connect(&d->disk,0,cur,0); Guarded_Assert( d->disk.close()==0 ); //Guarded_Assert( d->disk.open(filename,"w")==0); d->__scan_agent.disarm(10000/*timeout_ms*/); int isok=d->__scan_agent.arm(&grabstack,&d->scanner)==0; d->stage()->tiling()->resetCursor(); // this is here so that run/stop cycles will pick up where they left off return isok; //success Error: return 0; } static int _handle_wait_for_result(DWORD result, const char *msg) { return_val_if( result == WAIT_OBJECT_0 , 0 ); return_val_if( result == WAIT_OBJECT_0+1, 1 ); Guarded_Assert_WinErr( result != WAIT_FAILED ); if(result == WAIT_ABANDONED_0) warning("%s(%d)"ENDL "\tTiledAcquisition: Wait 0 abandoned"ENDL "\t%s"ENDL, __FILE__, __LINE__, msg); if(result == WAIT_ABANDONED_0+1) warning("%s(%d)"ENDL "\tTiledAcquisition: Wait 1 abandoned"ENDL "\t%s"ENDL, __FILE__, __LINE__, msg); if(result == WAIT_TIMEOUT) warning("%s(%d)"ENDL "\tTiledAcquisition: Wait timeout"ENDL "\t%s"ENDL, __FILE__, __LINE__, msg); Guarded_Assert_WinErr( result != WAIT_FAILED ); return -1; } unsigned int TiledAcquisition::run(device::Microscope *dc) { std::string filename; unsigned int eflag = 0; // success Vector3f tilepos; TS_OPEN("timer-tiles.f32"); CHKJMP(dc->__scan_agent.is_runnable()); device::StageTiling* tiling = dc->stage()->tiling(); tiling->resetCursor(); while(eflag==0 && !dc->_agent->is_stopping() && tiling->nextInPlanePosition(tilepos)) { TS_TIC; debug("%s(%d)"ENDL "\t[Tiling Task] tilepos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,tilepos[0],tilepos[1],tilepos[2]); filename = dc->stack_filename(); dc->file_series.ensurePathExists(); dc->disk.set_nchan(dc->scanner.get2d()->digitizer()->nchan()); eflag |= dc->disk.open(filename,"w"); if(eflag) { warning("Couldn't open file: %s"ENDL, filename.c_str()); return eflag; } // Move stage Vector3f curpos = dc->stage()->getTarget(); // use current target z for tilepos z debug("%s(%d)"ENDL "\t[Tiling Task] curpos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); //tilepos[2] = curpos[2]*1000.0f; // unit conversion here is a bit awkward if (tiling->useTwoDimensionalTiling_) tilepos[2] = curpos[2]*1000.0f; // DGA: Use current target z for tilepos z when using two dimensional tiling dc->stage()->setPos(0.001f*tilepos); // convert um to mm curpos = dc->stage()->getTarget(); // use current target z for tilepos z debug("%s(%d)"ENDL "\t[Tiling Task] curpos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); eflag |= dc->runPipeline(); eflag |= dc->__scan_agent.run() != 1; { // Wait for stack to finish HANDLE hs[] = { dc->__scan_agent._thread, dc->__self_agent._notify_stop}; DWORD res; int t; // wait for scan to complete (or cancel) res = WaitForMultipleObjects(2,hs,FALSE,INFINITE); t = _handle_wait_for_result(res,"TiledAcquisition::run - Wait for scanner to finish."); switch(t) { case 0: // in this case, the scanner thread stopped. Nothing left to do. eflag |= dc->__scan_agent.last_run_result(); // check the run result eflag |= dc->__io_agent.last_run_result(); if(eflag==0) // remove this if statement to mark tiles as "error" tiles. In practice, it seems it's ok to go back and reimage, so the if statement stays tiling->markDone(eflag==0); // only mark the tile done if the scanner task completed normally case 1: // in this case, the stop event triggered and must be propagated. eflag |= dc->__scan_agent.stop(SCANNER2D_DEFAULT_TIMEOUT) != 1; break; default: // in this case, there was a timeout or abandoned wait eflag |= 1; // failure } } // end waiting block // Output and Increment files dc->write_stack_metadata(); // write the metadata eflag |= dc->disk.close(); dc->file_series.inc(); // increment regardless of completion status eflag |= dc->stopPipeline(); // wait till everything stops TS_TOC; } // end loop over tiles eflag |= dc->stopPipeline(); // wait till the pipeline stops TS_CLOSE; return eflag; Error: TS_CLOSE; return 1; } } // namespace microscope } // namespace task } // namespace fetch
[ "ackermand@hhmi.org" ]
ackermand@hhmi.org
0a0512d7f3fc82b12a531383d87bcec04b6c95f8
8105d1b21a466bdc62b6f7d2766d39f97e9b138a
/1149/lectures/se/visitor/broken/textbook.h
f409971c7c4b450fc839241ea141d35b5347601f
[]
no_license
PANGMeng/uwaterloo-cs246
2984c9a98581250789ddb16a7e958968043f5b84
d2dba6ff093301ea32f0941b306f80dbf8159040
refs/heads/master
2021-01-11T16:01:24.064187
2016-06-26T17:53:12
2016-06-26T17:53:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
363
h
#ifndef __TEXTBOOK_H__ #define __TEXTBOOK_H__ #include <string> #include "book.h" #include "BookVisitor.h" class TextBook: public Book { std::string topic; public: TextBook(std::string title, std::string author, int numPages, std::string topic); bool isItHeavy(); std::string getTopic(); bool favourite(); void accept(BookVisitor &v); }; #endif
[ "jrutledge@kinduct.com" ]
jrutledge@kinduct.com
d3b018062711743d956f35590257c1464e623d7c
7e2465414cdca35ea6b948392d1929da10db7427
/chapter_4_number_theory_and_cryptography/4.6_cryptography/exercises/repo/problem_24.cpp
dceaf4c27610b9363bb60fd37a4226b05b3368ad
[]
no_license
6guojun/discrete_mathematics_and_its_applications
244bcc0a033cc218a1ba88390c4ad957c66e939c
a41e905179f88b91b1402b515c01b09716db5142
refs/heads/master
2021-03-23T07:25:27.545525
2020-01-16T05:37:48
2020-01-16T05:37:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,654
cpp
#include "integer.h" #include <cstdio> #include <string> #include <sstream> utility::integer::Integer power(int x, int y) { if (y == 0) { return 1; } else if (y == 1) { return x; } else { const utility::integer::Integer t = power(x, y / 2); if (y % 2) return t * t * x; else return t * t; } } std::string to_string(int n) { std::ostringstream oss; oss << n; return oss.str(); } std::string convert(const std::string& message) { std::string msg; for (std::size_t i = 0; i < message.size(); ++i) { const int index = message[i] - 'A'; if (index < 10) { msg += '0'; msg += index + '0'; } else { msg += (index / 10) + '0'; msg += (index % 10) + '0'; } } return msg; } void encrypt(const std::string& message) { const int p = 43; const int q = 59; const int e = 13; const int n = p * q; const std::string msg = convert(message); std::string cipher; for (std::size_t i = 0; i < msg.size(); i += 4) { const int x = std::atoi(msg.substr(i, 4).c_str()); utility::integer::Integer m = power(x, e); utility::integer::Integer a = m / n; utility::integer::Integer r = m - a * n; cipher += r.get(); cipher += ' '; } printf("Encrypted message == [%s]\n", cipher.c_str()); } int main() { printf("--------------------------------------------------\n"); std::string msg = "ATTACK"; encrypt(msg); printf("--------------------------------------------------\n"); return 0; }
[ "cpp.rakesh@gmail.com" ]
cpp.rakesh@gmail.com
034bf79226250bc37d672ffbee1e24a16e9db730
1305023dc5933375d916d3d0221fa8b5f8526628
/Practicum/week 13/Examples/TextFileCommandPattern/SimpleTextFileOperator.cpp
3011c0c3cd285097137b4a0d9f53ffe7f9a845e9
[]
no_license
RosinaGeorgieva/ObjectOrientedProgramming2021
60720fbd9f5e4d3532c747ff3ec20324c1411ec7
5ae0ca4b553e10df1e7a5d6566932c68643402da
refs/heads/main
2023-05-23T18:18:46.296181
2021-06-21T16:44:03
2021-06-21T16:44:03
341,258,041
0
0
null
2021-02-22T16:08:18
2021-02-22T16:08:17
null
UTF-8
C++
false
false
292
cpp
#include <string> class TextFileCommandExecutor { std::string name; public: TextFileCommandExecutor(std::string name) { this->name = name; } std::string openFile() { return "Opening file " + name; } std::string closeFile() { return "Closing file " + name; } };
[ "noreply@github.com" ]
noreply@github.com
3b9441a524ab3bd9b4335b788b3779334f0ea68f
2039498c2770eb7f1f32f25d24e8b20c141caa69
/utils/output.h
a65f7f2625a8872604f98da475a0eaf8d2b8b02b
[]
no_license
DavyVan/PhDStillNeedLeetCode
c10f38447d9b0ad5d50c2f529ee4a4159105e58d
0dd4dcd3a598a85cb2189ab4993e1f63c0305c4c
refs/heads/master
2023-08-11T01:14:30.483187
2023-07-31T02:33:30
2023-07-31T02:33:30
253,396,587
4
0
null
null
null
null
UTF-8
C++
false
false
595
h
#ifndef __UTILS_OUTPUT_H__ #define __UTILS_OUTPUT_H__ #include <iostream> #include <vector> using namespace std; template<typename T> void output_vector(vector<T> v) { cout << "Vector size: " << v.size() << endl; for (T x : v) { cout << x << " "; } cout << endl; } template<typename T> void output_matrix(vector<vector<T>> m) { cout << "Matrix size: " << m.size() << " x " << m[0].size() << endl; for (auto r : m) { for (auto x : r) { cout << x << " "; } cout << endl; } cout << endl; } #endif // __UTILS_OUTPUT_H__
[ "affqqa@163.com" ]
affqqa@163.com
e7d7b80c9acacde18845a1bdcca7c53e7e315a50
9885303424de9041e667b3e2ec084ac65dbea13c
/codes_auto/88.merge-sorted-array.cpp
64f20455797d633f73da73ba7a0bb93c7fe53385
[]
no_license
linxueya/LeetCodeauto
65e45f5f4c49127e5798c9b2a82f86f5c5c293a8
0df8382c0c52ffe43c125d9dff922394b5956bc1
refs/heads/master
2022-11-15T08:21:48.724021
2020-07-17T00:48:44
2020-07-17T00:48:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
523
cpp
# # @lc app=leetcode.cn id=88 lang=cpp # # [88] merge-sorted-array # class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { if (0 == n) return; if (0 == m) { nums1 = nums2; return; } vector<int> v; int i = 0, j = 0; while( i < m && j < n ) { if (nums1[i] <= nums2[j]) v.push_back(nums1[i++]); else v.push_back(nums2[j++]); } while(i<m) v.push_back(nums1[i++]); while (j < n) v.push_back(nums2[j++]); nums1 = v; } }; # @lc code=end
[ "1462857461@qq.com" ]
1462857461@qq.com
7f1ff7ee539ca57e1029a39f8f2786be8f15a3f4
e50b5f066628ef65fd7f79078b4b1088f9d11e87
/llvm/.svn/pristine/49/496669eaed32e62bc3f674acc3f7a3af9f140982.svn-base
d160c5ac9fdd6b556cbe835ff6a86921b8dcaa12
[ "NCSA" ]
permissive
uzleo/coast
1471e03b2a1ffc9883392bf80711e6159917dca1
04bd688ac9a18d2327c59ea0c90f72e9b49df0f4
refs/heads/master
2020-05-16T11:46:24.870750
2019-04-23T13:57:53
2019-04-23T13:57:53
183,025,687
0
0
null
2019-04-23T13:52:28
2019-04-23T13:52:27
null
UTF-8
C++
false
false
16,786
//===- llvm/unittest/IR/LegacyPassManager.cpp - Legacy PassManager tests --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This unit test exercises the legacy pass manager infrastructure. We use the // old names as well to ensure that the source-level compatibility is preserved // where possible. // //===----------------------------------------------------------------------===// #include "llvm/IR/LegacyPassManager.h" #include "llvm/Analysis/CallGraphSCCPass.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CallingConv.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/Verifier.h" #include "llvm/Pass.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include "gtest/gtest.h" using namespace llvm; namespace llvm { void initializeModuleNDMPass(PassRegistry&); void initializeFPassPass(PassRegistry&); void initializeCGPassPass(PassRegistry&); void initializeLPassPass(PassRegistry&); void initializeBPassPass(PassRegistry&); namespace { // ND = no deps // NM = no modifications struct ModuleNDNM: public ModulePass { public: static char run; static char ID; ModuleNDNM() : ModulePass(ID) { } bool runOnModule(Module &M) override { run++; return false; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); } }; char ModuleNDNM::ID=0; char ModuleNDNM::run=0; struct ModuleNDM : public ModulePass { public: static char run; static char ID; ModuleNDM() : ModulePass(ID) {} bool runOnModule(Module &M) override { run++; return true; } }; char ModuleNDM::ID=0; char ModuleNDM::run=0; struct ModuleNDM2 : public ModulePass { public: static char run; static char ID; ModuleNDM2() : ModulePass(ID) {} bool runOnModule(Module &M) override { run++; return true; } }; char ModuleNDM2::ID=0; char ModuleNDM2::run=0; struct ModuleDNM : public ModulePass { public: static char run; static char ID; ModuleDNM() : ModulePass(ID) { initializeModuleNDMPass(*PassRegistry::getPassRegistry()); } bool runOnModule(Module &M) override { run++; return false; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<ModuleNDM>(); AU.setPreservesAll(); } }; char ModuleDNM::ID=0; char ModuleDNM::run=0; template<typename P> struct PassTestBase : public P { protected: static int runc; static bool initialized; static bool finalized; int allocated; void run() { EXPECT_TRUE(initialized); EXPECT_FALSE(finalized); EXPECT_EQ(0, allocated); allocated++; runc++; } public: static char ID; static void finishedOK(int run) { EXPECT_GT(runc, 0); EXPECT_TRUE(initialized); EXPECT_TRUE(finalized); EXPECT_EQ(run, runc); } PassTestBase() : P(ID), allocated(0) { initialized = false; finalized = false; runc = 0; } void releaseMemory() override { EXPECT_GT(runc, 0); EXPECT_GT(allocated, 0); allocated--; } }; template<typename P> char PassTestBase<P>::ID; template<typename P> int PassTestBase<P>::runc; template<typename P> bool PassTestBase<P>::initialized; template<typename P> bool PassTestBase<P>::finalized; template<typename T, typename P> struct PassTest : public PassTestBase<P> { public: #ifndef _MSC_VER // MSVC complains that Pass is not base class. using llvm::Pass::doInitialization; using llvm::Pass::doFinalization; #endif bool doInitialization(T &t) override { EXPECT_FALSE(PassTestBase<P>::initialized); PassTestBase<P>::initialized = true; return false; } bool doFinalization(T &t) override { EXPECT_FALSE(PassTestBase<P>::finalized); PassTestBase<P>::finalized = true; EXPECT_EQ(0, PassTestBase<P>::allocated); return false; } }; struct CGPass : public PassTest<CallGraph, CallGraphSCCPass> { public: CGPass() { initializeCGPassPass(*PassRegistry::getPassRegistry()); } bool runOnSCC(CallGraphSCC &SCMM) override { run(); return false; } }; struct FPass : public PassTest<Module, FunctionPass> { public: bool runOnFunction(Function &F) override { // FIXME: PR4112 // EXPECT_TRUE(getAnalysisIfAvailable<DataLayout>()); run(); return false; } }; struct LPass : public PassTestBase<LoopPass> { private: static int initcount; static int fincount; public: LPass() { initializeLPassPass(*PassRegistry::getPassRegistry()); initcount = 0; fincount=0; EXPECT_FALSE(initialized); } static void finishedOK(int run, int finalized) { PassTestBase<LoopPass>::finishedOK(run); EXPECT_EQ(run, initcount); EXPECT_EQ(finalized, fincount); } using llvm::Pass::doInitialization; using llvm::Pass::doFinalization; bool doInitialization(Loop* L, LPPassManager &LPM) override { initialized = true; initcount++; return false; } bool runOnLoop(Loop *L, LPPassManager &LPM) override { run(); return false; } bool doFinalization() override { fincount++; finalized = true; return false; } }; int LPass::initcount=0; int LPass::fincount=0; struct BPass : public PassTestBase<BasicBlockPass> { private: static int inited; static int fin; public: static void finishedOK(int run, int N) { PassTestBase<BasicBlockPass>::finishedOK(run); EXPECT_EQ(inited, N); EXPECT_EQ(fin, N); } BPass() { inited = 0; fin = 0; } bool doInitialization(Module &M) override { EXPECT_FALSE(initialized); initialized = true; return false; } bool doInitialization(Function &F) override { inited++; return false; } bool runOnBasicBlock(BasicBlock &BB) override { run(); return false; } bool doFinalization(Function &F) override { fin++; return false; } bool doFinalization(Module &M) override { EXPECT_FALSE(finalized); finalized = true; EXPECT_EQ(0, allocated); return false; } }; int BPass::inited=0; int BPass::fin=0; struct OnTheFlyTest: public ModulePass { public: static char ID; OnTheFlyTest() : ModulePass(ID) { initializeFPassPass(*PassRegistry::getPassRegistry()); } bool runOnModule(Module &M) override { for (Module::iterator I=M.begin(),E=M.end(); I != E; ++I) { Function &F = *I; { SCOPED_TRACE("Running on the fly function pass"); getAnalysis<FPass>(F); } } return false; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<FPass>(); } }; char OnTheFlyTest::ID=0; TEST(PassManager, RunOnce) { LLVMContext Context; Module M("test-once", Context); struct ModuleNDNM *mNDNM = new ModuleNDNM(); struct ModuleDNM *mDNM = new ModuleDNM(); struct ModuleNDM *mNDM = new ModuleNDM(); struct ModuleNDM2 *mNDM2 = new ModuleNDM2(); mNDM->run = mNDNM->run = mDNM->run = mNDM2->run = 0; legacy::PassManager Passes; Passes.add(mNDM2); Passes.add(mNDM); Passes.add(mNDNM); Passes.add(mDNM); Passes.run(M); // each pass must be run exactly once, since nothing invalidates them EXPECT_EQ(1, mNDM->run); EXPECT_EQ(1, mNDNM->run); EXPECT_EQ(1, mDNM->run); EXPECT_EQ(1, mNDM2->run); } TEST(PassManager, ReRun) { LLVMContext Context; Module M("test-rerun", Context); struct ModuleNDNM *mNDNM = new ModuleNDNM(); struct ModuleDNM *mDNM = new ModuleDNM(); struct ModuleNDM *mNDM = new ModuleNDM(); struct ModuleNDM2 *mNDM2 = new ModuleNDM2(); mNDM->run = mNDNM->run = mDNM->run = mNDM2->run = 0; legacy::PassManager Passes; Passes.add(mNDM); Passes.add(mNDNM); Passes.add(mNDM2);// invalidates mNDM needed by mDNM Passes.add(mDNM); Passes.run(M); // Some passes must be rerun because a pass that modified the // module/function was run in between EXPECT_EQ(2, mNDM->run); EXPECT_EQ(1, mNDNM->run); EXPECT_EQ(1, mNDM2->run); EXPECT_EQ(1, mDNM->run); } Module *makeLLVMModule(LLVMContext &Context); template<typename T> void MemoryTestHelper(int run) { LLVMContext Context; std::unique_ptr<Module> M(makeLLVMModule(Context)); T *P = new T(); legacy::PassManager Passes; Passes.add(P); Passes.run(*M); T::finishedOK(run); } template<typename T> void MemoryTestHelper(int run, int N) { LLVMContext Context; Module *M = makeLLVMModule(Context); T *P = new T(); legacy::PassManager Passes; Passes.add(P); Passes.run(*M); T::finishedOK(run, N); delete M; } TEST(PassManager, Memory) { // SCC#1: test1->test2->test3->test1 // SCC#2: test4 // SCC#3: indirect call node { SCOPED_TRACE("Callgraph pass"); MemoryTestHelper<CGPass>(3); } { SCOPED_TRACE("Function pass"); MemoryTestHelper<FPass>(4);// 4 functions } { SCOPED_TRACE("Loop pass"); MemoryTestHelper<LPass>(2, 1); //2 loops, 1 function } { SCOPED_TRACE("Basic block pass"); MemoryTestHelper<BPass>(7, 4); //9 basic blocks } } TEST(PassManager, MemoryOnTheFly) { LLVMContext Context; Module *M = makeLLVMModule(Context); { SCOPED_TRACE("Running OnTheFlyTest"); struct OnTheFlyTest *O = new OnTheFlyTest(); legacy::PassManager Passes; Passes.add(O); Passes.run(*M); FPass::finishedOK(4); } delete M; } Module *makeLLVMModule(LLVMContext &Context) { // Module Construction Module *mod = new Module("test-mem", Context); mod->setDataLayout("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-" "i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-" "a:0:64-s:64:64-f80:128:128"); mod->setTargetTriple("x86_64-unknown-linux-gnu"); // Type Definitions std::vector<Type*>FuncTy_0_args; FunctionType *FuncTy_0 = FunctionType::get( /*Result=*/IntegerType::get(Context, 32), /*Params=*/FuncTy_0_args, /*isVarArg=*/false); std::vector<Type*>FuncTy_2_args; FuncTy_2_args.push_back(IntegerType::get(Context, 1)); FunctionType *FuncTy_2 = FunctionType::get( /*Result=*/Type::getVoidTy(Context), /*Params=*/FuncTy_2_args, /*isVarArg=*/false); // Function Declarations Function* func_test1 = Function::Create( /*Type=*/FuncTy_0, /*Linkage=*/GlobalValue::ExternalLinkage, /*Name=*/"test1", mod); func_test1->setCallingConv(CallingConv::C); AttributeSet func_test1_PAL; func_test1->setAttributes(func_test1_PAL); Function* func_test2 = Function::Create( /*Type=*/FuncTy_0, /*Linkage=*/GlobalValue::ExternalLinkage, /*Name=*/"test2", mod); func_test2->setCallingConv(CallingConv::C); AttributeSet func_test2_PAL; func_test2->setAttributes(func_test2_PAL); Function* func_test3 = Function::Create( /*Type=*/FuncTy_0, /*Linkage=*/GlobalValue::ExternalLinkage, /*Name=*/"test3", mod); func_test3->setCallingConv(CallingConv::C); AttributeSet func_test3_PAL; func_test3->setAttributes(func_test3_PAL); Function* func_test4 = Function::Create( /*Type=*/FuncTy_2, /*Linkage=*/GlobalValue::ExternalLinkage, /*Name=*/"test4", mod); func_test4->setCallingConv(CallingConv::C); AttributeSet func_test4_PAL; func_test4->setAttributes(func_test4_PAL); // Global Variable Declarations // Constant Definitions // Global Variable Definitions // Function Definitions // Function: test1 (func_test1) { BasicBlock *label_entry = BasicBlock::Create(Context, "entry", func_test1, nullptr); // Block entry (label_entry) CallInst* int32_3 = CallInst::Create(func_test2, "", label_entry); int32_3->setCallingConv(CallingConv::C); int32_3->setTailCall(false);AttributeSet int32_3_PAL; int32_3->setAttributes(int32_3_PAL); ReturnInst::Create(Context, int32_3, label_entry); } // Function: test2 (func_test2) { BasicBlock *label_entry_5 = BasicBlock::Create(Context, "entry", func_test2, nullptr); // Block entry (label_entry_5) CallInst* int32_6 = CallInst::Create(func_test3, "", label_entry_5); int32_6->setCallingConv(CallingConv::C); int32_6->setTailCall(false);AttributeSet int32_6_PAL; int32_6->setAttributes(int32_6_PAL); ReturnInst::Create(Context, int32_6, label_entry_5); } // Function: test3 (func_test3) { BasicBlock *label_entry_8 = BasicBlock::Create(Context, "entry", func_test3, nullptr); // Block entry (label_entry_8) CallInst* int32_9 = CallInst::Create(func_test1, "", label_entry_8); int32_9->setCallingConv(CallingConv::C); int32_9->setTailCall(false);AttributeSet int32_9_PAL; int32_9->setAttributes(int32_9_PAL); ReturnInst::Create(Context, int32_9, label_entry_8); } // Function: test4 (func_test4) { Function::arg_iterator args = func_test4->arg_begin(); Value *int1_f = &*args++; int1_f->setName("f"); BasicBlock *label_entry_11 = BasicBlock::Create(Context, "entry", func_test4, nullptr); BasicBlock *label_bb = BasicBlock::Create(Context, "bb", func_test4, nullptr); BasicBlock *label_bb1 = BasicBlock::Create(Context, "bb1", func_test4, nullptr); BasicBlock *label_return = BasicBlock::Create(Context, "return", func_test4, nullptr); // Block entry (label_entry_11) BranchInst::Create(label_bb, label_entry_11); // Block bb (label_bb) BranchInst::Create(label_bb, label_bb1, int1_f, label_bb); // Block bb1 (label_bb1) BranchInst::Create(label_bb1, label_return, int1_f, label_bb1); // Block return (label_return) ReturnInst::Create(Context, label_return); } return mod; } } } INITIALIZE_PASS(ModuleNDM, "mndm", "mndm", false, false) INITIALIZE_PASS_BEGIN(CGPass, "cgp","cgp", false, false) INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) INITIALIZE_PASS_END(CGPass, "cgp","cgp", false, false) INITIALIZE_PASS(FPass, "fp","fp", false, false) INITIALIZE_PASS_BEGIN(LPass, "lp","lp", false, false) INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) INITIALIZE_PASS_END(LPass, "lp","lp", false, false) INITIALIZE_PASS(BPass, "bp","bp", false, false)
[ "jeffrey.goeders@gmail.com" ]
jeffrey.goeders@gmail.com
2999ac2bebdeae76a3efdae9732dd2a71fe12d95
03cc889382946c83e7f230aa89a69b369e7fd53b
/Zombie Massacre Reattempt/Zombie Massacre Reattempt/Player.h
0deb7a72baad0fca7577f3072702419f916336f7
[]
no_license
aaron-hamil5/Zombie-Massacre
479b4d6b52c14406a238844ce5a723decaf72985
5c2f49469d0c039291a9f57418c35b6525e54a68
refs/heads/main
2023-08-21T21:08:46.893064
2021-11-03T21:54:12
2021-11-03T21:54:12
413,449,167
0
0
null
null
null
null
UTF-8
C++
false
false
2,047
h
#ifndef PLAYER_H #define PLAYER_H //SFML graphics #include<SFML/Graphics.hpp> class Player { private: #pragma region Variables /*Player speed*/ const float START_SPEED = 200.0f; /*Player health*/ const float START_HEALTH = 100.0f; int m_maxHealth; int m_health; /*Player location*/ sf::Vector2f m_position; /*Players sprite and texture*/ sf::Sprite m_Sprite; sf::Texture m_texture; /*Screen Bounderies*/ sf::Vector2f m_screenRes; /*Playspace Boundries and size*/ sf::IntRect m_arena; int m_tilesize; /* Player movement*/ bool m_upArrowPressed = false; bool m_downArrowPressed = false; bool m_leftArrowPressed = false; bool m_rightArrowPressed = false; /*Player Taking damage*/ sf::Time m_lastHit; /*Players movement in pixels per second*/ float m_speed; #pragma endregion public: /*Constuctor*/ Player(); //Spawning in the player void spawn(sf::IntRect arena, sf::Vector2f resolution, int tileSize); #pragma region Meathods #pragma region Player Hit //Handle if the player is being hit bool hit(sf::Time timeHit); /*Last Time Hit*/ sf::Time lastHitTime(); #pragma endregion #pragma region Location and angle /*Current position*/ sf::FloatRect getPosition(); /*Current angle*/ float getRotation(); #pragma endregion #pragma region Sprite center and share to main /*Give Copy of sprite to main fuction*/ sf::Sprite getSprite(); /*Center of sprite*/ sf::Vector2f getCenter(); #pragma endregion #pragma region Movement /*Movement Meathods*/ //Allow Movement void moveLeft(); void moveRight(); void moveUp(); void moveDown(); //Restrict movement void stopLeft(); void stopRight(); void stopUp(); void stopDown(); #pragma endregion /*Update per frame*/ void update(float elapsedTime, sf::Vector2i mousePos); #pragma region Upgrades //Giver Player Extra health void upgradeHealth(); void upgradeSpeed(); void increaseHealth(int amount); int getHealth(); #pragma endregion //Resets the player when game over void resetPlayerState(); #pragma endregion }; #endif
[ "aaronleon28@gmail.com" ]
aaronleon28@gmail.com
ccffb4ff59ad0ab4a321c21dfd911be192076081
1e63edddb4395121f06c5c7c052178ca93758180
/bsdfs/ComplexIor.cc
ad343e080d6503a198703079a6c431fadaadeceb
[]
no_license
yazici/serenity
f3b129b103ad1893e5d2f90dd115a0cfedc2b50f
19c108f3b910a81fd32a2c7126cbba18511cd644
refs/heads/master
2020-04-27T03:13:42.999742
2017-01-16T15:16:21
2017-01-16T15:16:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
467
cc
#include "ComplexIor.h" #include "ComplexIorData.h" // http://homepages.rpi.edu/~schubert/Educational-resources/Materials-Refractive-index-and-extinction-coefficient.pdf bool lookup(const std::string &name, Vec3f &eta, Vec3f &k) { for (int i = 0; i < ComplexIorCount; ++i) { if (complexIorList[i].name == name) { eta = complexIorList[i].eta; k = complexIorList[i].k; return true; } } return false; }
[ "Matthias.Fauconneau@gmail.com" ]
Matthias.Fauconneau@gmail.com
b3f9474dc3ba96487bd36b087b660ade3b5e8b70
abd777531683b07c3bed80da4a5ea4219fba5f34
/Tests/Source/NamespaceTests.cpp
f27e0562364c6f935d3781e758f1de45df21edb8
[ "BSD-3-Clause", "MIT" ]
permissive
solosure/LuaBridge53
d4d7859dfb3a211d253286aad1fdc7ea133cc82a
4fb3701532111b6deb4c29b5d3972e07bf7561ea
refs/heads/master
2022-01-28T20:59:29.314962
2019-07-22T07:35:13
2019-07-22T07:35:13
198,168,787
1
0
null
null
null
null
UTF-8
C++
false
false
5,847
cpp
// https://github.com/vinniefalco/LuaBridge // // Copyright 2019, Dmitry Tarakanov // SPDX-License-Identifier: MIT #include "TestBase.h" struct NamespaceTests : TestBase { template <class T> T variable (const std::string& name) { runLua ("result = " + name); return result <T> (); } }; TEST_F (NamespaceTests, Variables) { int int_ = -10; auto any = luabridge::newTable (L); any ["a"] = 1; ASSERT_THROW ( luabridge::getGlobalNamespace (L).addProperty ("int", &int_), std::logic_error); runLua ("result = int"); ASSERT_TRUE (result ().isNil ()); luabridge::getGlobalNamespace (L) .beginNamespace ("ns") .addProperty ("int", &int_) .addProperty ("any", &any) .endNamespace (); ASSERT_EQ (-10, variable <int> ("ns.int")); ASSERT_EQ (any, variable <luabridge::LuaRef> ("ns.any")); runLua ("ns.int = -20"); ASSERT_EQ (-20, int_); runLua ("ns.any = {b = 2}"); ASSERT_TRUE (any.isTable ()); ASSERT_TRUE (any ["b"].isNumber ()); ASSERT_EQ (2, any ["b"].cast <int> ()); } TEST_F (NamespaceTests, ReadOnlyVariables) { int int_ = -10; auto any = luabridge::newTable (L); any ["a"] = 1; ASSERT_THROW ( luabridge::getGlobalNamespace (L).addProperty ("int", &int_), std::logic_error); runLua ("result = int"); ASSERT_TRUE (result ().isNil ()); luabridge::getGlobalNamespace (L) .beginNamespace ("ns") .addProperty ("int", &int_, false) .addProperty ("any", &any, false) .endNamespace (); ASSERT_EQ (-10, variable <int> ("ns.int")); ASSERT_EQ (any, variable <luabridge::LuaRef> ("ns.any")); ASSERT_THROW (runLua ("ns.int = -20"), std::runtime_error); ASSERT_EQ (-10, variable <int> ("ns.int")); ASSERT_THROW (runLua ("ns.any = {b = 2}"), std::runtime_error); ASSERT_EQ (any, variable <luabridge::LuaRef> ("ns.any")); } namespace { template <class T> struct Property { static T value; }; template <class T> T Property <T>::value; template <class T> void setProperty (const T& value) { Property <T>::value = value; } template <class T> const T& getProperty () { return Property <T>::value; } } // namespace TEST_F (NamespaceTests, Properties) { setProperty <int> (-10); ASSERT_THROW ( luabridge::getGlobalNamespace (L) .addProperty ("int", &getProperty <int>, &setProperty <int>), std::logic_error); runLua ("result = int"); ASSERT_TRUE (result ().isNil ()); luabridge::getGlobalNamespace (L) .beginNamespace ("ns") .addProperty ("int", &getProperty <int>, &setProperty <int>) .endNamespace (); ASSERT_EQ (-10, variable <int> ("ns.int")); runLua ("ns.int = -20"); ASSERT_EQ (-20, getProperty <int> ()); } TEST_F (NamespaceTests, ReadOnlyProperties) { setProperty <int> (-10); ASSERT_THROW ( luabridge::getGlobalNamespace (L) .addProperty ("int", &getProperty <int>), std::logic_error); runLua ("result = int"); ASSERT_TRUE (result ().isNil ()); luabridge::getGlobalNamespace (L) .beginNamespace ("ns") .addProperty ("int", &getProperty <int>) .endNamespace (); ASSERT_EQ (-10, variable <int> ("ns.int")); ASSERT_THROW ( runLua ("ns.int = -20"), std::runtime_error); ASSERT_EQ (-10, getProperty <int> ()); } namespace { struct Class {}; } TEST_F (NamespaceTests, LuaStackIntegrity) { ASSERT_EQ (1, lua_gettop (L)); // Stack: ... { auto ns2 = luabridge::getGlobalNamespace (L) .beginNamespace ("namespace") .beginNamespace ("ns2"); ASSERT_EQ (4, lua_gettop (L)); // Stack: ..., global namespace table (gns), namespace table (ns), ns2 ns2.endNamespace (); // Stack: ... ASSERT_EQ (1, lua_gettop (L)); // Stack: ... } ASSERT_EQ (1, lua_gettop (L)); // Stack: ... { auto globalNs = luabridge::getGlobalNamespace (L); ASSERT_EQ (2, lua_gettop (L)); // Stack: ..., gns { auto ns = luabridge::getGlobalNamespace (L) .beginNamespace ("namespace"); // both globalNs an ns are active ASSERT_EQ (4, lua_gettop (L)); // Stack: ..., gns, gns, ns } ASSERT_EQ (2, lua_gettop (L)); // Stack: ..., gns { auto ns = globalNs .beginNamespace ("namespace"); // globalNs became inactive ASSERT_EQ (3, lua_gettop (L)); // Stack: ..., gns, ns } ASSERT_EQ (1, lua_gettop (L)); // Stack: ... ASSERT_THROW (globalNs.beginNamespace ("namespace"), std::exception); ASSERT_THROW (globalNs.beginClass <Class> ("Class"), std::exception); } { auto globalNs = luabridge::getGlobalNamespace (L) .beginNamespace ("namespace") .endNamespace (); // globalNs is active ASSERT_EQ (2, lua_gettop (L)); // Stack: ..., gns } ASSERT_EQ (1, lua_gettop (L)); // StacK: ... { auto cls = luabridge::getGlobalNamespace (L) .beginNamespace ("namespace") .beginClass <Class> ("Class"); ASSERT_EQ (6, lua_gettop (L)); // Stack: ..., gns, ns, const table, class table, static table { auto ns = cls.endClass (); ASSERT_EQ (3, lua_gettop (L)); // Stack: ..., gns, ns } ASSERT_EQ (1, lua_gettop (L)); // Stack: ... } ASSERT_EQ (1, lua_gettop (L)); // StacK: ... // Test class continuation { auto cls = luabridge::getGlobalNamespace (L) .beginNamespace ("namespace") .beginClass <Class> ("Class"); ASSERT_EQ (6, lua_gettop (L)); // Stack: ..., gns, ns, const table, class table, static table } ASSERT_EQ (1, lua_gettop (L)); // Stack: ... } #ifdef _M_IX86 // Windows 32bit only namespace { int __stdcall StdCall (int i) { return i + 10; } } // namespace TEST_F (NamespaceTests, StdCallFunctions) { luabridge::getGlobalNamespace (L) .addFunction ("StdCall", &StdCall); runLua ("result = StdCall (2)"); ASSERT_TRUE (result ().isNumber ()); ASSERT_EQ (12, result <int> ()); } #endif // _M_IX86
[ "noreply@github.com" ]
noreply@github.com
aef330ab049d115f5307ee426faef644e553e04f
2fc91ed4f1e1f0c37104bcb7a91a3fcb5e3e8c9b
/fetalReconstruction/source/reconstructionGPU2/stackMotionEstimator.h
9e79459abd99e05a1a6ea6646432d8ee3bf7d381
[]
no_license
handong32/ebbrt-contrib
fcdf097488f1bff7f605b559a0030be6640ace73
e89d16485f0345b5b022372051514646050d9c65
refs/heads/master
2020-05-30T07:14:50.297322
2016-03-01T02:10:35
2016-03-01T02:10:35
52,192,880
0
0
null
null
null
null
UTF-8
C++
false
false
3,327
h
/*========================================================================= Library : Image Registration Toolkit (IRTK) Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2011 onwards Date : $Date: 2013-11-15 14:36:30 +0100 (Fri, 15 Nov 2013) $ Version : $Revision: 1 $ Changes : $Author: bkainz $ Copyright (c) 2014, Bernhard Kainz, Markus Steinberger, Maria Murgasova, Kevin Keraudren All rights reserved. If you use this work for research we would very much appreciate if you cite Bernhard Kainz, Markus Steinberger, Maria Kuklisova-Murgasova, Christina Malamateniou, Wolfgang Wein, Thomas Torsney-Weir, Torsten Moeller, Mary Rutherford, Joseph V. Hajnal and Daniel Rueckert: Fast Volume Reconstruction from Motion Corrupted 2D Slices. IEEE Transactions on Medical Imaging, in press, 2015 IRTK IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #if HAVE_CULA #ifndef _stackMotionEstimator_H #define _stackMotionEstimator_H #include <irtkImage.h> #include <cuda.h> #include <cuda_runtime.h> #include <helper_cuda.h> #include <helper_functions.h> #include <vector_types.h> #include <vector_functions.h> #include <cula_lapack.h> #include <cula.h> //#include "recon_volumeHelper.cuh" #define imin(X, Y) ((X) < (Y) ? (X) : (Y)) class stackMotionEstimator { public: stackMotionEstimator(); ~stackMotionEstimator(); float evaluateStackMotion(irtkRealImage* img); private: culaStatus status; void checkStatus(culaStatus status); }; #endif #endif
[ "handong@bu.edu" ]
handong@bu.edu
751ad7ae184463564fdbbaf413d713c0099a1b49
4764318065e8eaa8a964a5beadaa964cba3a18e2
/Programowanie Obiektowe/3_Dziedziczenie/student.hpp
af945ef3d539e135db053811b112b41d6f25d2c1
[ "MIT" ]
permissive
GrPe/UMCS-Public
847cc5b7ef76b75fbd67b1eae59a855261be649b
20caaf471bc03e77e88b104eddc1f6d80168115a
refs/heads/master
2020-04-26T09:34:07.523505
2019-10-03T12:03:45
2019-10-03T12:03:45
173,460,077
2
2
null
null
null
null
UTF-8
C++
false
false
297
hpp
#ifndef STUDENT_HPP #define STUDENT_HPP #include "user.hpp" #include <string> class Student : public User { private: int semestr{}; public: Student(const User& user, int semestr); Student(const std::string& login, const std::string& password, int semestr); }; #endif // STUDENT_HPP
[ "grzesiek.p9804@gmail.com" ]
grzesiek.p9804@gmail.com
6fd3919ca69c31f1fcb28cfcac7555f45fcb864a
ed41323a718ee508d3e5db1a6352b036bfaa828d
/test/linux/gtest_rotation.cpp
c72324f4d8ff054f9b78eef8a017e565bcd59d23
[ "MIT" ]
permissive
sharaku/type
278a7bb3cb41cac7bde7824d253b59bf29277c40
b9c9fb23f2f3dbe09a6f10b32218b02526281956
refs/heads/master
2020-03-31T07:01:58.807263
2018-10-08T02:48:24
2018-10-08T02:48:24
152,005,192
0
0
null
null
null
null
UTF-8
C++
false
false
1,369
cpp
/* -- * * MIT License * * Copyright (c) 2018 Abe Takafumi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <libsharaku/type/rotation.hpp> #include <gtest/gtest.h> TEST(rotation, rotation3) { rotation3 rot3; rot3(0.0f, 0.0f, 0.0f); EXPECT_EQ(rot3.x, 0.0f); EXPECT_EQ(rot3.y, 0.0f); EXPECT_EQ(rot3.z, 0.0f); }
[ "t.abe.aegis@gmail.com" ]
t.abe.aegis@gmail.com
6ce36d629de2d7f84f27e9f16d59fc02fe505574
dc81c76a02995eb140d10a62588e3791a8c7de0d
/QuickArbitrage/TradeBuffer/TransactionDB.h
41ec48391a7c9c022952e06b2915b3e1ad23efc2
[]
no_license
xbotuk/cpp-proto-net
ab971a94899da7749b35d6586202bb4c52991461
d685bee57c8bf0e4ec2db0bfa21d028fa90240fd
refs/heads/master
2023-08-17T00:52:03.883886
2016-08-20T03:40:36
2016-08-20T03:40:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
573
h
#pragma once #include "dbaccess.h" #include "Portfolio.h" #include "protobuf_gen/trade.pb.h" class CTransactionDB : public CDBAccess { public: CTransactionDB(void); ~CTransactionDB(void); void EnsureValid(const char* dbFile); void AddPortfolio(CPortfolio* po); void FetchPortfolio(std::vector< boost::shared_ptr< CPortfolio > >& portfolioVec); void ModifyPortfolio(CPortfolio* po){} void RemovePortfolio(CPortfolio* po){} void AddTrade(protoc::Trade* trade); private: void EnsurePortfolioTable(); void EnsureTradesTable(); };
[ "zxiaoyong@163.com" ]
zxiaoyong@163.com
a204620806504d34cd04aebcc511bc0eda19fcfe
9d5d873b8712e36d75e64a205dfda262e6330c7e
/libs/base/src/utils/CEnhancedMetaFile_WIN.cpp
3a1af49a3f0c7acbbf284ea1e80dcb32e31334f5
[ "BSD-3-Clause" ]
permissive
pcuesta3/mrpt
5e3aafa49ce59970a47774de7e5756e5c7673bb0
d22f37f1c53f56a2de6beffdac0f3c97e7500e15
refs/heads/master
2020-04-05T11:49:55.777265
2015-01-14T19:13:22
2015-01-14T19:13:22
29,287,847
0
1
null
2015-01-19T10:36:43
2015-01-15T08:27:42
C++
UTF-8
C++
false
false
7,049
cpp
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2015, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "base-precomp.h" // Precompiled headers #include <MRPT/config.h> #ifdef MRPT_OS_WINDOWS #include <MRPT/UTILS/CEnhancedMetaFile.h> #include <mrpt/system/os.h> #include <mrpt/utils/CImage.h> #include <windows.h> using namespace mrpt; using namespace mrpt::utils; using namespace mrpt::system; int CEnhancedMetaFile::LINUX_IMG_WIDTH = 800; int CEnhancedMetaFile::LINUX_IMG_HEIGHT = 600; /*--------------------------------------------------------------- Constructor ---------------------------------------------------------------*/ CEnhancedMetaFile::CEnhancedMetaFile( const std::string &targetFileName, int scaleFactor ) : m_scale(scaleFactor), m_hFont(NULL) { m_hdc = CreateEnhMetaFileA( NULL, targetFileName.c_str(), NULL, NULL ); if (!m_hdc.get()) THROW_EXCEPTION("Can't create EMF file!!!"); } /*--------------------------------------------------------------- Destructor ---------------------------------------------------------------*/ CEnhancedMetaFile::~CEnhancedMetaFile( ) { // Free objects: if (m_hFont.get()) { DeleteObject(m_hFont.get()); m_hFont = NULL; } // Finish EMF: DeleteEnhMetaFile( CloseEnhMetaFile( (HDC)m_hdc.get() ) ); } /*--------------------------------------------------------------- drawImage ---------------------------------------------------------------*/ void CEnhancedMetaFile::drawImage( int x, int y, const utils::CImage &img ) { try { LPBITMAPINFO pBmpInfo = (LPBITMAPINFO) new unsigned char[sizeof(BITMAPINFOHEADER) + (256 * sizeof(RGBQUAD))]; // LPBITMAPINFO pBmpInfo = (LPBITMAPINFO) new unsigned char[sizeof(BITMAPINFOHEADER) ]; unsigned int imgWidth = (unsigned int)img.getWidth(); unsigned int imgHeight = (unsigned int)img.getHeight(); pBmpInfo->bmiHeader.biSize = sizeof( BITMAPINFOHEADER ); pBmpInfo->bmiHeader.biWidth = imgWidth; pBmpInfo->bmiHeader.biHeight = imgHeight; pBmpInfo->bmiHeader.biPlanes = 1; // pBmpInfo->bmiHeader.biBitCount = 24; pBmpInfo->bmiHeader.biBitCount = 8; pBmpInfo->bmiHeader.biCompression = BI_RGB; pBmpInfo->bmiHeader.biSizeImage = 0; pBmpInfo->bmiHeader.biXPelsPerMeter = pBmpInfo->bmiHeader.biYPelsPerMeter = 0; pBmpInfo->bmiHeader.biClrUsed = 0; pBmpInfo->bmiHeader.biClrImportant = 0; // Palette for (unsigned char i=0; i<255; i++) { pBmpInfo->bmiColors[i].rgbRed = i; pBmpInfo->bmiColors[i].rgbGreen = i; pBmpInfo->bmiColors[i].rgbBlue = i; pBmpInfo->bmiColors[i].rgbReserved = 0; } // unsigned int lineBytes = 3*bmp.Width; unsigned int lineBytes = imgWidth; if (lineBytes % 2) lineBytes++; if (lineBytes % 4) lineBytes+=2; BYTE *ptrBits = new BYTE[lineBytes * imgHeight]; for (unsigned int py=0;py<imgHeight;py++) for (unsigned int px=0;px<imgWidth;px++) ptrBits[(py*lineBytes+px)+0] = *img(px,py); HBITMAP hBitmap = CreateDIBitmap( (HDC)m_hdc.get(), &pBmpInfo->bmiHeader, CBM_INIT, ptrBits, pBmpInfo, DIB_RGB_COLORS); ASSERT_(hBitmap!=NULL); BITMAP bm; GetObject(hBitmap,sizeof(bm),&bm); HDC hdcMem = CreateCompatibleDC( (HDC)m_hdc.get() ); HBITMAP hbmT = (HBITMAP)SelectObject(hdcMem,hBitmap); BitBlt( (HDC)m_hdc.get(), x, y, (int)(m_scale*imgWidth), (int)(m_scale*imgHeight), hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem,hbmT); DeleteDC(hdcMem); // Free mem: // --------------------------------------- DeleteObject( hBitmap ); delete[] pBmpInfo; delete[] ptrBits; } catch(...) { THROW_EXCEPTION("Unexpected runtime error!!"); } } /*--------------------------------------------------------------- drawBitmap ---------------------------------------------------------------*/ void CEnhancedMetaFile::line( int x0, int y0, int x1, int y1, const mrpt::utils::TColor color, unsigned int width, TPenStyle penStyle ) { x0*= m_scale; y0*= m_scale; x1*= m_scale; y1*= m_scale; HPEN hPen = CreatePen( penStyle, width, (unsigned int)color ); HPEN hOldPen = (HPEN) SelectObject( (HDC)m_hdc.get(), hPen ); MoveToEx( (HDC)m_hdc.get(), x0,y0, NULL ); LineTo( (HDC)m_hdc.get(), x1,y1); SelectObject( (HDC)m_hdc.get(), hOldPen ); DeleteObject( hPen ); } /*--------------------------------------------------------------- drawBitmap ---------------------------------------------------------------*/ void CEnhancedMetaFile::textOut( int x0, int y0, const std::string &str, const mrpt::utils::TColor color ) { x0*=m_scale; y0*=m_scale; ::SetBkMode((HDC)m_hdc.get(), TRANSPARENT); ::SetTextColor( (HDC)m_hdc.get(),(unsigned int)color); ::TextOutA( (HDC)m_hdc.get(), x0,y0, str.c_str(), (int)str.size()); } /*--------------------------------------------------------------- selectVectorTextFont ---------------------------------------------------------------*/ void CEnhancedMetaFile::selectVectorTextFont( const std::string &fontName, int fontSize, bool bold, bool italic ) { HFONT hFont,oldFont; LOGFONTA lpf; lpf.lfHeight = fontSize; lpf.lfWidth = 0; lpf.lfEscapement = 0; lpf.lfOrientation = 0; lpf.lfWeight = bold ? 700:400; lpf.lfItalic = italic ? 1:0; lpf.lfUnderline = 0; lpf.lfStrikeOut = 0; lpf.lfCharSet = DEFAULT_CHARSET; lpf.lfOutPrecision = OUT_DEFAULT_PRECIS; lpf.lfClipPrecision = CLIP_DEFAULT_PRECIS; lpf.lfQuality = DEFAULT_QUALITY; lpf.lfPitchAndFamily = DEFAULT_PITCH; os::strcpy(lpf.lfFaceName,LF_FACESIZE,fontName.c_str()); hFont = ::CreateFontIndirectA( &lpf ); oldFont = (HFONT)::SelectObject( (HDC)m_hdc.get(),hFont ); if (oldFont) ::DeleteObject(oldFont); } /*--------------------------------------------------------------- setPixel ---------------------------------------------------------------*/ void CEnhancedMetaFile::setPixel( int x, int y, size_t color) { ::SetPixel((HDC)m_hdc.get(),x*m_scale,y*m_scale,color); } /*--------------------------------------------------------------- rectangle ---------------------------------------------------------------*/ void CEnhancedMetaFile::rectangle( int x0, int y0, int x1, int y1, TColor color, unsigned int width) { line(x0,y0,x1,y0,color,width); line(x1,y0,x1,y1,color,width); line(x1,y1,x0,y1,color,width); line(x0,y1,x0,y0,color,width); } #endif // MRPT_OS_WINDOWS
[ "joseluisblancoc@gmail.com" ]
joseluisblancoc@gmail.com
8aedbf317bf0afebc889785a83671aee99f7d4bb
f9277eae8195c609650eca2c2b9cd6686f4af279
/Socket编程实验/源码/TServer/mainwindow.cpp
bdb3ded9a1668266572a4a4b314088a42180acb3
[]
no_license
return001/-Qt-Socket-
b8e2d926c702071399f6173a2e6b431ecc1da46e
d90aea77873c13244417b8200a431756ea67240c
refs/heads/master
2021-10-20T11:17:00.260918
2019-02-27T12:47:57
2019-02-27T12:47:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,091
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "mysql.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->server = new QTcpServer(this); this->socket = new QTcpSocket(this); int port= 6666; server->listen(QHostAddress::Any,port);//监听本机的某个端口 //连接信号槽 connect(server,SIGNAL(newConnection()),this,SLOT(Connect())); //接受来自客户端的信号并连接 connect(socket,SIGNAL(error(QAbstractSocket::SocketError)), this,SLOT(displayError(QAbstractSocket::SocketError))); // connect(socket,SIGNAL(readyRead()),this,SLOT(ReadMSG())); //连接成功则引发槽函数 connect(ui->listWidget,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this,SLOT(doubleclicked(QListWidgetItem*))); //双击触发事件 //加载用户列表 QString str=NULL; query=new QSqlQuery; query->exec("select name from user "); while(query->next()) { QString str=query->value(0).toString(); QListWidgetItem *item = new QListWidgetItem; item->setText(str); //设置列表项的文本 ui->listWidget->addItem(item); //加载列表项到列表框 } } MainWindow::~MainWindow() { server->close(); delete ui; } int MainWindow::checkLogIn(QString name,QString pwd) { MySql *sql=new MySql(); int ret=sql->Login(name,pwd); return ret; } bool MainWindow::checkSignUp(QString name, QString pwd, QString tel,QString question,QString answer) { MySql *sql=new MySql(); bool ret=sql->Regist(name,pwd,tel,question,answer); return ret; } int MainWindow::findpwd(QString name,QString tel,QString question,QString answer) { MySql *sql=new MySql(); int temp=sql->findpwd(name,tel,question,answer); return temp; } void MainWindow::Connect() //连接客户端和服务端 { socket=server->nextPendingConnection(); connect(socket,SIGNAL(readyRead()),this,SLOT(ReadMSG())); //获取来自客户端的数据 } void MainWindow::ReadMSG() //读取来自客户端的数据 { QString data = socket->readAll(); //读取客户端发送的数据 qDebug()<<data; QStringList list=data.split("#"); bool ret=0; int temp=0; QString sendData=list[0]; QString password,str1,str2,str3,str4; if(list[0]=="a") //注册 { ret=checkSignUp(list[1],list[2],list[3],list[4],list[5]); if(ret) sendData=sendData+"#true"; else sendData=sendData+"#false"; socket->write(sendData.toLatin1()); } else if(list[0]=="b") //登录 { temp=checkLogIn(list[1],list[2]); if(temp==1) { query=new QSqlQuery; query->exec(QString("update user set status='%1' where name='%2'").arg(1).arg(list[1])); //设置数据库中的status为1 sendData=sendData+"#"+list[1]+"#true"; } else if(temp==0) sendData=sendData+"#false"+"#0"; else if(temp==2) sendData=sendData+"#false"+"#2"; else if(temp==3) sendData=sendData+"#false"+"#3"; socket->write(sendData.toUtf8()); } else if(list[0]=="c") //找回密码 { temp=findpwd(list[1],list[2],list[3],list[4]); if(temp==0) sendData=sendData+"#false"+"#0"; else if(temp==1) sendData=sendData+"#false"+"#1"; else if(temp==2) sendData=sendData+"#false"+"#2"; else if(temp==4) sendData=sendData+"#false"+"#4"; else { QString str=QString("select AES_DECRYPT(pwd,'key') from user where name='%1'").arg(list[1]); query=new QSqlQuery; query->exec(str); while(query->next()) { password=query->value(0).toString(); } sendData=sendData+"#true"+"#"+password; } socket->write(sendData.toUtf8()); } else if(list[0]=="d") //退出登录 { query=new QSqlQuery; query->exec(QString("update user set status='%1' where name='%2'").arg(0).arg(list[1])); //设置数据库中的status为0 } else if(list[0]=="e") //返回用户列表 { query=new QSqlQuery; query->exec(QString("update user set CIP='%1' , CPort='%2' where name='%3'").arg(list[2]).arg(list[3]).arg(list[1])); query=new QSqlQuery; query->exec("select name from user"); QString str6=NULL; while(query->next()) { str1=query->value(0).toString(); str6=str6+"#"+str1; } query=new QSqlQuery; query->exec(QString("select name1,MSG from msg where name2='%1'").arg(list[1])); while(query->next()) { str3=query->value(0).toString(); str4=query->value(1).toString(); } if(str4!=NULL) { str3=str3+":"+str4; } sendData=sendData+str6+"#"+"end"+"#"+str3; socket->write(sendData.toUtf8()); } else if(list[0]=="f") //群聊消息 { //获取系统时间 QDateTime time=QDateTime::currentDateTime(); QString Time=time.toString("yyyy-MM-dd ddd hh:mm:ss"); ui->textBrowser->append(Time); ui->textBrowser->append(list[1]+":"+list[2]); sendData=sendData+"#"+list[1]+"#"+list[2]; query=new QSqlQuery; int str5; query->exec(QString("select CIP, CPort from user where status = '%1'").arg(1)); while(query->next()) { QString str1=query->value(0).toString(); str5=query->value(1).toInt(); socket = new QTcpSocket(); socket->abort(); //取消已有的连接 socket->connectToHost(str1,str5); //连接到客户端 socket->waitForConnected(); socket->write(sendData.toUtf8()); qDebug()<<sendData<<str1<<str5; } } else if(list[0]=="g") //私聊 { QString Status; query=new QSqlQuery; query->exec(QString("select status from user where name='%1'").arg(list[1])); while(query->next()) { Status=query->value(0).toString(); } if(Status=="1") { query->exec(QString("select CIP, CPort from user where name = '%1'").arg(list[1])); while(query->next()) { str1=query->value(0).toString(); str2=query->value(1).toString(); } sendData=sendData+"#"+list[1]+"#"+"1"+"#"+str1+"#"+str2; } else { sendData=sendData+"#"+list[1]+"#"+"0"; } socket->write(sendData.toUtf8()); } else if(list[0]=="s") //获取信息以发送文件 { query->exec(QString("select CIP, CPort from user where name = '%1'").arg(list[1])); while(query->next()) { str1=query->value(0).toString(); str2=query->value(1).toString(); } sendData=sendData+"#"+list[1]+"#"+"1"+"#"+str1+"#"+str2; socket->write(sendData.toUtf8()); } else if(list[0]=="i") //离线消息 { query=new QSqlQuery; query->exec(QString("insert into msg (name1, name2, MSG) values('%1','%2','%3')").arg(list[1]).arg(list[2]).arg(list[3])); } else return; } void MainWindow::on_pushButton_2_clicked() //刷新用户列表 { //刷新用户列表 QString str=NULL; query=new QSqlQuery; query->exec("select name from user "); ui->listWidget->clear(); while(query->next()) { QString str=query->value(0).toString(); QListWidgetItem *item = new QListWidgetItem; item->setText(str); //设置列表项的文本 ui->listWidget->addItem(item); //加载列表项到列表框 } }
[ "noreply@github.com" ]
noreply@github.com
cbaecc8b8c43007132b430f15238233a7be7f580
c31619ba9a5661747fe2f56adb744eba8ed6cd57
/Number Theory/Diophantine.cpp
7891c97e16cc48a7d005545c9aafa44a5eb4268e
[ "MIT" ]
permissive
MYK12397/Algorithmic-Techniques
ac3b2e4397b420fba6234c227c96d088fd03a0cc
36b42aec550fba9ff49a74a383f6e9729e63dbc8
refs/heads/main
2023-07-05T04:28:12.779208
2021-09-02T06:11:34
2021-09-02T06:11:34
377,117,463
0
0
null
null
null
null
UTF-8
C++
false
false
2,902
cpp
#include<cstdio> #include<set> #include<vector> #include<algorithm> #include<queue> #include<map> #include<cstdlib> #include<time.h> #include<string> #include<stack> #include<cmath> #include<iostream> #include<cstring> #include<complex> #include<tr1/unordered_set> #include<tr1/unordered_map> // Useful constants #define INF (int)1e9 #define EPS 1e-9 #define MOD 1000000007 #define Pi 3.14159 // for input-output #define fio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) // iteration macros: have advantage of auto-casting and not recomputing arguments #define rep(i,a,n) for (int i=a;i<n;i++) #define per(i,a,n) for (int i=n-1;i>=a;i--) #define setBit(S, j) (S |= (1 << j)) #define clearBit(S, j) (S &= ~(1 << j)) #define toggleBit(S, j) (S ^= (1 << j)) // input macro #define IN(x,n) for(int e=0;e<n;e++){ll y;cin>>y;x.pb(y);} //output macro #define print(x) for(auto it:x) cout<<it<<' '; cout<<endl; #define printPI(x) for(auto it:x) cout<<it.F<<' '<<it.S<<'\t'; cout<<endl; // shortcut for data type #define ll long long #define PI pair<int,int> #define PL pair<ll,ll> #define vi vector<int> #define vl vector<ll> #define vvi vector<VI> #define vvl vector<VL> #define vvvi vector<VVI> #define vvvl vector<VVL> #define vpi vector<PI> #define vpl vector<PL> #define pb push_back #define ppb pop_back #define eb emplace_back #define mp make_pair #define F first #define S second #define uset unordered_set #define umap unordered_map #define dbg(x, y) cout << x << " = " << y << endl //namespace using namespace std; //const const int Ntest = 1e5 + 5; //useful function ll gcd(ll a, ll b){ll temp;while (b > 0){temp = a%b;a = b;b = temp;} return a;} ll lcm(ll a, ll b){return a*b/gcd(a,b);} ll fpow(ll b, ll exp, ll mod){if(exp == 0) return 1;ll t = fpow(b,exp/2,mod);if(exp&1) return t*t%mod*b%mod;return t*t%mod;} ll divmod(ll i, ll j, ll mod){i%=mod,j%=mod;return i*fpow(j,mod-2,mod)%mod;} // --clock function clock_t time_p=clock(); void TimeTaken() { time_p=clock()-time_p; cerr<<"Completion time : "<<(float)(time_p)/CLOCKS_PER_SEC<<"\n"; } int exgcd(int a,int b,int &x,int &y){ if(b==0){ x=0; y=1; return a; } int x1,y1; int d= exgcd(b,a%b, x1, y1); x=y1; y=x1- y1*(a/b); return d; } void onesolution(int a,int b,int n){ for(int i=0;i*a<=n;i++){ if((n-(i*a))%b==0){ cout<<"x = "<<i<<", y = "<<(n-(i*a))/b; return; } } } bool find_any_solution(int a,int b, int c,int &x0,int &y0,int &g){ g= exgcd(abs(a),abs(b),x0,y0); if(c%g) return false; x0*=c/g; y0*=c/g; if(a<0)x0=-x0; if(b<0)y0=-y0; return true; } void sol(){ int a,b,n; cin>>a>>b>>n; onesolution(a,b,n); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t = 1; //cin >> t; while(t--) sol(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
72d56058d4bf12d978606c1584cfc43277c4fe47
59b76dfbdbb96066ddd207e13c1d4495f924ed9c
/vtsServer/Managers/hgAlarmManager.cpp
0da49dc7a77bc99d5927c4f0baca830c7034f592
[]
no_license
GithubAtBob/vtsServer
371f7e7e9dc14b31fe3b15f2181446cea5efbf8d
64a34829cf1d6934df2f2f2f5c8053ed1ed2d5fd
refs/heads/master
2020-09-05T13:36:05.981336
2019-11-07T00:57:06
2019-11-07T00:57:06
220,121,084
0
0
null
null
null
null
GB18030
C++
false
false
97,617
cpp
#include "StdAfx.h" #include "Managers/hgAlarmManager.h" #include "Managers/hgLayerDataManager.h" #include "timer/hgPolygonTimerHandler.h" #include "timer/hgCricleTimerHandler.h" #include "timer/hgSectorTimerHandler.h" #include "timer/hgReportTimerHandler.h" #include "timer/hgAnchorAreaTimerHandler.h" #include "timer/hgAnchorAreaTimerHandler.h" #include "timer/hgAnchorWatchTimerHandler.h" #include "timer/hgAnchorReservTimerHandler.h" #include "timer/hgBerthWatchTimerHandler.h" #include "timer/hgCollisionWatchTimerHandler.h" #include "timer/hgDomainTimerHandler.h" #include "timer/hgGroundWatchTimerHandler.h" #include "timer/hgNavigatChannelTimerHandler.h" #include "timer/hgReportAreaTimerHandler.h" #include "timer/hgSpeedWatchTimerHandler.h" #include "timer/hgTurnCircleTimerHandler.h" #include "timer/hgMovementEndTimerHandler.h" #include "hgutils/PolygonLL.h" #include "hgutils/PointLL.h" #include "hgutils/NavUtil.h" #include "hgutils/MathUtil.h" #include "Managers/hgTargetManager.h" #include "frame/vtsConnectionManager.h" #include "frame/vtsServer.h" #include "Managers/hgWarningSetManager.h" #include "Managers/hgConfigManager.h" #include "Config/hgSysConfig.h" #include "hgSqlInsertCmd.h" #include "message/hgWarningMes.pb.h" #include "message/AlgorithmMode.pb.h" #include "Managers/hgSendManager.h" extern const char* hgWaringTypeGuid[]; extern const char* hgAnchorageTypeGuid[]; extern const char* hgAnchorageTypeName[]; hgLayerDataManager hgAlarmManager::m_LayerDataManager; hgWarningSetManager hgAlarmManager::m_WarningSetManager; QStringList hgAlarmManager::m_listArea; QMap <QString, int> hgAlarmManager::m_ShipPosition; int hgAlarmManager::m_AlgorithmMode = AlgorithmModeType::NoneModel; double hgAlarmManager::m_alarm1 = 3.2; double hgAlarmManager::m_alarm2 = 2.2; double hgAlarmManager::m_alarm3 = 1.0; hgAlarmManager::hgAlarmManager(void) { } hgAlarmManager::~hgAlarmManager(void) { } void hgAlarmManager::ReadLayerData(hgSqlOperator& sqlOperator) { for (int i = 0; i < 13; i++) { m_LayerDataManager.m_ShipMap.insert(hgAnchorageTypeName[i],hgAnchorageTypeGuid[i]); } m_LayerDataManager.ReadPloygon(sqlOperator); m_LayerDataManager.ReadEllipse(sqlOperator); m_LayerDataManager.ReadCricle(sqlOperator); m_LayerDataManager.ReadSector(sqlOperator); m_LayerDataManager.ReadDutyArea(sqlOperator); m_LayerDataManager.ReadReportLine(sqlOperator); m_LayerDataManager.ReadChannel(sqlOperator); m_LayerDataManager.ReadNotes(sqlOperator); m_LayerDataManager.ReadAidSail(sqlOperator); m_LayerDataManager.ReadFixedObject(sqlOperator); } void hgAlarmManager::StartWarning(const std::string ID,int type,vtsRequestHandler *handler) { if (hgConfigManager::m_sSysConfig->m_OpenWarning == false) { return; } vtsTimerHandler* l_timer = handler->getTimer(ID); if (l_timer != NULL) { return ; } switch (type) { case WaringPolygon: { hgPolygonTimerHandler * l_timer = new hgPolygonTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningCricle: { hgCricleTimerHandler * l_timer = new hgCricleTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningSector: { hgSectorTimerHandler * l_timer = new hgSectorTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningReportLine: { hgReportTimerHandler * l_timer = new hgReportTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningAnchorArea: { hgAnchorAreaTimerHandler * l_timer = new hgAnchorAreaTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningAnchorWatch: { hgAnchorWatchTimerHandler * l_timer = new hgAnchorWatchTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningAnchorReserv: { hgAnchorReservTimerHandler * l_timer = new hgAnchorReservTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningBerthWatch: { hgBerthWatchTimerHandler * l_timer = new hgBerthWatchTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningCollisionWatch: { hgCollisionWatchTimerHandler * l_timer = new hgCollisionWatchTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningDomainWatch: { hgDomainTimerHandler * l_timer = new hgDomainTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningGroundWatch: { hgGroundWatchTimerHandler * l_timer = new hgGroundWatchTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningChannel: { hgNavigatChannelTimerHandler * l_timer = new hgNavigatChannelTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; break; case WarningReportArea: { hgReportAreaTimerHandler * l_timer = new hgReportAreaTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningSpeed: { hgSpeedWatchTimerHandler * l_timer = new hgSpeedWatchTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningTurnCircle: { hgTurnCircleTimerHandler * l_timer = new hgTurnCircleTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; case WarningMovementEnd: { hgMovementEndTimerHandler * l_timer = new hgMovementEndTimerHandler(ID); l_timer->setDuration(1.0); handler->setTimer(l_timer); } break; } } void hgAlarmManager::StartWarning(const std::string ID,int type,vtsServer *s) { if (hgConfigManager::m_sSysConfig->m_OpenWarning == false) { return; } switch (type) { case WaringPolygon: { hgPolygonTimerHandler * l_timer = new hgPolygonTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; case WarningCricle: { hgCricleTimerHandler * l_timer = new hgCricleTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; case WarningSector: { hgSectorTimerHandler * l_timer = new hgSectorTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; case WarningReportLine: { hgReportTimerHandler * l_timer = new hgReportTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; case WarningAnchorArea: { hgAnchorAreaTimerHandler * l_timer = new hgAnchorAreaTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; case WarningAnchorWatch: { hgAnchorWatchTimerHandler * l_timer = new hgAnchorWatchTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; case WarningAnchorReserv: { hgAnchorReservTimerHandler * l_timer = new hgAnchorReservTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; case WarningBerthWatch: { hgBerthWatchTimerHandler * l_timer = new hgBerthWatchTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; case WarningCollisionWatch: { hgCollisionWatchTimerHandler * l_timer = new hgCollisionWatchTimerHandler(ID); l_timer->setDuration(1.0); } break; case WarningDomainWatch: { hgDomainTimerHandler * l_timer = new hgDomainTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; case WarningGroundWatch: { hgGroundWatchTimerHandler * l_timer = new hgGroundWatchTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; case WarningChannel: { hgNavigatChannelTimerHandler * l_timer = new hgNavigatChannelTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; break; case WarningReportArea: { hgReportAreaTimerHandler * l_timer = new hgReportAreaTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; case WarningSpeed: { hgSpeedWatchTimerHandler * l_timer = new hgSpeedWatchTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; case WarningTurnCircle: { hgTurnCircleTimerHandler * l_timer = new hgTurnCircleTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; case WarningMovementEnd: { hgMovementEndTimerHandler * l_timer = new hgMovementEndTimerHandler(ID); l_timer->setDuration(1.0); l_timer->start(s); } break; } } void hgAlarmManager::StopWarning(const std::string ID,vtsRequestHandler *handler) { vtsTimerHandler* l_timer = handler->getTimer(ID); if (l_timer != NULL) { handler->clearTimer(ID); } } void hgAlarmManager::SendMessage(google::protobuf::Message& msg,const std::string msgType,vtsTimerHandler* handler) { hgSendManager::SendClientMessage(msgType,msg,handler->server()); // handler->server()->connectionManager().for_each // ([&](ConnectionPtr p){ // p->write(msgType,msg); // }); } void hgAlarmManager::ReadSetData(hgSqlOperator& sqlOperator, vtsServer *s) { m_WarningSetManager.ReadDomain(sqlOperator,s); m_WarningSetManager.ReadAuthorized(sqlOperator,s); m_WarningSetManager.ReadAnchorArea(sqlOperator,s); m_WarningSetManager.ReadAnchorWatch(sqlOperator,s); m_WarningSetManager.ReadAnchorReserv(sqlOperator,s); m_WarningSetManager.ReadBerthWatch(sqlOperator,s); m_WarningSetManager.ReadCollisionWatch(sqlOperator,s); m_WarningSetManager.ReadGroundWatch(sqlOperator,s); m_WarningSetManager.ReadNavigatChannel(sqlOperator,s); m_WarningSetManager.ReadReportArea(sqlOperator,s); m_WarningSetManager.ReadSpeedWatch(sqlOperator,s); m_WarningSetManager.ReadSetShip(sqlOperator); m_WarningSetManager.ReadTurnCircle(sqlOperator,s); m_WarningSetManager.ReadMovementEnd(sqlOperator,s); } bool hgAlarmManager::PolygonEnterWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (l_SWI.EnterTime == -1 && l_SWI.Position == OutSidePos) { l_SWI.EnterTime = hgTargetManager::GetWarnTime(); } if (hgTargetManager::GetWarnTime() - l_SWI.EnterTime >= l_Layer.m_ULWaring.enter_time//在区域内时间 && Ais.SOG > l_Layer.m_ULWaring.enter_speed //速度 && l_SWI.IsSendEnter == false//是否发送过入侵警报 && l_SWI.Position == OutSidePos)//入侵监控 { l_SWI.IsSendEnter = true;//入侵警报 l_SWI.EnterTime = -1; l_SWI.Position = InsidePos;//警报触发后视为真正在内部 return true; } return false; } bool hgAlarmManager::PolygonLeaveWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (l_SWI.LeaveTime == -1 && l_SWI.Position == InsidePos) { l_SWI.LeaveTime = hgTargetManager::GetWarnTime(); } if (hgTargetManager::GetWarnTime() - l_SWI.LeaveTime > l_Layer.m_ULWaring.leave_time && Ais.SOG > l_Layer.m_ULWaring.leave_speed && l_SWI.IsSendLeave == false && l_SWI.Position == InsidePos)//离开监控 { l_SWI.Position = OutSidePos;//警报触发后视为真正在外部 l_SWI.IsSendLeave = true;//离开警报 l_SWI.LeaveTime = -1; return true; } return false; } bool hgAlarmManager::PolygonApproachWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 hg::utils::PointLL l_TargetPosition; l_TargetPosition.setLat(Ais.Lat); l_TargetPosition.setLon(Ais.Lon); double l_minDist = Ais.SOG * (l_Layer.m_ULWaring.app_time/3600.0); hg::utils::PointLL l_point = hg::utils::navutil::getPoint(l_TargetPosition,l_minDist,Ais.COG); if (l_Layer.m_Polygon.containsPoint(l_point,Qt::WindingFill)) { if (l_SWI.IsSendApproach == false)//判断是否发过警告 { l_SWI.IsSendApproach = true; return true; } } else { l_SWI.IsSendApproach = false; return false; } return false; } bool hgAlarmManager::PolygonProhibited(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (Ais.Class != AIS_CLASS_A && Ais.Class != AIS_CLASS_B) { return false; } if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 hg::utils::PolygonLL poly = l_polyiter.value().m_Polygon; hg::utils::PointLL l_TargetPosition; l_TargetPosition.setLat(Ais.Lat); l_TargetPosition.setLon(Ais.Lon); double l_a = (Ais.SOG - l_SWI.LastSOG)/((time(NULL)-l_SWI.LastTime)/*l_ais.ReportPeriod*/*3600.0);//加速度 if (l_a < 0 || (l_a == 0 && Ais.SOG == 0)) { double l_dist; if (Ais.SOG == 0) { l_dist = 0; } else { l_dist = Ais.SOG * Ais.SOG / 2. / l_a;//停下时的距离 } if (poly.containsPoint(hg::utils::navutil::getPoint(l_TargetPosition,abs(l_dist),Ais.COG),Qt::WindingFill))//停下的点在形状内触发警报 { if (l_SWI.IsProhibited == false) { l_SWI.IsProhibited = true; return true; } else { return false; } } } l_SWI.IsProhibited = false; return false; } bool hgAlarmManager::PolygonAnchorage(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 hg::utils::PolygonLL poly = l_polyiter.value().m_Polygon; hg::utils::PointLL l_TargetPosition; l_TargetPosition.setLat(Ais.Lat); l_TargetPosition.setLon(Ais.Lon); double l_a = (Ais.SOG - l_SWI.LastSOG)/((time(NULL)-l_SWI.LastTime)*3600.0);//加速度 if (l_a < 0 || (l_a == 0 && Ais.SOG == 0)) { double l_dist; if (Ais.SOG == 0) { l_dist = 0; } else { l_dist = Ais.SOG * Ais.SOG / 2. / l_a;//停下时的距离 } if (poly.containsPoint(hg::utils::navutil::getPoint(l_TargetPosition,abs(l_dist),Ais.COG),Qt::WindingFill))//停下的点在形状内触发警报 { if (hgAlarmManager::m_LayerDataManager.m_ShipMap.find(Ais.ShipType) != hgAlarmManager::m_LayerDataManager.m_ShipMap.end())//判断是否可抛锚 { if (l_Layer.m_ULWaring.anc_type.indexOf(hgAlarmManager::m_LayerDataManager.m_ShipMap.find(Ais.ShipType).value()) == -1) { if (l_SWI.IsAnchorage == false) { l_SWI.IsAnchorage = true; return true; } else { return false; } } } } } l_SWI.IsAnchorage = false; return false; } bool hgAlarmManager::PolygonHighSpeed(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.SOG > l_Layer.m_ULWaring.high_speed) { if (l_SWI.HighTime == -1) { l_SWI.HighTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } else if (hgTargetManager::GetWarnTime() - l_SWI.HighTime > l_Layer.m_ULWaring.high_duration && l_SWI.IsSendHighSpeed == false) { l_SWI.IsSendHighSpeed = true; return true; } } else { l_SWI.HighTime = -1; l_SWI.IsSendHighSpeed = false; } return false; } bool hgAlarmManager::PolygonLowSpeed(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.SOG < l_Layer.m_ULWaring.low_speed) { if (l_SWI.LowTime == -1) { l_SWI.LowTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } else if (hgTargetManager::GetWarnTime() - l_SWI.LowTime > l_Layer.m_ULWaring.low_duration && l_SWI.IsSendLowSpeed == false) { l_SWI.IsSendLowSpeed = true; return true; } } else { l_SWI.LowTime = -1; l_SWI.IsSendLowSpeed = false; } return false; } bool hgAlarmManager::PolygonAddMaxWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.SOG < l_SWI.LastSOG) { l_SWI.AddMaxTime = -1; l_SWI.IsSendAddMax = false; return false; } double l_dist = hg::utils::mathutil::KnToMsec(Ais.SOG - l_SWI.LastSOG);//两次速度差值节/小时->m/s double l_a = l_dist/((hgTargetManager::GetWarnTime()-l_SWI.LastTime)*1.0);//加速度、m/s2 if (l_a > l_Layer.m_ULWaring.add_max) { if (l_SWI.AddMaxTime == -1) { l_SWI.AddMaxTime = hgTargetManager::GetWarnTime(); } else if (hgTargetManager::GetWarnTime() - l_SWI.AddMaxTime > l_Layer.m_ULWaring.add_duration && l_SWI.IsSendAddMax == false) { l_SWI.IsSendAddMax = true; return true; } } else { l_SWI.AddMaxTime = -1; l_SWI.IsSendAddMax = false; } return false; } bool hgAlarmManager::PolygonAddMinWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.SOG > l_SWI.LastSOG) { l_SWI.AddMinTime = -1; l_SWI.IsSendAddMin = false; return false; } double l_dist = hg::utils::mathutil::KnToMsec(l_SWI.LastSOG - Ais.SOG);//两次速度差值节/小时->m/s double l_a = l_dist/((hgTargetManager::GetWarnTime()-l_SWI.LastTime)*1.0);//加速度、m/s2 if (l_a > l_Layer.m_ULWaring.add_min) { if (l_SWI.AddMinTime == -1) { l_SWI.AddMinTime = hgTargetManager::GetWarnTime(); } else if (hgTargetManager::GetWarnTime() - l_SWI.AddMinTime > l_Layer.m_ULWaring.add_duration && l_SWI.IsSendAddMin == false) { l_SWI.IsSendAddMin = true; return true; } } else { l_SWI.AddMinTime = -1; l_SWI.IsSendAddMin = false; } return false; } bool hgAlarmManager::PolygonCongestionWatch(QString Guid) { QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); if (l_polyiter == hgAlarmManager::m_LayerDataManager.m_pPloygonMap.end()) { return false; } if (l_polyiter.value().m_InsideMMSI.size() > l_polyiter.value().m_ULWaring.con_total) { if (l_polyiter.value().m_CongesTime == -1) { l_polyiter.value().m_CongesTime = hgTargetManager::GetWarnTime(); } else if (hgTargetManager::GetWarnTime() - l_polyiter.value().m_CongesTime > l_polyiter.value().m_ULWaring.con_time && l_polyiter.value().m_IsSendCongestion == false) { l_polyiter.value().m_IsSendCongestion = true; return true; } } else { l_polyiter.value().m_CongesTime = -1; l_polyiter.value().m_IsSendCongestion = false; } return false; } bool hgAlarmManager::PolygonGround(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.Draft > l_Layer.m_ULWaring.gro_depth) { if (l_SWI.GroundTime == -1) { l_SWI.GroundTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } else if (hgTargetManager::GetWarnTime() - l_SWI.GroundTime > l_Layer.m_ULWaring.gro_time && l_SWI.IsSendGround == false) { l_SWI.IsSendGround = true; return true; } } else { l_SWI.GroundTime = -1; l_SWI.IsSendGround = false; } return false; } bool hgAlarmManager::PolygonCourse(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.HDG > l_Layer.m_ULWaring.cou_change) { if (l_SWI.CourseTime == -1) { l_SWI.CourseTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } else if (hgTargetManager::GetWarnTime() - l_SWI.CourseTime > l_Layer.m_ULWaring.cou_time && l_SWI.IsSendCourse == false) { l_SWI.IsSendCourse = true; return true; } } else { l_SWI.CourseTime = -1; l_SWI.IsSendCourse = false; } return false; } void hgAlarmManager::PolygonCollision(QString Guid,QString MMSI,vtsTimerHandler* handler) { return ; // auto l_lockerTarget = hgTargetManager::getMapTargetLocker(); // auto &l_mapTarget = l_lockerTarget->raw(); // QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); // if (l_polyiter == hgAlarmManager::m_LayerDataManager.m_pPloygonMap.end()) // { // return ; // } // hg::utils::PointLL l_pointLLOwn,l_pointLLTarget; // if (l_mapTarget.find(MMSI) == l_mapTarget.end()) // { // return ; // } // hgTarget l_ais1 = l_mapTarget.find(MMSI).value(); // auto l_mapCollValue = hgAlarmManager::m_WarningSetManager.m_mapCollisionWatch.find(MMSI); // CollisionWatch l_col;// = hgAlarmManager::m_WarningSetManager.m_mapCollisionWatch.find(MMSI).value(); // if (l_mapCollValue != hgAlarmManager::m_WarningSetManager.m_mapCollisionWatch.end()) // { // l_col = l_mapCollValue.value(); // } // else // { // l_col.b_CollisionWatch = false; // } // l_pointLLOwn.setLat(l_ais1.Lat); // l_pointLLOwn.setLon(l_ais1.Lon); // auto l_coliterOth = l_polyiter.value().m_InsideMMSI.begin(); // for ( ; l_coliterOth != l_polyiter.value().m_InsideMMSI.end(); l_coliterOth++ ) // { // if (l_coliterOth.key() == MMSI) // { // continue; // } // auto &l_ais1COL = l_polyiter.value().m_CollisionData.find(MMSI); // if (l_ais1COL == l_polyiter.value().m_CollisionData.end())//判断船1是否在碰撞参数内,不在则加入 // { // QMap<QString, bool> l_map; // l_polyiter.value().m_CollisionData.insert(MMSI,l_map); // l_ais1COL = l_polyiter.value().m_CollisionData.find(MMSI); // } // QString l_oMMSI = l_coliterOth.key(); // auto &l_ais1COLValue = l_ais1COL.value();//船1碰撞参数列表 // if (l_ais1COLValue.find(l_oMMSI) == l_ais1COLValue.end())//判断船1的碰撞里是否有船2,不在则加入初始化为false // { // l_ais1COLValue.insert(l_oMMSI,false); // } // if (l_mapTarget.find(l_oMMSI) == l_mapTarget.end()) // { // l_ais1COLValue.remove(l_oMMSI); // l_coliterOth++; // if (l_coliterOth == l_polyiter.value().m_InsideMMSI.end()) // { // return; // } // l_coliterOth--; // l_polyiter.value().m_InsideMMSI.remove(l_oMMSI); // continue; // } // hgTarget l_ais2 = l_mapTarget.find(l_oMMSI).value(); // l_pointLLTarget.setLat(l_ais2.Lat); // l_pointLLTarget.setLon(l_ais2.Lon); // double l_dTCPA,l_dDCPA; // hg::utils::navutil::getTCPADCPA(l_pointLLOwn,l_ais1.SOG,l_ais1.COG,l_pointLLTarget,l_ais2.SOG,l_ais2.COG,&l_dTCPA,&l_dDCPA); // if (l_col.b_CollisionWatch == true) // { // if ( l_dDCPA < l_col.DCPA && l_dTCPA < l_col.TCPA) // { // if (l_ais1COLValue.find(l_oMMSI).value() == false)//是否发过警报 // { // l_ais1COLValue.find(l_oMMSI).value() = true; // hgWarningMes l_mes; // l_mes.set_warningid(hgWaringTypeGuid[COLLISIONWATCH]); // l_mes.set_warningguid(QUuid::createUuid().toString().toStdString()); // l_mes.set_warningpriority(PriorityRed); // l_mes.set_warningname("Collision Watch"); // l_mes.set_mmsi(MMSI.toStdString()); // l_mes.set_userlayguid(l_polyiter.key().toStdString()); // l_mes.set_userlayid(UserLayerType::UPolygon); // l_mes.set_warningtime(hgTargetManager::GetWarnTime()); // hgAlarmManager::SendMessage(l_mes,"hgWarningMes",handler); // //return true; // } // } // else // { // l_ais1COLValue.find(l_oMMSI).value() = false; // //return false; // } // } // else if (l_col.b_CollisionWatch == false) // { // if ( l_dDCPA < l_polyiter.value().m_ULWaring.col_dcpa && l_dTCPA < l_polyiter.value().m_ULWaring.col_tcpa) // { // if (l_ais1COLValue.find(l_oMMSI).value() == false)//是否发过警报 // { // l_ais1COLValue.find(l_oMMSI).value() = true; // hgWarningMes l_mes; // l_mes.set_warningid(hgWaringTypeGuid[COLLISIONWATCH]); // l_mes.set_warningguid(QUuid::createUuid().toString().toStdString()); // l_mes.set_warningpriority(PriorityRed); // l_mes.set_warningname("Collision Watch"); // l_mes.set_mmsi(MMSI.toStdString()); // l_mes.set_userlayguid(l_polyiter.key().toStdString()); // l_mes.set_userlayid(UserLayerType::UPolygon); // l_mes.set_warningtime(hgTargetManager::GetWarnTime()); // hgAlarmManager::SendMessage(l_mes,"hgWarningMes",handler); // } // } // else // { // l_ais1COLValue.find(l_oMMSI).value() = false; // } // } // } } void hgAlarmManager::PolygonFoggyArea(QString Guid,vtsTimerHandler* handler) { QMap <QString,hgPolygonLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.find(Guid); if (l_polyiter == hgAlarmManager::m_LayerDataManager.m_pPloygonMap.end()) { return ; } QTime l_beginTime = QTime::fromString(QDateTime::fromTime_t(l_polyiter->m_ULWaring.m_FogBeginTime).toString("HH:mm:ss"),"HH:mm:ss"); QTime l_endTime = QTime::fromString(QDateTime::fromTime_t(l_polyiter->m_ULWaring.m_FogEndTime).toString("HH:mm:ss"),"HH:mm:ss"); for ( int i = 0; i < l_polyiter->m_ULWaring.m_FogMMSI.size(); i++ ) { QString l_MMSI = l_polyiter->m_ULWaring.m_FogMMSI.at(i); if (l_polyiter.value().m_Info.find(l_MMSI) == l_polyiter.value().m_Info.end()) { continue; } auto & l_SWI = l_polyiter.value().m_Info.find(l_MMSI).value(); QTime l_nowTime = QTime::fromString(QDateTime::fromTime_t(hgTargetManager::GetWarnTime()).toString("HH:mm:ss"),"HH:mm:ss"); //hgShipWarningInfo l_SWI = l_polyiter.value().m_Info.find(l_MMSI).value(); if (l_SWI.FogTime == -1) { l_SWI.FogTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } if (l_nowTime >= l_beginTime && l_nowTime <= l_endTime) { if (hgTargetManager::GetWarnTime() - l_SWI.FogTime > l_polyiter->m_ULWaring.m_FogTime && l_SWI.IsSendFog == false) { hgWarningMes l_mes; l_mes.set_warningid(hgWaringTypeGuid[FoggyArea]); l_mes.set_warningguid(QUuid::createUuid().toString().toStdString()); l_mes.set_warningpriority(PriorityRed); l_mes.set_warningname("Foggy Area"); l_mes.set_mmsi(l_MMSI.toStdString()); l_mes.set_userlayguid(l_polyiter.key().toStdString()); l_mes.set_userlayid(UserLayerType::UPolygon); l_mes.set_warningtime(hgTargetManager::GetWarnTime()); hgAlarmManager::SendMessage(l_mes,"hgWarningMes",handler); l_SWI.IsSendFog = true; } } else { l_SWI.IsSendFog = false; l_SWI.FogTime = -1; } } } // void hgAlarmManager::GetApproachPoint(hg::utils::PolygonLL polygonLL, double angle,hg::utils::PointLL &point,double &dist) // { // double l_dist = -1; // hg::utils::PointLL l_unreal = hg::utils::navutil::getPoint(point,0.75,angle);//虚构出一个点 // hg::utils::PointLL l_node;//交点 // hg::utils::LineLL l_TarLine(point,l_unreal); // for ( int i = 1; i < polygonLL.size(); i++ ) // { // hg::utils::LineLL l_line(polygonLL.at(i-1),polygonLL.at(i)); // hg::utils::PointLL l_point; // int l_type = l_line.intersect(l_TarLine,&l_point); // if (l_type == hg::utils::LineLL::IntersectType::NoIntersection) // { // continue; // } // double l_bear; // double l_distance; // hg::utils::navutil::getDistanceBearing(polygonLL.at(i-1),l_point,&l_distance,&l_bear); // if (l_distance < l_line.distance() && abs(l_line.bearing() - l_bear ) < 10) // { // l_node = l_point; // if (abs(angle - hg::utils::navutil::getBearing(point,l_node)) > 10)//方向不同 则没有不是 // { // continue; // } // double l_dis = hg::utils::navutil::getDistance(point,l_point); // if (l_dist = -1) // { // l_dist = l_dis; // } // else // { // l_dist = l_dist < l_dis ? l_dist : l_dis; // } // } // } // dist = l_dist; // } bool hgAlarmManager::CricleEnterWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (l_SWI.EnterTime == -1 && l_SWI.Position == OutSidePos) { l_SWI.EnterTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } if (hgTargetManager::GetWarnTime() - l_SWI.EnterTime > l_polyiter.value().m_ULWaring.enter_time//在区域内时间 && Ais.SOG > l_Layer.m_ULWaring.enter_speed //速度 && l_SWI.IsSendEnter == false//是否发送过入侵警报 && l_SWI.Position == OutSidePos)//入侵监控 { l_SWI.IsSendEnter = true;//入侵警报 l_SWI.EnterTime = -1; l_SWI.Position = InsidePos;//警报触发后视为真正在内部 return true; } return false; } bool hgAlarmManager::CricleLeaveWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (l_SWI.LeaveTime == -1 && l_SWI.Position == InsidePos) { l_SWI.LeaveTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } if (hgTargetManager::GetWarnTime() - l_SWI.LeaveTime > l_Layer.m_ULWaring.leave_time && Ais.SOG > l_Layer.m_ULWaring.leave_speed && l_SWI.IsSendLeave == false && l_SWI.Position == InsidePos)//离开监控 { l_SWI.Position = OutSidePos;//警报触发后视为真正在外部 l_SWI.IsSendLeave = true;//离开警报 l_SWI.LeaveTime = -1; return true; } return false; } bool hgAlarmManager::CricleCongestionWatch(QString Guid) { QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); if (l_polyiter == hgAlarmManager::m_LayerDataManager.m_pCricleMap.end()) { return false; } if (l_polyiter.value().m_InsideMMSI.size() > l_polyiter.value().m_ULWaring.con_total) { if (l_polyiter.value().m_CongesTime == -1) { l_polyiter.value().m_CongesTime = hgTargetManager::GetWarnTime(); } else if (hgTargetManager::GetWarnTime() - l_polyiter.value().m_CongesTime > l_polyiter.value().m_ULWaring.con_time && l_polyiter.value().m_IsSendCongestion == false) { l_polyiter.value().m_IsSendCongestion = true; return true; } } else { l_polyiter.value().m_CongesTime = -1; l_polyiter.value().m_IsSendCongestion = false; } return false; } bool hgAlarmManager::CricleGround(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.Draft > l_Layer.m_ULWaring.gro_depth) { if (l_SWI.GroundTime == -1) { l_SWI.GroundTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } else if (hgTargetManager::GetWarnTime() - l_SWI.GroundTime > l_Layer.m_ULWaring.gro_time && l_SWI.IsSendGround == false) { l_SWI.IsSendGround = true; return true; } } else { l_SWI.GroundTime = -1; l_SWI.IsSendGround = false; } return false; } bool hgAlarmManager::CricleApproachWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 hg::utils::PointLL l_TargetPosition; l_TargetPosition.setLat(Ais.Lat); l_TargetPosition.setLon(Ais.Lon); hg::utils::PointLL l_CenterLL; l_CenterLL.setLat(l_Layer.m_Lat); l_CenterLL.setLon(l_Layer.m_Lon); double l_minDist = Ais.SOG * (l_Layer.m_ULWaring.app_time/3600.0); hg::utils::PointLL l_point = hg::utils::navutil::getPoint(l_TargetPosition,l_minDist,Ais.COG);//将要行驶到的位置 double l_dist = hg::utils::navutil::getDistance(l_point,l_CenterLL); if (l_Layer.m_Radius > l_dist)//在区域内 { if (l_SWI.IsSendApproach == false) { l_SWI.IsSendApproach = true; return true; } } else { l_SWI.IsSendApproach = false; } return false; } bool hgAlarmManager::CricleProhibited(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (Ais.Class != AIS_CLASS_A && Ais.Class != AIS_CLASS_B) { return false; } if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 hg::utils::PointLL l_TargetPosition; l_TargetPosition.setLat(Ais.Lat); l_TargetPosition.setLon(Ais.Lon); double l_a = (Ais.SOG - l_SWI.LastSOG)/((time(NULL)-l_SWI.LastTime)*3600.0);//加速度 if (l_a < 0 || (l_a == 0 && Ais.SOG == 0)) { double l_dist; if (Ais.SOG == 0) { l_dist = 0; } else { l_dist = Ais.SOG * Ais.SOG / 2. / l_a;//停下时的距离 } if (abs(l_dist) < l_Layer.m_Radius)//停下的点在形状内触发警报 { if (l_SWI.IsProhibited == false) { l_SWI.IsProhibited = true; return true; } else { return false; } } } l_SWI.IsProhibited = false; return false; } bool hgAlarmManager::CricleAnchorage(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 hg::utils::PointLL l_TargetPosition; l_TargetPosition.setLat(Ais.Lat); l_TargetPosition.setLon(Ais.Lon); double l_a = (Ais.SOG - l_SWI.LastSOG)/((time(NULL)-l_SWI.LastTime)*3600.0);//加速度 if (l_a < 0 || (l_a == 0 && Ais.SOG == 0)) { double l_dist; if (Ais.SOG == 0) { l_dist = 0; } else { l_dist = Ais.SOG * Ais.SOG / 2. / l_a;//停下时的距离 } if (abs(l_dist) < l_Layer.m_Radius)//停下的点在形状内触发警报 { if (hgAlarmManager::m_LayerDataManager.m_ShipMap.find(Ais.ShipType) != hgAlarmManager::m_LayerDataManager.m_ShipMap.end())//判断是否可抛锚 { if (l_Layer.m_ULWaring.anc_type.indexOf(hgAlarmManager::m_LayerDataManager.m_ShipMap.find(Ais.ShipType).value()) == -1) { if (l_SWI.IsAnchorage == false) { l_SWI.IsAnchorage = true; return true; } else { return false; } } } } } l_SWI.IsAnchorage = false; return false; } bool hgAlarmManager::CricleHighSpeed(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.SOG > l_Layer.m_ULWaring.high_speed) { if (l_SWI.HighTime == -1) { l_SWI.HighTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } else if (hgTargetManager::GetWarnTime() - l_SWI.HighTime > l_Layer.m_ULWaring.high_duration && l_SWI.IsSendHighSpeed == false) { l_SWI.IsSendHighSpeed = true; return true; } } else { l_SWI.HighTime = -1; l_SWI.IsSendHighSpeed = false; } return false; } bool hgAlarmManager::CricleLowSpeed(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.SOG < l_Layer.m_ULWaring.low_speed) { if (l_SWI.LowTime == -1) { l_SWI.LowTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } else if ( hgTargetManager::GetWarnTime() - l_SWI.LowTime > l_Layer.m_ULWaring.low_duration && l_SWI.IsSendLowSpeed == false) { l_SWI.IsSendLowSpeed = true; return true; } } else { l_SWI.LowTime = -1; l_SWI.IsSendLowSpeed = false; } return false; } bool hgAlarmManager::CricleAddMaxWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.SOG < l_SWI.LastSOG) { l_SWI.AddMaxTime = -1; l_SWI.IsSendAddMax = false; return false; } double l_dist = hg::utils::mathutil::KnToMsec(Ais.SOG - l_SWI.LastSOG);//两次速度差值节/小时->m/s double l_a = l_dist/((hgTargetManager::GetWarnTime()-l_SWI.LastTime)*1.0);//加速度、m/s2 if (l_a > l_Layer.m_ULWaring.add_max) { if (l_SWI.AddMaxTime == -1) { l_SWI.AddMaxTime = hgTargetManager::GetWarnTime(); } else if (hgTargetManager::GetWarnTime() - l_SWI.AddMaxTime > l_Layer.m_ULWaring.add_duration && l_SWI.IsSendAddMax == false) { l_SWI.IsSendAddMax = true; return true; } } else { l_SWI.AddMaxTime = -1; l_SWI.IsSendAddMax = false; } return false; } bool hgAlarmManager::CricleAddMinWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.SOG > l_SWI.LastSOG) { l_SWI.AddMinTime = -1; l_SWI.IsSendAddMin = false; return false; } double l_dist = hg::utils::mathutil::KnToMsec(l_SWI.LastSOG - Ais.SOG);//两次速度差值节/小时->m/s double l_a = l_dist/((hgTargetManager::GetWarnTime()-l_SWI.LastTime)*1.0);//加速度、m/s2 if (l_a > l_Layer.m_ULWaring.add_min) { if (l_SWI.AddMinTime == -1) { l_SWI.AddMinTime = hgTargetManager::GetWarnTime(); } else if (hgTargetManager::GetWarnTime() - l_SWI.AddMinTime > l_Layer.m_ULWaring.add_duration && l_SWI.IsSendAddMin == false) { l_SWI.IsSendAddMin = true; return true; } } else { l_SWI.AddMinTime = -1; l_SWI.IsSendAddMin = false; } return false; } bool hgAlarmManager::CricleCourse(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.HDG > l_Layer.m_ULWaring.cou_change) { if (l_SWI.CourseTime == -1) { l_SWI.CourseTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } else if (hgTargetManager::GetWarnTime() - l_SWI.CourseTime > l_Layer.m_ULWaring.cou_time && l_SWI.IsSendCourse == false) { l_SWI.IsSendCourse = true; return true; } } else { l_SWI.CourseTime = -1; l_SWI.IsSendCourse = false; } return false; } void hgAlarmManager::CricleCollision(QString Guid,QString MMSI,vtsTimerHandler* handler) { return ; // auto l_lockerTarget = hgTargetManager::getMapTargetLocker(); // auto &l_mapTarget = l_lockerTarget->raw(); // QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); // if (l_polyiter == hgAlarmManager::m_LayerDataManager.m_pCricleMap.end()) // { // return ; // } // hg::utils::PointLL l_pointLLOwn,l_pointLLTarget; // if (l_mapTarget.find(MMSI) == l_mapTarget.end()) // { // return ; // } // hgTarget l_ais1 = l_mapTarget.find(MMSI).value(); // auto l_mapCollValue = hgAlarmManager::m_WarningSetManager.m_mapCollisionWatch.find(MMSI); // CollisionWatch l_col; // if (l_mapCollValue != hgAlarmManager::m_WarningSetManager.m_mapCollisionWatch.end()) // { // l_col = l_mapCollValue.value(); // } // else // { // l_col.b_CollisionWatch = false; // } // l_pointLLOwn.setLat(l_ais1.Lat); // l_pointLLOwn.setLon(l_ais1.Lon); // auto l_coliterOth = l_polyiter.value().m_InsideMMSI.begin(); // for ( ; l_coliterOth != l_polyiter.value().m_InsideMMSI.end(); l_coliterOth++ ) // { // if (l_coliterOth.key() == MMSI) // { // continue; // } // auto &l_ais1COL = l_polyiter.value().m_CollisionData.find(MMSI); // if (l_ais1COL == l_polyiter.value().m_CollisionData.end())//判断船1是否在碰撞参数内,不在则加入 // { // QMap<QString, bool> l_map; // l_polyiter.value().m_CollisionData.insert(MMSI,l_map); // l_ais1COL = l_polyiter.value().m_CollisionData.find(MMSI); // } // QString l_oMMSI = l_coliterOth.key(); // auto &l_ais1COLValue = l_ais1COL.value();//船1碰撞参数列表 // if (l_ais1COLValue.find(l_oMMSI) == l_ais1COLValue.end())//判断船1的碰撞里是否有船2,不在则加入初始化为false // { // l_ais1COLValue.insert(l_oMMSI,false); // } // if (l_mapTarget.find(l_oMMSI) == l_mapTarget.end()) // { // l_ais1COLValue.remove(l_oMMSI); // l_coliterOth++; // if (l_coliterOth == l_polyiter.value().m_InsideMMSI.end()) // { // return; // } // l_coliterOth--; // l_polyiter.value().m_InsideMMSI.remove(l_oMMSI); // continue; // } // hgTarget l_ais2 = l_mapTarget.find(l_oMMSI).value(); // l_pointLLTarget.setLat(l_ais2.Lat); // l_pointLLTarget.setLon(l_ais2.Lon); // double l_dTCPA,l_dDCPA; // hg::utils::navutil::getTCPADCPA(l_pointLLOwn,l_ais1.SOG,l_ais1.COG,l_pointLLTarget,l_ais2.SOG,l_ais2.COG,&l_dTCPA,&l_dDCPA); // if (l_col.b_CollisionWatch == true) // { // if ( l_dDCPA < l_col.DCPA && l_dTCPA < l_col.TCPA) // { // if (l_ais1COLValue.find(l_oMMSI).value() == false)//是否发过警报 // { // l_ais1COLValue.find(l_oMMSI).value() = true; // hgWarningMes l_mes; // l_mes.set_warningid(hgWaringTypeGuid[COLLISIONWATCH]); // l_mes.set_warningguid(QUuid::createUuid().toString().toStdString()); // l_mes.set_warningpriority(PriorityRed); // l_mes.set_warningname("Collision Watch"); // l_mes.set_mmsi(MMSI.toStdString()); // l_mes.set_userlayguid(l_polyiter.key().toStdString()); // l_mes.set_userlayid(UserLayerType::UCricle); // l_mes.set_warningtime(hgTargetManager::GetWarnTime()); // hgAlarmManager::SendMessage(l_mes,"hgWarningMes",handler); // } // } // else // { // l_ais1COLValue.find(l_oMMSI).value() = false; // } // } // else if (l_col.b_CollisionWatch == false) // { // if ( l_dDCPA < l_polyiter.value().m_ULWaring.col_dcpa && l_dTCPA < l_polyiter.value().m_ULWaring.col_tcpa) // { // if (l_ais1COLValue.find(l_oMMSI).value() == false)//是否发过警报 // { // l_ais1COLValue.find(l_oMMSI).value() = true; // hgWarningMes l_mes; // l_mes.set_warningid(hgWaringTypeGuid[COLLISIONWATCH]); // l_mes.set_warningguid(QUuid::createUuid().toString().toStdString()); // l_mes.set_warningpriority(PriorityRed); // l_mes.set_warningname("Collision Watch"); // l_mes.set_mmsi(MMSI.toStdString()); // l_mes.set_userlayguid(l_polyiter.key().toStdString()); // l_mes.set_userlayid(UserLayerType::UCricle); // l_mes.set_warningtime(hgTargetManager::GetWarnTime()); // hgAlarmManager::SendMessage(l_mes,"hgWarningMes",handler); // } // } // else // { // l_ais1COLValue.find(l_oMMSI).value() = false; // } // } // } } void hgAlarmManager::CricleFoggyArea(QString Guid,vtsTimerHandler* handler) { QMap <QString,hgCricleLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pCricleMap.find(Guid); if (l_polyiter == hgAlarmManager::m_LayerDataManager.m_pCricleMap.end()) { return ; } QTime l_beginTime = QTime::fromString(QDateTime::fromTime_t(l_polyiter->m_ULWaring.m_FogBeginTime).toString("HH:mm:ss"),"HH:mm:ss"); QTime l_endTime = QTime::fromString(QDateTime::fromTime_t(l_polyiter->m_ULWaring.m_FogEndTime).toString("HH:mm:ss"),"HH:mm:ss"); for ( int i = 0; i < l_polyiter->m_ULWaring.m_FogMMSI.size(); i++ ) { QString l_MMSI = l_polyiter->m_ULWaring.m_FogMMSI.at(i); if (l_polyiter.value().m_Info.find(l_MMSI) == l_polyiter.value().m_Info.end()) { continue; } QTime l_nowTime = QTime::fromString(QDateTime::fromTime_t(hgTargetManager::GetWarnTime()).toString("HH:mm:ss"),"HH:mm:ss"); hgShipWarningInfo &l_SWI = l_polyiter.value().m_Info.find(l_MMSI).value(); if (l_SWI.FogTime == -1) { l_SWI.FogTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } if (l_nowTime >= l_beginTime && l_nowTime <= l_endTime) { if (hgTargetManager::GetWarnTime() - l_SWI.FogTime > l_polyiter->m_ULWaring.m_FogTime && l_SWI.IsSendFog == false) { hgWarningMes l_mes; l_mes.set_warningid(hgWaringTypeGuid[FoggyArea]); l_mes.set_warningguid(QUuid::createUuid().toString().toStdString()); l_mes.set_warningpriority(PriorityRed); l_mes.set_warningname("Foggy Area"); l_mes.set_mmsi(l_MMSI.toStdString()); l_mes.set_userlayguid(l_polyiter.key().toStdString()); l_mes.set_userlayid(UserLayerType::UCricle); l_mes.set_warningtime(hgTargetManager::GetWarnTime()); hgAlarmManager::SendMessage(l_mes,"hgWarningMes",handler); l_SWI.IsSendFog = true; } } else { l_SWI.IsSendFog = false; l_SWI.FogTime = -1; } } } bool hgAlarmManager::SectorEnterWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (l_SWI.EnterTime == -1 && l_SWI.Position == OutSidePos) { l_SWI.EnterTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } if (hgTargetManager::GetWarnTime() - l_SWI.EnterTime > l_Layer.m_ULWaring.enter_time//在区域内时间 && Ais.SOG > l_Layer.m_ULWaring.enter_speed //速度 && l_SWI.IsSendEnter == false//是否发送过入侵警报 && l_SWI.Position == OutSidePos)//入侵监控 { l_SWI.IsSendEnter = true;//入侵警报 l_SWI.EnterTime = -1; l_SWI.Position = InsidePos;//警报触发后视为真正在内部 return true; } return false; } bool hgAlarmManager::SectorLeaveWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (l_SWI.LeaveTime == -1 && l_SWI.Position == InsidePos) { l_SWI.LeaveTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } if (hgTargetManager::GetWarnTime() - l_SWI.LeaveTime > l_Layer.m_ULWaring.leave_time && Ais.SOG > l_Layer.m_ULWaring.leave_speed && l_SWI.IsSendLeave == false && l_SWI.Position == InsidePos)//离开监控 { l_SWI.Position = OutSidePos;//警报触发后视为真正在外部 l_SWI.IsSendLeave = true;//离开警报 l_SWI.LeaveTime = -1; return true; } return false; } bool hgAlarmManager::SectorApproachWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 hg::utils::PointLL l_TargetPosition; l_TargetPosition.setLat(Ais.Lat); l_TargetPosition.setLon(Ais.Lon); hg::utils::PointLL l_CenterLL; l_CenterLL.setLat(l_Layer.m_Lat); l_CenterLL.setLon(l_Layer.m_Lon); double l_minDist = Ais.SOG * (l_Layer.m_ULWaring.app_time/3600.0);//警报距离 hg::utils::PointLL l_point = hg::utils::navutil::getPoint(l_TargetPosition,l_minDist,Ais.COG);//按当前方向与警报点获取对应点位置 if (PointInsideSector(l_point.lat(),l_point.lon() ,l_Layer.m_Lat,l_Layer.m_Lon,l_Layer.m_Radius ,l_Layer.m_BeginAngle,l_Layer.m_EndAngle))//在区域内 { if (l_SWI.IsSendApproach == false) { l_SWI.IsSendApproach = true; return true; } } else { l_SWI.IsSendApproach = false; } return false; } bool hgAlarmManager::SectorProhibited(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (Ais.Class != AIS_CLASS_A && Ais.Class != AIS_CLASS_B) { return false; } if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 hg::utils::PointLL l_TargetPosition; l_TargetPosition.setLat(Ais.Lat); l_TargetPosition.setLon(Ais.Lon); double l_a = (Ais.SOG - l_SWI.LastSOG)/((time(NULL)-l_SWI.LastTime)*3600.0);//加速度 if (l_a < 0 || (l_a == 0 && Ais.SOG == 0)) { double l_dist; if (Ais.SOG == 0) { l_dist = 0; } else { l_dist = Ais.SOG * Ais.SOG / 2. / l_a;//停下时的距离 } hg::utils::PointLL l_pointLL = hg::utils::navutil::getPoint(l_TargetPosition,abs(l_dist),Ais.COG); if (PointInsideSector(l_TargetPosition.lat(),l_TargetPosition.lon(),l_Layer.m_Lat,l_Layer.m_Lon ,l_Layer.m_Radius,l_Layer.m_BeginAngle,l_Layer.m_EndAngle))//停下的点在形状内触发警报 { if (l_SWI.IsProhibited == false) { l_SWI.IsProhibited = true; return true; } else { return false; } } } l_SWI.IsProhibited = false; return false; } bool hgAlarmManager::SectorAnchorage(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 hg::utils::PointLL l_TargetPosition; l_TargetPosition.setLat(Ais.Lat); l_TargetPosition.setLon(Ais.Lon); double l_a = (Ais.SOG - l_SWI.LastSOG)/((time(NULL)-l_SWI.LastTime)*3600.0);//加速度 if (l_a < 0 || (l_a == 0 && Ais.SOG == 0)) { double l_dist; if (Ais.SOG == 0) { l_dist = 0; } else { l_dist = Ais.SOG * Ais.SOG / 2. / l_a;//停下时的距离 } hg::utils::PointLL l_pointLL = hg::utils::navutil::getPoint(l_TargetPosition,abs(l_dist),Ais.SOG); if (PointInsideSector(l_TargetPosition.lat(),l_TargetPosition.lon(),l_Layer.m_Lat,l_Layer.m_Lon ,l_Layer.m_Radius,l_Layer.m_BeginAngle,l_Layer.m_EndAngle))//停下的点在形状内触发警报 { if (hgAlarmManager::m_LayerDataManager.m_ShipMap.find(Ais.ShipType) != hgAlarmManager::m_LayerDataManager.m_ShipMap.end())//判断是否可抛锚 { if (l_Layer.m_ULWaring.anc_type.indexOf(hgAlarmManager::m_LayerDataManager.m_ShipMap.find(Ais.ShipType).value()) == -1) { if (l_SWI.IsAnchorage == false) { l_SWI.IsAnchorage = true; return true; } else { return false; } } } } } l_SWI.IsAnchorage = false; return false; } bool hgAlarmManager::SectorHighSpeed(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.SOG > l_Layer.m_ULWaring.high_speed) { if (l_SWI.HighTime == -1) { l_SWI.HighTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } else if (hgTargetManager::GetWarnTime() - l_SWI.HighTime > l_Layer.m_ULWaring.high_duration && l_SWI.IsSendHighSpeed == false) { l_SWI.IsSendHighSpeed = true; return true; } } else { l_SWI.HighTime = -1; l_SWI.IsSendHighSpeed = false; } return false; } bool hgAlarmManager::SectorLowSpeed(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.SOG < l_Layer.m_ULWaring.low_speed) { if (l_SWI.LowTime == -1) { l_SWI.LowTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } else if (hgTargetManager::GetWarnTime() - l_SWI.LowTime > l_Layer.m_ULWaring.low_duration && l_SWI.IsSendLowSpeed == false) { l_SWI.IsSendLowSpeed = true; return true; } } else { l_SWI.LowTime = -1; l_SWI.IsSendLowSpeed = false; } return false; } bool hgAlarmManager::SectorAddMaxWatch(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.SOG < l_SWI.LastSOG) { l_SWI.AddMaxTime = -1; l_SWI.IsSendAddMax = false; return false; } double l_dist = hg::utils::mathutil::KnToMsec(Ais.SOG - l_SWI.LastSOG);//两次速度差值节/小时->m/s double l_a = l_dist/((hgTargetManager::GetWarnTime()-l_SWI.LastTime)*1.0);//加速度、m/s2 if (l_a > l_Layer.m_ULWaring.add_max) { if (l_SWI.AddMaxTime == -1) { l_SWI.AddMaxTime = hgTargetManager::GetWarnTime(); } else if (hgTargetManager::GetWarnTime() - l_SWI.AddMaxTime > l_Layer.m_ULWaring.add_duration && l_SWI.IsSendAddMax == false) { l_SWI.IsSendAddMax = true; return true; } } else { l_SWI.AddMaxTime = -1; l_SWI.IsSendAddMax = false; } return false; } bool hgAlarmManager::SectorAddMinWatch(QString Guid,QString MMSI,hgTarget &Ais) { // auto l_lockerTarget = hgTargetManager::getMapTargetLocker(); // auto &l_mapTarget = l_lockerTarget->raw(); // hgTarget Ais = l_mapTarget.find(MMSI).value(); QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.SOG > l_SWI.LastSOG) { l_SWI.AddMinTime = -1; l_SWI.IsSendAddMin = false; return false; } double l_dist = hg::utils::mathutil::KnToMsec(l_SWI.LastSOG - Ais.SOG);//两次速度差值节/小时->m/s double l_a = l_dist/((hgTargetManager::GetWarnTime()-l_SWI.LastTime)*1.0);//加速度、m/s2 if (l_a > l_Layer.m_ULWaring.add_min) { if (l_SWI.AddMinTime == -1) { l_SWI.AddMinTime = hgTargetManager::GetWarnTime(); } else if (hgTargetManager::GetWarnTime() - l_SWI.AddMinTime > l_Layer.m_ULWaring.add_duration && l_SWI.IsSendAddMin == false) { l_SWI.IsSendAddMin = true; return true; } } else { l_SWI.AddMinTime = -1; l_SWI.IsSendAddMin = false; } return false; } bool hgAlarmManager::SectorCongestionWatch(QString Guid) { // auto l_lockerTarget = hgTargetManager::getMapTargetLocker(); // auto &l_mapTarget = l_lockerTarget->raw(); QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); if (l_polyiter == hgAlarmManager::m_LayerDataManager.m_pSectorMap.end()) { return false; } if (l_polyiter.value().m_InsideMMSI.size() > l_polyiter.value().m_ULWaring.con_total) { if (l_polyiter.value().m_CongesTime == -1) { l_polyiter.value().m_CongesTime = hgTargetManager::GetWarnTime(); } else if (hgTargetManager::GetWarnTime() - l_polyiter.value().m_CongesTime > l_polyiter.value().m_ULWaring.con_time && l_polyiter.value().m_IsSendCongestion == false) { l_polyiter.value().m_IsSendCongestion = true; return true; } } else { l_polyiter.value().m_CongesTime = -1; l_polyiter.value().m_IsSendCongestion = false; } return false; } bool hgAlarmManager::SectorGround(QString Guid,QString MMSI,hgTarget &Ais) { // auto l_lockerTarget = hgTargetManager::getMapTargetLocker(); // auto &l_mapTarget = l_lockerTarget->raw(); // hgTarget Ais = l_mapTarget.find(MMSI).value(); QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.Draft > l_Layer.m_ULWaring.gro_depth) { if (l_SWI.GroundTime == -1) { l_SWI.GroundTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } else if (hgTargetManager::GetWarnTime() - l_SWI.GroundTime > l_Layer.m_ULWaring.gro_time && l_SWI.IsSendGround == false) { l_SWI.IsSendGround = true; return true; } } else { l_SWI.GroundTime = -1; l_SWI.IsSendGround = false; } return false; } bool hgAlarmManager::SectorCourse(QString Guid,QString MMSI,hgTarget &Ais) { QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); auto & l_Layer = l_polyiter.value();//对应图形参数 if (!l_Layer.m_Info.contains(MMSI)) { vtsError << "No Such MMSI"; return false; } auto & l_SWI = l_Layer.m_Info.find(MMSI).value();//对应图形内对应船参数 if (Ais.HDG > l_Layer.m_ULWaring.cou_change) { if (l_SWI.CourseTime == -1) { l_SWI.CourseTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } else if (hgTargetManager::GetWarnTime() - l_SWI.CourseTime > l_Layer.m_ULWaring.cou_time && l_SWI.IsSendCourse == false) { l_SWI.IsSendCourse = true; return true; } } else { l_SWI.CourseTime = -1; l_SWI.IsSendCourse = false; } return false; } void hgAlarmManager::SectorCollision(QString Guid,QString MMSI,vtsTimerHandler* handler) { return ; // auto l_lockerTarget = hgTargetManager::getMapTargetLocker(); // auto &l_mapTarget = l_lockerTarget->raw(); // QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); // if (l_polyiter == hgAlarmManager::m_LayerDataManager.m_pSectorMap.end()) // { // return ; // } // hg::utils::PointLL l_pointLLOwn,l_pointLLTarget; // if (l_mapTarget.find(MMSI) == l_mapTarget.end()) // { // return ; // } // hgTarget l_ais1 = l_mapTarget.find(MMSI).value(); // auto l_mapCollValue = hgAlarmManager::m_WarningSetManager.m_mapCollisionWatch.find(MMSI); // CollisionWatch l_col; // if (l_mapCollValue != hgAlarmManager::m_WarningSetManager.m_mapCollisionWatch.end()) // { // l_col = l_mapCollValue.value(); // } // else // { // l_col.b_CollisionWatch = false; // } // l_pointLLOwn.setLat(l_ais1.Lat); // l_pointLLOwn.setLon(l_ais1.Lon); // auto l_coliterOth = l_polyiter.value().m_InsideMMSI.begin(); // for ( ; l_coliterOth != l_polyiter.value().m_InsideMMSI.end(); l_coliterOth++ ) // { // if (l_coliterOth.key() == MMSI) // { // continue; // } // auto &l_ais1COL = l_polyiter.value().m_CollisionData.find(MMSI); // if (l_ais1COL == l_polyiter.value().m_CollisionData.end())//判断船1是否在碰撞参数内,不在则加入 // { // QMap<QString, bool> l_map; // l_polyiter.value().m_CollisionData.insert(MMSI,l_map); // l_ais1COL = l_polyiter.value().m_CollisionData.find(MMSI); // } // QString l_oMMSI = l_coliterOth.key(); // auto &l_ais1COLValue = l_ais1COL.value();//船1碰撞参数列表 // if (l_ais1COLValue.find(l_oMMSI) == l_ais1COLValue.end())//判断船1的碰撞里是否有船2,不在则加入初始化为false // { // l_ais1COLValue.insert(l_oMMSI,false); // } // if (l_mapTarget.find(l_oMMSI) == l_mapTarget.end()) // { // l_ais1COLValue.remove(l_oMMSI); // l_coliterOth++; // if (l_coliterOth == l_polyiter.value().m_InsideMMSI.end()) // { // return; // } // l_coliterOth--; // l_polyiter.value().m_InsideMMSI.remove(l_oMMSI); // continue; // } // hgTarget l_ais2 = l_mapTarget.find(l_oMMSI).value(); // l_pointLLTarget.setLat(l_ais2.Lat); // l_pointLLTarget.setLon(l_ais2.Lon); // double l_dTCPA,l_dDCPA; // hg::utils::navutil::getTCPADCPA(l_pointLLOwn,l_ais1.SOG,l_ais1.COG,l_pointLLTarget,l_ais2.SOG,l_ais2.COG,&l_dTCPA,&l_dDCPA); // if (l_col.b_CollisionWatch == true) // { // if ( l_dDCPA < l_col.DCPA && l_dTCPA < l_col.TCPA) // { // if (l_ais1COLValue.find(l_oMMSI).value() == false)//是否发过警报 // { // l_ais1COLValue.find(l_oMMSI).value() = true; // hgWarningMes l_mes; // l_mes.set_warningid(hgWaringTypeGuid[COLLISIONWATCH]); // l_mes.set_warningguid(QUuid::createUuid().toString().toStdString()); // l_mes.set_warningpriority(PriorityRed); // l_mes.set_warningname("Collision Watch"); // l_mes.set_mmsi(MMSI.toStdString()); // l_mes.set_userlayguid(l_polyiter.key().toStdString()); // l_mes.set_userlayid(UserLayerType::UCricle); // l_mes.set_warningtime(hgTargetManager::GetWarnTime()); // hgAlarmManager::SendMessage(l_mes,"hgWarningMes",handler); // } // } // else // { // l_ais1COLValue.find(l_oMMSI).value() = false; // } // } // else if (l_col.b_CollisionWatch == false) // { // if ( l_dDCPA < l_polyiter.value().m_ULWaring.col_dcpa && l_dTCPA < l_polyiter.value().m_ULWaring.col_tcpa) // { // if (l_ais1COLValue.find(l_oMMSI).value() == false)//是否发过警报 // { // l_ais1COLValue.find(l_oMMSI).value() = true; // hgWarningMes l_mes; // l_mes.set_warningid(hgWaringTypeGuid[COLLISIONWATCH]); // l_mes.set_warningguid(QUuid::createUuid().toString().toStdString()); // l_mes.set_warningpriority(PriorityRed); // l_mes.set_warningname("Collision Watch"); // l_mes.set_mmsi(MMSI.toStdString()); // l_mes.set_userlayguid(l_polyiter.key().toStdString()); // l_mes.set_userlayid(UserLayerType::UCricle); // l_mes.set_warningtime(hgTargetManager::GetWarnTime()); // hgAlarmManager::SendMessage(l_mes,"hgWarningMes",handler); // } // } // else // { // l_ais1COLValue.find(l_oMMSI).value() = false; // } // } // } } void hgAlarmManager::SectorFoggyArea(QString Guid,vtsTimerHandler* handler) { QMap <QString,hgSectorLayer>::Iterator l_polyiter = hgAlarmManager::m_LayerDataManager.m_pSectorMap.find(Guid); if (l_polyiter == hgAlarmManager::m_LayerDataManager.m_pSectorMap.end()) { return ; } QTime l_beginTime = QTime::fromString(QDateTime::fromTime_t(l_polyiter->m_ULWaring.m_FogBeginTime).toString("HH:mm:ss"),"HH:mm:ss"); QTime l_endTime = QTime::fromString(QDateTime::fromTime_t(l_polyiter->m_ULWaring.m_FogEndTime).toString("HH:mm:ss"),"HH:mm:ss"); for ( int i = 0; i < l_polyiter->m_ULWaring.m_FogMMSI.size(); i++ ) { QString l_MMSI = l_polyiter->m_ULWaring.m_FogMMSI.at(i); if (l_polyiter.value().m_Info.find(l_MMSI) == l_polyiter.value().m_Info.end()) { continue; } QTime l_nowTime = QTime::fromString(QDateTime::fromTime_t(hgTargetManager::GetWarnTime()).toString("HH:mm:ss"),"HH:mm:ss"); hgShipWarningInfo& l_SWI = l_polyiter.value().m_Info.find(l_MMSI).value(); if (l_SWI.FogTime == -1) { l_SWI.FogTime = hgTargetManager::GetWarnTime();//QDateTime::currentDateTime().toTime_t(); } if (l_nowTime >= l_beginTime && l_nowTime <= l_endTime) { if (hgTargetManager::GetWarnTime() - l_SWI.FogTime > l_polyiter->m_ULWaring.m_FogTime && l_SWI.IsSendFog == false) { hgWarningMes l_mes; l_mes.set_warningid(hgWaringTypeGuid[FoggyArea]); l_mes.set_warningguid(QUuid::createUuid().toString().toStdString()); l_mes.set_warningpriority(PriorityRed); l_mes.set_warningname("Foggy Area"); l_mes.set_mmsi(l_MMSI.toStdString()); l_mes.set_userlayguid(l_polyiter.key().toStdString()); l_mes.set_userlayid(UserLayerType::USector); l_mes.set_warningtime(hgTargetManager::GetWarnTime()); hgAlarmManager::SendMessage(l_mes,"hgWarningMes",handler); l_SWI.IsSendFog = true; } } else { l_SWI.IsSendFog = false; l_SWI.FogTime = -1; } } } bool hgAlarmManager::PointInsideSector(double lat,double lon,double CenterLat,double CenterLon,double radius,double Begin,double End) { // auto l_lockerTarget = hgTargetManager::getMapTargetLocker(); // auto &l_mapTarget = l_lockerTarget->raw(); hg::utils::PointLL l_PointLL(lon,lat); hg::utils::PointLL l_CenterLL(CenterLon,CenterLat); double l_dist,l_angle; hg::utils::navutil::getDistanceBearing(l_CenterLL,l_PointLL,&l_dist,&l_angle); if (l_dist > radius || radius == 0) { return false; } if (Begin == End) { return true; } if (Begin < End) { if (l_angle > Begin && l_angle < End) { return true; } else { return false; } } if (Begin > End) { if (l_angle > Begin || l_angle < End) { return true; } else { return false; } } return false; } //抛锚区 bool hgAlarmManager::FindTarget(QString id, QString MMSI,int &type,QString &GUID) { mymap<QString,hgTarget>::iterator l_itAis; l_itAis = hgTargetManager::m_mapTarget.find(MMSI); QMap <QString,hgPolygonLayer>::Iterator l_polyiter; for (l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.begin(); l_polyiter != hgAlarmManager::m_LayerDataManager.m_pPloygonMap.end(); ++l_polyiter) { if ( l_polyiter.value().m_WaringID.indexOf(hgWaringTypeGuid[ANCHORAGE]) != -1) { hg::utils::PointLL l_aisPointLL; l_aisPointLL.setLat(l_itAis->Lat); l_aisPointLL.setLon(l_itAis->Lon); if (l_polyiter->m_Polygon.containsPoint(l_aisPointLL,Qt::OddEvenFill)) { if (l_polyiter.key() == id) { return false; } else { type = UPolygon; GUID = l_polyiter.key(); return true; } } } } QMap <QString,hgCricleLayer>::Iterator l_cricle; for (l_cricle = hgAlarmManager::m_LayerDataManager.m_pCricleMap.begin(); l_cricle != hgAlarmManager::m_LayerDataManager.m_pCricleMap.end(); ++l_cricle) { if ( l_cricle.value().m_WaringID.indexOf(hgWaringTypeGuid[ANCHORAGE]) != -1) { hg::utils::PointLL l_aisPointLL; hg::utils::PointLL l_criclePointLL; double l_dDistance; l_aisPointLL.setLat(l_itAis->Lat); l_aisPointLL.setLon(l_itAis->Lon); l_criclePointLL.setLat(l_cricle->m_Lat); l_criclePointLL.setLon(l_cricle->m_Lon); l_dDistance = hg::utils::navutil::getDistance(l_aisPointLL,l_criclePointLL); if (l_dDistance <= l_cricle->m_Radius) { if (l_polyiter.key() == id) { return false; } else { type = UCricle; GUID = l_polyiter.key(); return true; } } } } QMap <QString,hgSectorLayer>::Iterator l_sector; for (l_sector = hgAlarmManager::m_LayerDataManager.m_pSectorMap.begin(); l_sector != hgAlarmManager::m_LayerDataManager.m_pSectorMap.end(); l_sector++) { if ( l_sector.value().m_WaringID.indexOf(hgWaringTypeGuid[ANCHORAGE]) != -1) { if (PointInsideSector(l_itAis->Lat,l_itAis->Lon,l_sector->m_Lat,l_sector->m_Lon,l_sector->m_Radius,l_sector->m_BeginAngle,l_sector->m_EndAngle)) { if (l_polyiter.key() == id) { return false; } else { type = USector; GUID = l_polyiter.key(); return true; } } } } return false; } int hgAlarmManager::CurrentsTracks(QString id, long int eta, long int etd) { int l_iCurrentCount = 0; QMap<QString,AnchorReserv>::iterator l_it; for (l_it = m_WarningSetManager.m_mapAnchorReserv.begin(); l_it != m_WarningSetManager.m_mapAnchorReserv.end(); l_it++) { if (l_it->b_AnchorReserv == true && l_it->ID == id) { if ((eta > l_it->ETA && eta < l_it->ETD) || ((eta < l_it->ETA || eta == l_it->ETA) && etd > l_it->ETD)) { l_iCurrentCount++; } } } return l_iCurrentCount; } bool hgAlarmManager::DomainWatchMsg(QString MMSI, double lat, double lon, double distance) { auto l_infoIt = m_WarningSetManager.m_mapWarnInfo.find(MMSI); if (l_infoIt != m_WarningSetManager.m_mapWarnInfo.end()) { l_infoIt->m_listDomainCancel.clear(); } if (m_WarningSetManager.m_mapWarnInfo.find(MMSI) == m_WarningSetManager.m_mapWarnInfo.end())// [6/7/2017 LianXinDuan] { return false; } mymap<QString,hgTarget>::iterator l_itAisLoop; for (l_itAisLoop = hgTargetManager::m_mapTarget.begin(); l_itAisLoop != hgTargetManager::m_mapTarget.end(); ++l_itAisLoop) { if (MMSI == l_itAisLoop->ID) { continue; } hg::utils::PointLL l_pointLLOwn,l_pointLLTarget; double l_dDistance; l_pointLLOwn.setLat(lat); l_pointLLOwn.setLon(lon); l_pointLLTarget.setLat(l_itAisLoop->Lat); l_pointLLTarget.setLon(l_itAisLoop->Lon); l_dDistance = hg::utils::navutil::getDistance(l_pointLLOwn,l_pointLLTarget)*NM2M; //海里->米 if (l_dDistance <= distance) { QMap<double,hgTarget>::iterator l_itDis; l_itDis = m_WarningSetManager.m_mapWarnInfo.find(MMSI)->m_mapDomainWatch.begin(); bool l_bSame = false; while (l_itDis != m_WarningSetManager.m_mapWarnInfo.find(MMSI)->m_mapDomainWatch.end()) { if (l_itAisLoop->MMSI == l_itDis->MMSI) { if (l_itDis->DomainWatch == true) { l_bSame = true; } l_itDis = m_WarningSetManager.m_mapWarnInfo.find(MMSI)->m_mapDomainWatch.erase(l_itDis); } else { l_itDis++; } } if (l_bSame == false) { m_WarningSetManager.m_mapWarnInfo.find(MMSI)->m_mapDomainWatch.insert(l_dDistance,l_itAisLoop.value()); m_WarningSetManager.m_mapWarnInfo.find(MMSI)->m_mapDomainWatch.find(l_dDistance)->DomainWatch = false; } else { m_WarningSetManager.m_mapWarnInfo.find(MMSI)->m_mapDomainWatch.insert(l_dDistance,l_itAisLoop.value()); m_WarningSetManager.m_mapWarnInfo.find(MMSI)->m_mapDomainWatch.find(l_dDistance)->DomainWatch = true; } } else { QMap<double,hgTarget>::iterator l_itDis; l_itDis = m_WarningSetManager.m_mapWarnInfo.find(MMSI)->m_mapDomainWatch.begin(); while (l_itDis != m_WarningSetManager.m_mapWarnInfo.find(MMSI)->m_mapDomainWatch.end()) { if (l_itAisLoop->MMSI == l_itDis->MMSI) { m_WarningSetManager.m_mapWarnInfo.find(MMSI)->m_listDomainCancel.push_back(l_itAisLoop->MMSI); l_itDis = m_WarningSetManager.m_mapWarnInfo.find(MMSI)->m_mapDomainWatch.erase(l_itDis); } else { l_itDis++; } } } } if (m_WarningSetManager.m_mapWarnInfo.find(MMSI)->m_mapDomainWatch.size() > 0) { return true; } else { return false; } } //报告区 bool hgAlarmManager::ReportEnter(QString MMSI) { mymap<QString,hgTarget>::iterator l_itAis; l_itAis = hgTargetManager::m_mapTarget.find(MMSI); QMap <QString,hgPolygonLayer>::Iterator l_polyiter; for (l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.begin(); l_polyiter != hgAlarmManager::m_LayerDataManager.m_pPloygonMap.end(); l_polyiter++) { if ( l_polyiter.value().m_WaringID.indexOf(hgWaringTypeGuid[REPORTINGAREA]) != -1) { hg::utils::PointLL l_aisPointLL; l_aisPointLL.setLat(l_itAis->Lat); l_aisPointLL.setLon(l_itAis->Lon); if (l_polyiter->m_Polygon.containsPoint(l_aisPointLL,Qt::OddEvenFill)) { return true; } } } QMap <QString,hgCricleLayer>::Iterator l_cricle; for (l_cricle = hgAlarmManager::m_LayerDataManager.m_pCricleMap.begin(); l_cricle != hgAlarmManager::m_LayerDataManager.m_pCricleMap.end(); l_cricle++) { if ( l_cricle.value().m_WaringID.indexOf(hgWaringTypeGuid[REPORTINGAREA]) != -1) { hg::utils::PointLL l_aisPointLL; hg::utils::PointLL l_criclePointLL; double l_dDistance; l_aisPointLL.setLat(l_itAis->Lat); l_aisPointLL.setLon(l_itAis->Lon); l_criclePointLL.setLat(l_cricle->m_Lat); l_criclePointLL.setLon(l_cricle->m_Lon); l_dDistance = hg::utils::navutil::getDistance(l_aisPointLL,l_criclePointLL); if (l_dDistance <= l_cricle->m_Radius) { return true; } } } QMap <QString,hgSectorLayer>::Iterator l_sector; for (l_sector = hgAlarmManager::m_LayerDataManager.m_pSectorMap.begin(); l_sector != hgAlarmManager::m_LayerDataManager.m_pSectorMap.end(); l_sector++) { if ( l_sector.value().m_WaringID.indexOf(hgWaringTypeGuid[REPORTINGAREA]) != -1) { if (PointInsideSector(l_itAis->Lat,l_itAis->Lon,l_sector->m_Lat,l_sector->m_Lon,l_sector->m_Radius,l_sector->m_BeginAngle,l_sector->m_EndAngle)) { return true; } } } return false; } long int hgAlarmManager::ReportNoEnter(QMap<QString,AreaData>& map, QString MMSI) { QString id; QMap<QString,AreaData>::iterator itArea; mymap<QString,hgTarget>::iterator l_itAis; l_itAis = hgTargetManager::m_mapTarget.find(MMSI); QMap <QString,hgPolygonLayer>::Iterator l_polyiter; for (l_polyiter = hgAlarmManager::m_LayerDataManager.m_pPloygonMap.begin(); l_polyiter != hgAlarmManager::m_LayerDataManager.m_pPloygonMap.end(); l_polyiter++) { /////////报告区 if ( l_polyiter.value().m_WaringID.indexOf(hgWaringTypeGuid[REPORTINGAREA]) != -1) { hg::utils::PointLL l_aisPointLL; l_aisPointLL.setLat(l_itAis->Lat); l_aisPointLL.setLon(l_itAis->Lon); if (l_polyiter->m_Polygon.containsPoint(l_aisPointLL,Qt::OddEvenFill)) { itArea = map.find(l_polyiter.key()); if (itArea != map.end()) { return time(NULL); } else { return Yes; } } } } QMap <QString,hgCricleLayer>::Iterator l_cricle; for (l_cricle = hgAlarmManager::m_LayerDataManager.m_pCricleMap.begin(); l_cricle != hgAlarmManager::m_LayerDataManager.m_pCricleMap.end(); l_cricle++) { if ( l_cricle.value().m_WaringID.indexOf(hgWaringTypeGuid[REPORTINGAREA]) != -1) { hg::utils::PointLL l_aisPointLL; hg::utils::PointLL l_criclePointLL; double l_dDistance; l_aisPointLL.setLat(l_itAis->Lat); l_aisPointLL.setLon(l_itAis->Lon); l_criclePointLL.setLat(l_cricle->m_Lat); l_criclePointLL.setLon(l_cricle->m_Lon); l_dDistance = hg::utils::navutil::getDistance(l_aisPointLL,l_criclePointLL); if (l_dDistance <= l_cricle->m_Radius) { itArea = map.find(l_polyiter.key()); if (itArea != map.end()) { return time(NULL); } else { return Yes; } } } } QMap <QString,hgSectorLayer>::Iterator l_sector; for (l_sector = hgAlarmManager::m_LayerDataManager.m_pSectorMap.begin(); l_sector != hgAlarmManager::m_LayerDataManager.m_pSectorMap.end(); l_sector++) { if ( l_sector.value().m_WaringID.indexOf(hgWaringTypeGuid[REPORTINGAREA]) != -1) { if (PointInsideSector(l_itAis->Lat,l_itAis->Lon,l_sector->m_Lat,l_sector->m_Lon,l_sector->m_Radius,l_sector->m_BeginAngle,l_sector->m_EndAngle)) { itArea = map.find(l_polyiter.key()); if (itArea != map.end()) { return time(NULL); } else { return Yes; } } } } return No; } int hgAlarmManager::SpeedWatching(SpeedWatch speed) { mymap<QString,hgTarget>::iterator l_itAis; QMap<QString,SpeedWatch>::iterator l_itSpeedWatch; l_itSpeedWatch = hgAlarmManager::m_WarningSetManager.m_mapSpeedWatch.find(speed.TargetID); l_itAis = hgTargetManager::m_mapTarget.find(speed.TargetID); if (l_itAis->SOG < speed.MinSpeed) { l_itSpeedWatch->MinTimeKeep++; } else { l_itSpeedWatch->MinTimeKeep = 0; m_WarningSetManager.m_mapWarnInfo.find(speed.TargetID)->m_bIsMinSpeed = false; } if (l_itAis->SOG > speed.MaxSpeed) { l_itSpeedWatch->MaxTimeKeep++; } else { l_itSpeedWatch->MaxTimeKeep = 0; m_WarningSetManager.m_mapWarnInfo.find(speed.TargetID)->m_bIsMaxSpeed = false; } if (l_itSpeedWatch->MinTimeKeep > speed.MinDuration + 1) { return MinSpeed; } else if (l_itSpeedWatch->MaxTimeKeep > speed.MaxDuration + 3) { return MaxSpeed; } else { return Other; } } int hgAlarmManager::CollisionWatching(CollisionWatch collision, hgTarget ais, hgTarget collisionValue) { hg::utils::PointLL l_pointLLOwn,l_pointLLTarget,l_pointLLEnd; double l_dTCPA,l_dDCPA; l_pointLLOwn.setLat(collisionValue.Lat); l_pointLLOwn.setLon(collisionValue.Lon); l_pointLLTarget.setLat(ais.Lat); l_pointLLTarget.setLon(ais.Lon); hg::utils::navutil::getTCPADCPA(l_pointLLOwn,collisionValue.SOG,collisionValue.COG,l_pointLLTarget,ais.SOG,ais.COG,&l_dTCPA,&l_dDCPA); if (l_dDCPA <= collision.DCPA && abs(l_dTCPA) <= collision.TCPA) { /*for (int i = 0; i < m_WarningSetManager.m_mapWarnInfo.find(collision.MMSI)->m_listCollision.size(); i++) { if (ais.MMSI == m_WarningSetManager.m_mapWarnInfo.find(collision.MMSI)->m_listCollision[i]) { return false; } }*/ m_WarningSetManager.m_mapWarnInfo.find(collision.TargetID)->m_listCollision.append(ais.ID); return IsSendWarn; } else { for (int i = 0; i < m_WarningSetManager.m_mapWarnInfo.find(collision.TargetID)->m_listCollision.size(); i++) { if (ais.ID == m_WarningSetManager.m_mapWarnInfo.find(collision.TargetID)->m_listCollision[i]) { m_WarningSetManager.m_mapWarnInfo.find(collision.TargetID)->m_listCollision.removeAt(i); return CancelWarn; } } return UnSendWarn; } } bool hgAlarmManager::TurnOver(TurnCircle turn) { mymap<QString,hgTarget>::iterator l_itAisMsg; l_itAisMsg = hgTargetManager::m_mapTarget.find(turn.TargetID); hg::utils::PointLL l_pointLLOwn,l_pointLLTarget; double l_dDistance; l_pointLLOwn.setLat(l_itAisMsg->Lat); l_pointLLOwn.setLon(l_itAisMsg->Lon); l_pointLLTarget.setLat(turn.TurnLat); l_pointLLTarget.setLon(turn.TurnLon); l_dDistance = hg::utils::navutil::getDistance(l_pointLLOwn,l_pointLLTarget)*NM2M; //海里->米 if (l_dDistance <= turn.TurnRadius) { return false; } else { return true; } } void hgAlarmManager::SaveWarnData(hgSqlOperator& sqlOperator, hgWarningMes &msg) { hgSqlInsertCmd* l_pSqlInsertCmd = new hgSqlInsertCmd; l_pSqlInsertCmd->SetTableName("warning_table"); QMap<QString, QVariant> l_data; l_data.insert("WarnID",QString::fromStdString(msg.warningid())); l_data.insert("WarnDUID",QString::fromStdString(msg.warningguid())); l_data.insert("WarningPriority",msg.warningpriority()); l_data.insert("WarningName",QString::fromStdString(msg.warningname())); //l_data.insert("Message",msg.message()); l_data.insert("MMSI",QString::fromStdString(msg.mmsi())); l_data.insert("UserLayGUID",QString::fromStdString(msg.userlayguid())); l_data.insert("UserLayID",msg.userlayid()); l_data.insert("ID",QString::fromStdString(msg.id())); l_data.insert("WarningTime",msg.warningtime()); l_data.insert("WarningType",msg.warningtype()); l_data.insert("TargetMMSI",QString::fromStdString(msg.targetmmsi())); l_pSqlInsertCmd->SetData(l_data); if (!sqlOperator.ImplementCmd(l_pSqlInsertCmd)) { std::cout << "Open datatabase error:" << sqlOperator.LastError().text().toLatin1().data(); delete l_pSqlInsertCmd; l_pSqlInsertCmd = NULL; return; } QList<QSqlRecord>* l_pSqlRecord = sqlOperator.Records(); if (l_pSqlInsertCmd) { delete l_pSqlInsertCmd; l_pSqlInsertCmd = NULL; } }
[ "Administrator@MUTGU62RE12Z4H2" ]
Administrator@MUTGU62RE12Z4H2
a400554ea12e704b45c0882fae24df0dec68b71a
434c2e415380396525d49bb1b550c97962719418
/src/sound_manager.cpp
5400646edff28462834fdef7c99eed02b20a05ca
[ "MIT" ]
permissive
klei1984/max
29e1ab79cb384ab50552cc1888919bcd6da1a4c5
17dac93e194597815782c9a50e9261de5d99b257
refs/heads/master
2023-08-29T20:16:54.683634
2023-08-29T15:54:43
2023-08-29T15:54:43
228,703,696
40
1
MIT
2022-12-21T22:33:04
2019-12-17T21:21:38
C++
UTF-8
C++
false
false
34,920
cpp
/* Copyright (c) 2020 M.A.X. Port Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "sound_manager.hpp" #include <cstring> #include <new> #include "enums.hpp" #include "game_manager.hpp" #include "gnw.h" #include "inifile.hpp" #include "resource_manager.hpp" #define SOUNDMGR_MAX_SAMPLES 20 #define SOUNDMGR_CHUNK_SIZE 4096 #define SOUNDMGR_INVALID_CHANNEL -1 #define SOUNDMGR_MAX_VALUE 0x7FFFu #define SOUNDMGR_PANNING_LEFT 0x0000u #define SOUNDMGR_PANNING_CENTER 0x8000u #define SOUNDMGR_PANNING_RIGHT 0xFFFFu #define SOUNDMGR_SFX_FLAG_INVALID 0 #define SOUNDMGR_SFX_FLAG_UNKNOWN_1 1 #define SOUNDMGR_SFX_FLAG_UNKNOWN_2 2 #define SOUNDMGR_SFX_FLAG_INFINITE_LOOPING 4 #define SOUNDMGR_SCALE_VOLUME(volume) (((volume)*MIX_MAX_VOLUME) / SOUNDMGR_MAX_VALUE) #define SOUNDMGR_SCALE_PANNING_RIGHT(panning) (((panning)*254u) / SOUNDMGR_PANNING_RIGHT) CSoundManager SoundManager; static const uint8_t soundmgr_sfx_type_flags[SFX_TYPE_LIMIT] = { SOUNDMGR_SFX_FLAG_INVALID, SOUNDMGR_SFX_FLAG_UNKNOWN_2 | SOUNDMGR_SFX_FLAG_INFINITE_LOOPING, SOUNDMGR_SFX_FLAG_UNKNOWN_2 | SOUNDMGR_SFX_FLAG_INFINITE_LOOPING, SOUNDMGR_SFX_FLAG_UNKNOWN_2 | SOUNDMGR_SFX_FLAG_INFINITE_LOOPING, SOUNDMGR_SFX_FLAG_UNKNOWN_2 | SOUNDMGR_SFX_FLAG_INFINITE_LOOPING, SOUNDMGR_SFX_FLAG_UNKNOWN_2, SOUNDMGR_SFX_FLAG_UNKNOWN_2, SOUNDMGR_SFX_FLAG_UNKNOWN_2, SOUNDMGR_SFX_FLAG_UNKNOWN_2 | SOUNDMGR_SFX_FLAG_INFINITE_LOOPING, SOUNDMGR_SFX_FLAG_UNKNOWN_1, SOUNDMGR_SFX_FLAG_UNKNOWN_1, SOUNDMGR_SFX_FLAG_UNKNOWN_1, SOUNDMGR_SFX_FLAG_UNKNOWN_1, SOUNDMGR_SFX_FLAG_UNKNOWN_1, SOUNDMGR_SFX_FLAG_UNKNOWN_1, SOUNDMGR_SFX_FLAG_UNKNOWN_2, SOUNDMGR_SFX_FLAG_UNKNOWN_2, SOUNDMGR_SFX_FLAG_UNKNOWN_2, SOUNDMGR_SFX_FLAG_UNKNOWN_2}; static const int16_t soundmgr_voice_priority[V_END - V_START + 1] = { 0, 10, 10, 10, 10, 10, 10, 10, 10, 20, 20, 20, 20, 35, 35, 30, 30, 40, 40, 40, 40, 0, 0, 45, 45, 45, 45, 10, 10, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 50, 50, 50, 50, 0, 50, 50, 50, 50, 50, 50, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 40, 40, 40, 0, 0, 0, 0, 30, 30, 30, 30, 0, 5, 5, 5, 5, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 0, 0, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 10, 10, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static void Soundmgr_bk_process(void) { SoundManager.BkProcess(); } CSoundManager::CSoundManager() { is_audio_enabled = false; mixer_channels_count = 0; volumes = nullptr; last_music_played = INVALID_ID; current_music_played = INVALID_ID; shuffle_music = false; SDL_zero(shuffle_music_playlist); voice_played = INVALID_ID; music = nullptr; voice = nullptr; sfx = nullptr; } CSoundManager::~CSoundManager() { Deinit(); } void CSoundManager::Init() { if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, SOUNDMGR_CHUNK_SIZE) == -1) { SDL_Log("Unable to initialize SDL audio: %s\n", SDL_GetError()); is_audio_enabled = false; /// \todo MVE_SOS_sndInit(-1); } else { IniSoundVolumes ini_soundvol; is_audio_enabled = true; /* setup sound effect volume table */ volumes = new (std::nothrow) SoundVolume[FXS_END - FXS_STRT - 1]; SDL_assert(volumes); for (int32_t i = 0; i < (FXS_END - FXS_STRT - 1); i++) { volumes[i].volume = ini_soundvol.GetUnitVolume((ResourceID)(FXS_STRT + i + 1)); volumes[i].flags = -1; } /* allocate SOUNDMGR_MAX_SAMPLES number of sound channels */ mixer_channels_count = Mix_AllocateChannels(SOUNDMGR_MAX_SAMPLES); if (mixer_channels_count != SOUNDMGR_MAX_SAMPLES) { SDL_Log("Only allocated %i sound mixing channels instead of %i", mixer_channels_count, SOUNDMGR_MAX_SAMPLES); } samples.clear(); jobs.clear(); /// \todo MVE_SOS_sndInit(HANDLE); add_bk_process(Soundmgr_bk_process); enable_bk(); } } void CSoundManager::Deinit() { is_audio_enabled = false; samples.clear(); jobs.clear(); Mix_AllocateChannels(0); if (volumes) { delete[] volumes; volumes = nullptr; } while (Mix_QuerySpec(nullptr, nullptr, nullptr)) { Mix_CloseAudio(); } } void CSoundManager::UpdateMusic() { if (music && !Mix_PlayingMusic()) { if (shuffle_music) { ResourceID resource_id; int32_t index; /* if all tracks were played from the list, reset list state */ for (index = 0; (index < (BKG9_MSC - MAIN_MSC + 1)) && (shuffle_music_playlist[index] != true); index++) { ; } if (index == (BKG9_MSC - MAIN_MSC + 1)) { for (index = 0; index < (BKG9_MSC - MAIN_MSC + 1); index++) { shuffle_music_playlist[index] = true; } } for (;;) { do { index = (((BKG9_MSC - MAIN_MSC + 1) * dos_rand()) >> 15); resource_id = (ResourceID)(index + MAIN_MSC); } while (!shuffle_music_playlist[index]); shuffle_music_playlist[index] = false; if (LoadMusic(resource_id)) { break; } for (index = 0; (index < (BKG9_MSC - MAIN_MSC + 1)) && (shuffle_music_playlist[index] != true); index++) { ; } if (index == (BKG9_MSC - MAIN_MSC + 1)) { SDL_assert(music->music); Mix_PlayMusic(music->music, 1); return; } } } else { SDL_assert(music->music); Mix_PlayMusic(music->music, 1); } } } void CSoundManager::FreeSfx(UnitInfo* unit) { uint16_t unit_id; if (sfx) { sfx->time_stamp = timer_get(); } sfx = nullptr; unit->sound = SFX_TYPE_INVALID; unit_id = unit->GetId(); for (auto it = jobs.begin(); it != jobs.end();) { if (it->unit_id == unit_id && it->type == JOB_TYPE_SFX0) { it = jobs.erase(it); } else { it++; } } } void CSoundManager::FreeSample(SoundSample* sample) { if (is_audio_enabled) { SDL_assert(sample); if (sample->mixer_channel != SOUNDMGR_INVALID_CHANNEL) { SDL_assert(sample->mixer_channel < mixer_channels_count); if (sample->type == JOB_TYPE_MUSIC) { if (music && music->music == sample->music) { music = nullptr; } if (Mix_PlayingMusic()) { Mix_HaltMusic(); current_music_played = INVALID_ID; } Mix_FreeMusic(sample->music); sample->music = nullptr; sample->mixer_channel = SOUNDMGR_INVALID_CHANNEL; } else { /// \todo SDL_assert(Mix_GetChunk(sample->mixer_channel) == sample->chunk); if (sfx && sfx->chunk == sample->chunk) { sfx = nullptr; } if (voice && voice->chunk == sample->chunk) { voice = nullptr; voice_played = INVALID_ID; } Mix_HaltChannel(sample->mixer_channel); Mix_FreeChunk(sample->chunk); sample->chunk = nullptr; sample->mixer_channel = SOUNDMGR_INVALID_CHANNEL; } } } } void CSoundManager::PlayMusic(ResourceID id, bool shuffle) { if ((id != INVALID_ID) && (id != current_music_played)) { if (ini_get_setting(INI_DISABLE_MUSIC)) { last_music_played = id; } else { FreeMusic(); shuffle_music = shuffle; if ((shuffle_music) && ((id < MAIN_MSC) || (id > BKG9_MSC))) { for (int32_t i = 0; i < (BKG9_MSC - MAIN_MSC + 1); i++) { shuffle_music_playlist[i] = true; } } SoundJob job; job.id = id; job.type = JOB_TYPE_MUSIC; job.volume_1 = SOUNDMGR_MAX_VALUE; job.volume_2 = SOUNDMGR_MAX_VALUE; job.panning = SOUNDMGR_PANNING_CENTER; job.loop_count = 0; job.grid_x = 0; job.grid_y = 0; job.priority = 0; job.sound = SFX_TYPE_INVALID; job.unit_id = -1; AddJob(job); } } } void CSoundManager::HaltMusicPlayback(bool disable) { if (disable) { last_music_played = current_music_played; FreeMusic(); } else { PlayMusic(last_music_played, shuffle_music); } } void CSoundManager::FreeMusic() { if (music) { FreeSample(music); music = nullptr; } } void CSoundManager::PlaySfx(ResourceID id) { if (!ini_get_setting(INI_DISABLE_FX)) { SoundJob job; job.id = id; job.type = JOB_TYPE_SFX2; job.volume_1 = SOUNDMGR_MAX_VALUE; job.volume_2 = SOUNDMGR_MAX_VALUE; job.panning = SOUNDMGR_PANNING_CENTER; job.loop_count = 0; job.grid_x = 0; job.grid_y = 0; job.priority = 0; job.sound = SFX_TYPE_INVALID; job.unit_id = -1; AddJob(job); BkProcess(); } } void CSoundManager::PlaySfx(UnitInfo* unit, int32_t sound, bool mode) { uint8_t flags; int32_t previous_sound; SDL_assert(unit); SDL_assert(sound < SFX_TYPE_LIMIT); if (mode) { flags = SOUNDMGR_SFX_FLAG_UNKNOWN_1; } else { flags = soundmgr_sfx_type_flags[sound]; } if (!(flags & SOUNDMGR_SFX_FLAG_UNKNOWN_2) || (previous_sound = unit->sound, unit->sound = sound, previous_sound != sound)) { if (SFX_TYPE_INVALID == sound) { FreeSfx(unit); return; } if (!ini_get_setting(INI_DISABLE_FX) && is_audio_enabled) { int32_t grid_center_x; int32_t grid_center_y; int32_t grid_offset_x; int32_t grid_offset_y; int32_t grid_distance_x; int32_t grid_distance_y; SoundJob job; int32_t loop_count; int32_t sound_index; int32_t volume_index; int32_t resource_id; for (sound_index = 0; sound_index < unit->sound_table->size() && (*unit->sound_table)[sound_index].type != sound; ++sound_index) { ; } if (sound_index == unit->sound_table->size()) { if (soundmgr_sfx_type_flags[sound] != SOUNDMGR_SFX_FLAG_UNKNOWN_1) { FreeSfx(unit); return; } resource_id = sound + FXS_STRT; } else { resource_id = (*unit->sound_table)[sound_index].resource_id; } if (sound >= SFX_TYPE_IDLE && sound <= SFX_TYPE_STOP && (unit->flags & (MOBILE_LAND_UNIT | MOBILE_SEA_UNIT)) == (MOBILE_LAND_UNIT | MOBILE_SEA_UNIT) && unit->image_base == 8) { resource_id++; } volume_index = resource_id - GEN_IDLE; if (volumes[resource_id - GEN_IDLE].flags == -1) { char* filename; volumes[volume_index].flags = 1; filename = reinterpret_cast<char*>(ResourceManager_ReadResource(static_cast<ResourceID>(resource_id))); if (filename) { FILE* fp; ResourceManager_ToUpperCase(filename); fp = fopen(filename, "rb"); if (fp) { volumes[volume_index].flags = 0; fclose(fp); } delete[] filename; } } if (volumes[volume_index].flags == 1) { resource_id = sound + FXS_STRT; volume_index = sound - 1; } job.type = (JOB_TYPE)((flags & SOUNDMGR_SFX_FLAG_UNKNOWN_2) != 0); job.id = (ResourceID)resource_id; job.grid_x = unit->grid_x; job.grid_y = unit->grid_y; if (flags & SOUNDMGR_SFX_FLAG_INFINITE_LOOPING) { loop_count = -1; } else { loop_count = 0; } job.loop_count = loop_count; job.sound = sound; grid_center_x = (GameManager_GridPosition.ulx + GameManager_GridPosition.lrx) / 2; grid_center_y = (GameManager_GridPosition.uly + GameManager_GridPosition.lry) / 2; grid_offset_x = job.grid_x - grid_center_x; grid_offset_y = job.grid_y - grid_center_y; grid_distance_x = labs(grid_offset_x); grid_distance_y = labs(grid_offset_y); job.volume_2 = volumes[volume_index].volume; job.volume_1 = job.volume_2 - job.volume_2 * std::max(grid_distance_x, grid_distance_y) / 112; job.panning = GetPanning(grid_distance_x, (job.grid_x - grid_center_x) < 0); job.priority = 0; job.unit_id = unit->GetId(); AddJob(job); } } } void CSoundManager::UpdateSfxPosition() { int32_t grid_center_x; int32_t grid_center_y; int32_t grid_offset_x; int32_t grid_offset_y; int32_t grid_distance_x; int32_t grid_distance_y; int32_t pan_location; int32_t sound_level; grid_center_x = (GameManager_GridPosition.ulx + GameManager_GridPosition.lrx) / 2; grid_center_y = (GameManager_GridPosition.uly + GameManager_GridPosition.lry) / 2; for (auto it = samples.begin(); it != samples.end(); it++) { if (it->mixer_channel != SOUNDMGR_INVALID_CHANNEL && it->type <= JOB_TYPE_SFX1) { grid_offset_x = it->grid_x - grid_center_x; grid_offset_y = it->grid_y - grid_center_y; grid_distance_x = labs(grid_offset_x); grid_distance_y = labs(grid_offset_y); if (grid_offset_x >= 0) { pan_location = GetPanning(grid_distance_x, false); } else { pan_location = GetPanning(grid_distance_x, true); } int32_t pan_right = SOUNDMGR_SCALE_PANNING_RIGHT(pan_location); int32_t pan_left = 254 - pan_right; if (!Mix_SetPanning(it->mixer_channel, pan_left, pan_right)) { SDL_Log("SDL_Mixer failed to set stereo pan position: %s\n", Mix_GetError()); } sound_level = it->volume_2 - it->volume_2 * std::max(grid_distance_x, grid_distance_y) / 112; sound_level = (ini_get_setting(INI_FX_SOUND_LEVEL) * sound_level) / 100; Mix_Volume(it->mixer_channel, SOUNDMGR_SCALE_VOLUME(sound_level)); } } } void CSoundManager::UpdateSfxPosition(UnitInfo* unit) { int32_t grid_center_x; int32_t grid_center_y; int32_t grid_offset_x; int32_t grid_offset_y; int32_t grid_distance_x; int32_t grid_distance_y; int32_t pan_location; int32_t sound_level; SDL_assert(unit); if (sfx && sfx->mixer_channel != SOUNDMGR_INVALID_CHANNEL) { sfx->grid_x = unit->grid_x; sfx->grid_y = unit->grid_y; grid_center_x = (GameManager_GridPosition.ulx + GameManager_GridPosition.lrx) / 2; grid_center_y = (GameManager_GridPosition.uly + GameManager_GridPosition.lry) / 2; grid_offset_x = sfx->grid_x - grid_center_x; grid_offset_y = sfx->grid_y - grid_center_y; grid_distance_x = labs(grid_offset_x); grid_distance_y = labs(grid_offset_y); if (grid_offset_x >= 0) { pan_location = GetPanning(grid_distance_x, false); } else { pan_location = GetPanning(grid_distance_x, true); } int32_t pan_right = SOUNDMGR_SCALE_PANNING_RIGHT(pan_location); int32_t pan_left = 254 - pan_right; if (!Mix_SetPanning(sfx->mixer_channel, pan_left, pan_right)) { SDL_Log("SDL_Mixer failed to set stereo pan position: %s\n", Mix_GetError()); } sound_level = sfx->volume_2 - sfx->volume_2 * std::max(grid_distance_x, grid_distance_y) / 112; sound_level = (ini_get_setting(INI_FX_SOUND_LEVEL) * sound_level) / 100; Mix_Volume(sfx->mixer_channel, SOUNDMGR_SCALE_VOLUME(sound_level)); } } void CSoundManager::UpdateAllSfxPositions() {} void CSoundManager::HaltSfxPlayback(bool disable) { if (disable) { for (auto it = samples.begin(); it != samples.end();) { if (it->mixer_channel != SOUNDMGR_INVALID_CHANNEL && it->type <= JOB_TYPE_SFX2) { FreeSample(&(*it)); it = samples.erase(it); } else { it++; } } } else if (GameManager_SelectedUnit != nullptr) { PlaySfx(&*GameManager_SelectedUnit, SFX_TYPE_INVALID, false); PlaySfx(&*GameManager_SelectedUnit, GameManager_SelectedUnit->sound, false); } } void CSoundManager::PlayVoice(ResourceID id1, ResourceID id2, int16_t priority) { if (priority >= 0) { if (!IsVoiceGroupScheduled(id1, id2) && !ini_get_setting(INI_DISABLE_VOICE)) { int16_t priority_value; uint16_t randomized_voice_id; if (priority > 0) { priority_value = priority; } else { priority_value = soundmgr_voice_priority[id1 - V_START]; } randomized_voice_id = 2 * ((((id2 - id1) / 2 + 1) * dos_rand()) >> 15) + 1 + id1; SDL_assert(randomized_voice_id != id1 && randomized_voice_id <= id2); for (auto it = jobs.begin(); it != jobs.end(); it++) { if (it->type == JOB_TYPE_VOICE) { if (priority_value >= it->priority) { it->id = (ResourceID)randomized_voice_id; it->priority = priority_value; } return; } } SoundJob job; job.id = (ResourceID)randomized_voice_id; job.type = JOB_TYPE_VOICE; job.volume_1 = SOUNDMGR_MAX_VALUE; job.volume_2 = SOUNDMGR_MAX_VALUE; job.panning = SOUNDMGR_PANNING_CENTER; job.loop_count = 0; job.grid_x = 0; job.grid_y = 0; job.priority = priority_value; job.sound = SFX_TYPE_INVALID; job.unit_id = -1; AddJob(job); } } else { FreeVoice(id1, id2); } } void CSoundManager::HaltVoicePlayback(bool disable) { if (disable) { if (voice) { FreeSample(voice); voice = nullptr; } } } void CSoundManager::FreeAllSamples() { FreeMusic(); for (auto it = samples.begin(); it != samples.end();) { FreeSample(&(*it)); it = samples.erase(it); } SDL_assert(samples.empty()); } void CSoundManager::SetVolume(int32_t type, int32_t volume) { SDL_assert(type <= JOB_TYPE_MUSIC); SDL_assert(volume <= 100); for (auto it = samples.begin(); it != samples.end(); it++) { if (it->mixer_channel != SOUNDMGR_INVALID_CHANNEL && (it->type == type || (type == JOB_TYPE_SFX2 && it->type <= JOB_TYPE_SFX2))) { int32_t new_volume = (it->volume_1 * volume) / 100; if (it->type == JOB_TYPE_MUSIC) { Mix_VolumeMusic(SOUNDMGR_SCALE_VOLUME(new_volume)); } else { Mix_Volume(it->mixer_channel, SOUNDMGR_SCALE_VOLUME(new_volume)); } } } } void CSoundManager::BkProcess() { if (is_audio_enabled) { UpdateMusic(); for (auto it = jobs.begin(); it != jobs.end();) { if (0 == ProcessJob(*it)) { it = jobs.erase(it); } else { it++; } } for (auto it = samples.begin(); it != samples.end();) { if (it->type <= JOB_TYPE_SFX2) { if (it->mixer_channel != SOUNDMGR_INVALID_CHANNEL && it->time_stamp && timer_elapsed_time(it->time_stamp) > 125) { it->volume_2 /= 2; if (it->volume_2) { int32_t sfx_volume = ini_get_setting(INI_FX_SOUND_LEVEL); SDL_assert(sfx_volume <= 100); it->volume_1 /= 2; Mix_Volume(it->mixer_channel, SOUNDMGR_SCALE_VOLUME(sfx_volume * it->volume_1 / 100)); it->time_stamp = timer_get(); } else { FreeSample(&(*it)); it = samples.erase(it); continue; } } } it++; } } } void CSoundManager::AddJob(SoundJob& job) { if ((is_audio_enabled) && (job.id != INVALID_ID) && (jobs.size() < SOUNDMGR_MAX_SAMPLES)) { if (job.type <= JOB_TYPE_SFX2) { for (auto it = jobs.begin(); it != jobs.end(); it++) { if (it->id == job.id) { if (job.volume_1 > it->volume_1) { it->volume_1 = job.volume_1; } return; } if ((it->type == JOB_TYPE_SFX1) && (job.type == JOB_TYPE_SFX1)) { *it = job; return; } } if (job.type == JOB_TYPE_SFX2) { for (auto it = samples.begin(); it != samples.end(); it++) { if (job.id == it->id && it->mixer_channel != SOUNDMGR_INVALID_CHANNEL && Mix_Playing(it->mixer_channel)) { return; } } } } if (job.priority > 0) { for (auto it = jobs.begin(); it != jobs.end(); it++) { if (job.priority > it->priority) { jobs.insert(it, job); return; } } } jobs.push_back(job); } } int32_t CSoundManager::ProcessJob(SoundJob& job) { int32_t result; if (job.type == JOB_TYPE_VOICE && voice && voice->mixer_channel != SOUNDMGR_INVALID_CHANNEL && Mix_Playing(voice->mixer_channel)) { result = 11; } else { for (auto it = samples.begin(); it != samples.end();) { if (it->mixer_channel == SOUNDMGR_INVALID_CHANNEL || (it->type != JOB_TYPE_MUSIC && !Mix_Playing(it->mixer_channel)) || (it->type == JOB_TYPE_MUSIC && !Mix_PlayingMusic())) { FreeSample(&(*it)); it = samples.erase(it); } else { it++; } } if (samples.size() < mixer_channels_count) { SoundSample sample; SDL_zero(sample); result = LoadSound(job, sample); if (0 == result) { int32_t sound_level; if (sample.loop_point_start != 0) { if (job.sound == SFX_TYPE_BUILDING) { ; /// \todo Cut sample part before loop point start position and limit sample size to loop /// point size in case of building type sound } else { ; /// \todo SDL_mixer does not support loop points for Mix_Chunks } job.loop_count = -1; } if (job.type == JOB_TYPE_MUSIC) { sound_level = ini_get_setting(INI_MUSIC_LEVEL); } else if (job.type == JOB_TYPE_VOICE) { sound_level = ini_get_setting(INI_VOICE_LEVEL); } else { sound_level = ini_get_setting(INI_FX_SOUND_LEVEL); } SDL_assert(sound_level <= 100); sample.id = job.id; sample.type = job.type; sample.volume_1 = job.volume_1; sample.volume_2 = job.volume_2; sample.loop_count = job.loop_count; sample.grid_x = job.grid_x; sample.grid_y = job.grid_y; sample.priority = job.priority; sample.time_stamp = 0; /// \todo Should we set chunk volume instead of channel volume? if (JOB_TYPE_MUSIC == sample.type) { sample.mixer_channel = 0; Mix_VolumeMusic(SOUNDMGR_SCALE_VOLUME(sample.volume_1 * sound_level / 100)); int32_t local_result = Mix_PlayMusic(sample.music, sample.loop_count); SDL_assert(local_result != -1); } else { int32_t pan_right = SOUNDMGR_SCALE_PANNING_RIGHT(job.panning); int32_t pan_left = 254 - pan_right; if (!Mix_SetPanning(sample.mixer_channel, pan_left, pan_right)) { SDL_Log("SDL_Mixer failed to set stereo pan position: %s\n", Mix_GetError()); } { int32_t i = 0; while (Mix_Playing(i)) { i++; } SDL_assert(i < mixer_channels_count); sample.mixer_channel = i; } Mix_Volume(sample.mixer_channel, SOUNDMGR_SCALE_VOLUME(sample.volume_1 * sound_level / 100)); int32_t channel = Mix_PlayChannel(sample.mixer_channel, sample.chunk, sample.loop_count); SDL_assert(channel == sample.mixer_channel); } samples.push_back(sample); if (job.type <= JOB_TYPE_SFX2) { if (job.type == JOB_TYPE_SFX1) { if (sfx && sfx->chunk != sample.chunk) { sfx->time_stamp = timer_get(); } sfx = &samples.back(); } } else if (job.type == JOB_TYPE_VOICE) { voice = &samples.back(); voice_played = job.id; } else if (job.type == JOB_TYPE_MUSIC) { music = &samples.back(); current_music_played = job.id; } } } else { result = 11; } } return result; } void CSoundManager::FreeVoice(ResourceID id1, ResourceID id2) { if (voice && voice_played >= id1 && voice_played <= id2) { FreeSample(voice); } for (auto it = jobs.begin(); it != jobs.end();) { if (it->type == JOB_TYPE_VOICE && it->id >= id1 && it->id <= id2) { it = jobs.erase(it); } else { it++; } } } bool CSoundManager::IsVoiceGroupScheduled(ResourceID id1, ResourceID id2) { if (voice_played >= id1 && voice_played <= id2 && voice && Mix_Playing(voice->mixer_channel)) { return true; } for (auto it = jobs.begin(); it != jobs.end(); it++) { if (it->type == JOB_TYPE_VOICE && it->id >= id1 && it->id <= id2) { return true; } } return false; } int32_t CSoundManager::GetPanning(int32_t distance, bool reverse) { int32_t panning; if (distance > 28) { distance = 28; } if (reverse) { distance = -distance; } panning = (SOUNDMGR_PANNING_RIGHT * (distance + 56)) / 112; if (ini_get_setting(INI_CHANNELS_REVERSED)) { panning = SOUNDMGR_PANNING_RIGHT - panning; } return panning; } bool CSoundManager::LoadMusic(ResourceID id) { Mix_Music* sample; char* file; char file_path[PATH_MAX]; bool result = false; file = reinterpret_cast<char*>(ResourceManager_ReadResource(id)); if (file) { strncpy(file_path, ResourceManager_FilePathMsc, PATH_MAX - 1); strncat(file_path, file, (PATH_MAX - 1) - strlen(file_path)); delete[] file; file_path[PATH_MAX - 1] = '\0'; sample = Mix_LoadMUS(file_path); if (sample) { if (music->music) { Mix_FreeMusic(music->music); } music->music = sample; current_music_played = id; result = true; } } return result; } int32_t CSoundManager::LoadSound(SoundJob& job, SoundSample& sample) { char* file; char file_path[PATH_MAX]; int32_t result; file = reinterpret_cast<char*>(ResourceManager_ReadResource(job.id)); if (file) { if (JOB_TYPE_VOICE == job.type) { strncpy(file_path, ResourceManager_FilePathVoiceSpw, PATH_MAX - 1); } else if (JOB_TYPE_MUSIC == job.type) { strncpy(file_path, ResourceManager_FilePathMsc, PATH_MAX - 1); } else { strncpy(file_path, ResourceManager_FilePathSfxSpw, PATH_MAX - 1); } ResourceManager_ToUpperCase(file); strncat(file_path, file, (PATH_MAX - 1) - strlen(file_path)); delete[] file; file_path[PATH_MAX - 1] = '\0'; FILE* fp = fopen(file_path, "rb"); if (fp) { LoadLoopPoints(fp, sample); fclose(fp); if (JOB_TYPE_MUSIC == job.type) { sample.music = Mix_LoadMUS(file_path); if (sample.music) { sample.chunk = nullptr; current_music_played = job.id; result = 0; } else { sample.chunk = nullptr; current_music_played = INVALID_ID; result = 4; } } else { sample.music = nullptr; sample.chunk = Mix_LoadWAV(file_path); if (sample.chunk) { result = 0; } else { result = 4; } } } else { result = 6; } } else { result = 6; } return result; } void CSoundManager::LoadLoopPoints(FILE* fp, SoundSample& sample) { char chunk_id[4]; uint32_t chunk_size; sample.loop_point_start = 0; sample.loop_point_length = 0; if (fread(chunk_id, sizeof(chunk_id), 1, fp)) { if (!strncmp(chunk_id, "RIFF", sizeof(chunk_id))) { if (fread(&chunk_size, sizeof(chunk_size), 1, fp)) { if (fread(chunk_id, sizeof(chunk_id), 1, fp)) { if (!strncmp(chunk_id, "WAVE", sizeof(chunk_id))) { for (; fread(chunk_id, sizeof(chunk_id), 1, fp);) { if (!fread(&chunk_size, sizeof(chunk_size), 1, fp)) { break; /* something is wrong */ } if (!strncmp(chunk_id, "smpl", sizeof(chunk_id))) { typedef struct { uint32_t manufacturer; uint32_t product; uint32_t sample_period; uint32_t midi_unity_note; uint32_t midi_pitch_fraction; uint32_t smpte_format; uint32_t smpte_offset; uint32_t num_sample_loops; uint32_t sampler_data; } SamplerChunk; SamplerChunk sampler_chunk; if (fread(&sampler_chunk, sizeof(sampler_chunk), 1, fp)) { typedef struct { uint32_t cue_point_id; uint32_t type; uint32_t start; uint32_t end; uint32_t fraction; uint32_t play_count; } SampleLoop; SampleLoop sample_loop; for (int32_t i = 0; i < sampler_chunk.num_sample_loops && fread(&sample_loop, sizeof(sample_loop), 1, fp); i++) { sample.loop_point_start = sample_loop.start; sample.loop_point_length = sample_loop.end - sample_loop.start; return; /* only one loop point is supported */ } } break; } if (fseek(fp, chunk_size, SEEK_CUR)) { break; } } } } } } } }
[ "53688147+klei1984@users.noreply.github.com" ]
53688147+klei1984@users.noreply.github.com
44b2d87d5963a0b6b99312810ac56d4b4f6076ce
aa924bbb174676c00dfef9b976790a01506bd37e
/Sources/NodeEngineTest/StringUtilsTest.cpp
f850a171cb853f3aa35997915ddae19c0caa4503
[ "MIT" ]
permissive
kovacsv/VisualScriptEngine
5b3b8b7b6999082b0f916034a83d6e9675510ed6
185a451e2391fbff0bb4dd5929e8634517382c4e
refs/heads/master
2023-03-15T19:00:48.535709
2021-12-17T15:47:51
2021-12-17T15:47:51
113,492,822
156
32
MIT
2023-02-24T16:07:36
2017-12-07T19:57:56
C++
UTF-8
C++
false
false
2,645
cpp
#include "SimpleTest.hpp" #include "NE_StringUtils.hpp" using namespace NE; namespace StringUtilsTest { TEST (ReplaceAllTest) { std::wstring text = L"example of example of example"; ASSERT (ReplaceAll (text, L"e", L"") == L"xampl of xampl of xampl"); ASSERT (ReplaceAll (text, L"e", L"a") == L"axampla of axampla of axampla"); ASSERT (ReplaceAll (text, L"z", L"a") == L"example of example of example"); ASSERT (ReplaceAll (text, L"e", L"u") == L"uxamplu of uxamplu of uxamplu"); ASSERT (ReplaceAll (text, L"e", L"e") == L"example of example of example"); ASSERT (ReplaceAll (text, L"e", L"ee") == L"eexamplee of eexamplee of eexamplee"); ASSERT (ReplaceAll (text, L"example", L"s") == L"s of s of s"); ASSERT (ReplaceAll (text, L"example", L"something") == L"something of something of something"); } TEST (ReplaceAllMultipleTest) { std::wstring text = L"example of example of example"; ASSERT (ReplaceAll (text, L"e", { L"", L"", L"", L"", L"", L"" }) == L"xampl of xampl of xampl"); ASSERT (ReplaceAll (text, L"z", {}) == L"example of example of example"); ASSERT (ReplaceAll (text, L"e", { L"a", L"b", L"c", L"d", L"e", L"f" }) == L"axamplb of cxampld of examplf"); ASSERT (ReplaceAll (text, L"e", { L"a", L"bb", L"ccc", L"dddd", L"eeeee", L"ffffff" }) == L"axamplbb of cccxampldddd of eeeeexamplffffff"); ASSERT (ReplaceAll (text, L"example", { L"x", L"y", L"z" }) == L"x of y of z"); ASSERT (ReplaceAll (text, L"example", { L"example", L"example", L"example" }) == L"example of example of example"); ASSERT (ReplaceAll (text, L"example", { L"something", L"more something", L"much more something" }) == L"something of more something of much more something"); } TEST (ReplaceAllUnicodeTest) { ASSERT (ReplaceAll (L"ABA", L"B", L"\u03c0") == L"A\u03c0A"); ASSERT (ReplaceAll (L"ABA", L"B", L"\u03c0\u03c0") == L"A\u03c0\u03c0A"); ASSERT (ReplaceAll (L"A\u03c0A", L"\u03c0", L"B") == L"ABA"); ASSERT (ReplaceAll (L"A\u03c0B\u03c0A", L"\u03c0B\u03c0", L"B") == L"ABA"); ASSERT (ReplaceAll (L"ABA", L"B", { L"\u03c0" }) == L"A\u03c0A"); ASSERT (ReplaceAll (L"ABA", L"B", { L"\u03c0\u03c0" }) == L"A\u03c0\u03c0A"); ASSERT (ReplaceAll (L"A\u03c0A", L"\u03c0", { L"B" }) == L"ABA"); ASSERT (ReplaceAll (L"A\u03c0B\u03c0A", L"\u03c0B\u03c0", { L"B" }) == L"ABA"); ASSERT (ReplaceAll (L"ABA", L"A", { L"\u03c0", L"\u03c0" }) == L"\u03c0B\u03c0"); ASSERT (ReplaceAll (L"ABA", L"A", { L"\u03c0\u03c0", L"\u03c0\u03c0" }) == L"\u03c0\u03c0B\u03c0\u03c0"); ASSERT (ReplaceAll (L"\u03c0B\u03c0", L"\u03c0", { L"A", L"A" }) == L"ABA"); ASSERT (ReplaceAll (L"A\u03c0B\u03c0A", L"\u03c0B\u03c0", { L"B" }) == L"ABA"); } }
[ "viktorkovacs@gmail.com" ]
viktorkovacs@gmail.com
0cfded26c0973b15c2c76afa1289a2750948c30e
9d91d16fe9a57968fd173ed26c9b005675f320e3
/MySnake/MySnake.cpp
0e543f0eaeaed689e3a544f6c331760c0d949e81
[]
no_license
txkxk/MySnake
da2796d6d704487990dd6b2877963a38115f186b
7fa8ee619b82a6d93f0218daf547c100b24ca6eb
refs/heads/master
2021-01-10T02:25:57.377220
2015-10-09T13:46:51
2015-10-09T13:46:51
43,892,225
0
0
null
null
null
null
GB18030
C++
false
false
7,970
cpp
#include<iostream> #include<string> #include<windows.h> #include<conio.h> #include<time.h> #include<random> #include<thread> #include<sstream> using namespace std; string ChessBoard[20][20]; HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); enum State { UP, DOWN, LEFT, RIGHT} ; struct Point { Point(int xx,int yy):x(xx),y(yy){} Point() = default; int x; int y; }; Point food; int point = 0; int SPEED = 500; int level = 5; bool hasfood = false; int direction = 0; bool canchange = true; bool operator==(const Point& lhs, const Point& rhs) { if ((lhs.x == rhs.x) && (lhs.y == rhs.y)) { return true; } return false; } struct SnakeNode { SnakeNode(string s = "●", SnakeNode* n = nullptr, SnakeNode* p = nullptr) :ico(s), next(n), previous(p) {} ~SnakeNode() = default; string ico; SnakeNode* next; SnakeNode* previous; Point position; Point getNextPosition() { return this->previous->position; } }; struct Snake { Snake(int dump) { tail = new SnakeNode; Hand = new SnakeNode("★"); cleanNode = new SnakeNode(" "); SnakeNode* node_2 = new SnakeNode; SnakeNode* node_3 = new SnakeNode; tail->previous = node_2; node_2->next = tail; node_2->previous = node_3; node_3->next = node_2; node_3->previous = Hand; Hand->next = node_3; state = RIGHT; tail->next = cleanNode; cleanNode->previous = tail; } void destructSnake() { SnakeNode* tmpNode = Hand; while (tmpNode != nullptr) { SnakeNode* deleteNode=tmpNode; tmpNode = tmpNode->next; delete deleteNode; } } Snake() = default; SnakeNode* cleanNode; State state; SnakeNode* Hand; SnakeNode* tail; }; void init(); void print(); void up(); void down(); void left(); void right(); void addSnake(); void run(); void setPosition(int x, int y, string str); void makefood(); bool isinbody(Point &p); void eatfood(); void catchKey(); void ctrl(); void dead(); void do_run(); void setLevelAndSpeed(); bool isdead = false; string IntToString(int number); Snake snk; void print() { for (int i = 0;i<20;i++) { for (int j = 0;j<20;j++) { cout << ChessBoard[i][j]; } cout << endl; } } void init() { point = 0; SPEED = 500; level = 5; hasfood = false; canchange = true; isdead = false; snk = Snake::Snake(1); direction = 0; for (int i = 0;i<20;i++) { for (int j = 0;j<20;j++) { if (i == 0 && j == 0) { ChessBoard[i][j] = "┏"; continue; } else if (i == 0 && j == 19) { ChessBoard[i][j] = "┓"; } else if (i == 19 && j == 0) { ChessBoard[i][j] = "┗"; } else if (i == 19 && j == 19) { ChessBoard[i][j] = "┛"; } else if (i == 0 || i == 19) { ChessBoard[i][j] = "─"; } else if (j == 0 || j == 19) { ChessBoard[i][j] = "│"; } else { ChessBoard[i][j] = " "; } } } addSnake(); } void up() { SnakeNode* tmpNode = snk.cleanNode; while (tmpNode != nullptr) { setPosition(tmpNode->position.y * 2, tmpNode->position.x, tmpNode->ico); if (tmpNode == snk.Hand) { tmpNode->position.x--; } else { tmpNode->position = tmpNode->getNextPosition(); } tmpNode = tmpNode->previous; } eatfood(); } void down() { SnakeNode* tmpNode = snk.cleanNode; while (tmpNode != nullptr) { setPosition(tmpNode->position.y * 2, tmpNode->position.x, tmpNode->ico); if (tmpNode == snk.Hand) { tmpNode->position.x++; } else { tmpNode->position = tmpNode->getNextPosition(); } tmpNode = tmpNode->previous; } eatfood(); } void setState() { while (!isdead) { if (!_kbhit()) { continue; } if (_getch() == 224) direction = _getch(); } } void left() { SnakeNode* tmpNode = snk.cleanNode; while (tmpNode != nullptr) { setPosition(tmpNode->position.y * 2, tmpNode->position.x, tmpNode->ico); if (tmpNode == snk.Hand) { tmpNode->position.y--; } else { tmpNode->position = tmpNode->getNextPosition(); } tmpNode = tmpNode->previous; } eatfood(); } void right() { SnakeNode* tmpNode = snk.cleanNode; while (tmpNode != nullptr) { setPosition(tmpNode->position.y * 2, tmpNode->position.x, tmpNode->ico); if (tmpNode == snk.Hand) { tmpNode->position.y++; } else { tmpNode->position = tmpNode->getNextPosition(); } tmpNode = tmpNode->previous; } eatfood(); } void addSnake() { SnakeNode *tmpNode = snk.tail; for (int i = 4;tmpNode != nullptr;i++) { tmpNode->position.x = 7; tmpNode->position.y = i; tmpNode = tmpNode->previous; } } void setPosition(int x, int y, string str) { COORD c; c.X = x; c.Y = y; SetConsoleCursorPosition(handle, c); cout << str; } void makefood() { default_random_engine e(time(NULL)); uniform_int_distribution<int> dis; int food_p_x = dis(e) % 20; int food_p_y = dis(e) % 20; while (food_p_x == 0 || food_p_y == 0 || food_p_x == 19 || food_p_y == 19 || isinbody(Point(food_p_x, food_p_y))) { food_p_x = dis(e) % 20; food_p_y = dis(e) % 20; } food = Point(food_p_x, food_p_y); } bool isinbody(Point &p) { SnakeNode* tmpNode = snk.cleanNode; while (tmpNode != nullptr) { if (tmpNode->position == p) return true; tmpNode = tmpNode->previous; } return false; } void eatfood() { if (food == snk.Hand->position) { SnakeNode* NewNode = new SnakeNode; NewNode->previous = snk.tail; NewNode->next = snk.cleanNode; snk.tail->next = NewNode; snk.cleanNode->previous = NewNode; snk.tail = NewNode; NewNode->position = snk.cleanNode->position; point += 100; hasfood = false; } return; } void catchKey() { while (!isdead) { switch (direction) { case 72: { if (snk.state != DOWN&&snk.state != UP&&canchange) { canchange = false; snk.state = UP; } }break; case 77: { if (snk.state != LEFT&&snk.state != RIGHT&&canchange) { canchange = false; snk.state = RIGHT; } };break; case 80: { if (snk.state != UP&&snk.state != DOWN&&canchange) { canchange = false; snk.state = DOWN; } };break; case 75: { if (snk.state != RIGHT&&snk.state != LEFT&&canchange) { canchange = false; snk.state = LEFT; } }break; default: break; } } } void dead() { SnakeNode* tmpNode = snk.tail; while (tmpNode != snk.Hand) { if (snk.Hand->position == tmpNode->position) { isdead = true; return; } tmpNode = tmpNode->previous; } if (snk.Hand->position.x == 0 || snk.Hand->position.x == 19) { isdead = true; return; } if (snk.Hand->position.y == 0 || snk.Hand->position.y == 19) { isdead = true; return; } isdead = false; } void do_run() { switch (snk.state) { case State::UP:up();break; case State::DOWN:down();break; case State::RIGHT:right();break; case State::LEFT:left();break; default: break; } } void setLevelAndSpeed() { switch (point) { case 700: { SPEED =400; level=4; }break; case 1400: { SPEED = 300; level=3; }break; case 2100: { SPEED = 200; level = 2; }break; case 2800: { SPEED = 100; level=1; }break; case 3500: { SPEED -= 50; level=0; }break; default: break; } } string IntToString(int number) { stringstream ssr; ssr << number; return ssr.str(); } void run() { while (!isdead) { Sleep(SPEED); if (!hasfood) { makefood(); setPosition(food.y * 2, food.x, "◆"); setLevelAndSpeed(); setPosition(0, 21, "你当前的得分是:" + IntToString(point)); setPosition(0, 22, "你当前的级别是:LEVEL " + IntToString(level)); hasfood = true; } do_run(); canchange = true; dead(); } } int main() { while (true) { init(); print(); thread th1(run); thread th2(catchKey); thread th3(setState); th1.join(); th2.join(); th3.join(); setPosition(0, 23, "你已经死亡,你最终的得分是:" + IntToString(point)); cout << endl; cout << "输入y择重新再来,其他输入结束游戏。" << endl; char c; c = _getch(); if (c == 'y') { system("cls"); snk.destructSnake(); continue; } else { exit(0); } } return 0; }
[ "327016998@qq.com" ]
327016998@qq.com
c431451dd1a4c669bf8f6d6d1240f8016839c7fa
461f95c44e620e67271183c952e72b06ddd12358
/jni/JavaHook/dvm_object.h
d95e5ebee8bb30907ef222a2513e14487cb68c2a
[]
no_license
peterdocter/AllHookInOne
c3146b436174ee69e19d8fcbe3225c237b01aa1b
14b59013f6ffb6402b1b7cd239310447c96ee44f
refs/heads/master
2020-12-25T22:20:24.792484
2015-12-31T02:47:52
2015-12-31T02:47:52
33,915,504
0
1
null
2015-12-31T02:47:52
2015-04-14T06:48:58
C++
UTF-8
C++
false
false
42,378
h
/* * Copyright (C) 2008 The Android Open Source Project * * 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. */ /* * Declaration of the fundamental Object type and refinements thereof, plus * some functions for manipulating them. */ #ifndef _DALVIK_OO_OBJECT_4_H__ #define _DALVIK_OO_OBJECT_4_H__ #include <stddef.h> #include <stdbool.h> #include <stdint.h> #include <pthread.h> #include <jni.h> #ifndef INLINE # define INLINE extern __inline__ #endif /* * These match the definitions in the VM specification. */ #ifdef HAVE_STDINT_H # include <stdint.h> /* C99 */ typedef uint8_t u1; typedef uint16_t u2; typedef uint32_t u4; typedef uint64_t u8; typedef int8_t s1; typedef int16_t s2; typedef int32_t s4; typedef int64_t s8; #else typedef unsigned char u1; typedef unsigned short u2; typedef unsigned int u4; typedef unsigned long long u8; typedef signed char s1; typedef signed short s2; typedef signed int s4; typedef signed long long s8; #endif /* fwd decl */ struct DataObject; struct InitiatingLoaderList; struct ClassObject; struct StringObject; struct ArrayObject; struct Method; struct ExceptionEntry; struct LineNumEntry; struct StaticField; struct InstField; struct Field; struct RegisterMap; struct DvmDex; struct DexFile; struct Object; struct Thread; union JValue { u1 z; s1 b; u2 c; s2 s; s4 i; s8 j; float f; double d; void* l; }; /* * Storage for primitive types and object references. * * Some parts of the code (notably object field access) assume that values * are "left aligned", i.e. given "JValue jv", "jv.i" and "*((s4*)&jv)" * yield the same result. This seems to be guaranteed by gcc on big- and * little-endian systems. */ # define STRING_FIELDOFF_VALUE 8 # define STRING_FIELDOFF_HASHCODE 12 # define STRING_FIELDOFF_OFFSET 16 # define STRING_FIELDOFF_COUNT 20 /* * Enumeration of all the primitive types. */ enum PrimitiveType { PRIM_NOT = 0, /* value is a reference type, not a primitive type */ PRIM_VOID = 1, PRIM_BOOLEAN = 2, PRIM_BYTE = 3, PRIM_SHORT = 4, PRIM_CHAR = 5, PRIM_INT = 6, PRIM_LONG = 7, PRIM_FLOAT = 8, PRIM_DOUBLE = 9, }; enum { ACC_PUBLIC = 0x00000001, // class, field, method, ic ACC_PRIVATE = 0x00000002, // field, method, ic ACC_PROTECTED = 0x00000004, // field, method, ic ACC_STATIC = 0x00000008, // field, method, ic ACC_FINAL = 0x00000010, // class, field, method, ic ACC_SYNCHRONIZED = 0x00000020, // method (only allowed on natives) ACC_SUPER = 0x00000020, // class (not used in Dalvik) ACC_VOLATILE = 0x00000040, // field ACC_BRIDGE = 0x00000040, // method (1.5) ACC_TRANSIENT = 0x00000080, // field ACC_VARARGS = 0x00000080, // method (1.5) ACC_NATIVE = 0x00000100, // method ACC_INTERFACE = 0x00000200, // class, ic ACC_ABSTRACT = 0x00000400, // class, method, ic ACC_STRICT = 0x00000800, // method ACC_SYNTHETIC = 0x00001000, // field, method, ic ACC_ANNOTATION = 0x00002000, // class, ic (1.5) ACC_ENUM = 0x00004000, // class, field, ic (1.5) ACC_CONSTRUCTOR = 0x00010000, // method (Dalvik only) ACC_DECLARED_SYNCHRONIZED = 0x00020000, // method (Dalvik only) ACC_CLASS_MASK = (ACC_PUBLIC | ACC_FINAL | ACC_INTERFACE | ACC_ABSTRACT | ACC_SYNTHETIC | ACC_ANNOTATION | ACC_ENUM), ACC_INNER_CLASS_MASK = (ACC_CLASS_MASK | ACC_PRIVATE | ACC_PROTECTED | ACC_STATIC), ACC_FIELD_MASK = (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED | ACC_STATIC | ACC_FINAL | ACC_VOLATILE | ACC_TRANSIENT | ACC_SYNTHETIC | ACC_ENUM), ACC_METHOD_MASK = (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED | ACC_STATIC | ACC_FINAL | ACC_SYNCHRONIZED | ACC_BRIDGE | ACC_VARARGS | ACC_NATIVE | ACC_ABSTRACT | ACC_STRICT | ACC_SYNTHETIC | ACC_CONSTRUCTOR | ACC_DECLARED_SYNCHRONIZED), }; /* * Native function return type; used by dvmPlatformInvoke(). * * This is part of Method.jniArgInfo, and must fit in 3 bits. * Note: Assembly code in arch/<arch>/Call<arch>.S relies on * the enum values defined here. */ enum DalvikJniReturnType { DALVIK_JNI_RETURN_VOID = 0, /* must be zero */ DALVIK_JNI_RETURN_FLOAT = 1, DALVIK_JNI_RETURN_DOUBLE = 2, DALVIK_JNI_RETURN_S8 = 3, DALVIK_JNI_RETURN_S4 = 4, DALVIK_JNI_RETURN_S2 = 5, DALVIK_JNI_RETURN_U2 = 6, DALVIK_JNI_RETURN_S1 = 7 }; #define DALVIK_JNI_NO_ARG_INFO 0x80000000 #define DALVIK_JNI_RETURN_MASK 0x70000000 #define DALVIK_JNI_RETURN_SHIFT 28 #define DALVIK_JNI_COUNT_MASK 0x0f000000 #define DALVIK_JNI_COUNT_SHIFT 24 // #define PAD_SAVE_AREA /* help debug stack trampling */ // #define EASY_GDB /* * The VM-specific internal goop. * * The idea is to mimic a typical native stack frame, with copies of the * saved PC and FP. At some point we'd like to have interpreted and * native code share the same stack, though this makes portability harder. */ struct StackSaveArea { #ifdef PAD_SAVE_AREA u4 pad0, pad1, pad2; #endif #ifdef EASY_GDB /* make it easier to trek through stack frames in GDB */ StackSaveArea* prevSave; #endif /* saved frame pointer for previous frame, or NULL if this is at bottom */ u4* prevFrame; /* saved program counter (from method in caller's frame) */ const u2* savedPc; /* pointer to method we're *currently* executing; handy for exceptions */ const Method* method; #ifdef TDROID u4 argsCount; #endif union { /* for JNI native methods: bottom of local reference segment */ u4 localRefCookie; /* for interpreted methods: saved current PC, for exception stack * traces and debugger traces */ const u2* currentPc; } xtra; /* Native return pointer for JIT, or 0 if interpreted */ const u2* returnAddr; #ifdef PAD_SAVE_AREA u4 pad3, pad4, pad5; #endif }; /* move between the stack save area and the frame pointer */ #define SAVEAREA_FROM_FP(_fp) ((StackSaveArea*)(_fp) -1) #define FP_FROM_SAVEAREA(_save) ((u4*) ((StackSaveArea*)(_save) +1)) /* when calling a function, get a pointer to outs[0] */ #define OUTS_FROM_FP(_fp, _argCount) \ ((u4*) ((u1*)SAVEAREA_FROM_FP(_fp) - sizeof(u4) * (_argCount))) /* * Method prototype structure, which refers to a protoIdx in a * particular DexFile. */ struct DexProto { const void* dexFile; /* file the idx refers to */ // const DexFile u4 protoIdx; /* index into proto_ids table of dexFile */ }; /* * Native function pointer type. * * "args[0]" holds the "this" pointer for virtual methods. * * The "Bridge" form is a super-set of the "Native" form; in many places * they are used interchangeably. Currently, all functions have all * arguments passed in, but some functions only care about the first two. * Passing extra arguments to a C function is (mostly) harmless. */ typedef void (*DalvikBridgeFunc)(const u4* args, JValue* pResult, const Method* method, struct Thread* self); typedef void (*DalvikNativeFunc)(const u4* args, JValue* pResult); /* vm-internal access flags and related definitions */ enum AccessFlags { ACC_MIRANDA = 0x8000, // method (internal to VM) JAVA_FLAGS_MASK = 0xffff, // bits set from Java sources (low 16) }; /* Use the top 16 bits of the access flags field for * other class flags. Code should use the *CLASS_FLAG*() * macros to set/get these flags. */ enum ClassFlags { CLASS_ISFINALIZABLE = (1 << 31), // class/ancestor overrides finalize() CLASS_ISARRAY = (1 << 30), // class is a "[*" CLASS_ISOBJECTARRAY = (1 << 29), // class is a "[L*" or "[[*" CLASS_ISCLASS = (1 << 28), // class is *the* class Class CLASS_ISREFERENCE = (1 << 27), // class is a soft/weak/phantom ref // only ISREFERENCE is set --> soft CLASS_ISWEAKREFERENCE = (1 << 26), // class is a weak reference CLASS_ISFINALIZERREFERENCE = (1 << 25), // class is a finalizer reference CLASS_ISPHANTOMREFERENCE = (1 << 24), // class is a phantom reference CLASS_MULTIPLE_DEFS = (1 << 23), // DEX verifier: defs in multiple DEXs /* unlike the others, these can be present in the optimized DEX file */ CLASS_ISOPTIMIZED = (1 << 17), // class may contain opt instrs CLASS_ISPREVERIFIED = (1 << 16), // class has been pre-verified }; /* bits we can reasonably expect to see set in a DEX access flags field */ #define EXPECTED_FILE_FLAGS \ (ACC_CLASS_MASK | CLASS_ISPREVERIFIED | CLASS_ISOPTIMIZED) /* * Get/set class flags. */ #define SET_CLASS_FLAG(clazz, flag) \ do { (clazz)->accessFlags |= (flag); } while (0) #define CLEAR_CLASS_FLAG(clazz, flag) \ do { (clazz)->accessFlags &= ~(flag); } while (0) #define IS_CLASS_FLAG_SET(clazz, flag) \ (((clazz)->accessFlags & (flag)) != 0) #define GET_CLASS_FLAG_GROUP(clazz, flags) \ ((u4)((clazz)->accessFlags & (flags))) #define RETURN_VOID() do { (void)(pResult); return; } while(0) #define RETURN_BOOLEAN(_val) do { pResult->i = (_val); return; } while(0) #define RETURN_INT(_val) do { pResult->i = (_val); return; } while(0) #define RETURN_LONG(_val) do { pResult->j = (_val); return; } while(0) #define RETURN_FLOAT(_val) do { pResult->f = (_val); return; } while(0) #define RETURN_DOUBLE(_val) do { pResult->d = (_val); return; } while(0) #define RETURN_PTR(_val) do { pResult->l = (Object*)(_val); return; } while(0) /* * Use the top 16 bits of the access flags field for other method flags. * Code should use the *METHOD_FLAG*() macros to set/get these flags. */ enum MethodFlags { METHOD_ISWRITABLE = (1 << 31), // the method's code is writable }; /* * Get/set method flags. */ #define SET_METHOD_FLAG(method, flag) \ do { (method)->accessFlags |= (flag); } while (0) #define CLEAR_METHOD_FLAG(method, flag) \ do { (method)->accessFlags &= ~(flag); } while (0) #define IS_METHOD_FLAG_SET(method, flag) \ (((method)->accessFlags & (flag)) != 0) #define GET_METHOD_FLAG_GROUP(method, flags) \ ((u4)((method)->accessFlags & (flags))) /* current state of the class, increasing as we progress */ enum ClassStatus { CLASS_ERROR = -1, CLASS_NOTREADY = 0, CLASS_IDX = 1, /* loaded, DEX idx in super or ifaces */ CLASS_LOADED = 2, /* DEX idx values resolved */ CLASS_RESOLVED = 3, /* part of linking */ CLASS_VERIFYING = 4, /* in the process of being verified */ CLASS_VERIFIED = 5, /* logically part of linking; done pre-init */ CLASS_INITIALIZING = 6, /* class init in progress */ CLASS_INITIALIZED = 7, /* ready to go */ }; /* * Used for iftable in ClassObject. */ struct InterfaceEntry { /* pointer to interface class */ ClassObject* clazz; /* * Index into array of vtable offsets. This points into the ifviPool, * which holds the vtables for all interfaces declared by this class. */ int* methodIndexArray; }; /* * There are three types of objects: * Class objects - an instance of java.lang.Class * Array objects - an object created with a "new array" instruction * Data objects - an object that is neither of the above * * We also define String objects. At present they're equivalent to * DataObject, but that may change. (Either way, they make some of the * code more obvious.) * * All objects have an Object header followed by type-specific data. */ struct Object { /* ptr to class object */ ClassObject* clazz; /* * A word containing either a "thin" lock or a "fat" monitor. See * the comments in Sync.c for a description of its layout. */ u4 lock; }; /* * Properly initialize an Object. * void DVM_OBJECT_INIT(Object *obj, ClassObject *clazz_) */ #define DVM_OBJECT_INIT(obj, clazz_) \ dvmSetFieldObject(obj, OFFSETOF_MEMBER(Object, clazz), clazz_) /* * Data objects have an Object header followed by their instance data. */ struct DataObject: Object { /* variable #of u4 slots; u8 uses 2 slots */ u4 instanceData[1]; }; /* * Strings are used frequently enough that we may want to give them their * own unique type. * * Using a dedicated type object to access the instance data provides a * performance advantage but makes the java/lang/String.java implementation * fragile. * * Currently this is just equal to DataObject, and we pull the fields out * like we do for any other object. */ struct StringObject: Object { /* variable #of u4 slots; u8 uses 2 slots */ u4 instanceData[1]; /** Returns this string's length in characters. */ int length() const; /** * Returns this string's length in bytes when encoded as modified UTF-8. * Does not include a terminating NUL byte. */ int utfLength() const; /** Returns this string's char[] as an ArrayObject. */ ArrayObject* array() const; /** Returns this string's char[] as a u2*. */ const u2* chars() const; }; /* * Array objects have these additional fields. * * We don't currently store the size of each element. Usually it's implied * by the instruction. If necessary, the width can be derived from * the first char of obj->clazz->descriptor. */ struct ArrayObject: Object { /* number of elements; immutable after init */ u4 length; /* * Array contents; actual size is (length * sizeof(type)). This is * declared as u8 so that the compiler inserts any necessary padding * (e.g. for EABI); the actual allocation may be smaller than 8 bytes. */ u8 contents[1]; }; /* * For classes created early and thus probably in the zygote, the * InitiatingLoaderList is kept in gDvm. Later classes use the structure in * Object Class. This helps keep zygote pages shared. */ struct InitiatingLoaderList { /* a list of initiating loader Objects; grown and initialized on demand */ Object** initiatingLoaders; /* count of loaders in the above list */ int initiatingLoaderCount; }; /* * Generic field header. We pass this around when we want a generic Field * pointer (e.g. for reflection stuff). Testing the accessFlags for * ACC_STATIC allows a proper up-cast. */ struct Field { ClassObject* clazz; /* class in which the field is declared */ const char* name; const char* signature; /* e.g. "I", "[C", "Landroid/os/Debug;" */ u4 accessFlags; }; /* * Static field. */ struct StaticField: Field { JValue value; /* initially set from DEX for primitives */ }; /* * Instance field. */ struct InstField: Field { /* * This field indicates the byte offset from the beginning of the * (Object *) to the actual instance data; e.g., byteOffset==0 is * the same as the object pointer (bug!), and byteOffset==4 is 4 * bytes farther. */ int byteOffset; }; /* * This defines the amount of space we leave for field slots in the * java.lang.Class definition. If we alter the class to have more than * this many fields, the VM will abort at startup. */ #define CLASS_FIELD_SLOTS 4 /* * Class objects have many additional fields. This is used for both * classes and interfaces, including synthesized classes (arrays and * primitive types). * * Class objects are unusual in that they have some fields allocated with * the system malloc (or LinearAlloc), rather than on the GC heap. This is * handy during initialization, but does require special handling when * discarding java.lang.Class objects. * * The separation of methods (direct vs. virtual) and fields (class vs. * instance) used in Dalvik works out pretty well. The only time it's * annoying is when enumerating or searching for things with reflection. */ struct ClassObject: Object { /* leave space for instance data; we could access fields directly if we freeze the definition of java/lang/Class */ #ifdef TDROID u4 instanceData[CLASS_FIELD_SLOTS * 2]; #else u4 instanceData[CLASS_FIELD_SLOTS]; #endif /* UTF-8 descriptor for the class; from constant pool, or on heap if generated ("[C") */ const char* descriptor; char* descriptorAlloc; /* access flags; low 16 bits are defined by VM spec */ u4 accessFlags; /* VM-unique class serial number, nonzero, set very early */ u4 serialNumber; /* DexFile from which we came; needed to resolve constant pool entries */ /* (will be NULL for VM-generated, e.g. arrays and primitive classes) */ DvmDex* pDvmDex; /* state of class initialization */ ClassStatus status; /* if class verify fails, we must return same error on subsequent tries */ ClassObject* verifyErrorClass; /* threadId, used to check for recursive <clinit> invocation */ u4 initThreadId; /* * Total object size; used when allocating storage on gc heap. (For * interfaces and abstract classes this will be zero.) */ size_t objectSize; /* arrays only: class object for base element, for instanceof/checkcast (for String[][][], this will be String) */ ClassObject* elementClass; /* arrays only: number of dimensions, e.g. int[][] is 2 */ int arrayDim; /* primitive type index, or PRIM_NOT (-1); set for generated prim classes */ PrimitiveType primitiveType; /* superclass, or NULL if this is java.lang.Object */ ClassObject* super; /* defining class loader, or NULL for the "bootstrap" system loader */ Object* classLoader; /* initiating class loader list */ /* NOTE: for classes with low serialNumber, these are unused, and the values are kept in a table in gDvm. */ InitiatingLoaderList initiatingLoaderList; /* array of interfaces this class implements directly */ int interfaceCount; ClassObject** interfaces; /* static, private, and <init> methods */ int directMethodCount; Method* directMethods; /* virtual methods defined in this class; invoked through vtable */ int virtualMethodCount; Method* virtualMethods; /* * Virtual method table (vtable), for use by "invoke-virtual". The * vtable from the superclass is copied in, and virtual methods from * our class either replace those from the super or are appended. */ int vtableCount; Method** vtable; /* * Interface table (iftable), one entry per interface supported by * this class. That means one entry for each interface we support * directly, indirectly via superclass, or indirectly via * superinterface. This will be null if neither we nor our superclass * implement any interfaces. * * Why we need this: given "class Foo implements Face", declare * "Face faceObj = new Foo()". Invoke faceObj.blah(), where "blah" is * part of the Face interface. We can't easily use a single vtable. * * For every interface a concrete class implements, we create a list of * virtualMethod indices for the methods in the interface. */ int iftableCount; InterfaceEntry* iftable; /* * The interface vtable indices for iftable get stored here. By placing * them all in a single pool for each class that implements interfaces, * we decrease the number of allocations. */ int ifviPoolCount; int* ifviPool; /* instance fields * * These describe the layout of the contents of a DataObject-compatible * Object. Note that only the fields directly defined by this class * are listed in ifields; fields defined by a superclass are listed * in the superclass's ClassObject.ifields. * * All instance fields that refer to objects are guaranteed to be * at the beginning of the field list. ifieldRefCount specifies * the number of reference fields. */ int ifieldCount; int ifieldRefCount; // number of fields that are object refs InstField* ifields; /* bitmap of offsets of ifields */ u4 refOffsets; /* source file name, if known */ const char* sourceFile; /* static fields */ int sfieldCount; StaticField sfields[]; /* MUST be last item */ }; /* * A method. We create one of these for every method in every class * we load, so try to keep the size to a minimum. * * Much of this comes from and could be accessed in the data held in shared * memory. We hold it all together here for speed. Everything but the * pointers could be held in a shared table generated by the optimizer; * if we're willing to convert them to offsets and take the performance * hit (e.g. "meth->insns" becomes "baseAddr + meth->insnsOffset") we * could move everything but "nativeFunc". */ struct Method { /* the class we are a part of */ ClassObject* clazz; /* access flags; low 16 bits are defined by spec (could be u2?) */ u4 accessFlags; /* * For concrete virtual methods, this is the offset of the method * in "vtable". * * For abstract methods in an interface class, this is the offset * of the method in "iftable[n]->methodIndexArray". */ u2 methodIndex; /* * Method bounds; not needed for an abstract method. * * For a native method, we compute the size of the argument list, and * set "insSize" and "registerSize" equal to it. */ u2 registersSize; /* ins + locals */ u2 outsSize; u2 insSize; /* method name, e.g. "<init>" or "eatLunch" */ const char* name; /* * Method prototype descriptor string (return and argument types). * * TODO: This currently must specify the DexFile as well as the proto_ids * index, because generated Proxy classes don't have a DexFile. We can * remove the DexFile* and reduce the size of this struct if we generate * a DEX for proxies. */ DexProto prototype; /* short-form method descriptor string */ const char* shorty; /* * The remaining items are not used for abstract or native methods. * (JNI is currently hijacking "insns" as a function pointer, set * after the first call. For internal-native this stays null.) */ /* the actual code */ const u2* insns; /* instructions, in memory-mapped .dex */ /* JNI: cached argument and return-type hints */ int jniArgInfo; /* * JNI: native method ptr; could be actual function or a JNI bridge. We * don't currently discriminate between DalvikBridgeFunc and * DalvikNativeFunc; the former takes an argument superset (i.e. two * extra args) which will be ignored. If necessary we can use * insns==NULL to detect JNI bridge vs. internal native. */ DalvikBridgeFunc nativeFunc; /* * JNI: true if this static non-synchronized native method (that has no * reference arguments) needs a JNIEnv* and jclass/jobject. Libcore * uses this. */ bool fastJni; /* * JNI: true if this method has no reference arguments. This lets the JNI * bridge avoid scanning the shorty for direct pointers that need to be * converted to local references. * * TODO: replace this with a list of indexes of the reference arguments. */ bool noRef; /* * JNI: true if we should log entry and exit. This is the only way * developers can log the local references that are passed into their code. * Used for debugging JNI problems in third-party code. */ bool shouldTrace; /* * Register map data, if available. This will point into the DEX file * if the data was computed during pre-verification, or into the * linear alloc area if not. */ const RegisterMap* registerMap; /* set if method was called during method profiling */ bool inProfile; }; INLINE bool dvmIsPublicMethod(const Method* method) { return (method->accessFlags & ACC_PUBLIC) != 0; } INLINE bool dvmIsProtectedMethod(const Method* method) { return (method->accessFlags & ACC_PROTECTED) != 0; } INLINE bool dvmIsPrivateMethod(const Method* method) { return (method->accessFlags & ACC_PRIVATE) != 0; } INLINE bool dvmIsStaticMethod(const Method* method) { return (method->accessFlags & ACC_STATIC) != 0; } INLINE bool dvmIsSynchronizedMethod(const Method* method) { return (method->accessFlags & ACC_SYNCHRONIZED) != 0; } INLINE bool dvmIsDeclaredSynchronizedMethod(const Method* method) { return (method->accessFlags & ACC_DECLARED_SYNCHRONIZED) != 0; } INLINE bool dvmIsFinalMethod(const Method* method) { return (method->accessFlags & ACC_FINAL) != 0; } INLINE bool dvmIsNativeMethod(const Method* method) { return (method->accessFlags & ACC_NATIVE) != 0; } INLINE bool dvmIsAbstractMethod(const Method* method) { return (method->accessFlags & ACC_ABSTRACT) != 0; } INLINE bool dvmIsSyntheticMethod(const Method* method) { return (method->accessFlags & ACC_SYNTHETIC) != 0; } INLINE bool dvmIsMirandaMethod(const Method* method) { return (method->accessFlags & ACC_MIRANDA) != 0; } INLINE bool dvmIsConstructorMethod(const Method* method) { return *method->name == '<'; } #define BYTE_OFFSET(_ptr, _offset) ((void*) (((u1*)(_ptr)) + (_offset))) INLINE JValue* dvmFieldPtr(const Object* obj, int offset) { return ((JValue*) BYTE_OFFSET(obj, offset) ); } INLINE bool dvmGetFieldBoolean(const Object* obj, int offset) { return ((JValue*) BYTE_OFFSET(obj, offset) )->z; } INLINE s1 dvmGetFieldByte(const Object* obj, int offset) { return ((JValue*) BYTE_OFFSET(obj, offset) )->b; } INLINE s2 dvmGetFieldShort(const Object* obj, int offset) { return ((JValue*) BYTE_OFFSET(obj, offset) )->s; } INLINE u2 dvmGetFieldChar(const Object* obj, int offset) { return ((JValue*) BYTE_OFFSET(obj, offset) )->c; } INLINE s4 dvmGetFieldInt(const Object* obj, int offset) { return ((JValue*) BYTE_OFFSET(obj, offset) )->i; } INLINE s8 dvmGetFieldLong(const Object* obj, int offset) { return ((JValue*) BYTE_OFFSET(obj, offset) )->j; } INLINE float dvmGetFieldFloat(const Object* obj, int offset) { return ((JValue*) BYTE_OFFSET(obj, offset) )->f; } INLINE double dvmGetFieldDouble(const Object* obj, int offset) { return ((JValue*) BYTE_OFFSET(obj, offset) )->d; } INLINE Object* dvmGetFieldObject(const Object* obj, int offset) { return (Object*) (((JValue*) BYTE_OFFSET(obj, offset) )->l); } INLINE float dvmU4ToFloat(u4 val) { union { u4 in; float out; } conv; conv.in = val; return conv.out; } struct InterpSaveState { const u2* pc; // Dalvik PC u4* curFrame; // Dalvik frame pointer const Method *method; // Method being executed DvmDex* methodClassDex; JValue retval; void* bailPtr; #if defined(WITH_TRACKREF_CHECKS) int debugTrackedRefStart; #else int unused; // Keep struct size constant #endif struct InterpSaveState* prev; // To follow nested activations } __attribute__ ((__packed__)); /* * Interpreter control struction. Packed into a long long to enable * atomic updates. */ union InterpBreak { volatile int64_t all; struct { uint16_t subMode; uint8_t breakFlags; int8_t unused; /* for future expansion */ #ifndef DVM_NO_ASM_INTERP void* curHandlerTable; #else int32_t unused1; #endif } ctl; }; /* * Information we store for each slot in the reference table. */ struct IndirectRefSlot { Object* obj; /* object pointer itself, NULL if the slot is unused */ u4 serial; /* slot serial number */ }; union IRTSegmentState { u4 all; struct { u4 topIndex:16; /* index of first unused entry */ u4 numHoles:16; /* #of holes in entire table */ } parts; }; class iref_iterator { private: IndirectRefSlot* table_; size_t i_; size_t capacity_; }; enum IndirectRefKind { kIndirectKindInvalid = 0, kIndirectKindLocal = 1, kIndirectKindGlobal = 2, kIndirectKindWeakGlobal = 3 }; struct IndirectRefTable { public: typedef iref_iterator iterator; /* semi-public - read/write by interpreter in native call handler */ IRTSegmentState segmentState; /* * private: * * TODO: we can't make these private as long as the interpreter * uses offsetof, since private member data makes us non-POD. */ /* bottom of the stack */ IndirectRefSlot* table_; /* bit mask, ORed into all irefs */ IndirectRefKind kind_; /* #of entries we have space for */ size_t alloc_entries_; /* max #of entries allowed */ size_t max_entries_; }; enum ThreadStatus { THREAD_UNDEFINED = -1, /* makes enum compatible with int32_t */ /* these match up with JDWP values */ THREAD_ZOMBIE = 0, /* TERMINATED */ THREAD_RUNNING = 1, /* RUNNABLE or running now */ THREAD_TIMED_WAIT = 2, /* TIMED_WAITING in Object.wait() */ THREAD_MONITOR = 3, /* BLOCKED on a monitor */ THREAD_WAIT = 4, /* WAITING in Object.wait() */ /* non-JDWP states */ THREAD_INITIALIZING = 5, /* allocated, not yet running */ THREAD_STARTING = 6, /* started, not yet on thread list */ THREAD_NATIVE = 7, /* off in a JNI native method */ THREAD_VMWAIT = 8, /* waiting on a VM resource */ THREAD_SUSPENDED = 9, /* suspended, usually by GC or debugger */ }; typedef bool (*SafePointCallback)(struct Thread* thread, void* arg); /* * Error constants. */ enum JdwpError { ERR_NONE = 0, ERR_INVALID_THREAD = 10, ERR_INVALID_THREAD_GROUP = 11, ERR_INVALID_PRIORITY = 12, ERR_THREAD_NOT_SUSPENDED = 13, ERR_THREAD_SUSPENDED = 14, ERR_INVALID_OBJECT = 20, ERR_INVALID_CLASS = 21, ERR_CLASS_NOT_PREPARED = 22, ERR_INVALID_METHODID = 23, ERR_INVALID_LOCATION = 24, ERR_INVALID_FIELDID = 25, ERR_INVALID_FRAMEID = 30, ERR_NO_MORE_FRAMES = 31, ERR_OPAQUE_FRAME = 32, ERR_NOT_CURRENT_FRAME = 33, ERR_TYPE_MISMATCH = 34, ERR_INVALID_SLOT = 35, ERR_DUPLICATE = 40, ERR_NOT_FOUND = 41, ERR_INVALID_MONITOR = 50, ERR_NOT_MONITOR_OWNER = 51, ERR_INTERRUPT = 52, ERR_INVALID_CLASS_FORMAT = 60, ERR_CIRCULAR_CLASS_DEFINITION = 61, ERR_FAILS_VERIFICATION = 62, ERR_ADD_METHOD_NOT_IMPLEMENTED = 63, ERR_SCHEMA_CHANGE_NOT_IMPLEMENTED = 64, ERR_INVALID_TYPESTATE = 65, ERR_HIERARCHY_CHANGE_NOT_IMPLEMENTED = 66, ERR_DELETE_METHOD_NOT_IMPLEMENTED = 67, ERR_UNSUPPORTED_VERSION = 68, ERR_NAMES_DONT_MATCH = 69, ERR_CLASS_MODIFIERS_CHANGE_NOT_IMPLEMENTED = 70, ERR_METHOD_MODIFIERS_CHANGE_NOT_IMPLEMENTED = 71, ERR_NOT_IMPLEMENTED = 99, ERR_NULL_POINTER = 100, ERR_ABSENT_INFORMATION = 101, ERR_INVALID_EVENT_TYPE = 102, ERR_ILLEGAL_ARGUMENT = 103, ERR_OUT_OF_MEMORY = 110, ERR_ACCESS_DENIED = 111, ERR_VM_DEAD = 112, ERR_INTERNAL = 113, ERR_UNATTACHED_THREAD = 115, ERR_INVALID_TAG = 500, ERR_ALREADY_INVOKING = 502, ERR_INVALID_INDEX = 503, ERR_INVALID_LENGTH = 504, ERR_INVALID_STRING = 506, ERR_INVALID_CLASS_LOADER = 507, ERR_INVALID_ARRAY = 508, ERR_TRANSPORT_LOAD = 509, ERR_TRANSPORT_INIT = 510, ERR_NATIVE_METHOD = 511, ERR_INVALID_COUNT = 512, }; typedef u8 ObjectId; struct DebugInvokeReq { /* boolean; only set when we're in the tail end of an event handler */ bool ready; /* boolean; set if the JDWP thread wants this thread to do work */ bool invokeNeeded; /* request */ Object* obj; /* not used for ClassType.InvokeMethod */ Object* thread; ClassObject* clazz; Method* method; u4 numArgs; u8* argArray; /* will be NULL if numArgs==0 */ u4 options; /* result */ JdwpError err; u1 resultTag; JValue resultValue; ObjectId exceptObj; /* condition variable to wait on while the method executes */ pthread_mutex_t lock; pthread_cond_t cv; }; struct AllocProfState { bool enabled; // is allocation tracking enabled? int allocCount; // #of objects allocated int allocSize; // cumulative size of objects int failedAllocCount; // #of times an allocation failed int failedAllocSize; // cumulative size of failed allocations int freeCount; // #of objects freed int freeSize; // cumulative size of freed objects int gcCount; // #of times an allocation triggered a GC int classInitCount; // #of initialized classes u8 classInitTime; // cumulative time spent in class init (nsec) }; struct Monitor; struct ReferenceTable { Object** nextEntry; /* top of the list */ Object** table; /* bottom of the list */ int allocEntries; /* #of entries we have space for */ int maxEntries; /* max #of entries allowed */ }; struct Thread { /* * Interpreter state which must be preserved across nested * interpreter invocations (via JNI callbacks). Must be the first * element in Thread. */ InterpSaveState interpSave; /* small unique integer; useful for "thin" locks and debug messages */ u4 threadId; /* * Begin interpreter state which does not need to be preserved, but should * be located towards the beginning of the Thread structure for * efficiency. */ /* * interpBreak contains info about the interpreter mode, as well as * a count of the number of times the thread has been suspended. When * the count drops to zero, the thread resumes. */ InterpBreak interpBreak; /* * "dbgSuspendCount" is the portion of the suspend count that the * debugger is responsible for. This has to be tracked separately so * that we can recover correctly if the debugger abruptly disconnects * (suspendCount -= dbgSuspendCount). The debugger should not be able * to resume GC-suspended threads, because we ignore the debugger while * a GC is in progress. * * Both of these are guarded by gDvm.threadSuspendCountLock. * * Note the non-debug component will rarely be other than 1 or 0 -- (not * sure it's even possible with the way mutexes are currently used.) */ int suspendCount; int dbgSuspendCount; u1* cardTable; /* current limit of stack; flexes for StackOverflowError */ const u1* interpStackEnd; /* FP of bottom-most (currently executing) stack frame on interp stack */ void* XcurFrame; /* current exception, or NULL if nothing pending */ Object* exception; bool debugIsMethodEntry; /* interpreter stack size; our stacks are fixed-length */ int interpStackSize; bool stackOverflowed; /* thread handle, as reported by pthread_self() */ pthread_t handle; /* Assembly interpreter handler tables */ #ifndef DVM_NO_ASM_INTERP void* mainHandlerTable; // Table of actual instruction handler void* altHandlerTable; // Table of breakout handlers #else void* unused0; // Consume space to keep offsets void* unused1; // the same between builds with #endif /* * singleStepCount is a countdown timer used with the breakFlag * kInterpSingleStep. If kInterpSingleStep is set in breakFlags, * singleStepCount will decremented each instruction execution. * Once it reaches zero, the kInterpSingleStep flag in breakFlags * will be cleared. This can be used to temporarily prevent * execution from re-entering JIT'd code or force inter-instruction * checks by delaying the reset of curHandlerTable to mainHandlerTable. */ int singleStepCount; #ifdef WITH_JIT struct JitToInterpEntries jitToInterpEntries; /* * Whether the current top VM frame is in the interpreter or JIT cache: * NULL : in the interpreter * non-NULL: entry address of the JIT'ed code (the actual value doesn't * matter) */ void* inJitCodeCache; unsigned char* pJitProfTable; int jitThreshold; const void* jitResumeNPC; // Translation return point const u4* jitResumeNSP; // Native SP at return point const u2* jitResumeDPC; // Dalvik inst following single-step JitState jitState; int icRechainCount; const void* pProfileCountdown; const ClassObject* callsiteClass; const Method* methodToCall; #endif /* JNI local reference tracking */ IndirectRefTable jniLocalRefTable; #if defined(WITH_JIT) #if defined(WITH_SELF_VERIFICATION) /* Buffer for register state during self verification */ struct ShadowSpace* shadowSpace; #endif int currTraceRun; int totalTraceLen; // Number of Dalvik insts in trace const u2* currTraceHead; // Start of the trace we're building const u2* currRunHead; // Start of run we're building int currRunLen; // Length of run in 16-bit words const u2* lastPC; // Stage the PC for the threaded interpreter const Method* traceMethod; // Starting method of current trace intptr_t threshFilter[JIT_TRACE_THRESH_FILTER_SIZE]; JitTraceRun trace[MAX_JIT_RUN_LEN]; #endif /* * Thread's current status. Can only be changed by the thread itself * (i.e. don't mess with this from other threads). */ volatile ThreadStatus status; /* thread ID, only useful under Linux */ pid_t systemTid; /* start (high addr) of interp stack (subtract size to get malloc addr) */ u1* interpStackStart; /* the java/lang/Thread that we are associated with */ Object* threadObj; /* the JNIEnv pointer associated with this thread */ JNIEnv* jniEnv; /* internal reference tracking */ ReferenceTable internalLocalRefTable; /* JNI native monitor reference tracking (initialized on first use) */ ReferenceTable jniMonitorRefTable; /* hack to make JNI_OnLoad work right */ Object* classLoaderOverride; /* mutex to guard the interrupted and the waitMonitor members */ pthread_mutex_t waitMutex; /* pointer to the monitor lock we're currently waiting on */ /* guarded by waitMutex */ /* TODO: consider changing this to Object* for better JDWP interaction */ Monitor* waitMonitor; /* thread "interrupted" status; stays raised until queried or thrown */ /* guarded by waitMutex */ bool interrupted; /* links to the next thread in the wait set this thread is part of */ struct Thread* waitNext; /* object to sleep on while we are waiting for a monitor */ pthread_cond_t waitCond; /* * Set to true when the thread is in the process of throwing an * OutOfMemoryError. */ bool throwingOOME; /* links to rest of thread list; grab global lock before traversing */ struct Thread* prev; struct Thread* next; /* used by threadExitCheck when a thread exits without detaching */ int threadExitCheckCount; /* JDWP invoke-during-breakpoint support */ DebugInvokeReq invokeReq; /* base time for per-thread CPU timing (used by method profiling) */ bool cpuClockBaseSet; u8 cpuClockBase; /* memory allocation profiling state */ AllocProfState allocProf; #ifdef WITH_JNI_STACK_CHECK u4 stackCrc; #endif #if WITH_EXTRA_GC_CHECKS > 1 /* PC, saved on every instruction; redundant with StackSaveArea */ const u2* currentPc2; #endif /* Safepoint callback state */ pthread_mutex_t callbackMutex; SafePointCallback callback; void* callbackArg; #if defined(ARCH_IA32) && defined(WITH_JIT) u4 spillRegion[MAX_SPILL_JIT_IA]; #endif }; #endif // _DALVIK_OO_OBJECT_4_H__
[ "imcoffeeboy@foxmail.com" ]
imcoffeeboy@foxmail.com
19eda9bfd903e71d6d2fc05a9032b197644190c4
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/browser/ui/views/controls/page_switcher_view.cc
3ffbcfe628f91cc69f56f37cd4b0d833a5a64a4d
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
1,012
cc
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/controls/page_switcher_view.h" #include <utility> #include "chrome/browser/ui/views/page_info/page_info_view_factory.h" #include "ui/views/layout/fill_layout.h" PageSwitcherView::PageSwitcherView(std::unique_ptr<views::View> initial_page) { SetLayoutManager(std::make_unique<views::FillLayout>()); current_page_ = AddChildView(std::move(initial_page)); } PageSwitcherView::~PageSwitcherView() = default; void PageSwitcherView::SwitchToPage(std::unique_ptr<views::View> page) { if (current_page_) { RemoveChildViewT(std::exchange(current_page_, nullptr).get()); } current_page_ = AddChildView(std::move(page)); PreferredSizeChanged(); } views::View* PageSwitcherView::GetCurrentPage() { return current_page_; } void PageSwitcherView::ChildPreferredSizeChanged(views::View* child) { PreferredSizeChanged(); }
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
610b54357ae1410bbd2ff6343c29bace81884893
fae551eb54ab3a907ba13cf38aba1db288708d92
/third_party/blink/renderer/modules/clipboard/clipboard.h
1bdb00e116967c9719d94bee0a9c5a4d61790f0b
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "Apache-2.0", "MIT" ]
permissive
xtblock/chromium
d4506722fc6e4c9bc04b54921a4382165d875f9a
5fe0705b86e692c65684cdb067d9b452cc5f063f
refs/heads/main
2023-04-26T18:34:42.207215
2021-05-27T04:45:24
2021-05-27T04:45:24
371,258,442
2
1
BSD-3-Clause
2021-05-27T05:36:28
2021-05-27T05:36:28
null
UTF-8
C++
false
false
1,588
h
// Copyright 2017 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 THIRD_PARTY_BLINK_RENDERER_MODULES_CLIPBOARD_CLIPBOARD_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_CLIPBOARD_CLIPBOARD_H_ #include "base/macros.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/core/dom/events/event_target.h" #include "third_party/blink/renderer/core/fileapi/blob.h" #include "third_party/blink/renderer/modules/clipboard/clipboard_item.h" #include "third_party/blink/renderer/platform/supplementable.h" namespace blink { class ClipboardItemOptions; class Navigator; class ScriptState; class Clipboard : public EventTargetWithInlineData, public Supplement<Navigator> { DEFINE_WRAPPERTYPEINFO(); public: static const char kSupplementName[]; static Clipboard* clipboard(Navigator&); explicit Clipboard(Navigator&); ScriptPromise read(ScriptState*); ScriptPromise read(ScriptState*, ClipboardItemOptions*); ScriptPromise readText(ScriptState*); ScriptPromise write(ScriptState*, const HeapVector<Member<ClipboardItem>>&); ScriptPromise writeText(ScriptState*, const String&); // EventTarget const AtomicString& InterfaceName() const override; ExecutionContext* GetExecutionContext() const override; void Trace(Visitor*) const override; private: DISALLOW_COPY_AND_ASSIGN(Clipboard); }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_CLIPBOARD_CLIPBOARD_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
49e12151d4c0e118eb2d16876ae680e9f01ed73d
bc2880e89eb4eea93d0b324e86ded4211f2e067b
/DesignPattern/DesignPattern/Paralysis.cpp
7a3a44f1f0b51f2bb6867e9c5d844ba12d101bd4
[]
no_license
2018intern001/intern_Abdullah
ccdb7029677470ad1c639c61d5a59f257a388ca3
72763f65b761149ed2f876ba9945187b125c41fb
refs/heads/master
2020-03-22T07:34:41.355009
2018-07-06T06:33:01
2018-07-06T06:33:01
139,709,274
0
0
null
null
null
null
UTF-8
C++
false
false
716
cpp
#include "stdafx.h" #include "Paralysis.h" #include "Unit.h" #include "Normal.h" Paralysis::Paralysis() { expiresInHowManyTurns = 3; } Paralysis::~Paralysis() { } string Paralysis::Name() { string status = "Paralysis ("; return status.append(to_string(expiresInHowManyTurns)).append(")"); } bool Paralysis::StatusEffectAction(Unit* unit){ probabilityOfFailure = 50; int random_variable = rand() % 100; DecreaseTurn(); if (ShouldExpire()) { unit->statusEffect = new Normal(); } //cout << random_variable << '\n'; if (random_variable <50) { return false; } else { cout << "\t" << unit->GetName() << " is Paralysed.\n"; return true; } }
[ "40792648+2018intern001@users.noreply.github.com" ]
40792648+2018intern001@users.noreply.github.com
43d666e6a6b5385c2994600c7e0a3b83245941b5
5b36dddd66e1086a7968dc74e7764a8f803916a8
/Rasterizer/src/Graphics/Vertex.cpp
92da11e0d9c156cf61f44c547c7c01e15bd7f50e
[ "MIT" ]
permissive
elouanhaquin/Rasterizer
fd78f8a8edd654ed9abd077d0f73f931ba272d36
500a5dbb848018f8a13c13e7ef0533650eadcab2
refs/heads/main
2023-02-27T20:51:59.065952
2021-02-01T14:55:02
2021-02-01T14:55:02
334,979,583
0
0
null
null
null
null
UTF-8
C++
false
false
842
cpp
#include <iostream> #include "../../includes/Graphics/Vertex.h" using namespace Graphics; Vertex::Vertex(const Vec3& p_position, const Vec3& p_normal, const Color& p_color) : m_position {p_position}, m_normal {p_normal}, m_color {p_color} { m_normal.Normalize(); // std::cout << "Vertex created" << std::endl; } Vertex::~Vertex() { // std::cout << "Vertex destroyed" << std::endl; } void Vertex::SetPosition(const Vec3& p_position) { m_position = p_position; } void Graphics::Vertex::SetNormal(const Vec3& p_normal) { m_normal = p_normal; } const Vec3& Vertex::GetPosition() const { return m_position; } const Vec3& Vertex::GetNormal() const { return m_normal; } const Color& Vertex::GetColor() const { return m_color; }
[ "haquin.elouan@gmail.com" ]
haquin.elouan@gmail.com
888a4e86cac59644c2c5c2c023ed81e74360f1a1
cc59dad34b3a67b2db4e2bc2b246fc96b3637374
/IRTest_Receive/IRTest_Receive.ino
59f05e260eb6e18510e963ef2a996e19137fe4cb
[]
no_license
paulnarz/icebox
93813a1fa02640ace126c5188a11f6180d4afc71
36712801fa4ce50965990a4ad42c615f793597ea
refs/heads/master
2016-09-06T03:26:30.105318
2015-06-24T03:56:02
2015-06-24T03:56:02
37,891,423
0
0
null
null
null
null
UTF-8
C++
false
false
1,275
ino
#include <IRremote.h> #include <IRremoteInt.h> const int RECV_PIN = 2; IRrecv irrecv(RECV_PIN); IRsend irsend; decode_results results; void setup() { Serial.begin(9600); irrecv.enableIRIn(); // Start the receiver irrecv.blink13(true); Serial.print("TIMER_PWM_PIN: "); Serial.print(TIMER_PWM_PIN); Serial.println(); Serial.println(); Serial.print("decode_type"); Serial.print("\t"); Serial.print("value"); Serial.print("\t"); Serial.print("valueHEX"); Serial.print("\t"); Serial.print("bits"); Serial.println(); } void loop() { if (irrecv.decode(&results)) { if (results.decode_type == NEC) { Serial.print("NEC"); } else if (results.decode_type == SONY) { Serial.print("SONY"); } else if (results.decode_type == RC5) { Serial.print("RC5"); } else if (results.decode_type == RC6) { Serial.print("RC6"); } else if (results.decode_type == UNKNOWN) { Serial.print("UNKNOWN"); } else { Serial.print(results.decode_type); } Serial.print("\t"); Serial.print(results.value); Serial.print("\t"); Serial.print(results.value, HEX); Serial.print("\t"); Serial.print(results.bits); Serial.println(); irrecv.resume(); // Receive the next value } }
[ "paulnarz@gmail.com" ]
paulnarz@gmail.com
41078cd33706f2a2a69985ddcce66283f53f876f
274d432100208789a872dae493d0fa2c6fb6f1e8
/uva108.cpp
23e52b08979cb0adb27ae43c837b55790c8f86fc
[]
no_license
CatalinFetoiu/Competitive-Programming
45d8dd162283d234bf0192b386bef5d13fa89454
a32d7d22ed21065764aa2f2e550626df8fc91905
refs/heads/master
2021-06-23T00:32:51.733333
2017-09-09T17:09:42
2017-09-09T17:09:42
102,971,071
0
0
null
null
null
null
UTF-8
C++
false
false
1,431
cpp
#include <cstdio> #include <iostream> #include <vector> #include <cstdlib> #include <cstring> #include <algorithm> #include <limits.h> using namespace std; int kadane(vector<int> v, int* start, int* finish) { int sum = 0; int maxSum = 0; int local_start = 0; *finish = -1; for(int i = 0; i < v.size(); i++) { sum += v[i]; if(sum < 0) { sum = 0; local_start = i + 1; } if(sum > maxSum) { maxSum = sum; *start = local_start; *finish = i; } } if(*finish != -1) return maxSum; //daca toate elementele sunt negative maxSum = v[0]; *start = 0; *finish = 0; for(int i = 1 ; i < v.size(); i++) { if(v[i] > maxSum) { maxSum = v[i]; *start = i; *finish = i; } } return maxSum; } int uva(vector<vector<int> > a) { int maxSum = INT_MIN; int sum, start, finish; vector<int> rowSum(a.size(), 0); for(int left = 0; left < a.size(); left++) { fill(rowSum.begin(), rowSum.end(), 0); for(int right = left; right < a.size(); right++) { for(int i = 0; i < a.size(); i++) rowSum[i] += a[i][right]; sum = kadane(rowSum, &start, &finish); if(sum > maxSum) maxSum = sum; } } return maxSum; } int main() { int n; scanf("%d", &n); vector<vector<int> > a; a.resize(n); for(int i = 0; i < a.size(); i++) { a[i].resize(n); for(int j = 0; j < a.size(); j++) cin >> a[i][j]; } printf("%d\n", uva(a)); return 0; }
[ "fetoiucatalin@gmail.com" ]
fetoiucatalin@gmail.com
e3a971da72a50af64a39897e14f29eacc6ccc1fd
c3041d2dc117300ac1de38bbca40f90462d157d1
/src/shared/util/timedefs.h
b58e684e9f4d6ac8e952a35dd4d0e41ac6096757
[]
no_license
srdgame/srdgame_mmo
2efe3749906a8539604ad3a59f7a686727766633
0b3fe2a58b18ed1b49e10d2ecb1deb9f3df0daea
refs/heads/master
2021-08-02T19:06:57.639310
2013-02-02T10:57:35
2013-02-02T10:57:35
128,683
0
1
null
null
null
null
UTF-8
C++
false
false
716
h
#ifndef TIME_DEFS_H_ #define TIME_DEFS_H_ #include <ctime> #include <sys/time.h> namespace srdgame { /// platform-abstracted tick retrieval inline unsigned int tick(void) { #if defined(WIN32) return GetTickCount(); #elif (defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0 && defined(_POSIX_MONOTONIC_CLOCK) /* posix compliant */) || (defined(__FreeBSD_cc_version) && __FreeBSD_cc_version >= 500005 /* FreeBSD >= 5.1.0 */) struct timespec tval; clock_gettime(CLOCK_MONOTONIC, &tval); return tval.tv_sec * 1000 + tval.tv_nsec / 1000000; #else struct timeval tval; gettimeofday(&tval, NULL); return tval.tv_sec * 1000 + tval.tv_usec / 1000; #endif } inline unsigned int gettick(void) { return tick(); } } #endif
[ "srdgame@gmail.com" ]
srdgame@gmail.com
3053f747131b51dc0832d4296a97757de61c1b09
43506cb351f9d180bc761b70a4611ebd6b9427ac
/modules/cvv/src/qtutil/filter/diffFilterWidget.cpp
7a819d1068efbd8dbed626ba56f477b9d6d694cd
[ "BSD-3-Clause" ]
permissive
cdmh/opencv_contrib
de74a6883a79cc13c075256048d352a839af0ee3
d0c3a2ee035e85beea76aad546025815482a5253
refs/heads/master
2021-01-20T16:12:48.507208
2014-12-05T11:16:56
2014-12-05T11:16:56
23,887,605
0
1
null
null
null
null
UTF-8
C++
false
false
3,518
cpp
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <unordered_map> #include <QComboBox> #include <QLabel> #include <QString> #include <QVBoxLayout> #include "../../util/util.hpp" #include "diffFilterWidget.hpp" namespace cvv { namespace qtutil { DiffFilterFunction::DiffFilterFunction(QWidget *parent) : FilterFunctionWidget<2, 1>{ parent }, filterType_{ DiffFilterType::GRAYSCALE } { auto layout = util::make_unique<QVBoxLayout>(); auto comboBox = util::make_unique<QComboBox>(); filterMap_.insert( std::make_pair<std::string, std::function<void(void)>>( "Hue", [this]() { filterType_ = DiffFilterType::HUE; })); filterMap_.insert( std::make_pair<std::string, std::function<void(void)>>( "Saturation", [this]() { filterType_ = DiffFilterType::SATURATION; })); filterMap_.insert( std::make_pair<std::string, std::function<void(void)>>( "Value", [this]() { filterType_ = DiffFilterType::VALUE; })); filterMap_.insert( std::make_pair<std::string, std::function<void(void)>>( "Grayscale", [this]() { filterType_ = DiffFilterType::GRAYSCALE; })); // Register filter names at comboBox comboBox->addItems(DiffFilterFunction::extractStringListfromMap()); connect(comboBox.get(), SIGNAL(currentIndexChanged(const QString &)), this, SLOT(updateFilterType(const QString &))); // Add title of comboBox and comboBox to the layout layout->addWidget( util::make_unique<QLabel>("Select a filter").release()); layout->addWidget(comboBox.release()); setLayout(layout.release()); } void DiffFilterFunction::applyFilter(InputArray in, OutputArray out) const { auto check = checkInput(in); if (!check.first) { return; } if (filterType_ == DiffFilterType::GRAYSCALE) { out.at(0).get() = cv::abs(in.at(0).get() - in.at(1).get()); return; } cv::Mat originalHSV, filteredHSV; cv::cvtColor(in.at(0).get(), originalHSV, CV_BGR2HSV); cv::cvtColor(in.at(1).get(), filteredHSV, CV_BGR2HSV); auto diffHSV = cv::abs(originalHSV - filteredHSV); std::array<cv::Mat, 3> splitVector; cv::split(diffHSV, splitVector.data()); out.at(0).get() = splitVector.at(static_cast<size_t>(filterType_)); } std::pair<bool, QString> DiffFilterFunction::checkInput(InputArray in) const { if (in.at(0).get().size() != in.at(1).get().size()) { return std::make_pair(false, "Images need to have same size"); } size_t inChannels = in.at(0).get().channels(); if (inChannels != static_cast<size_t>(in.at(1).get().channels())) { return std::make_pair( false, "Images need to have same number of channels"); } if (inChannels == 1 && filterType_ != DiffFilterType::GRAYSCALE) { return std::make_pair(false, "Images are grayscale, but " "selected Filter can only " "progress 3-channel images"); } if (inChannels != 1 && inChannels != 3 && inChannels != 4) { return std::make_pair( false, "Images must have one, three or four channels"); } return std::make_pair(true, "Images can be converted"); } QStringList DiffFilterFunction::extractStringListfromMap() const { QStringList stringList{}; for (auto mapElem : filterMap_) { stringList << QString::fromStdString(mapElem.first); } return stringList; } void DiffFilterFunction::updateFilterType(const QString &name) { filterMap_.find(name.toStdString())->second(); signalFilterSettingsChanged().emitSignal(); } } }
[ "andreas.bihlmaier@gmx.de" ]
andreas.bihlmaier@gmx.de
5f570216ce7c897fb697a8d72a86c037df1a73a0
0a47d2eeb492c42e7f06e053bb07136871baa39b
/sources/City.hpp
296edcc6d837972ef71ad37888465b3d023f9b11
[]
no_license
AviaTzadok/ex4_b_cpp
7f105bdd08f5796e267d130fe050bb68d110829f
b15aa77f2c6a8c5c5d93a1bfcbd1251cba5e8b95
refs/heads/main
2023-04-28T11:12:59.509586
2021-05-19T20:48:50
2021-05-19T20:48:50
368,997,181
0
0
null
null
null
null
UTF-8
C++
false
false
888
hpp
#pragma once namespace pandemic { enum class City { Algiers, Atlanta, Baghdad, Bangkok, Beijing, Bogota, BuenosAires, Cairo, Chennai, Chicago, Delhi, Essen, HoChiMinhCity, HongKong, Istanbul, Jakarta, Johannesburg, Karachi, Khartoum, Kinshasa, Kolkata, Lagos, Lima, London, LosAngeles, Madrid, Manila, MexicoCity, Miami, Milan, Montreal, Moscow, Mumbai, NewYork, Osaka, Paris, Riyadh, SanFrancisco, Santiago, SaoPaulo, Seoul, Shanghai, StPetersburg, Sydney, Taipei, Tehran, Tokyo, Washington }; }
[ "Avia12Tzadok@gmail.com" ]
Avia12Tzadok@gmail.com
c35fb15e01280c1de4dd4ebe5d5d881205eb7ef8
0378a8b567b5b9d8f4a6ecc99710c3318cfa8a30
/src/main.cpp
11953339588b9787d147e4a506eeae8f3ad333d9
[]
no_license
rileyrg/Sweep
497defa05e569a12b21e68f5435a280a4adff38b
b3aece2155e43cc529edd40d8306c39d7e0278cc
refs/heads/master
2020-07-31T01:28:15.089059
2019-09-24T19:25:15
2019-09-24T19:25:15
210,434,355
0
0
null
null
null
null
UTF-8
C++
false
false
169
cpp
#include<myServoLib.h> //Servo myServo; void setup() { myServo.attach(9); // attaches the servo on pin 9 to the servo object } void loop() { myServoLib(); }
[ "rileyrg@gmail.com" ]
rileyrg@gmail.com
76d40e192f1a0bb6b61d18fbff3c060b8e463f96
6d7a3bb26053cb180f35c88daf108f5a773ff293
/wasm_llvm/tools/llvm-mca/Stage.cpp
f4eb8db188105f674e2eb0c78ad20d1080cafe6b
[ "MIT", "NCSA" ]
permissive
WaykiChain/wicc-wasm-cdt
e4088f0313fbeb1aae7f4631b2735fbd2fc3c0c6
fcf9edcc9d8abf689c6a2452399735c887185bfa
refs/heads/master
2021-07-06T15:20:58.417585
2020-10-12T01:25:17
2020-10-12T01:25:17
237,560,833
1
2
MIT
2020-10-12T01:25:19
2020-02-01T04:19:53
C++
UTF-8
C++
false
false
813
cpp
//===---------------------- Stage.cpp ---------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// /// This file defines a stage. /// A chain of stages compose an instruction pipeline. /// //===----------------------------------------------------------------------===// #include "Stage.h" #include "llvm/Support/ErrorHandling.h" namespace mca { // Pin the vtable here in the implementation file. Stage::Stage() {} void Stage::addListener(HWEventListener *Listener) { llvm_unreachable("Stage-based eventing is not implemented."); } } // namespace mca
[ "1634054493@qq.com" ]
1634054493@qq.com
b499a40b77302521997b97a170cd70f8847e9d12
91e6985f8425813052c646330b84d09a9dac800e
/bitfield.hpp
91a2ab4872e6fa353ad3d74355ea11e16ae59093
[]
no_license
randvoorhies/bitfield
af71827b9f2b46763040c426d7ea30966cf6f30f
ac92b28a50ad8a0bdd3f95ca93a7e8ae68f2430b
refs/heads/master
2020-05-30T15:09:48.009828
2014-02-07T18:20:02
2014-02-07T18:20:02
16,532,711
2
2
null
null
null
null
UTF-8
C++
false
false
9,238
hpp
#pragma once #include <array> #include <type_traits> #include <stdexcept> #include <string> #include <algorithm> #include <iostream> namespace bitfield_private { //! A helper class to determine which integer type can hold all of our bits /*! Note that this limits us to 64 bit bitfields! */ template<size_t size, class enable=void> struct uintx_t { typedef void type; }; template<size_t size> struct uintx_t<size, typename std::enable_if<(size <= 8)>::type > { typedef uint8_t type; }; template<size_t size> struct uintx_t<size, typename std::enable_if<(size > 8 && size <= 16)>::type> { typedef uint16_t type; }; template<size_t size> struct uintx_t<size, typename std::enable_if<(size > 16 && size <= 32)>::type> { typedef uint32_t type; }; template<size_t size> struct uintx_t<size, typename std::enable_if<(size > 32 && size <= 64)>::type> { typedef uint64_t type; }; template<size_t parent_bits, size_t b, size_t e, bool is_const> struct range; } template<size_t n_bits> class bitfield { static_assert(n_bits <= 64, "bitfield must be created with <= 64 bits"); public: //! The native storage type typedef std::array<bool, n_bits> storage_t; //! The integral type that this bitfield can store. typedef typename bitfield_private::uintx_t<n_bits>::type native_type; //! Default constructor - set to all zeros bitfield() { b_.fill(false); } //! Construct from an integer value bitfield(native_type v) { range<0,n_bits-1>() = v; } //! Copy constructor bitfield(bitfield<n_bits> const & other) : b_(other.b_) { } //! Copy from a range /*! For example: * @code * bitfield<4> b2 = b1.range<0,3>(); * @endcode */ template<size_t o_bits, size_t b, size_t e, bool is_const> bitfield(bitfield_private::range<o_bits,b,e,is_const> const & other_range) { static_assert(e-b+1 == n_bits, "Trying to assign range to bitfield with mismatching sizes"); range<0,n_bits-1>() = other_range; } //! Access a range of the bitfield template<size_t b, size_t e> bitfield_private::range<n_bits,b,e,false> range() { static_assert(b <= e, "bitfield<bits>::range<b,e> must be called with b <= e"); static_assert(e < n_bits, "bitfield<bits>::range<b,e> must be called with b and e < bits"); return bitfield_private::range<n_bits,b,e,false>(*this); } //! Access a range of the bitfield (const version) template<size_t b, size_t e> bitfield_private::range<n_bits,b,e,true> range() const { static_assert(b <= e, "bitfield<bits>::range<b,e> must be called with b <= e"); static_assert(e < n_bits, "bitfield<bits>::range<b,e> must be called with b and e < bits"); return bitfield_private::range<n_bits,b,e,true>(*this); } //! Assign a character string to the bitfield, e.g. bitset<3> mybitset; mybitset = "101"; template<std::size_t N> void operator=(char const (& x) [N] ) { range<0,n_bits-1>() = x; } //! Assign an integer value to the bitfield, e.g. bitset<8> mybitset; mybitset = 0xFA; void operator=(native_type v) { range<0,n_bits-1>() = v; } //! Convert the bitfield to a string for printing std::string to_string() const { return this->range<0,n_bits-1>().to_string(); } //! Convert the bitfield to a number typename bitfield_private::uintx_t<n_bits>::type to_num() const { return this->range<0,n_bits-1>().to_num(); } //! Access a single bit of the bitfield bool & operator[](size_t i) { return this->range<0,n_bits-1>()[i]; } //! Access a single bit of the bitfield (const version) bool operator[](size_t i) const { return this->range<0,n_bits-1>()[i]; } //! Reverse the bitfield in place /*! \todo This needs to just self-assign the range reversed */ void reverse() { std::reverse(b_.begin(), b_.end()); } //! Reverse a copy of the bitfield and return it /*! \todo This needs to just return the range reversed */ bitfield<n_bits> reversed() const { bitfield<n_bits> other(*this); other.reverse(); return other; } private: template<size_t,size_t,size_t,bool> friend struct bitfield_private::range; storage_t b_; }; namespace bitfield_private { template<class parent_type, bool is_const> struct parent_wrapper; template<class parent_type> struct parent_wrapper<parent_type, true> { typedef parent_type const & type; }; template<class parent_type> struct parent_wrapper<parent_type, false> { typedef parent_type & type; }; //! A range class holds a reference to the parent bitfield, and can be used to set a range of its bits template<size_t parent_bits, size_t b, size_t e, bool is_const> struct range { //! The number of bits this range can hold static size_t const n_range_bits = e-b+1; //! The integral type that this range can store. typedef typename uintx_t<n_range_bits>::type native_range_type; //! The type of the parent (either const or not) typedef typename parent_wrapper<bitfield<parent_bits>, is_const>::type parent_type; //! Construct from a parent range(parent_type parent) : parent_(parent) {} //! Copy constructor from template<size_t other_parent_bits, size_t other_b, size_t other_e> range(range<other_parent_bits, other_b, other_e, true> const & other) : parent_(other.parent), reversed_(other.reversed_) { } //! Assign a character string to the range, e.g. mybitset.range<2,4>() = "101"; template<std::size_t N, bool is_const_dummy = is_const> typename std::enable_if<is_const_dummy == false, void>::type operator=(char const (& x) [N] ) { static_assert(N-1 == n_range_bits, "Wrong number of characters in range assignment"); for(size_t i=b; i<=e; ++i) { if(x[i-b] == '0' || x[i-b] == '1') parent_[e-i] = (x[i-b] == '1'); else throw std::invalid_argument("Only 0 and 1 are allowed in assignment strings. You gave " + std::string(1, x[b-i])); } } //! Assign an integer value to the range, e.g. mybitset.range<0,7>() = 0xFA; template<bool is_const_dummy = is_const> typename std::enable_if<is_const_dummy == false, void>::type operator=(native_range_type v) { if(v > ((1 << n_range_bits) - 1)) throw std::invalid_argument("Too large a value given to range"); for(size_t i=b; i<=e; ++i) { parent_[i] = v & 0x01; v = v >> 1; } } //! Copy another range's values to this one /*! For example * @code * b2.range<0,3>() = b1.range<4,7>(); * @endcode */ template<size_t other_parent_bits, size_t other_b, size_t other_e, bool other_is_const, bool is_const_dummy = is_const> typename std::enable_if<is_const_dummy == false, void>::type operator=(range<other_parent_bits, other_b, other_e, other_is_const> const & other) { static_assert(n_range_bits == other_e-other_b+1, "Trying to assign ranges with mismatching sizes"); for(size_t i=0; i<n_range_bits; ++i) (*this)[i] = other[i]; } //! Convert the bitfield range to a string for printing std::string to_string() { std::string s(n_range_bits, '-'); for(size_t i=0; i<n_range_bits; ++i) s[n_range_bits-i-1] = (*this)[i] ? '1' : '0'; return s; } //! Convert the bitfield to a number native_range_type to_num() { native_range_type n(0); for(size_t i=0; i<n_range_bits; ++i) if((*this)[i]) n += (0x01 << i); return n; } //! Access an element of the range template<bool is_const_dummy = is_const> typename std::enable_if<is_const_dummy == false, bool &>::type operator[](size_t i) { if(reversed_) return parent_.b_[e-i]; else return parent_.b_[b+i]; } //! Access an element of the range (const version) bool operator[](size_t i) const { if(reversed_) return parent_.b_[e-i]; else return parent_.b_[b+i]; } //! Reverse the bitfield in place /*! This will actually reverse the bits in the original bitfield*/ template<bool is_const_dummy = is_const> typename std::enable_if<is_const_dummy == false, void>::type reverse() { std::reverse(&(*this)[0], &(*this)[n_range_bits-1]); } //! Return a "view" of the bitfield range with the bits reversed /*! This is a non-destructive call, and will not actually reverse any bits in the parent bitfield */ range<parent_bits,b,e,is_const> reversed() { range<parent_bits,b,e,is_const> other = *this; other.reversed_ = !reversed_; return other; } parent_type parent_; bool reversed_ = false; }; }
[ "rand.voorhies@gmail.com" ]
rand.voorhies@gmail.com
9014b7560693d388da0e406a0ddee1cb2ce65771
2c83b8c8a40e816aaa77330c8caafbc31fcaf562
/GameServer/GameServer/MySQL.cpp
c3b597466c77f03c28abae4797a833561a55d840
[]
no_license
Seobeeee/Seobee_network
98360ed67bfda45369ef2143802a5d22293ca817
31f06589039b48f21d2d86dc5b09e16722b64793
refs/heads/master
2020-03-26T16:25:46.597074
2018-08-22T02:25:46
2018-08-22T02:25:46
145,101,102
0
0
null
null
null
null
UTF-8
C++
false
false
687
cpp
#include "MySQL.h" #include <iostream> bool DBQueryBase::TryConnectToDB(char* dbIP, char* dbUser, char* dbPassword, char* dbName, char* dbPort) { int nPort = atoi(dbPort); mysql_init(&m_conn); m_connection = mysql_real_connect(&m_conn, "1111", dbUser, dbPassword, dbName, nPort, NULL, 0); if (m_connection == NULL) { const char* errorString = mysql_error(&m_conn); std::cout << "error is : " << errorString << std::endl; return FALSE; } return TRUE; } void DBQueryBase::SetQuery(const char* query) { if (!query) { return; } int length = strlen(query); memcpy(m_query, query, length); } void DBQueryBase::EndQuery() { memset(m_query, 0, sizeof(m_query)); }
[ "oaudtjq@gmail.com" ]
oaudtjq@gmail.com
678edf0393e9b1616d59570e8ce1c8ab2e25ae30
cf3b1dfd302dec52ead35d2e7babaad7deda9c42
/PandaKeyBoard Extension/latin/core/src/suggest/policyimpl/gesture/gesture_suggest_policy_factory.h
c59159f2b55fc6331a3606b684cb24475d666166
[]
no_license
unnamed666/personal_ios_key
00e9f9fe9aa04640ed1722cb320a5899e6ec73ca
4dd0176a20763018d293e5cd15871bec931eb0f3
refs/heads/master
2020-08-15T21:14:24.343520
2019-10-14T05:10:20
2019-10-14T05:10:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,454
h
/* * Copyright (C) 2012 The Android Open Source Project * * 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 LATINIME_GESTURE_SUGGEST_POLICY_FACTORY_H #define LATINIME_GESTURE_SUGGEST_POLICY_FACTORY_H #include "defines.h" namespace latinime { class SuggestPolicy; class GestureSuggestPolicy; class GestureSuggestPolicyFactory { public: static void setGestureSuggestPolicyFactoryMethod(const GestureSuggestPolicy *(*factoryMethod)()) { sGestureSuggestFactoryMethod = factoryMethod; } static const SuggestPolicy *getGestureSuggestPolicy() { if (!sGestureSuggestFactoryMethod) { return 0; } return (SuggestPolicy*) sGestureSuggestFactoryMethod(); } private: DISALLOW_COPY_AND_ASSIGN(GestureSuggestPolicyFactory); static const GestureSuggestPolicy *(*sGestureSuggestFactoryMethod)(); }; } // namespace latinime #endif // LATINIME_GESTURE_SUGGEST_POLICY_FACTORY_H
[ "niecongcong@cmcm.com" ]
niecongcong@cmcm.com
9a73796ae89c8553dcd478184179b0eabc4c17dc
fb6c297065ef0a125174c2b13a85020cd6bcbcfd
/src/terrain/TerrainTile.cpp
2b936ca752e4abfc40e79029d2d7bcf91504ad60
[ "MIT" ]
permissive
hainam2101/irrrpgbuilder
359a61f076d8ead7befbd54f1161dc831351f527
d31b9403e5f6d95deadb4693b93360d5e4630628
refs/heads/master
2021-03-18T01:50:21.163035
2015-07-26T15:07:04
2015-07-26T15:07:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,155
cpp
#include "TerrainTile.h" #include "../App.h" #include "TerrainManager.h" #include "../gui/GUIManager.h" #include "../fx/EffectsManager.h" using namespace irr; using namespace core; using namespace scene; using namespace video; using namespace io; using namespace gui; using namespace std; // const irr::f32 TerrainTile::vegetationRange = 60; // old value=60 TerrainTile::TerrainTile(ISceneManager* smgr, ISceneNode* parent, vector3df pos, stringc name, bool custom, bool param) { this->smgr=smgr; ocean=NULL; node=NULL; selector=NULL; undobuffer.clear(); undohistory.clear(); needrecalc=false; //Define if the tile need to be calculated scale = TerrainManager::getInstance()->getScale(); if (!custom) createTerrain(parent,pos,name,param); srand(App::getInstance()->getDevice()->getTimer()->getRealTime()); } // Create a new tile. From 0.3+ Tiles will be parametric and will not use the reference mesh. void TerrainTile::createTerrain(ISceneNode* parent, vector3df pos, stringc name, bool param) { stringc tilename = TerrainManager::getInstance()->getTileMeshName(); if (tilename=="") tilename="../media/land.obj"; IMesh* baseMesh = NULL; if (!param) { baseMesh = smgr->getMesh(tilename.c_str()); } else { //Tries to create a mesh that is 1024 in size (mesh size), scaled then by IRB. //"tilesegment" is used to determine the density of the mesh, smaller=less dense f32 size = TerrainManager::getInstance()->getScale(); f32 calc = App::getInstance()->terraindensity/size; u32 tilesegment = (u32)(calc*size); if (tilesegment < 10) tilesegment = 10; //u32 tilesegment = (u32)(0.024414f*size); Old fixed density baseMesh = smgr->addHillPlaneMesh( "myHill", core::dimension2d<f32>(f32(1024/tilesegment),f32(1024/tilesegment)), core::dimension2d<u32>(tilesegment,tilesegment), 0, 0, core::dimension2d<f32>(0,0), core::dimension2d<f32>(1,1)); } SMesh* newMesh = NULL; newMesh = smgr->getMeshManipulator()->createMeshCopy(baseMesh); newMesh->setHardwareMappingHint(EHM_STATIC); if (node) node->drop(); // Create the terrain mesh node node = smgr->addMeshSceneNode(newMesh,parent,100); node->setMaterialFlag(EMF_LIGHTING,false); //node->setMaterialFlag(EMF_WIREFRAME,true); // node->setMaterialFlag(EMF_BLEND_OPERATION,true); // Create the terrain mesh node //Add shadow to this in the XEffect if (EffectsManager::getInstance()->isXEffectsEnabled()) { node->setMaterialFlag(EMF_LIGHTING,false); EffectsManager::getInstance()->addShadowToNode(node); } nodescale = node->getBoundingBox().getExtent().X; TerrainManager::getInstance()->setTileMeshSize(nodescale); node->setName(name); node->setScale(vector3df(scale/nodescale,scale/nodescale,scale/nodescale)); node->setPosition(pos*scale); selector = smgr->createTriangleSelector(newMesh,node); node->setTriangleSelector(selector); assignTerrainShader(node); // Create the water mesh, using the same reference as the terrain, applied shader will use the vertices informations to set the transparency of the water. ocean=smgr->addMeshSceneNode(newMesh,node,0); // use "newMesh" as the same reference. Will use the vertices height to get the transparency for the water. // assignWaterShader(ocean); ocean->getMaterial(0).MaterialType = video::EMT_SOLID; ocean->getMaterial(0).BlendOperation = EBO_ADD; ocean->getMaterial(0).BlendFactor = pack_textureBlendFunc(EBF_SRC_ALPHA, EBF_ONE_MINUS_SRC_ALPHA); meshBuffer = ((IMeshSceneNode*)node)->getMesh()->getMeshBuffer(0); mb_vertices = (S3DVertex*) meshBuffer->getVertices(); mb_indices = meshBuffer->getIndices(); /* // Reset the vertices height of the mesh to 0.0f (Y axis) for (unsigned int j = 0; j < meshBuffer->getVertexCount(); j += 1) { mb_vertices[j].Pos.Y = 0.0f; } */ driver = smgr->getGUIEnvironment()->getVideoDriver(); recalculate(); custom = false; storeUndo(); } void TerrainTile::createCustom(ISceneNode* parent, vector3df pos, stringc name, stringc model) { // Remove terrain if it was there if (ocean) { ocean->remove(); ocean=NULL; } if (node) { node->remove(); node=NULL; } //core::stringc path="../media/dynamic_objects/"; //core::stringc file=path.append(model); core::stringc file=model; IMesh* baseMesh = smgr->getMesh(file.c_str()); if (!baseMesh) { GUIManager::getInstance()->setConsoleText(L"ERROR! Failed to load custom tile",video::SColor(255,255,0,0)); //Tries to create a mesh that is 1024 in size (mesh size), scaled then by IRB. //"tilesegment" is used to determine the density of the mesh, smaller=less dense f32 size = TerrainManager::getInstance()->getScale(); u32 tilesegment = (u32)(0.024414f*size); baseMesh = smgr->addHillPlaneMesh( "myHill", core::dimension2d<f32>(f32(1024/tilesegment),f32(1024/tilesegment)), core::dimension2d<u32>(tilesegment,tilesegment), 0, 0, core::dimension2d<f32>(0,0), core::dimension2d<f32>(1,1)); } // Create the custom mesh node node = smgr->addMeshSceneNode(baseMesh,parent,100); // Create the terrain mesh node nodescale = node->getBoundingBox().getExtent().X; TerrainManager::getInstance()->setTileMeshSize(nodescale); node->setName(name); node->setPosition(pos*scale); selector = smgr->createTriangleSelector(baseMesh,node); meshBuffer = ((IMeshSceneNode*)node)->getMesh()->getMeshBuffer(0); mb_vertices = (S3DVertex*) meshBuffer->getVertices(); mb_indices = meshBuffer->getIndices(); node->setTriangleSelector(selector); //custom = true; assignTerrainShader(node); nodescale = node->getBoundingBox().getExtent().X; node->setScale(vector3df(scale/nodescale,scale/nodescale,scale/nodescale)); // Work for the water mesh. //SMesh* newMesh = NULL; //newMesh = smgr->getMeshManipulator()->createMeshCopy(baseMesh); //newMesh->setHardwareMappingHint(EHM_STATIC); // Create the water mesh, using the same reference as the terrain, applied shader will use the vertices informations to set the transparency of the water. //ocean=smgr->addMeshSceneNode(newMesh,node,0); // use "newMesh" as the same reference. Will use the vertices height to get the transparency for the water. ocean=smgr->addMeshSceneNode(baseMesh,node,0); //NEW (12/18/14) Found out that I can use the same reference for the water mesh, and generate 2 objects from the same mesh reference. ocean->setMaterialFlag(EMF_BLEND_OPERATION,true); assignWaterShader(ocean); baseMesh->setHardwareMappingHint(EHM_STATIC); storeUndo(); } TerrainTile::~TerrainTile() { for (int i=0 ; i<(int)vegetationVector.size() ; i++) { Vegetation* temp = (Vegetation*)vegetationVector[i]; if (temp->getNode()) temp->getNode()->remove(); //if (temp) // delete temp; } vegetationVector.clear(); if (selector) selector->drop(); if (node) { node->remove(); } } Vegetation* TerrainTile::getVegetationAt(vector3df pos) { for (int i=0 ; i<(int)vegetationVector.size() ; i++) { Vegetation* temp = (Vegetation*)vegetationVector[i]; if(temp->getPosition().getDistanceFrom(pos) < vegetationRange ) return temp; } return 0; } //Reposition the vegetation (trees) to touch the ground void TerrainTile::resetVegetationHeight() { for (int i=0 ; i<(int)vegetationVector.size() ; i++) { Vegetation* temp = (Vegetation*)vegetationVector[i]; f32 newpos = this->getHeightAt(temp->getPosition(),4000.0f); if (newpos<-200.0f) //Remove the tree if it's too low (underwater) { temp->getNode()->remove(); vegetationVector.erase(vegetationVector.begin()+i); } else temp->setPosition(vector3df(temp->getPosition().X,newpos-3.0f,temp->getPosition().Z)); //little offset of 3 units. } } stringc TerrainTile::getName() { return node->getName(); } ISceneNode* TerrainTile::getNode() { return node; } ISceneNode* TerrainTile::getOcean() { return ocean; } f32 TerrainTile::getNodeScale() { return nodescale; } ITriangleSelector* TerrainTile::getTriangleSelector() { return selector; } IMeshBuffer* TerrainTile::getMeshBuffer() { return ((IMeshSceneNode*)node)->getMesh()->getMeshBuffer(0); } IMesh* TerrainTile::getMesh() { return ((IMeshSceneNode*)node)->getMesh(); } void TerrainTile::mergeToTile(TerrainTile* tile) { if(!tile || custom) { #ifdef DEBUG cout << "DEBUG : TERRAIN TILE : MERGE FAILED, TILE IS NULL: " << endl; #endif return; } else { IMeshBuffer* meshBuffer = ((IMeshSceneNode*)node)->getMesh()->getMeshBuffer(0); IMeshBuffer* neighborBuffer = tile->getMeshBuffer(); S3DVertex* mb_vertices = (S3DVertex*) meshBuffer->getVertices(); S3DVertex* n_mb_vertices = (S3DVertex*) neighborBuffer->getVertices(); u16* mb_indices = meshBuffer->getIndices(); u16* n_mb_indices = neighborBuffer->getIndices(); for (unsigned int j = 0; j < meshBuffer->getVertexCount(); j += 1) { for (unsigned int i = 0; i < neighborBuffer->getVertexCount(); i += 1) { vector3df realPos = mb_vertices[j].Pos*(scale/nodescale) + node->getPosition(); vector3df nRealPos = n_mb_vertices[i].Pos*(scale/nodescale) + tile->getNode()->getPosition(); if((realPos.X == nRealPos.X) && (realPos.Z == nRealPos.Z)) { mb_vertices[j].Pos.Y = n_mb_vertices[i].Pos.Y; mb_vertices[j].Normal = n_mb_vertices[i].Normal; //New Copy the normal information needrecalc=true; } } } //smgr->getMeshManipulator()->recalculateNormals(((IMeshSceneNode*)node)->getMesh(),true); ((IMeshSceneNode*)node)->getMesh()->setDirty(); needrecalc = true; } } void TerrainTile::storeUndo() { IMeshBuffer* meshBuffer = ((IMeshSceneNode*)node)->getMesh()->getMeshBuffer(0); S3DVertex* mb_vertices = (S3DVertex*)meshBuffer->getVertices(); u16* mb_indices = meshBuffer->getIndices(); for (unsigned int j = 0; j < meshBuffer->getVertexCount(); j += 1) { undobuffer.push_back(mb_vertices[j].Pos.Y); } undohistory.push_back(undobuffer); undobuffer.clear(); } void TerrainTile::restoreUndo() { if (undohistory.size()>0) { IMeshBuffer* meshBuffer = ((IMeshSceneNode*)node)->getMesh()->getMeshBuffer(0); S3DVertex* mb_vertices = (S3DVertex*)meshBuffer->getVertices(); u16* mb_indices = meshBuffer->getIndices(); printf("Here is the undo history size: %i\n", undohistory.size()); undobuffer = undohistory.back(); printf("Here is the undo buffer size: %i\n", undobuffer.size()); for (unsigned int j = 0; j < undohistory[undohistory.size()-1].size(); j += 1) { mb_vertices[j].Pos.Y = undohistory[undohistory.size() - 1][j]; } meshBuffer = ((IMeshSceneNode*)ocean)->getMesh()->getMeshBuffer(0); mb_vertices = (S3DVertex*)meshBuffer->getVertices(); mb_indices = meshBuffer->getIndices(); for (unsigned int j = 0; j < undohistory[undohistory.size() - 1].size(); j += 1) { mb_vertices[j].Pos.Y = undohistory[undohistory.size() - 1][j]; } needrecalc = true; recalculate(); undohistory.pop_back(); //Remove the last element of the vector by 1; undobuffer.clear(); //Clear the buffer; } } void TerrainTile::saveToXML(TiXmlElement* parentElement) { // Save the terrain land f32 x = 0; f32 z = 0; x = node->getPosition().X; z = node->getPosition().Z; TiXmlElement* segmentXML = new TiXmlElement("terrainSegment"); segmentXML->SetDoubleAttribute("x",x); segmentXML->SetDoubleAttribute("z",z); core::stringc file=TerrainManager::getInstance()->filename; segmentXML->SetAttribute("mesh",file.c_str()); //Saving the vegetation information with the tile if (vegetationVector.size()>0) { for (int i=0 ; i<(int)vegetationVector.size() ; i++) { TiXmlElement* vertexXML = new TiXmlElement("tree"); Vegetation * tree = (Vegetation*)vegetationVector[i]; if (tree!=NULL) { vector3df treepos=tree->getPosition(); vertexXML->SetAttribute("v",tree->getType()); vertexXML->SetDoubleAttribute("tx",tree->getPosition().X); vertexXML->SetDoubleAttribute("ty",tree->getPosition().Y); vertexXML->SetDoubleAttribute("tz",tree->getPosition().Z); vertexXML->SetDoubleAttribute("tr",tree->getNode()->getRotation().Y); vertexXML->SetDoubleAttribute("ts",tree->getNode()->getScale().X); } segmentXML->LinkEndChild(vertexXML); } } parentElement->LinkEndChild(segmentXML); } bool TerrainTile::loadFromXML(TiXmlElement* parentElement) { s32 id = 0; f32 y = 0.0f; vector<TerrainData> vertices; vector3df pos=vector3df(0,0,0); f32 rota = 0; f32 scal = 0; f32 tsize = 0; int ttype = -1; bool atree=false; u32 counter=0; u32 counter1=0; u32 treecounter=0; if (!TerrainManager::getInstance()->isParametric()) //Old format for tiles { TiXmlNode* vertex = parentElement->FirstChild( "vertex" ); //printf("A non-parametric project is loaded, loading tile vertices...\n"); while( vertex != NULL ) { if (!custom) { id = atoi(vertex->ToElement()->Attribute("id")); y = (f32)atof(vertex->ToElement()->Attribute("y")); this->transformMeshByVertex(id,y,false,true); core::stringw title=L"Getting terrain vertices:"; title.append(stringw(counter)); title.append(L" loaded trees:"); title.append(stringw(treecounter)); GUIManager::getInstance()->setTextLoader(title); App::getInstance()->getDevice()->getGUIEnvironment()->drawAll(); counter1++; } stringc sttype = vertex->ToElement()->Attribute("v"); if (sttype.size()>0) { atree=true; ttype=atoi(sttype.c_str()); stringc stposx = vertex->ToElement()->Attribute("tx"); if (stposx.size()>0) { treecounter++; pos.X = (f32)atof(stposx.c_str()); pos.Y = (f32)atof(vertex->ToElement()->Attribute("ty")); pos.Z = (f32)atof(vertex->ToElement()->Attribute("tz")); stringc tsizes = vertex->ToElement()->Attribute("ts"); stringc ttr = vertex->ToElement()->Attribute("ts"); if (tsizes.size()>0) tsize=(f32)atof(vertex->ToElement()->Attribute("ts")); if (ttr.size()>0) rota=(f32)atof(vertex->ToElement()->Attribute("tr")); if (!TerrainManager::getInstance()->isParametric()) { printf("Terrain is NOT parametric\n"); // Now create a new tree with the informations Vegetation* v = new Vegetation(ttype); v->setPosition(pos); if (tsize==0.0f) //Old format, try to compensate with "default values" { f32 treesize = (f32)(rand() % 100 + 50)/100; treesize*= 0.3f; v->setScale(vector3df(treesize*(scale/7.5f),treesize*(scale/7.5f),treesize*(scale/7.5f))); v->setRotation(vector3df(0,0,0)); } else { v->setScale(vector3df(tsize,tsize,tsize)); v->setRotation(vector3df(0,rota,0)); } // Update the infos vegetationVector.push_back(v); } } } vertex = parentElement->IterateChildren( "vertex", vertex ); } } else { printf("A parametric project is loaded, loading tree informations...\n"); TiXmlNode* tree = parentElement->FirstChild( "tree" ); while( tree != NULL ) { core::stringw title=L"Getting terrain vertices:"; title.append(stringw(counter)); title.append(L" loaded trees:"); title.append(stringw(treecounter)); GUIManager::getInstance()->setTextLoader(title); App::getInstance()->getDevice()->getGUIEnvironment()->drawAll(); counter++; //Put back default values atree=false; ttype=-1; stringc sttype = tree->ToElement()->Attribute("v"); if (sttype.size()>0) { atree=true; ttype=atoi(sttype.c_str()); stringc stposx = tree->ToElement()->Attribute("tx"); if (stposx.size()>0) { treecounter++; pos.X = (f32)atof(stposx.c_str()); pos.Y = (f32)atof(tree->ToElement()->Attribute("ty")); pos.Z = (f32)atof(tree->ToElement()->Attribute("tz")); stringc tsizes = tree->ToElement()->Attribute("ts"); stringc ttr = tree->ToElement()->Attribute("ts"); if (tsizes.size()>0) tsize=(f32)atof(tree->ToElement()->Attribute("ts")); if (ttr.size()>0) rota=(f32)atof(tree->ToElement()->Attribute("tr")); if (TerrainManager::getInstance()->isParametric()) { printf("Terrain is NOT parametric\n"); // Now create a new tree with the informations Vegetation* v = new Vegetation(ttype); v->setPosition(pos); if (tsize==0.0f) //Old format, try to compensate with "default values" { f32 treesize = (f32)(rand() % 100 + 50)/100; treesize*= 0.3f; v->setScale(vector3df(treesize*(scale/7.5f),treesize*(scale/7.5f),treesize*(scale/7.5f))); v->setRotation(vector3df(0,0,0)); } else { v->setScale(vector3df(tsize,tsize,tsize)); v->setRotation(vector3df(0,rota,0)); } // Update the infos vegetationVector.push_back(v); } } } if (!custom)// This slow down when loading and should be optimized. { if (TerrainManager::getInstance()->isParametric()) { TerrainData data; data.id=id; data.value=y; data.pos=pos; data.type=ttype; data.tree=atree; data.rot=vector3df(0,rota,0); data.sca=vector3df(tsize,tsize,tsize); vertices.push_back(data); } else this->transformMeshByVertex(id,y,false,true); } tree = parentElement->IterateChildren( "tree", tree ); } } //Temporary solution so we can edit the tiles (editing was only permitted on non-custom tiles) custom=false; needrecalc=true; //this->recalculate(); return true; } Vegetation* TerrainTile::paintVegetation(vector3df clickPos, bool erase) { //Do a prior check to see if there is a least one tree active in the list of active objects vector<bool> enabled=VegetationSeed::getInstance()->getEnabled(); vector<int> newlist; for(int i = 0; i<(int)enabled.size(); i++) { if (enabled[i]==true) newlist.push_back(i); //New list will contain the list of the enabled items } if (newlist.size()==0) return NULL; IMeshBuffer* meshBuffer = ((IMeshSceneNode*)node)->getMesh()->getMeshBuffer(0); S3DVertex* mb_vertices = (S3DVertex*) meshBuffer->getVertices(); u16* mb_indices = meshBuffer->getIndices(); Vegetation* returnvalue = NULL; for (unsigned int j = 0; j < meshBuffer->getVertexCount(); j += 1) { if(erase) { vector3df realPos = vector3df (0.0f,0.0f,0.0f); //Should be able to place a tree anywhere on a custom model if (!custom) realPos = mb_vertices[j].Pos*(scale/nodescale) + node->getPosition(); else realPos = clickPos; clickPos.Y = realPos.Y; if(realPos.getDistanceFrom(clickPos) < vegetationRange/2 && getVegetationAt(vector3df(realPos.X,realPos.Y,realPos.Z))) { Vegetation* toRemove = getVegetationAt(vector3df(realPos.X,realPos.Y,realPos.Z)); returnvalue = toRemove; return returnvalue; // Done outside the function (caller will do the removal) } } else { vector3df realPos = vector3df (0.0f,0.0f,0.0f); //Should be able to place a tree anywhere on a custom model if (!custom) realPos = mb_vertices[j].Pos*(scale/nodescale) + node->getPosition(); else realPos = clickPos; clickPos.Y = realPos.Y; if(realPos.getDistanceFrom(clickPos) < (vegetationRange/2) && !getVegetationAt(vector3df(realPos.X,realPos.Y,realPos.Z))) { Vegetation* v = new Vegetation(); //v->setPosition(vector3df(realPos.X + (rand()%5)*0.1f - 0.25f,realPos.Y/(scale/nodescale),realPos.Z + (rand()%5)*0.1f - 0.25f)); //v->setPosition(vector3df(realPos.X + (rand()%5)*scale/100,realPos.Y,realPos.Z + (rand()%5)*scale/100)); v->setPosition(vector3df(realPos.X,realPos.Y,realPos.Z)); f32 treesize = (f32)(rand() % 50 + 25); f32 treerot = (f32)(rand() % 1 + 359); v->setScale(vector3df(treesize,treesize,treesize)); v->setRotation(vector3df(0,treerot,0)); #ifdef DEBUG printf("Attempting to place a tree with this size: %f\n",treesize); #endif vegetationVector.push_back(v); returnvalue = v; return returnvalue; #ifdef APP_DEBUG cout << "DEBUG : TERRAIN TILE : VEGETATION CREATED: " << realPos.X << "," << realPos.Y << "," << realPos.Z << " TOTAL:" << vegetationVector.size() << endl; #endif } } } return returnvalue; } // Test the tile if it was being modified bool TerrainTile::checkModified() { bool modified = false; IMeshBuffer* meshBuffer = ((IMeshSceneNode*)node)->getMesh()->getMeshBuffer(0); S3DVertex* mb_vertices = (S3DVertex*) meshBuffer->getVertices(); for (unsigned int j = 0; j < meshBuffer->getVertexCount(); j += 1) { vector3df realPos = mb_vertices[j].Pos*(scale/nodescale) + node->getPosition(); if(realPos.Y != 0.0f ) { modified = true; j=meshBuffer->getVertexCount(); break; } } return modified; } void TerrainTile::transformMeshByVertices(vector<TerrainData> list, bool norecalc) { core::stringw title=L"Generating terrain"; GUIManager::getInstance()->setTextLoader(title); App::getInstance()->getDevice()->getGUIEnvironment()->drawAll(); //Terrain first for (u32 a=0; a<list.size(); a++) { mb_vertices[list[a].id].Pos.Y = list[a].value; } App::getInstance()->quickUpdate(); int counter=0; //Then plant the trees title=L"Generating trees"; GUIManager::getInstance()->setTextLoader(title); App::getInstance()->getDevice()->getGUIEnvironment()->drawAll(); for (u32 a=0; a<list.size(); a++) { if (list[a].tree && list[a].type>=0) { // Now create a new tree with the informations Vegetation* v = new Vegetation(list[a].type); if (v) { counter++; v->setPosition(list[a].pos); v->setScale(list[a].sca); v->setRotation(list[a].rot); // Update the infos vegetationVector.push_back(v); } } } if (!norecalc) recalculate(); else { needrecalc=true; recalculate(true); } } void TerrainTile::transformMeshByVertex(s32 id, f32 y, bool addVegetation, bool norecalc) { if (custom) return; mb_vertices[id].Pos.Y = y; if(addVegetation) { vector3df treePos = vector3df(mb_vertices[id].Pos.X,y , mb_vertices[id].Pos.Z); treePos *= node->getScale(); treePos.Y = y; treePos += node->getPosition(); paintVegetation(treePos ,false); } App::getInstance()->quickUpdate(); if (!norecalc) recalculate(); else { needrecalc=true; recalculate(true); } } void TerrainTile::recalculate(bool simple) { if (custom) return; if (needrecalc) { //This part only refresh the visual model, will not change the collision shape smgr->getMeshManipulator()->recalculateNormals(((IMeshSceneNode*)node)->getMesh(),true); core::aabbox3df box=node->getBoundingBox(); ((IMeshSceneNode*)node)->getMesh()->setBoundingBox(core::aabbox3df(-box.getExtent().X/2,-256.0f,-box.getExtent().Z/2,box.getExtent().X/2,1024,box.getExtent().Z/2)); ((IMeshSceneNode*)node)->getMesh()->setDirty(); } // Simple is used by the brush when carving, once the carve is done, if needrecalc is activated will redo the collision shape // also used by terrainManager::recalculate() if (!simple && needrecalc) { // Attempt to update the triangle selector with the new mesh, will get the modified mesh and recreate the collision mesh ITriangleSelector * selector = smgr->createTriangleSelector(((IMeshSceneNode*)node)->getMesh(),node); //----ITriangleSelector * selector = smgr->createOctTreeTriangleSelector(((IMeshSceneNode*)node)->getMesh(),node); node->setTriangleSelector(selector); selector->drop(); needrecalc = false; #ifdef DEBUG printf("RECALCULATING SEGMENT: %s\n",getName().c_str()); #endif } } void TerrainTile::transformMesh(vector3df clickPos, f32 radius, f32 radius2, f32 strength, bool norecalc) { if (custom) return; IMeshBuffer* meshBuffer = ((IMeshSceneNode*)node)->getMesh()->getMeshBuffer(0); S3DVertex* mb_vertices = (S3DVertex*) meshBuffer->getVertices(); u16* mb_indices = meshBuffer->getIndices(); for (unsigned int j = 0; j < meshBuffer->getVertexCount(); j += 1) { vector3df realPos = mb_vertices[j].Pos*(scale/nodescale) + node->getPosition(); clickPos.Y = realPos.Y; if(realPos.getDistanceFrom(clickPos) < radius) { needrecalc=true; // This will flag the tile since it's in the radius and will modify the tile vertices. //f32 ratio = sin(radius - realPos.getDistanceFrom(clickPos)); //- (realPos.getDistanceFrom(clickPos)-radius2) f32 ratio = radius; if (radius2-realPos.getDistanceFrom(clickPos)<0) ratio = (radius+radius2)-realPos.getDistanceFrom(clickPos); mb_vertices[j].Pos.Y += (strength * (ratio)/(scale/nodescale)); //printf("found something here: vertice %i, vertice Y: %f\n",j, mb_vertices[j].Pos.Y); } //if(mb_vertices[j].Pos.Y > nodescale/4) mb_vertices[j].Pos.Y = nodescale/4; // Fix up/down limits if(mb_vertices[j].Pos.Y > nodescale*0.75f) mb_vertices[j].Pos.Y = nodescale*0.75f; if(mb_vertices[j].Pos.Y < -(nodescale*0.25f)) mb_vertices[j].Pos.Y = -(nodescale*0.25f); } if (norecalc) { recalculate(true); } else recalculate(); } void TerrainTile::transformMeshToValue(vector3df clickPos, f32 radius, f32 radius2, f32 strength, f32 value, bool norecalc) { if (custom) return; if(strength<0) strength = -strength; IMeshBuffer* meshBuffer = ((IMeshSceneNode*)node)->getMesh()->getMeshBuffer(0); S3DVertex* mb_vertices = (S3DVertex*) meshBuffer->getVertices(); u16* mb_indices = meshBuffer->getIndices(); for (unsigned int j = 0; j < meshBuffer->getVertexCount(); j += 1) { vector3df realPos = mb_vertices[j].Pos*(scale/nodescale) + node->getPosition(); clickPos.Y = realPos.Y; if(realPos.getDistanceFrom(clickPos) < radius) { needrecalc=true; //f32 ratio = sin(radius - realPos.getDistanceFrom(clickPos)); f32 ratio = radius; if (radius2-realPos.getDistanceFrom(clickPos)<0) ratio = (radius+radius2)-realPos.getDistanceFrom(clickPos); if(mb_vertices[j].Pos.Y > value) { //mb_vertices[j].Pos.Y -= strength * ratio / (scale/nodescale); mb_vertices[j].Pos.Y -= strength * ratio / (scale/nodescale); if(mb_vertices[j].Pos.Y <= value) mb_vertices[j].Pos.Y = value; } if(mb_vertices[j].Pos.Y < value) { //mb_vertices[j].Pos.Y += strength * ratio / (scale / nodescale); mb_vertices[j].Pos.Y += strength *ratio / (scale / nodescale); if(mb_vertices[j].Pos.Y >= value) mb_vertices[j].Pos.Y = value; } } } if (norecalc) { recalculate(true); } else recalculate(); } //Get the elevation from a ray test on the tile. //For this to work, the collision mesh must be up to date f32 TerrainTile::getHeightAt(vector3df pos, f32 rayheight) { // Check from the top of the character // old value is 4000.0f, new default is 80.0f irr::f32 maxRayHeight = rayheight; scene::ISceneCollisionManager* collMan = smgr->getSceneCollisionManager(); core::line3d<f32> ray; // Start the ray 500 unit from the character, ray lenght is 1000 unit. ray.start = pos+vector3df(0,+(maxRayHeight/2.0f),0); //ray.end = ray.start + (pos+vector3df(0,-maxRayHeight/2.0f,0) - ray.start).normalize() * maxRayHeight; ray.end = pos+vector3df(0,-(maxRayHeight/2),0); // Tracks the current intersection point with the level or a mesh core::vector3df intersection; // Used to show with triangle has been hit core::triangle3df hitTriangle; scene::ISceneNode * selectedSceneNode = collMan->getSceneNodeAndCollisionPointFromRay( ray, intersection, hitTriangle, 100, //100 is the default ID for walkable (ground obj + props) 0); // Check the entire scene (this is actually the implicit default) if (selectedSceneNode) { // return the height found. return intersection.Y; } else // if not return -1000 (Impossible value, so it failed) return -1000; } f32 TerrainTile::getVerticeHeight(vector3df pos) { f32 radius = 100; f32 returnvalue = 0; f32 smallest = radius; IMeshBuffer* meshBuffer = ((IMeshSceneNode*)node)->getMesh()->getMeshBuffer(0); S3DVertex* mb_vertices = (S3DVertex*) meshBuffer->getVertices(); u16* mb_indices = meshBuffer->getIndices(); //Check all indices in the mesh to find the one that is nearest the position for (unsigned int j = 0; j < meshBuffer->getVertexCount(); j += 1) { vector3df realPos = mb_vertices[j].Pos*(scale/nodescale) + node->getPosition(); pos.Y = realPos.Y; //Put the height at the same height //Check if its the smallest distance if((realPos.getDistanceFrom(pos) < smallest)) { smallest = realPos.getDistanceFrom(pos); returnvalue = realPos.Y; } } return returnvalue; } void TerrainTile::showDebugData(bool show) { for(int i=0;i<(int)vegetationVector.size();i++) { vegetationVector[i]->showDebugData(show); } } void TerrainTile::assignTerrainShader(irr::scene::ISceneNode *node) { //stringc texture0 = TerrainManager::getInstance()->getTerrainTexture(0); stringc texture1 = TerrainManager::getInstance()->getTerrainTexture(1); stringc texture2 = TerrainManager::getInstance()->getTerrainTexture(2); stringc texture3 = TerrainManager::getInstance()->getTerrainTexture(3); stringc texture4 = TerrainManager::getInstance()->getTerrainTexture(4); //static ITexture* layer0 = smgr->getVideoDriver()->getTexture(texture0.c_str()); static ITexture* layer1 = smgr->getVideoDriver()->getTexture(texture1.c_str()); static ITexture* layer2 = smgr->getVideoDriver()->getTexture(texture2.c_str()); static ITexture* layer3 = smgr->getVideoDriver()->getTexture(texture3.c_str()); static ITexture* layer4 = smgr->getVideoDriver()->getTexture(texture4.c_str()); static s32 materialTerrain = 0; // Disable 8 textures for the moment, will be enabled by the user directly. bool heighttextures = false; //Create a Custom GLSL Material (Terrain Splatting) if (heighttextures) { //Hardware support for 8 textures materialTerrain=smgr->getVideoDriver()->getGPUProgrammingServices()->addHighLevelShaderMaterialFromFiles( "../media/shaders/splat.vert", "vertexMain", video::EVST_VS_1_1, "../media/shaders/splat8.frag", "pixelMain", video::EPST_PS_1_4, ShaderCallBack::getInstance(), video::EMT_SOLID); //Assign Textures //node->setMaterialTexture(0,layer0); node->setMaterialTexture(1,layer1); node->setMaterialTexture(2,layer2); node->setMaterialTexture(3,layer3); node->setMaterialTexture(4,layer4); } else { // Hardware support for 4 textures materialTerrain=smgr->getVideoDriver()->getGPUProgrammingServices()->addHighLevelShaderMaterialFromFiles( "../media/shaders/splat.vert", "vertexMain", video::EVST_VS_1_1, "../media/shaders/splat4.frag", "pixelMain", video::EPST_PS_1_4, ShaderCallBack::getInstance(), video::EMT_SOLID); //Assign Textures #ifdef WIN32 // Strange // On Windows node->setMaterialTexture(0,layer1); node->setMaterialTexture(1,layer2); node->setMaterialTexture(2,layer3); node->setMaterialTexture(3,layer4); #else // On Linux node->setMaterialTexture(0,layer1); node->setMaterialTexture(0,layer1); node->setMaterialTexture(1,layer2); node->setMaterialTexture(2,layer3); node->setMaterialTexture(3,layer4); node->setMaterialTexture(4,layer4); #endif } //node->setMaterialTexture(0,layer1); //Assign GLSL Shader node->getMaterial(0).setFlag(EMF_LIGHTING,false); node->getMaterial(0).setFlag(EMF_FOG_ENABLE,true); node->setMaterialType((E_MATERIAL_TYPE)materialTerrain); } void TerrainTile::assignWaterShader(irr::scene::ISceneNode *node) { //Create a Custom GLSL Material (Water shader) static s32 materialOcean=smgr->getVideoDriver()->getGPUProgrammingServices()->addHighLevelShaderMaterialFromFiles( "../media/shaders/ocean.vert", "vertexMain", video::EVST_VS_1_1, "../media/shaders/ocean.frag", "pixelMain", video::EPST_PS_1_4, ShaderCallBack::getInstance(), video::EMT_TRANSPARENT_ALPHA_CHANNEL); static ITexture* oceanLayer0 = smgr->getVideoDriver()->getTexture("../media/waveNM.png"); static ITexture* oceanLayer1 = smgr->getVideoDriver()->getTexture("../media/sky.jpg"); static ITexture* oceanLayer2 = smgr->getVideoDriver()->getTexture("../media/WaterFoam01.jpg"); // Water shader node->setMaterialType((E_MATERIAL_TYPE)materialOcean); node->setMaterialTexture(0,oceanLayer0); node->setMaterialTexture(1,oceanLayer1); node->setMaterialTexture(2,oceanLayer2); //node->setMaterialFlag(EMF_FOG_ENABLE,true); //node->setMaterialFlag(EMF_BLEND_OPERATION,true); } void TerrainTile::clean() { for(int i=0;i<(int)vegetationVector.size();i++) { vegetationVector[i]->getNode()->remove(); } vegetationVector.clear(); }
[ "clavetc@irrrpgbuilder.sourceforge.net" ]
clavetc@irrrpgbuilder.sourceforge.net
5a86e002c5be11a9957bdb89c9de1da344e8efe6
b0a95d39262476e058d5504c9d26d176375629cf
/include/packet_filter.h
fad7ba0751dcad1821e52748cb6e71db5a06e339
[]
no_license
xiafzh/net
3573df1a2ca4ed34bfd5872030d195afc827ecc6
288816f6df512f7e53ec0b4644163d9288a0f325
refs/heads/master
2021-01-21T06:52:57.668835
2017-03-03T10:26:49
2017-03-03T10:26:49
83,291,794
0
0
null
null
null
null
UTF-8
C++
false
false
622
h
#ifndef __PACKET_FILTER_H__ #define __PACKET_FILTER_H__ #include "mem_stream.h" namespace summit { namespace network { class CPacket; class CStreamInput; class CPacketFactoryMgr; struct SPacketHead { TInt32 m_PacketID; TInt32 m_PacketLen; }; class CPacketFilter { public: TInt32 PacketRead(CStreamInput& Input, CPacketFactoryMgr& PacketMgr); CMemStream* PacketWrite(CPacket& Packet); CPacket* GetCachePacket(); public: CPacketFilter(); ~CPacketFilter(); private: CMemStream m_MemStream; CPacket* m_CachePacket; }; } } #endif
[ "noreply@github.com" ]
noreply@github.com
9832b6b2ce476b11d916b79eb4f76b2fa4ece97c
048f3026075f9809dfcee96fd6181c3678008190
/Source/MyProject/CollidingPawnMovementComponent.cpp
7153722d8ebea5f642f3a8b77923ef37f1aa8596
[]
no_license
woodRock/Jump
7837d052e15f16a7c62cd0cf2af1b9f2c67c49c1
af58d1590a5b130b5cf0b6bb6f0303f5c30a0b5a
refs/heads/master
2022-12-12T11:54:03.164561
2020-08-08T06:42:33
2020-08-08T06:42:33
283,970,274
0
0
null
null
null
null
UTF-8
C++
false
false
1,899
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "CollidingPawnMovementComponent.h" void UCollidingPawnMovementComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); // Make sure everything is still valid, and that we are allowed to move here if (!PawnOwner || !UpdatedComponent || ShouldSkipUpdate(DeltaTime)) { return; } // Get (and then clear) the movement vector that we set in ACollidingPawn::Tick FVector DesiredMovementThisFrame = ConsumeInputVector().GetClampedToMaxSize(1.0f) * DeltaTime * 150.0f; if (!DesiredMovementThisFrame.IsNearlyZero()) { FHitResult Hit; SafeMoveUpdatedComponent(DesiredMovementThisFrame, UpdatedComponent->GetComponentRotation(), true, Hit); // If we bumbed into something, try to slide a long it if (Hit.IsValidBlockingHit()) { // This code will move our Pawn smoothly around the world, sliding off of surfaces where appropriate. // There is no gravity applied to our Pawn, and its maximum speed is hard-coded to 150 Unreal Units per second SlideAlongSurface(DesiredMovementThisFrame, 1.f - Hit.Time, Hit.Normal, Hit); } } } // NOTE // This TickComponent function makes use of a few of the powerful features offered by the UPawnMovementComponent class: // - ConsumeInputVector reports and clears the value of a build-in variable that we will use to store our movement inputs // - SafeMoveUpdatedComponent uses Unreal Engine physics to move our pawn Movement Component while respecting solid barriers // - SlideAlongSurface handles the calculations and physics involved with sliding smoothly along collision surfaces like walls and ramps when a move results in a collision, // rather than simply stopping in place and sticking to the wall or ramp
[ "woodRock@users.noreply.github.com" ]
woodRock@users.noreply.github.com
2b0c0508f5c3f3db49a2fde67c78c55882ac0d14
09cd91e462a591a14e217d85748b89fb229aef32
/main.cpp
a2f87a31990c163b0189a6e75600e97881047fdf
[ "MIT" ]
permissive
serafimprozorov/giftcard-flower
b25f9a8ff142b4460f84ee901eb40c48b5cd0677
cfd75868684c39d2c4c894c3a2ca3357ab7fb638
refs/heads/master
2021-06-21T02:56:30.904017
2017-08-16T07:20:22
2017-08-16T07:20:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
cpp
#include "App.hpp" int main(int argc, char **argv) { try { return App::run(argc, argv); } catch (...) { } }
[ "serafim.prozorov@outlook.com" ]
serafim.prozorov@outlook.com
8d191e00d8e6e2e53b6e6a223b27595c3781452e
c5b93a9b23b4ddec0913ae41e60223877c0b65a0
/code/processespane.cpp
00dd11a3eea3e2613f655309d22ac0eb3febc89a
[]
no_license
PamirGhimire/seeWithCpp
593f276a63382335fe9a7c9f27c313149894baa2
c9d8088e72af5aa534367b94e928f6f564279aa4
refs/heads/master
2021-01-19T23:14:25.068259
2017-06-07T17:53:33
2017-06-07T17:53:33
88,941,638
0
0
null
null
null
null
UTF-8
C++
false
false
4,788
cpp
#include "processespane.h" #include "ui_processespane.h" processesPane::processesPane(QWidget *parent) : QDialog(parent), ui(new Ui::processesPane) { ui->setupUi(this); // Initialize default one-view process as identity transformation mv_currentOneViewProcess = identity; //---------------------------------------------------- // ADD IMAGE-TO-IMAGE PROCESSES //---------------------------------------------------- ui->i2iProcesses->addItem("Add salt and pepper noise"); //oneviewPcode 0 ui->i2iProcesses->addItem("Show Logo at bottom right corner"); //oneviewPcode 1 ui->i2iProcesses->addItem("Convert to new colorspace"); //oneviewPcode 2 ui->i2iProcesses->addItem("Equalize histogram"); //oneviewPcode 3 ui->i2iProcesses->addItem("Dilate"); //oneviewPcode 4 ui->i2iProcesses->addItem("Erode"); //oneviewPcode 5 ui->i2iProcesses->addItem("Open"); //oneviewPcode 6 ui->i2iProcesses->addItem("Close"); //oneviewPcode 7 ui->i2iProcesses->addItem("Gaussian Blur"); //oneviewPcode 8 ui->i2iProcesses->addItem("Sobel Edges"); //oneviewPcode 9 ui->i2iProcesses->addItem("Laplacian"); //oneviewPcode 10 ui->i2iProcesses->addItem("Apply custom kernel"); //oneviewPcode 11 ui->i2iProcesses->addItem("Edges using Canny"); //oneviewPcode 12 ui->i2iProcesses->addItem("Lines using P.Hough"); //oneviewPcode 13 ui->i2iProcesses->addItem("Circles using P.Hough"); //oneviewPcode 14 ui->i2iProcesses->addItem("Contours of connected components"); //oneviewPcode 15 ui->i2iProcesses->addItem("Min. Enclosing Circles of Shapes"); //oneviewPcode 16 ui->i2iProcesses->addItem("Bounding Boxes of shapes"); //oneviewPcode 17 ui->i2iProcesses->addItem("Harris Corners"); //oneviewPcode 18 ui->i2iProcesses->addItem("FAST Keypoints"); //oneviewPcode 19 ui->i2iProcesses->addItem("SURF Keypoints"); //oneviewPcode 20 ui->i2iProcesses->addItem("SIFT Keypoints"); //oneviewPcode 21 //---------------------------------------------------- //---------------------------------------------------- // ADD IMAGE-TO-MEASUREMENT PROCESSES: //---------------------------------------------------- ui->i2mProcesses->addItem("Histogram of Input"); ui->i2mProcesses->addItem("Histogram of Output"); } //--------------------------------------------------------------------- // Destructor of one-view process pane: //--------------------------------------------------------------------- processesPane::~processesPane() { delete ui; } //--------------------------------------------------------------------- // I2I Processes: //--------------------------------------------------------------------- void processesPane::on_i2iProcesses_activated(const QModelIndex &index) { ui->i2mProcesses->setCurrentRow(-100); } //--------------------------------------------------------------------- // Close the one-view process pane: //--------------------------------------------------------------------- void processesPane::on_close_clicked() { this->close(); } //--------------------------------------------------------------------- // Apply user's selection of one-view process: //--------------------------------------------------------------------- void processesPane::on_apply_clicked() { qDebug() << ui->i2iProcesses->currentRow(); if (ui->i2iProcesses->currentRow() >= 0){ mv_currentOneViewProcess = ui->i2iProcesses->currentRow(); }else{ mv_currentOneViewProcess = showHistogram + ui->i2mProcesses->currentRow(); } qDebug()<< mv_currentOneViewProcess; emit ms_applyButtonClicked(); } //--------------------------------------------------------------------- // Returns process-code word of current 'applied' process //--------------------------------------------------------------------- int processesPane::mf_getCurrentOneViewProcess(){ return mv_currentOneViewProcess; } //--------------------------------------------------------------------- // Sets parameters (details) for user's process of choice: // Signals the mainwindow that user wants to set details //--------------------------------------------------------------------- void processesPane::on_setDetails_clicked() { if (ui->i2iProcesses->currentRow() >= 0){ mv_currentOneViewProcess = ui->i2iProcesses->currentRow(); emit ms_setDetailsButtonClicked(); } } //--------------------------------------------------------------------- // I2Measurement Processes: //--------------------------------------------------------------------- void processesPane::on_i2mProcesses_activated(const QModelIndex &index) { ui->i2iProcesses->setCurrentRow(-100); }
[ "pamirghimire@gmail.com" ]
pamirghimire@gmail.com
17c1f2669855e96c3774a4a286b357feb47ee95f
8d7216784a23c9b5708be65a5ee5d94ba2f07631
/src/qt/macdockiconhandler.h
45c5484261237a0d340e284c9ffd395aa27e321b
[ "MIT" ]
permissive
Neomnf/NEOM
5986ab775860d3304cad60ea82000ab0d2468c1d
daf60c9ffc3f85d758c114f1e511d246a2fd178d
refs/heads/main
2023-04-07T21:27:46.423611
2021-04-20T18:13:12
2021-04-20T18:13:12
338,231,788
0
0
null
null
null
null
UTF-8
C++
false
false
589
h
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef NEOM_QT_MACDOCKICONHANDLER_H #define NEOM_QT_MACDOCKICONHANDLER_H #include <QObject> /** macOS-specific Dock icon handler. */ class MacDockIconHandler : public QObject { Q_OBJECT public: static MacDockIconHandler *instance(); static void cleanup(); Q_SIGNALS: void dockIconClicked(); private: MacDockIconHandler(); }; #endif // NEOM_QT_MACDOCKICONHANDLER_H
[ "78947632+Neomnf@users.noreply.github.com" ]
78947632+Neomnf@users.noreply.github.com
d4d9f2ffc61b8c6402137988483212a6f5c5f9ea
7092ce84e0c5bc4747796eab66912786609be832
/benchmark/kostya/simdjson_ondemand.h
c7df09731465c0249c1e575327da378d2117a604
[ "BSL-1.0", "MIT", "Apache-2.0" ]
permissive
virtoso/simdjson
e11acaf4155eb0fd29abf3f38740b50e5a2c076a
451c393ef18befc0d62aba19ce354a5dbb5a22db
refs/heads/master
2023-02-16T10:56:05.102625
2021-01-12T00:08:01
2021-01-12T00:08:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
635
h
#pragma once #if SIMDJSON_EXCEPTIONS #include "kostya.h" namespace kostya { using namespace simdjson; using namespace simdjson::builtin; struct simdjson_ondemand { ondemand::parser parser{}; bool run(simdjson::padded_string &json, std::vector<point> &result) { auto doc = parser.iterate(json); for (ondemand::object point : doc.find_field("coordinates")) { result.emplace_back(kostya::point{point.find_field("x"), point.find_field("y"), point.find_field("z")}); } return true; } }; BENCHMARK_TEMPLATE(kostya, simdjson_ondemand)->UseManualTime(); } // namespace kostya #endif // SIMDJSON_EXCEPTIONS
[ "john@johnkeiser.com" ]
john@johnkeiser.com
6d1eb8912ac2d48f9183be8b6e124798f7839229
78918391a7809832dc486f68b90455c72e95cdda
/boost_lib/boost/phoenix/statement/detail/preprocessed/switch_10.hpp
265a98ef3f96dd2010f8aaaec1df64b38e663df0
[ "MIT" ]
permissive
kyx0r/FA_Patcher
50681e3e8bb04745bba44a71b5fd04e1004c3845
3f539686955249004b4483001a9e49e63c4856ff
refs/heads/master
2022-03-28T10:03:28.419352
2020-01-02T09:16:30
2020-01-02T09:16:30
141,066,396
2
0
null
null
null
null
UTF-8
C++
false
false
54,031
hpp
/*============================================================================== Copyright (c) 2005-2010 Joel de Guzman Copyright (c) 2010 Thomas Heller Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<2> , mpl::false_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<2> , mpl::true_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; default: boost::phoenix::eval( proto::child_c<0>( fusion::deref( fusion::advance_c< 1 >(fusion::begin(flat_view)) ) ) , ctx ); } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<3> , mpl::false_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<3> , mpl::true_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; default: boost::phoenix::eval( proto::child_c<0>( fusion::deref( fusion::advance_c< 2 >(fusion::begin(flat_view)) ) ) , ctx ); } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<4> , mpl::false_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 3 >::type >::type case3; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case3, 0 >::type >::type >::type case_label3; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label3::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 3>(fusion::begin(flat_view)) ) ), ctx ); break; } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<4> , mpl::true_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; default: boost::phoenix::eval( proto::child_c<0>( fusion::deref( fusion::advance_c< 3 >(fusion::begin(flat_view)) ) ) , ctx ); } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<5> , mpl::false_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 3 >::type >::type case3; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case3, 0 >::type >::type >::type case_label3; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 4 >::type >::type case4; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case4, 0 >::type >::type >::type case_label4; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label3::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 3>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label4::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 4>(fusion::begin(flat_view)) ) ), ctx ); break; } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<5> , mpl::true_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 3 >::type >::type case3; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case3, 0 >::type >::type >::type case_label3; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label3::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 3>(fusion::begin(flat_view)) ) ), ctx ); break; default: boost::phoenix::eval( proto::child_c<0>( fusion::deref( fusion::advance_c< 4 >(fusion::begin(flat_view)) ) ) , ctx ); } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<6> , mpl::false_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 3 >::type >::type case3; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case3, 0 >::type >::type >::type case_label3; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 4 >::type >::type case4; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case4, 0 >::type >::type >::type case_label4; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 5 >::type >::type case5; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case5, 0 >::type >::type >::type case_label5; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label3::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 3>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label4::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 4>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label5::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 5>(fusion::begin(flat_view)) ) ), ctx ); break; } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<6> , mpl::true_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 3 >::type >::type case3; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case3, 0 >::type >::type >::type case_label3; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 4 >::type >::type case4; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case4, 0 >::type >::type >::type case_label4; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label3::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 3>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label4::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 4>(fusion::begin(flat_view)) ) ), ctx ); break; default: boost::phoenix::eval( proto::child_c<0>( fusion::deref( fusion::advance_c< 5 >(fusion::begin(flat_view)) ) ) , ctx ); } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<7> , mpl::false_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 3 >::type >::type case3; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case3, 0 >::type >::type >::type case_label3; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 4 >::type >::type case4; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case4, 0 >::type >::type >::type case_label4; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 5 >::type >::type case5; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case5, 0 >::type >::type >::type case_label5; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 6 >::type >::type case6; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case6, 0 >::type >::type >::type case_label6; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label3::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 3>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label4::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 4>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label5::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 5>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label6::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 6>(fusion::begin(flat_view)) ) ), ctx ); break; } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<7> , mpl::true_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 3 >::type >::type case3; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case3, 0 >::type >::type >::type case_label3; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 4 >::type >::type case4; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case4, 0 >::type >::type >::type case_label4; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 5 >::type >::type case5; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case5, 0 >::type >::type >::type case_label5; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label3::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 3>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label4::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 4>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label5::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 5>(fusion::begin(flat_view)) ) ), ctx ); break; default: boost::phoenix::eval( proto::child_c<0>( fusion::deref( fusion::advance_c< 6 >(fusion::begin(flat_view)) ) ) , ctx ); } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<8> , mpl::false_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 3 >::type >::type case3; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case3, 0 >::type >::type >::type case_label3; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 4 >::type >::type case4; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case4, 0 >::type >::type >::type case_label4; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 5 >::type >::type case5; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case5, 0 >::type >::type >::type case_label5; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 6 >::type >::type case6; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case6, 0 >::type >::type >::type case_label6; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 7 >::type >::type case7; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case7, 0 >::type >::type >::type case_label7; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label3::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 3>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label4::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 4>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label5::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 5>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label6::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 6>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label7::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 7>(fusion::begin(flat_view)) ) ), ctx ); break; } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<8> , mpl::true_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 3 >::type >::type case3; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case3, 0 >::type >::type >::type case_label3; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 4 >::type >::type case4; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case4, 0 >::type >::type >::type case_label4; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 5 >::type >::type case5; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case5, 0 >::type >::type >::type case_label5; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 6 >::type >::type case6; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case6, 0 >::type >::type >::type case_label6; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label3::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 3>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label4::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 4>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label5::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 5>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label6::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 6>(fusion::begin(flat_view)) ) ), ctx ); break; default: boost::phoenix::eval( proto::child_c<0>( fusion::deref( fusion::advance_c< 7 >(fusion::begin(flat_view)) ) ) , ctx ); } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<9> , mpl::false_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 3 >::type >::type case3; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case3, 0 >::type >::type >::type case_label3; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 4 >::type >::type case4; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case4, 0 >::type >::type >::type case_label4; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 5 >::type >::type case5; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case5, 0 >::type >::type >::type case_label5; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 6 >::type >::type case6; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case6, 0 >::type >::type >::type case_label6; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 7 >::type >::type case7; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case7, 0 >::type >::type >::type case_label7; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 8 >::type >::type case8; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case8, 0 >::type >::type >::type case_label8; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label3::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 3>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label4::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 4>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label5::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 5>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label6::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 6>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label7::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 7>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label8::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 8>(fusion::begin(flat_view)) ) ), ctx ); break; } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<9> , mpl::true_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 3 >::type >::type case3; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case3, 0 >::type >::type >::type case_label3; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 4 >::type >::type case4; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case4, 0 >::type >::type >::type case_label4; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 5 >::type >::type case5; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case5, 0 >::type >::type >::type case_label5; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 6 >::type >::type case6; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case6, 0 >::type >::type >::type case_label6; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 7 >::type >::type case7; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case7, 0 >::type >::type >::type case_label7; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label3::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 3>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label4::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 4>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label5::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 5>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label6::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 6>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label7::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 7>(fusion::begin(flat_view)) ) ), ctx ); break; default: boost::phoenix::eval( proto::child_c<0>( fusion::deref( fusion::advance_c< 8 >(fusion::begin(flat_view)) ) ) , ctx ); } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<10> , mpl::false_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 3 >::type >::type case3; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case3, 0 >::type >::type >::type case_label3; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 4 >::type >::type case4; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case4, 0 >::type >::type >::type case_label4; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 5 >::type >::type case5; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case5, 0 >::type >::type >::type case_label5; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 6 >::type >::type case6; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case6, 0 >::type >::type >::type case_label6; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 7 >::type >::type case7; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case7, 0 >::type >::type >::type case_label7; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 8 >::type >::type case8; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case8, 0 >::type >::type >::type case_label8; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 9 >::type >::type case9; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case9, 0 >::type >::type >::type case_label9; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label3::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 3>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label4::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 4>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label5::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 5>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label6::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 6>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label7::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 7>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label8::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 8>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label9::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 9>(fusion::begin(flat_view)) ) ), ctx ); break; } } template <typename Context, typename Cond, typename Cases> result_type evaluate( Context const & ctx , Cond const & cond , Cases const & cases , mpl::int_<10> , mpl::true_ ) const { typedef typename proto::result_of::flatten<Cases const&>::type flat_view_type; typedef typename fusion::result_of::begin<flat_view_type>::type flat_view_begin; flat_view_type flat_view(proto::flatten(cases)); typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 0 >::type >::type case0; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case0, 0 >::type >::type >::type case_label0; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 1 >::type >::type case1; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case1, 0 >::type >::type >::type case_label1; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 2 >::type >::type case2; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case2, 0 >::type >::type >::type case_label2; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 3 >::type >::type case3; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case3, 0 >::type >::type >::type case_label3; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 4 >::type >::type case4; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case4, 0 >::type >::type >::type case_label4; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 5 >::type >::type case5; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case5, 0 >::type >::type >::type case_label5; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 6 >::type >::type case6; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case6, 0 >::type >::type >::type case_label6; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 7 >::type >::type case7; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case7, 0 >::type >::type >::type case_label7; typedef typename fusion::result_of::deref< typename fusion::result_of::advance_c< flat_view_begin, 8 >::type >::type case8; typedef typename proto::detail::uncvref< typename proto::result_of::value< typename proto::result_of::child_c< case8, 0 >::type >::type >::type case_label8; switch(boost::phoenix::eval(cond, ctx)) { case case_label0::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 0>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label1::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 1>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label2::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 2>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label3::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 3>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label4::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 4>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label5::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 5>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label6::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 6>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label7::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 7>(fusion::begin(flat_view)) ) ), ctx ); break; case case_label8::value : boost::phoenix::eval( proto::child_c<1>( fusion::deref( fusion::advance_c< 8>(fusion::begin(flat_view)) ) ), ctx ); break; default: boost::phoenix::eval( proto::child_c<0>( fusion::deref( fusion::advance_c< 9 >(fusion::begin(flat_view)) ) ) , ctx ); } }
[ "k.melekhin@gmail.com" ]
k.melekhin@gmail.com
2cc84fac65ce90b9c1b05ec9557a9ccb42912775
3e7ae0d825853090372e5505f103d8f3f39dce6d
/AutMarine v4.2.0/AutLib/Cad/Solid/Cad3d_CurveOnSurfaceI.hxx
36a4ebb727fddd978be91d8adbb65f588317fa97
[]
no_license
amir5200fx/AutMarine-v4.2.0
bba1fe1aa1a14605c22a389c1bd3b48d943dc228
6beedbac1a3102cd1f212381a9800deec79cb31a
refs/heads/master
2020-11-27T05:04:27.397790
2019-12-20T17:59:03
2019-12-20T17:59:03
227,961,590
0
0
null
null
null
null
UTF-8
C++
false
false
333
hxx
#pragma once inline const Handle(Geom_Curve)& AutLib::CadLib::Cad3d_CurveOnSurface::Curve() const { return theCurve_; } inline Standard_Real AutLib::CadLib::Cad3d_CurveOnSurface::FirstParameter() const { return theFirst_; } inline Standard_Real AutLib::CadLib::Cad3d_CurveOnSurface::LastParameter() const { return theLast_; }
[ "aasoleimani86@gmail.com" ]
aasoleimani86@gmail.com
817f075be9d639128f367dead69f3a12fc288bff
318597d09b608e89f5379d1c7ae9b24c6c29990d
/router/skel.cpp
6a21254490dacffd9d311b237905d20fe205b43d
[]
no_license
TibiAlex/Router
91c9d756605fcb658d6b762de2e653bc0d63624f
29e4ee82365f06cf80a304f8ee997ff8b9927ad6
refs/heads/main
2023-06-27T06:10:40.557207
2021-07-21T17:41:42
2021-07-21T17:41:42
388,198,678
0
0
null
null
null
null
UTF-8
C++
false
false
4,866
cpp
#include "skel.h" int interfaces[ROUTER_NUM_INTERFACES]; int get_sock(const char *if_name) { int res; int s = socket(AF_PACKET, SOCK_RAW, 768); DIE(s == -1, "socket"); struct ifreq intf; strcpy(intf.ifr_name, if_name); res = ioctl(s, SIOCGIFINDEX, &intf); DIE(res, "ioctl SIOCGIFINDEX"); struct sockaddr_ll addr; memset(&addr, 0x00, sizeof(addr)); addr.sll_family = AF_PACKET; addr.sll_ifindex = intf.ifr_ifindex; res = bind(s , (struct sockaddr *)&addr , sizeof(addr)); DIE(res == -1, "bind"); return s; } packet* socket_receive_message(int sockfd, packet *m) { m->size = read(sockfd, m->payload, MAX_LEN); DIE(m->size == -1, "read"); return m; } int send_packet(int sockfd, packet *m) { return write(interfaces[sockfd], m->payload, m->size); } int get_packet(packet *m) { int res; fd_set set; FD_ZERO(&set); while (1) { for (int i = 0; i < ROUTER_NUM_INTERFACES; i++) { FD_SET(interfaces[i], &set); } res = select(interfaces[ROUTER_NUM_INTERFACES - 1] + 1, &set, NULL, NULL, NULL); DIE(res == -1, "select"); for (int i = 0; i < ROUTER_NUM_INTERFACES; i++) { if (FD_ISSET(interfaces[i], &set)) { socket_receive_message(interfaces[i], m); m->interface = i; return 0; } } } return -1; } char *get_interface_ip(int interface) { struct ifreq ifr; sprintf(ifr.ifr_name, "r-%u", interface); ioctl(interfaces[interface], SIOCGIFADDR, &ifr); return inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr); } int get_interface_mac(int interface, uint8_t *mac) { struct ifreq ifr; sprintf(ifr.ifr_name, "r-%u", interface); ioctl(interfaces[interface], SIOCGIFHWADDR, &ifr); memcpy(mac, ifr.ifr_addr.sa_data, 6); return 1; } void init() { int s0 = get_sock("r-0"); int s1 = get_sock("r-1"); int s2 = get_sock("r-2"); int s3 = get_sock("r-3"); interfaces[0] = s0; interfaces[1] = s1; interfaces[2] = s2; interfaces[3] = s3; } uint16_t checksum(void* vdata,size_t length) { char* data=(char*)vdata; uint64_t acc=0xffff; unsigned int offset=((uintptr_t)data)&3; if (offset) { size_t count=4-offset; if (count>length) count=length; uint32_t word=0; memcpy(offset+(char*)&word,data,count); acc+=ntohl(word); data+=count; length-=count; } char* data_end=data+(length&~3); while (data!=data_end) { uint32_t word; memcpy(&word,data,4); acc+=ntohl(word); data+=4; } length&=3; if (length) { uint32_t word=0; memcpy(&word,data,length); acc+=ntohl(word); } acc=(acc&0xffffffff)+(acc>>32); while (acc>>16) { acc=(acc&0xffff)+(acc>>16); } if (offset&1) { acc=((acc&0xff00)>>8)|((acc&0x00ff)<<8); } return htons(~acc); } static int hex2num(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } int hex2byte(const char *hex) { int a, b; a = hex2num(*hex++); if (a < 0) return -1; b = hex2num(*hex++); if (b < 0) return -1; return (a << 4) | b; } int hwaddr_aton(const char *txt, uint8_t *addr) { int i; for (i = 0; i < 6; i++) { int a, b; a = hex2num(*txt++); if (a < 0) return -1; b = hex2num(*txt++); if (b < 0) return -1; *addr++ = (a << 4) | b; if (i < 5 && *txt++ != ':') return -1; } return 0; } void hex_dump(const void* data, size_t size) { char ascii[17]; size_t i, j; ascii[16] = '\0'; for (i = 0; i < size; ++i) { printf("%02X ", ((unsigned char*)data)[i]); if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') { ascii[i % 16] = ((unsigned char*)data)[i]; } else { ascii[i % 16] = '.'; } if ((i+1) % 8 == 0 || i+1 == size) { printf(" "); if ((i+1) % 16 == 0) { printf("| %s \n", ascii); } else if (i+1 == size) { ascii[(i+1) % 16] = '\0'; if ((i+1) % 16 <= 8) { printf(" "); } for (j = (i+1) % 16; j < 16; ++j) { printf(" "); } printf("| %s \n", ascii); } } } } void init_packet(packet *pkt) { memset(pkt->payload, 0, sizeof(pkt->payload)); pkt->size = 0; } void swap_arp_ip(u_char str1[4], u_char str2[4]) { char temp[4]; for(int i = 0; i < 4; i++) { temp[i] = str1[i]; str1[i] = str2[i]; str2[i] = temp[i]; } } void swap_mac(u_char str1[6], u_char str2[6]) { char temp[6]; for(int i = 0; i < 6; i++) { temp[i] = str1[i]; str1[i] = str2[i]; str2[i] = temp[i]; } } void swap_ip(__u32& source, __u32& dest) { __u32 old_source = source; source = dest; dest = old_source; } uint32_t to_u32(u_char str[4]) { uint32_t conversion = *((uint32_t*) str); return conversion; } u_char* u32_to_array(uint32_t nr) { uint8_t* arr = (uint8_t*) malloc(5 * sizeof(uint8_t)); for (int i = 0; i < 4; i++) { arr[i] = ((uint8_t*)&nr)[3 - i]; } return arr; }
[ "tibi.alex@yahoo.com" ]
tibi.alex@yahoo.com
3ad3af22f5c6bfe5662629db825857a900cfa93e
04b1803adb6653ecb7cb827c4f4aa616afacf629
/third_party/blink/renderer/platform/graphics/placeholder_image_test.cc
b3367adea8f16b9abed724b4e9adb60b864e9696
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
19,496
cc
// 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. #include "third_party/blink/renderer/platform/graphics/placeholder_image.h" #include <stdint.h> #include "base/memory/scoped_refptr.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/web_localized_string.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/renderer/platform/fonts/font.h" #include "third_party/blink/renderer/platform/fonts/font_description.h" #include "third_party/blink/renderer/platform/geometry/float_rect.h" #include "third_party/blink/renderer/platform/geometry/int_rect.h" #include "third_party/blink/renderer/platform/geometry/int_size.h" #include "third_party/blink/renderer/platform/graphics/image.h" #include "third_party/blink/renderer/platform/graphics/image_orientation.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_canvas.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_flags.h" #include "third_party/blink/renderer/platform/graphics/test/mock_paint_canvas.h" #include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/blink/renderer/platform/text/platform_locale.h" #include "third_party/blink/renderer/platform/wtf/text/string_view.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkRect.h" namespace blink { namespace { using testing::_; using testing::AllOf; using testing::FloatNear; using testing::InvokeWithoutArgs; using testing::Property; constexpr float kBaseIconWidth = 24.0f; constexpr float kBaseIconHeight = 24.0f; constexpr float kBaseFeaturePaddingX = 8.0f; constexpr float kBaseIconPaddingY = 5.0f; constexpr float kBasePaddingBetweenIconAndText = 2.0f; constexpr float kBaseTextPaddingY = 9.0f; constexpr float kBaseFontSize = 14.0f; constexpr float kBaseIconOnlyFeatureWidth = kBaseFeaturePaddingX + kBaseIconWidth + kBaseFeaturePaddingX; constexpr float kBaseFeatureHeight = kBaseIconPaddingY + kBaseIconHeight + kBaseIconPaddingY; void ExpectDrawGrayBox(MockPaintCanvas& canvas, const FloatRect& expected_rect) { EXPECT_CALL( canvas, drawRect(AllOf(Property(&SkRect::x, FloatNear(expected_rect.X(), 0.01)), Property(&SkRect::y, FloatNear(expected_rect.Y(), 0.01)), Property(&SkRect::width, FloatNear(expected_rect.Width(), 0.01)), Property(&SkRect::height, FloatNear(expected_rect.Height(), 0.01))), AllOf(Property(&PaintFlags::getStyle, PaintFlags::kFill_Style), Property(&PaintFlags::getColor, SkColorSetARGB(0x80, 0xD9, 0xD9, 0xD9))))) .Times(1); } void DrawImageExpectingGrayBoxOnly(PlaceholderImage& image, const FloatRect& dest_rect) { MockPaintCanvas canvas; ExpectDrawGrayBox(canvas, dest_rect); EXPECT_CALL(canvas, drawImageRect(_, _, _, _, _)).Times(0); EXPECT_CALL(canvas, drawTextBlob(_, _, _, _)).Times(0); image.Draw(&canvas, PaintFlags(), dest_rect, FloatRect(0.0f, 0.0f, 100.0f, 100.0f), kDoNotRespectImageOrientation, Image::kClampImageToSourceRect, Image::kUnspecifiedDecode); } void DrawImageExpectingIconOnly(PlaceholderImage& image, const FloatRect& dest_rect, float scale_factor) { MockPaintCanvas canvas; ExpectDrawGrayBox(canvas, dest_rect); EXPECT_CALL( canvas, drawImageRect( /*image=*/_, /*src=*/_, /*dst=*/ AllOf(Property(&SkRect::x, FloatNear(dest_rect.Center().X() - scale_factor * kBaseIconWidth / 2.0f, 0.01)), Property(&SkRect::y, FloatNear(dest_rect.Center().Y() - scale_factor * kBaseIconHeight / 2.0f, 0.01)), Property(&SkRect::width, FloatNear(scale_factor * kBaseIconWidth, 0.01)), Property(&SkRect::height, FloatNear(scale_factor * kBaseIconHeight, 0.01))), /*flags=*/_, /*constraint=*/_)) .Times(1); EXPECT_CALL(canvas, drawTextBlob(_, _, _, _)).Times(0); image.Draw(&canvas, PaintFlags(), dest_rect, FloatRect(0.0f, 0.0f, 100.0f, 100.0f), kDoNotRespectImageOrientation, Image::kClampImageToSourceRect, Image::kUnspecifiedDecode); } float GetExpectedPlaceholderTextWidth(const StringView& text, float scale_factor) { FontDescription description; description.FirstFamily().SetFamily("Roboto"); scoped_refptr<SharedFontFamily> helvetica_neue = SharedFontFamily::Create(); helvetica_neue->SetFamily("Helvetica Neue"); scoped_refptr<SharedFontFamily> helvetica = SharedFontFamily::Create(); helvetica->SetFamily("Helvetica"); scoped_refptr<SharedFontFamily> arial = SharedFontFamily::Create(); arial->SetFamily("Arial"); helvetica->AppendFamily(std::move(arial)); helvetica_neue->AppendFamily(std::move(helvetica)); description.FirstFamily().AppendFamily(std::move(helvetica_neue)); description.SetGenericFamily(FontDescription::kSansSerifFamily); description.SetComputedSize(scale_factor * 14.0f); description.SetWeight(FontSelectionValue(500)); Font font(description); font.Update(nullptr); return font.Width(TextRun(text)); } void DrawImageExpectingIconAndTextLTR(PlaceholderImage& image, const FloatRect& dest_rect, float scale_factor) { EXPECT_FALSE(Locale::DefaultLocale().IsRTL()); MockPaintCanvas canvas; ExpectDrawGrayBox(canvas, dest_rect); const float expected_text_width = GetExpectedPlaceholderTextWidth(image.GetTextForTesting(), scale_factor); const float expected_feature_width = scale_factor * (kBaseIconOnlyFeatureWidth + kBasePaddingBetweenIconAndText) + expected_text_width; const float expected_feature_x = dest_rect.Center().X() - expected_feature_width / 2.0f; const float expected_feature_y = dest_rect.Center().Y() - scale_factor * kBaseFeatureHeight / 2.0f; EXPECT_CALL( canvas, drawImageRect( /*image=*/_, /*src=*/_, /*dst=*/ AllOf(Property(&SkRect::x, FloatNear(expected_feature_x + scale_factor * kBaseFeaturePaddingX, 0.01)), Property(&SkRect::y, FloatNear(expected_feature_y + scale_factor * kBaseIconPaddingY, 0.01)), Property(&SkRect::width, FloatNear(scale_factor * kBaseIconWidth, 0.01)), Property(&SkRect::height, FloatNear(scale_factor * kBaseIconHeight, 0.01))), /*flags=*/_, /*constraint=*/_)) .Times(1); EXPECT_CALL( canvas, drawTextBlob( _, FloatNear(expected_feature_x + scale_factor * (kBaseFeaturePaddingX + kBaseIconWidth + kBasePaddingBetweenIconAndText), 0.01), FloatNear(expected_feature_y + scale_factor * (kBaseTextPaddingY + kBaseFontSize), 0.01), AllOf( Property(&PaintFlags::getStyle, PaintFlags::kFill_Style), Property(&PaintFlags::getColor, SkColorSetARGB(0xAB, 0, 0, 0))))) .WillOnce(InvokeWithoutArgs([&image, scale_factor]() { EXPECT_NEAR( scale_factor * kBaseFontSize, image.GetFontForTesting()->GetFontDescription().ComputedSize(), 0.01); })); image.Draw(&canvas, PaintFlags(), dest_rect, FloatRect(0.0f, 0.0f, 100.0f, 100.0f), kDoNotRespectImageOrientation, Image::kClampImageToSourceRect, Image::kUnspecifiedDecode); } class TestingUnitsPlatform : public TestingPlatformSupport { public: TestingUnitsPlatform() {} ~TestingUnitsPlatform() override; WebString QueryLocalizedString(WebLocalizedString::Name name, const WebString& parameter) override { String p = parameter; switch (name) { case WebLocalizedString::kUnitsKibibytes: return String(p + " KB"); case WebLocalizedString::kUnitsMebibytes: return String(p + " MB"); case WebLocalizedString::kUnitsGibibytes: return String(p + " GB"); case WebLocalizedString::kUnitsTebibytes: return String(p + " TB"); case WebLocalizedString::kUnitsPebibytes: return String(p + " PB"); default: return WebString(); } } }; TestingUnitsPlatform::~TestingUnitsPlatform() = default; class PlaceholderImageTest : public testing::Test { public: void SetUp() override { old_user_preferred_languages_ = UserPreferredLanguages(); OverrideUserPreferredLanguagesForTesting(Vector<AtomicString>(1U, "en-US")); } void TearDown() override { OverrideUserPreferredLanguagesForTesting(old_user_preferred_languages_); } private: ScopedTestingPlatformSupport<TestingUnitsPlatform> platform_; Vector<AtomicString> old_user_preferred_languages_; }; TEST_F(PlaceholderImageTest, FormatPlaceholderText) { const struct { int64_t bytes; const char* expected; } tests[] = { // Placeholder image number format specifications: // https://docs.google.com/document/d/1BHeA1azbgCdZgCnr16VN2g7A9MHPQ_dwKn5szh8evMQ/edit#heading=h.d135l9z7tn0a {1, "1 KB"}, {500, "1 KB"}, {5 * 1024 + 200, "5 KB"}, {50 * 1024 + 200, "50 KB"}, {1000 * 1024 - 1, "999 KB"}, {1000 * 1024, "1 MB"}, {1024 * 1024 + 103 * 1024, "1.1 MB"}, {10 * 1024 * 1024, "10 MB"}, {10 * 1024 * 1024 + 103 * 1024, "10 MB"}, {1000 * 1024 * 1024 - 1, "999 MB"}, {1000 * 1024 * 1024, "1 GB"}, {1024 * 1024 * 1024, "1 GB"}, {(1LL << 50), "1 PB"}, {(1LL << 50) + 103 * (1LL << 40), "1.1 PB"}, {10 * (1LL << 50), "10 PB"}, {10 * (1LL << 50) + 103 * (1LL << 40), "10 PB"}, {~(1LL << 63), "8191 PB"}, }; for (const auto& test : tests) { String expected = test.expected; expected.Ensure16Bit(); EXPECT_EQ(expected, PlaceholderImage::Create(nullptr, IntSize(400, 300), test.bytes) ->GetTextForTesting()); } } TEST_F(PlaceholderImageTest, DrawLazyImage) { MockPaintCanvas canvas; EXPECT_CALL(canvas, drawRect(_, _)).Times(0); EXPECT_CALL(canvas, drawImageRect(_, _, _, _, _)).Times(0); EXPECT_CALL(canvas, drawTextBlob(_, _, _, _)).Times(0); PlaceholderImage::CreateForLazyImages(nullptr, IntSize(800, 600)) ->Draw(&canvas, PaintFlags(), FloatRect(0.0f, 0.0f, 800.0f, 600.0f), FloatRect(0.0f, 0.0f, 800.0f, 600.0f), kDoNotRespectImageOrientation, Image::kClampImageToSourceRect, Image::kUnspecifiedDecode); } TEST_F(PlaceholderImageTest, DrawNonIntersectingSrcRect) { MockPaintCanvas canvas; EXPECT_CALL(canvas, drawRect(_, _)).Times(0); EXPECT_CALL(canvas, drawImageRect(_, _, _, _, _)).Times(0); EXPECT_CALL(canvas, drawTextBlob(_, _, _, _)).Times(0); PlaceholderImage::Create(nullptr, IntSize(800, 600), 0) ->Draw(&canvas, PaintFlags(), FloatRect(0.0f, 0.0f, 800.0f, 600.0f), // The source rectangle is outside the 800x600 bounds of the image, // so nothing should be drawn. FloatRect(1000.0f, 0.0f, 800.0f, 600.0f), kDoNotRespectImageOrientation, Image::kClampImageToSourceRect, Image::kUnspecifiedDecode); } TEST_F(PlaceholderImageTest, DrawWithoutOriginalResourceSize) { scoped_refptr<PlaceholderImage> image = PlaceholderImage::Create(nullptr, IntSize(800, 600), 0); constexpr float kTestScaleFactors[] = {0.5f, 1.0f, 2.0f}; for (const float scale_factor : kTestScaleFactors) { image->SetIconAndTextScaleFactor(scale_factor); DrawImageExpectingGrayBoxOnly( *image, FloatRect(1000.0f, 2000.0f, scale_factor * kBaseIconOnlyFeatureWidth - 1.0f, scale_factor * kBaseFeatureHeight + 1.0f)); DrawImageExpectingGrayBoxOnly( *image, FloatRect(1000.0f, 2000.0f, scale_factor * kBaseIconOnlyFeatureWidth + 1.0f, scale_factor * kBaseFeatureHeight - 1.0f)); DrawImageExpectingIconOnly( *image, FloatRect(1000.0f, 2000.0f, scale_factor * kBaseIconOnlyFeatureWidth + 1.0f, scale_factor * kBaseFeatureHeight + 1.0f), scale_factor); DrawImageExpectingIconOnly( *image, FloatRect(1000.0f, 2000.0f, 800.0f, 600.0f), scale_factor); } } TEST_F(PlaceholderImageTest, DrawWithOriginalResourceSizeLTR) { scoped_refptr<PlaceholderImage> image = PlaceholderImage::Create(nullptr, IntSize(800, 600), 50 * 1024); String expected_text = "50 KB"; expected_text.Ensure16Bit(); EXPECT_EQ(expected_text, image->GetTextForTesting()); constexpr float kTestScaleFactors[] = {0.5f, 1.0f, 2.0f}; for (const float scale_factor : kTestScaleFactors) { image->SetIconAndTextScaleFactor(scale_factor); DrawImageExpectingGrayBoxOnly( *image, FloatRect(1000.0f, 2000.0f, scale_factor * kBaseIconOnlyFeatureWidth - 1.0f, scale_factor * kBaseFeatureHeight + 1.0f)); DrawImageExpectingGrayBoxOnly( *image, FloatRect(1000.0f, 2000.0f, scale_factor * kBaseIconOnlyFeatureWidth + 1.0f, scale_factor * kBaseFeatureHeight - 1.0f)); DrawImageExpectingGrayBoxOnly( *image, FloatRect(1000.0f, 2000.0f, 800.0f, scale_factor * kBaseFeatureHeight - 1.0f)); const float expected_text_width = GetExpectedPlaceholderTextWidth( image->GetTextForTesting(), scale_factor); const float expected_icon_and_text_width = scale_factor * (kBaseIconOnlyFeatureWidth + kBasePaddingBetweenIconAndText) + expected_text_width; DrawImageExpectingIconOnly( *image, FloatRect(1000.0f, 2000.0f, scale_factor * kBaseIconOnlyFeatureWidth + 1.0f, scale_factor * kBaseFeatureHeight + 1.0f), scale_factor); DrawImageExpectingIconOnly( *image, FloatRect(1000.0f, 2000.0f, expected_icon_and_text_width - 1.0f, scale_factor * kBaseFeatureHeight + 1.0f), scale_factor); DrawImageExpectingIconAndTextLTR( *image, FloatRect(1000.0f, 2000.0f, expected_icon_and_text_width + 1.0f, scale_factor * kBaseFeatureHeight + 1.0f), scale_factor); DrawImageExpectingIconAndTextLTR( *image, FloatRect(1000.0f, 2000.0f, 800.0f, 600.0f), scale_factor); } } TEST_F(PlaceholderImageTest, DrawWithOriginalResourceSizeRTL) { scoped_refptr<PlaceholderImage> image = PlaceholderImage::Create(nullptr, IntSize(800, 600), 50 * 1024); String expected_text = "50 KB"; expected_text.Ensure16Bit(); EXPECT_EQ(expected_text, image->GetTextForTesting()); OverrideUserPreferredLanguagesForTesting(Vector<AtomicString>(1U, "ar")); EXPECT_TRUE(Locale::DefaultLocale().IsRTL()); static constexpr float kScaleFactor = 2.0f; image->SetIconAndTextScaleFactor(kScaleFactor); const FloatRect dest_rect(1000.0f, 2000.0f, 800.0f, 600.0f); MockPaintCanvas canvas; ExpectDrawGrayBox(canvas, dest_rect); const float expected_text_width = GetExpectedPlaceholderTextWidth(image->GetTextForTesting(), kScaleFactor); const float expected_feature_width = kScaleFactor * (kBaseIconOnlyFeatureWidth + kBasePaddingBetweenIconAndText) + expected_text_width; const float expected_feature_x = dest_rect.Center().X() - expected_feature_width / 2.0f; const float expected_feature_y = dest_rect.Center().Y() - kScaleFactor * kBaseFeatureHeight / 2.0f; EXPECT_CALL( canvas, drawImageRect( /*image=*/_, /*src=*/_, /*dst=*/ AllOf(Property(&SkRect::x, FloatNear(expected_feature_x + kScaleFactor * (kBaseFeaturePaddingX + kBasePaddingBetweenIconAndText) + expected_text_width, 0.01)), Property(&SkRect::y, FloatNear(expected_feature_y + kScaleFactor * kBaseIconPaddingY, 0.01)), Property(&SkRect::width, FloatNear(kScaleFactor * kBaseIconWidth, 0.01)), Property(&SkRect::height, FloatNear(kScaleFactor * kBaseIconHeight, 0.01))), /*flags=*/_, /*constraint=*/_)) .Times(1); EXPECT_CALL( canvas, drawTextBlob( _, FloatNear(expected_feature_x + kScaleFactor * kBaseFeaturePaddingX, 0.01), FloatNear(expected_feature_y + kScaleFactor * (kBaseTextPaddingY + kBaseFontSize), 0.01), AllOf( Property(&PaintFlags::getStyle, PaintFlags::kFill_Style), Property(&PaintFlags::getColor, SkColorSetARGB(0xAB, 0, 0, 0))))) .WillOnce(InvokeWithoutArgs([image]() { EXPECT_NEAR( kScaleFactor * kBaseFontSize, image->GetFontForTesting()->GetFontDescription().ComputedSize(), 0.01); })); image->Draw(&canvas, PaintFlags(), dest_rect, FloatRect(0.0f, 0.0f, 100.0f, 100.0f), kDoNotRespectImageOrientation, Image::kClampImageToSourceRect, Image::kUnspecifiedDecode); } TEST_F(PlaceholderImageTest, DrawSeparateImageWithDifferentScaleFactor) { scoped_refptr<PlaceholderImage> image_1 = PlaceholderImage::Create(nullptr, IntSize(800, 600), 50 * 1024); constexpr float kScaleFactor1 = 0.5f; image_1->SetIconAndTextScaleFactor(kScaleFactor1); DrawImageExpectingIconAndTextLTR( *image_1, FloatRect(1000.0f, 2000.0f, 800.0f, 600.0f), kScaleFactor1); scoped_refptr<PlaceholderImage> image_2 = PlaceholderImage::Create(nullptr, IntSize(800, 600), 100 * 1024); constexpr float kScaleFactor2 = 2.0f; image_2->SetIconAndTextScaleFactor(kScaleFactor2); DrawImageExpectingIconAndTextLTR( *image_2, FloatRect(1000.0f, 2000.0f, 800.0f, 600.0f), kScaleFactor2); DrawImageExpectingIconAndTextLTR( *image_1, FloatRect(1000.0f, 2000.0f, 1600.0f, 1200.0f), kScaleFactor1); } } // namespace } // namespace blink
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
ea01c162e85cb5b8dbbf2b320c3b9f10b6cdb66c
642630fc1f6747663f08c6357e3b2c3ecaa994a5
/libraries/rc-switch/RCSwitch.cpp
db3877d95ae37b9aef7631e4fe2fef8a26411200
[ "CC-BY-4.0" ]
permissive
whid-injector/EvilCrow-RF
e099644a4248484c8d4276e496f2e4d6f8025e7f
d47ac1204fcd2fea070a1d9e80f12f9e15c3a64a
refs/heads/main
2023-04-09T16:09:40.864399
2021-04-20T09:04:22
2021-04-20T09:04:22
359,750,025
3
1
CC-BY-4.0
2021-04-20T08:59:59
2021-04-20T08:59:59
null
UTF-8
C++
false
false
23,968
cpp
/* RCSwitch - Arduino libary for remote control outlet switches Copyright (c) 2011 Suat Özgür. All right reserved. Contributors: - Andre Koehler / info(at)tomate-online(dot)de - Gordeev Andrey Vladimirovich / gordeev(at)openpyro(dot)com - Skineffect / http://forum.ardumote.com/viewtopic.php?f=2&t=46 - Dominik Fischer / dom_fischer(at)web(dot)de - Frank Oltmanns / <first name>.<last name>(at)gmail(dot)com - Andreas Steinel / A.<lastname>(at)gmail(dot)com - Max Horn / max(at)quendi(dot)de - Robert ter Vehn / <first name>.<last name>(at)gmail(dot)com - Johann Richard / <first name>.<last name>(at)gmail(dot)com - Vlad Gheorghe / <first name>.<last name>(at)gmail(dot)com https://github.com/vgheo - Matias Cuenca-Acuna Project home: https://github.com/sui77/rc-switch/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "RCSwitch.h" #ifdef RaspberryPi // PROGMEM and _P functions are for AVR based microprocessors, // so we must normalize these for the ARM processor: #define PROGMEM #define memcpy_P(dest, src, num) memcpy((dest), (src), (num)) #endif #if defined(ESP8266) // interrupt handler and related code must be in RAM on ESP8266, // according to issue #46. #define RECEIVE_ATTR ICACHE_RAM_ATTR #define VAR_ISR_ATTR #elif defined(ESP32) #define RECEIVE_ATTR IRAM_ATTR #define VAR_ISR_ATTR DRAM_ATTR #else #define RECEIVE_ATTR #define VAR_ISR_ATTR #endif /* Format for protocol definitions: * {pulselength, Sync bit, "0" bit, "1" bit, invertedSignal} * * pulselength: pulse length in microseconds, e.g. 350 * Sync bit: {1, 31} means 1 high pulse and 31 low pulses * (perceived as a 31*pulselength long pulse, total length of sync bit is * 32*pulselength microseconds), i.e: * _ * | |_______________________________ (don't count the vertical bars) * "0" bit: waveform for a data bit of value "0", {1, 3} means 1 high pulse * and 3 low pulses, total length (1+3)*pulselength, i.e: * _ * | |___ * "1" bit: waveform for a data bit of value "1", e.g. {3,1}: * ___ * | |_ * * These are combined to form Tri-State bits when sending or receiving codes. */ #if defined(ESP8266) || defined(ESP32) static const VAR_ISR_ATTR RCSwitch::Protocol proto[] = { #else static const RCSwitch::Protocol PROGMEM proto[] = { #endif { 350, { 1, 31 }, { 1, 3 }, { 3, 1 }, false }, // protocol 1 { 650, { 1, 10 }, { 1, 2 }, { 2, 1 }, false }, // protocol 2 { 100, { 30, 71 }, { 4, 11 }, { 9, 6 }, false }, // protocol 3 { 380, { 1, 6 }, { 1, 3 }, { 3, 1 }, false }, // protocol 4 { 500, { 6, 14 }, { 1, 2 }, { 2, 1 }, false }, // protocol 5 { 450, { 23, 1 }, { 1, 2 }, { 2, 1 }, true }, // protocol 6 (HT6P20B) { 150, { 2, 62 }, { 1, 6 }, { 6, 1 }, false }, // protocol 7 (HS2303-PT, i. e. used in AUKEY Remote) { 200, { 3, 130}, { 7, 16 }, { 3, 16}, false}, // protocol 8 Conrad RS-200 RX { 200, { 130, 7 }, { 16, 7 }, { 16, 3 }, true}, // protocol 9 Conrad RS-200 TX { 365, { 18, 1 }, { 3, 1 }, { 1, 3 }, true }, // protocol 10 (1ByOne Doorbell) { 270, { 36, 1 }, { 1, 2 }, { 2, 1 }, true }, // protocol 11 (HT12E) { 320, { 36, 1 }, { 1, 2 }, { 2, 1 }, true }, // protocol 12 (SM5212) { 100, { 3, 100 }, { 3, 8 }, { 8, 3 }, false } // protocol 13 (Mumbi RC-10 }; enum { numProto = sizeof(proto) / sizeof(proto[0]) }; #if not defined( RCSwitchDisableReceiving ) volatile unsigned long long RCSwitch::nReceivedValue = 0; volatile unsigned int RCSwitch::nReceivedBitlength = 0; volatile unsigned int RCSwitch::nReceivedDelay = 0; volatile unsigned int RCSwitch::nReceivedProtocol = 0; int RCSwitch::nReceiveTolerance = 60; const unsigned int RCSwitch::nSeparationLimit = 4300; // separationLimit: minimum microseconds between received codes, closer codes are ignored. // according to discussion on issue #14 it might be more suitable to set the separation // limit to the same time as the 'low' part of the sync signal for the current protocol. unsigned int RCSwitch::timings[RCSWITCH_MAX_CHANGES]; #endif RCSwitch::RCSwitch() { this->nTransmitterPin = -1; this->setRepeatTransmit(10); this->setProtocol(1); #if not defined( RCSwitchDisableReceiving ) this->nReceiverInterrupt = -1; this->setReceiveTolerance(60); RCSwitch::nReceivedValue = 0; #endif } /** * Sets the protocol to send. */ void RCSwitch::setProtocol(Protocol protocol) { this->protocol = protocol; } /** * Sets the protocol to send, from a list of predefined protocols */ void RCSwitch::setProtocol(int nProtocol) { if (nProtocol < 1 || nProtocol > numProto) { nProtocol = 1; printf("Error, bad protocol ID. Falling back to protocol 1.\n"); } #if defined(ESP8266) || defined(ESP32) this->protocol = proto[nProtocol-1]; #else memcpy_P(&this->protocol, &proto[nProtocol-1], sizeof(Protocol)); #endif } /** * Sets the protocol to send with pulse length in microseconds. */ void RCSwitch::setProtocol(int nProtocol, int nPulseLength) { setProtocol(nProtocol); this->setPulseLength(nPulseLength); } /** * Sets pulse length in microseconds */ void RCSwitch::setPulseLength(int nPulseLength) { this->protocol.pulseLength = nPulseLength; } /** * Sets Repeat Transmits */ void RCSwitch::setRepeatTransmit(int nRepeatTransmit) { this->nRepeatTransmit = nRepeatTransmit; } /** * Set Receiving Tolerance */ #if not defined( RCSwitchDisableReceiving ) void RCSwitch::setReceiveTolerance(int nPercent) { RCSwitch::nReceiveTolerance = nPercent; } #endif /** * Enable transmissions * * @param nTransmitterPin Arduino Pin to which the sender is connected to */ void RCSwitch::enableTransmit(int nTransmitterPin) { this->nTransmitterPin = nTransmitterPin; pinMode(this->nTransmitterPin, OUTPUT); } /** * Disable transmissions */ void RCSwitch::disableTransmit() { this->nTransmitterPin = -1; } /** * Switch a remote switch on (Type D REV) * * @param sGroup Code of the switch group (A,B,C,D) * @param nDevice Number of the switch itself (1..3) */ void RCSwitch::switchOn(char sGroup, int nDevice) { this->sendTriState( this->getCodeWordD(sGroup, nDevice, true) ); } /** * Switch a remote switch off (Type D REV) * * @param sGroup Code of the switch group (A,B,C,D) * @param nDevice Number of the switch itself (1..3) */ void RCSwitch::switchOff(char sGroup, int nDevice) { this->sendTriState( this->getCodeWordD(sGroup, nDevice, false) ); } /** * Switch a remote switch on (Type C Intertechno) * * @param sFamily Familycode (a..f) * @param nGroup Number of group (1..4) * @param nDevice Number of device (1..4) */ void RCSwitch::switchOn(char sFamily, int nGroup, int nDevice) { this->sendTriState( this->getCodeWordC(sFamily, nGroup, nDevice, true) ); } /** * Switch a remote switch off (Type C Intertechno) * * @param sFamily Familycode (a..f) * @param nGroup Number of group (1..4) * @param nDevice Number of device (1..4) */ void RCSwitch::switchOff(char sFamily, int nGroup, int nDevice) { this->sendTriState( this->getCodeWordC(sFamily, nGroup, nDevice, false) ); } /** * Switch a remote switch on (Type B with two rotary/sliding switches) * * @param nAddressCode Number of the switch group (1..4) * @param nChannelCode Number of the switch itself (1..4) */ void RCSwitch::switchOn(int nAddressCode, int nChannelCode) { this->sendTriState( this->getCodeWordB(nAddressCode, nChannelCode, true) ); } /** * Switch a remote switch off (Type B with two rotary/sliding switches) * * @param nAddressCode Number of the switch group (1..4) * @param nChannelCode Number of the switch itself (1..4) */ void RCSwitch::switchOff(int nAddressCode, int nChannelCode) { this->sendTriState( this->getCodeWordB(nAddressCode, nChannelCode, false) ); } /** * Deprecated, use switchOn(const char* sGroup, const char* sDevice) instead! * Switch a remote switch on (Type A with 10 pole DIP switches) * * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param nChannelCode Number of the switch itself (1..5) */ void RCSwitch::switchOn(const char* sGroup, int nChannel) { const char* code[6] = { "00000", "10000", "01000", "00100", "00010", "00001" }; this->switchOn(sGroup, code[nChannel]); } /** * Deprecated, use switchOff(const char* sGroup, const char* sDevice) instead! * Switch a remote switch off (Type A with 10 pole DIP switches) * * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param nChannelCode Number of the switch itself (1..5) */ void RCSwitch::switchOff(const char* sGroup, int nChannel) { const char* code[6] = { "00000", "10000", "01000", "00100", "00010", "00001" }; this->switchOff(sGroup, code[nChannel]); } /** * Switch a remote switch on (Type A with 10 pole DIP switches) * * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param sDevice Code of the switch device (refers to DIP switches 6..10 (A..E) where "1" = on and "0" = off, if all DIP switches are on it's "11111") */ void RCSwitch::switchOn(const char* sGroup, const char* sDevice) { this->sendTriState( this->getCodeWordA(sGroup, sDevice, true) ); } /** * Switch a remote switch off (Type A with 10 pole DIP switches) * * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param sDevice Code of the switch device (refers to DIP switches 6..10 (A..E) where "1" = on and "0" = off, if all DIP switches are on it's "11111") */ void RCSwitch::switchOff(const char* sGroup, const char* sDevice) { this->sendTriState( this->getCodeWordA(sGroup, sDevice, false) ); } /** * Returns a char[13], representing the code word to be send. * */ char* RCSwitch::getCodeWordA(const char* sGroup, const char* sDevice, bool bStatus) { static char sReturn[13]; int nReturnPos = 0; for (int i = 0; i < 5; i++) { sReturn[nReturnPos++] = (sGroup[i] == '0') ? 'F' : '0'; } for (int i = 0; i < 5; i++) { sReturn[nReturnPos++] = (sDevice[i] == '0') ? 'F' : '0'; } sReturn[nReturnPos++] = bStatus ? '0' : 'F'; sReturn[nReturnPos++] = bStatus ? 'F' : '0'; sReturn[nReturnPos] = '\0'; return sReturn; } /** * Encoding for type B switches with two rotary/sliding switches. * * The code word is a tristate word and with following bit pattern: * * +-----------------------------+-----------------------------+----------+------------+ * | 4 bits address | 4 bits address | 3 bits | 1 bit | * | switch group | switch number | not used | on / off | * | 1=0FFF 2=F0FF 3=FF0F 4=FFF0 | 1=0FFF 2=F0FF 3=FF0F 4=FFF0 | FFF | on=F off=0 | * +-----------------------------+-----------------------------+----------+------------+ * * @param nAddressCode Number of the switch group (1..4) * @param nChannelCode Number of the switch itself (1..4) * @param bStatus Whether to switch on (true) or off (false) * * @return char[13], representing a tristate code word of length 12 */ char* RCSwitch::getCodeWordB(int nAddressCode, int nChannelCode, bool bStatus) { static char sReturn[13]; int nReturnPos = 0; if (nAddressCode < 1 || nAddressCode > 4 || nChannelCode < 1 || nChannelCode > 4) { return 0; } for (int i = 1; i <= 4; i++) { sReturn[nReturnPos++] = (nAddressCode == i) ? '0' : 'F'; } for (int i = 1; i <= 4; i++) { sReturn[nReturnPos++] = (nChannelCode == i) ? '0' : 'F'; } sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = bStatus ? 'F' : '0'; sReturn[nReturnPos] = '\0'; return sReturn; } /** * Like getCodeWord (Type C = Intertechno) */ char* RCSwitch::getCodeWordC(char sFamily, int nGroup, int nDevice, bool bStatus) { static char sReturn[13]; int nReturnPos = 0; int nFamily = (int)sFamily - 'a'; if ( nFamily < 0 || nFamily > 15 || nGroup < 1 || nGroup > 4 || nDevice < 1 || nDevice > 4) { return 0; } // encode the family into four bits sReturn[nReturnPos++] = (nFamily & 1) ? 'F' : '0'; sReturn[nReturnPos++] = (nFamily & 2) ? 'F' : '0'; sReturn[nReturnPos++] = (nFamily & 4) ? 'F' : '0'; sReturn[nReturnPos++] = (nFamily & 8) ? 'F' : '0'; // encode the device and group sReturn[nReturnPos++] = ((nDevice-1) & 1) ? 'F' : '0'; sReturn[nReturnPos++] = ((nDevice-1) & 2) ? 'F' : '0'; sReturn[nReturnPos++] = ((nGroup-1) & 1) ? 'F' : '0'; sReturn[nReturnPos++] = ((nGroup-1) & 2) ? 'F' : '0'; // encode the status code sReturn[nReturnPos++] = '0'; sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = bStatus ? 'F' : '0'; sReturn[nReturnPos] = '\0'; return sReturn; } /** * Encoding for the REV Switch Type * * The code word is a tristate word and with following bit pattern: * * +-----------------------------+-------------------+----------+--------------+ * | 4 bits address | 3 bits address | 3 bits | 2 bits | * | switch group | device number | not used | on / off | * | A=1FFF B=F1FF C=FF1F D=FFF1 | 1=0FF 2=F0F 3=FF0 | 000 | on=10 off=01 | * +-----------------------------+-------------------+----------+--------------+ * * Source: http://www.the-intruder.net/funksteckdosen-von-rev-uber-arduino-ansteuern/ * * @param sGroup Name of the switch group (A..D, resp. a..d) * @param nDevice Number of the switch itself (1..3) * @param bStatus Whether to switch on (true) or off (false) * * @return char[13], representing a tristate code word of length 12 */ char* RCSwitch::getCodeWordD(char sGroup, int nDevice, bool bStatus) { static char sReturn[13]; int nReturnPos = 0; // sGroup must be one of the letters in "abcdABCD" int nGroup = (sGroup >= 'a') ? (int)sGroup - 'a' : (int)sGroup - 'A'; if ( nGroup < 0 || nGroup > 3 || nDevice < 1 || nDevice > 3) { return 0; } for (int i = 0; i < 4; i++) { sReturn[nReturnPos++] = (nGroup == i) ? '1' : 'F'; } for (int i = 1; i <= 3; i++) { sReturn[nReturnPos++] = (nDevice == i) ? '1' : 'F'; } sReturn[nReturnPos++] = '0'; sReturn[nReturnPos++] = '0'; sReturn[nReturnPos++] = '0'; sReturn[nReturnPos++] = bStatus ? '1' : '0'; sReturn[nReturnPos++] = bStatus ? '0' : '1'; sReturn[nReturnPos] = '\0'; return sReturn; } /** * @param sCodeWord a tristate code word consisting of the letter 0, 1, F */ void RCSwitch::sendTriState(const char* sCodeWord) { // turn the tristate code word into the corresponding bit pattern, then send it unsigned long long code = 0; unsigned int length = 0; for (const char* p = sCodeWord; *p; p++) { code <<= 2L; switch (*p) { case '0': // bit pattern 00 break; case 'F': // bit pattern 01 code |= 1LL; break; case '1': // bit pattern 11 code |= 3LL; break; } length += 2; } this->send(code, length); } /** * @param sCodeWord a binary code word consisting of the letter 0, 1 */ void RCSwitch::send(const char* sCodeWord) { // turn the tristate code word into the corresponding bit pattern, then send it unsigned long long code = 0; unsigned int length = 0; for (const char* p = sCodeWord; *p; p++) { code <<= 1LL; if (*p != '0') code |= 1LL; length++; } this->send(code, length); } /** * Transmit the first 'length' bits of the integer 'code'. The * bits are sent from MSB to LSB, i.e., first the bit at position length-1, * then the bit at position length-2, and so on, till finally the bit at position 0. */ void RCSwitch::send(unsigned long long code, unsigned int length) { if (this->nTransmitterPin == -1) return; #if not defined( RCSwitchDisableReceiving ) // make sure the receiver is disabled while we transmit int nReceiverInterrupt_backup = nReceiverInterrupt; if (nReceiverInterrupt_backup != -1) { this->disableReceive(); } #endif for (int nRepeat = 0; nRepeat < nRepeatTransmit; nRepeat++) { for (int i = length-1; i >= 0; i--) { if (code & (1LL << i)) this->transmit(protocol.one); else this->transmit(protocol.zero); } this->transmit(protocol.syncFactor); } // Disable transmit after sending (i.e., for inverted protocols) digitalWrite(this->nTransmitterPin, LOW); #if not defined( RCSwitchDisableReceiving ) // enable receiver again if we just disabled it if (nReceiverInterrupt_backup != -1) { this->enableReceive(nReceiverInterrupt_backup); } #endif } /** * Transmit a single high-low pulse. */ void RCSwitch::transmit(HighLow pulses) { uint8_t firstLogicLevel = (this->protocol.invertedSignal) ? LOW : HIGH; uint8_t secondLogicLevel = (this->protocol.invertedSignal) ? HIGH : LOW; digitalWrite(this->nTransmitterPin, firstLogicLevel); delayMicroseconds( this->protocol.pulseLength * pulses.high); digitalWrite(this->nTransmitterPin, secondLogicLevel); delayMicroseconds( this->protocol.pulseLength * pulses.low); } #if not defined( RCSwitchDisableReceiving ) /** * Enable receiving data */ void RCSwitch::enableReceive(int interrupt) { pinMode(interrupt,INPUT); this->nReceiverInterrupt = digitalPinToInterrupt(interrupt); this->enableReceive(); } void RCSwitch::enableReceive() { if (this->nReceiverInterrupt != -1) { RCSwitch::nReceivedValue = 0; RCSwitch::nReceivedBitlength = 0; #if defined(RaspberryPi) // Raspberry Pi wiringPiISR(this->nReceiverInterrupt, INT_EDGE_BOTH, &handleInterrupt); #else // Arduino attachInterrupt(this->nReceiverInterrupt, handleInterrupt, CHANGE); #endif } } /** * Disable receiving data */ void RCSwitch::disableReceive() { #if not defined(RaspberryPi) // Arduino detachInterrupt(this->nReceiverInterrupt); #endif // For Raspberry Pi (wiringPi) you can't unregister the ISR this->nReceiverInterrupt = -1; } bool RCSwitch::available() { return RCSwitch::nReceivedValue != 0; } void RCSwitch::resetAvailable() { RCSwitch::nReceivedValue = 0; } unsigned long long RCSwitch::getReceivedValue() { return RCSwitch::nReceivedValue; } unsigned int RCSwitch::getReceivedBitlength() { return RCSwitch::nReceivedBitlength; } unsigned int RCSwitch::getReceivedDelay() { return RCSwitch::nReceivedDelay; } unsigned int RCSwitch::getReceivedProtocol() { return RCSwitch::nReceivedProtocol; } unsigned int* RCSwitch::getReceivedRawdata() { return RCSwitch::timings; } /* helper function for the receiveProtocol method */ static inline unsigned int diff(int A, int B) { return abs(A - B); } /** * */ bool RECEIVE_ATTR RCSwitch::receiveProtocol(const int p, unsigned int changeCount) { #if defined(ESP8266) || defined(ESP32) const Protocol &pro = proto[p-1]; #else Protocol pro; memcpy_P(&pro, &proto[p-1], sizeof(Protocol)); #endif unsigned long long code = 0; //Assuming the longer pulse length is the pulse captured in timings[0] const unsigned int syncLengthInPulses = ((pro.syncFactor.low) > (pro.syncFactor.high)) ? (pro.syncFactor.low) : (pro.syncFactor.high); const unsigned int delay = RCSwitch::timings[0] / syncLengthInPulses; const unsigned int delayTolerance = delay * RCSwitch::nReceiveTolerance / 100; /* For protocols that start low, the sync period looks like * _________ * _____________| |XXXXXXXXXXXX| * * |--1st dur--|-2nd dur-|-Start data-| * * The 3rd saved duration starts the data. * * For protocols that start high, the sync period looks like * * ______________ * | |____________|XXXXXXXXXXXXX| * * |-filtered out-|--1st dur--|--Start data--| * * The 2nd saved duration starts the data */ const unsigned int firstDataTiming = (pro.invertedSignal) ? (2) : (1); for (unsigned int i = firstDataTiming; i < changeCount - 1; i += 2) { code <<= 1LL; if (diff(RCSwitch::timings[i], delay * pro.zero.high) < delayTolerance && diff(RCSwitch::timings[i + 1], delay * pro.zero.low) < delayTolerance) { // zero } else if (diff(RCSwitch::timings[i], delay * pro.one.high) < delayTolerance && diff(RCSwitch::timings[i + 1], delay * pro.one.low) < delayTolerance) { // one code |= 1LL; } else { // Failed return false; } } if (changeCount > 7) { // ignore very short transmissions: no device sends them, so this must be noise RCSwitch::nReceivedValue = code; RCSwitch::nReceivedBitlength = (changeCount - 1) / 2; RCSwitch::nReceivedDelay = delay; RCSwitch::nReceivedProtocol = p; return true; } return false; } void RECEIVE_ATTR RCSwitch::handleInterrupt() { static unsigned int changeCount = 0; static unsigned long lastTime = 0; static unsigned int repeatCount = 0; const long time = micros(); const unsigned int duration = time - lastTime; if (duration > RCSwitch::nSeparationLimit) { // A long stretch without signal level change occurred. This could // be the gap between two transmission. if ((repeatCount==0) || (diff(duration, RCSwitch::timings[0]) < 200)) { // This long signal is close in length to the long signal which // started the previously recorded timings; this suggests that // it may indeed by a a gap between two transmissions (we assume // here that a sender will send the signal multiple times, // with roughly the same gap between them). repeatCount++; if (repeatCount == 2) { for(unsigned int i = 1; i <= numProto; i++) { if (receiveProtocol(i, changeCount)) { // receive succeeded for protocol i break; } } repeatCount = 0; } } changeCount = 0; } // detect overflow if (changeCount >= RCSWITCH_MAX_CHANGES) { changeCount = 0; repeatCount = 0; } RCSwitch::timings[changeCount++] = duration; lastTime = time; } #endif
[ "jserna@phoenixintelligencesecurity.com" ]
jserna@phoenixintelligencesecurity.com
300fbf195ffcf17fc012b019b598ab04a2e023ac
590eb4cc4d0fe83d9740ce478f857ca3a98e7dae
/OGDF/src/coin/Cgl/CglMessage.cpp
7497d33f3084b7264025203e78b286eb305ac02f
[ "MIT", "LGPL-2.1-or-later", "GPL-3.0-only", "GPL-1.0-or-later", "EPL-1.0", "GPL-2.0-only", "LicenseRef-scancode-generic-exception", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
cerebis/MetaCarvel
d0ca77645e9a964e349144974a05e17fa48c6e99
a047290e88769773d43e0a9f877a88c2a8df89d5
refs/heads/master
2020-12-05T05:40:19.460644
2020-01-06T05:38:34
2020-01-06T05:38:34
232,023,146
0
0
MIT
2020-01-06T04:22:00
2020-01-06T04:21:59
null
UTF-8
C++
false
false
2,249
cpp
// $Id: CglMessage.cpp 948 2011-01-04 23:28:13Z lou $ // Copyright (C) 2005, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). #include "CoinPragma.hpp" #include "CglMessage.hpp" #include <cstring> /// Structure for use by CglMessage.cpp typedef struct { CGL_Message internalNumber; int externalNumber; // or continuation char detail; const char * message; } Cgl_message; static Cgl_message us_english[]= { {CGL_INFEASIBLE,0,1,"Cut generators found to be infeasible!"}, {CGL_CLIQUES,1,2,"%d cliques of average size %g"}, {CGL_FIXED,2,1,"%d variables fixed"}, {CGL_PROCESS_STATS,3,1,"%d fixed, %d tightened bounds, %d strengthened rows, %d substitutions"}, {CGL_SLACKS,8,1,"%d inequality constraints converted to equality constraints"}, {CGL_PROCESS_STATS2,4,1,"processed model has %d rows, %d columns (%d integer) and %d elements"}, {CGL_PROCESS_SOS1,5,1,"%d SOS with %d members"}, {CGL_PROCESS_SOS2,6,2,"%d SOS (%d members out of %d) with %d overlaps - too much overlap or too many others"}, {CGL_UNBOUNDED,7,1,"Continuous relaxation is unbounded!"}, {CGL_ELEMENTS_CHANGED1,9,2,"%d elements changed"}, {CGL_ELEMENTS_CHANGED2,10,3,"element in row %d for column %d changed from %g to %g"}, {CGL_MADE_INTEGER,11,1,"%d variables made integer"}, {CGL_ADDED_INTEGERS,12,1,"Added %d variables (from %d rows) with %d elements"}, {CGL_POST_INFEASIBLE,13,1,"Postprocessed model is infeasible - possible tolerance issue - try without preprocessing"}, {CGL_POST_CHANGED,14,1,"Postprocessing changed objective from %g to %g - possible tolerance issue - try without preprocessing"}, {CGL_DUMMY_END,999999,0,""} }; /* Constructor */ CglMessage::CglMessage(Language language) : CoinMessages(sizeof(us_english)/sizeof(Cgl_message)) { language_=language; strcpy(source_,"Cgl"); class_ = 3; // Cuts Cgl_message * message = us_english; while (message->internalNumber!=CGL_DUMMY_END) { CoinOneMessage oneMessage(message->externalNumber,message->detail, message->message); addMessage(message->internalNumber,oneMessage); message ++; } // Put into compact form toCompact(); }
[ "jayg@cbcbsub00.umiacs.umd.edu" ]
jayg@cbcbsub00.umiacs.umd.edu
d28179602b443f9cf622f0c0a697b75dbedb24c1
e68dd6cdee3e473f9fbc720410bc248fab728f7e
/transports/tr-spidriver.h
f86d0f583bf05243ed9bf9cfded9d9ead4bffc7e
[]
no_license
craftmetrics/gd2-lib
c10e6979313511cf919168e32256fa99576807f6
c14ce3798c3885eef234cbc85f0ecbd7ee6ecbdc
refs/heads/master
2020-05-23T07:34:20.648187
2019-05-11T13:36:30
2019-05-11T13:36:30
186,679,590
0
0
null
2019-05-14T18:38:10
2019-05-14T18:38:09
null
UTF-8
C++
false
false
3,405
h
#include "spidriver.h" class GDTransport { SPIDriver sd; uint16_t space, wp; uint8_t buf[64]; size_t nbuf; public: void begin0(void) { char *port = getenv("PORT"); spi_connect(&sd, port ? port : "/dev/ttyUSB0"); hostcmd(0x42); // SLEEP hostcmd(0x61); // CLKSEL default hostcmd(0x00); // ACTIVE hostcmd(0x48); // CLKINT hostcmd(0x49); // PD_ROMS all up hostcmd(0x68); // RST_PULSE ft8xx_model = 1; } void begin1(void) { while ((__rd16(0xc0000UL) & 0xff) != 0x08) ; wp = 0; stream(); } void ios(void) {} void external_crystal() { __end(); hostcmd(0x44); } void cmdbyte(char x) { if (nbuf == 64) flush(); buf[nbuf++] = x; } void cmd32(uint32_t x) { if (nbuf == 64) flush(); *(uint32_t*)&buf[nbuf] = x; nbuf += 4; } void cmd_n(byte *s, size_t n) { flush(); getspace(n); spi_write(&sd, (char*)s, n); wp += n; } void hostcmd(uint8_t a) { char buf[3] = {(char)a, 0, 0}; spi_sel(&sd); spi_write(&sd, buf, 3); spi_unsel(&sd); } uint16_t rd16(uint32_t a) { __end(); uint16_t r = __rd16(a); stream(); return r; } void wr16(uint32_t a, uint16_t v) { __end(); __wr16(a, v); stream(); } uint8_t rd(uint32_t a) { return rd16(a); } #define ADDR3(a) (char)((a >> 16) ), (char)(a >> 8), (char)(a) #define WADDR3(a) (char)((a >> 16) | 0x80), (char)(a >> 8), (char)(a) void wr(uint32_t a, byte v) { __end(); char buf[4] = {WADDR3(a), (char)v}; spi_sel(&sd); spi_write(&sd, buf, sizeof(buf)); spi_unsel(&sd); stream(); } void __end() { spi_unsel(&sd); } void stream(void) { space = __rd16(REG_CMDB_SPACE); assert((space & 3) == 0); __wstart(REG_CMDB_WRITE); } void resume(void) { stream(); } void getspace(uint16_t n) { while (space < n) { __end(); stream(); } space -= n; } uint32_t getwp(void) { flush(); return RAM_CMD + (wp & 0xffc); } uint32_t rd32(uint32_t a) { uint32_t r; rd_n((byte*)&r, a, 4); return r; } void rd_n(byte *dst, uint32_t a, uint16_t n) { __end(); char buf[4] = {ADDR3(a)}; spi_sel(&sd); spi_write(&sd, buf, sizeof(buf)); spi_read(&sd, (char*)dst, n); spi_unsel(&sd); stream(); } void wr32(uint32_t a, uint32_t v) { } void flush() { if (nbuf) { getspace(nbuf); spi_write(&sd, (char*)buf, nbuf); wp += nbuf; nbuf = 0; } } void finish() { flush(); while (space < 4092) { __end(); stream(); } } void bulk(uint32_t addr) {} void __wstart(uint32_t a) { char buf[3] = {WADDR3(a)}; spi_sel(&sd); spi_write(&sd, buf, sizeof(buf)); } unsigned int __rd16(uint32_t a) { char buf[6] = {ADDR3(a), (char)-1, (char)-1, (char)-1}; spi_sel(&sd); spi_writeread(&sd, buf, sizeof(buf)); spi_unsel(&sd); return *(uint16_t*)&buf[4]; } void __wr16(uint32_t a, unsigned int v) { char buf[5] = {WADDR3(a), (char)v, (char)(v >> 8)}; spi_sel(&sd); spi_write(&sd, buf, sizeof(buf)); spi_unsel(&sd); } void stop() {} // end the SPI transaction void wr_n(uint32_t addr, byte *src, uint16_t n) { __end(); __wstart(addr); spi_write(&sd, (char*)src, n); spi_unsel(&sd); stream(); } };
[ "jamesb@excamera.com" ]
jamesb@excamera.com
583b4ec754d728076c0043befccb58818cd664c4
e51520cdaf5c0b1e44906a9c948f468be5737eec
/chap6 - conditionals/6.card/card.cpp
ccbe985fd67eb57c60262b680c9c6028a3dda593
[]
no_license
nirajmahajan/Abhiram-Ranade
c2df229ff7184e2892defeae7e98a34df3ccf4e7
b6367b17df939f47649ed361d408265b093994bc
refs/heads/master
2020-05-29T17:58:37.749347
2019-05-29T20:12:07
2019-05-29T20:12:07
189,291,030
0
0
null
null
null
null
UTF-8
C++
false
false
1,309
cpp
// inputs a number and outputs the card number // sequence : club, diamond, heart, spade // By Niraj Mahajan IITB CSE #include <iostream> #include <cstdio> #include <cstdlib> #include <string> int main(void) { int num; // error checking do { std::cout << "Card number: "; std::cin >> num; } while (num > 52 || num <= 0); // find the suite using integer division!! int suite = (num - 1) / 13; // the magnitude of the card int magnitude = num - (13 * suite); // define a string! char mag[6]; // take cases for the card to be jac or queen or king or ace or ten // we take case for ten, because we are gonna convert single digit integers to ascii directly if(magnitude == 11) { char mag[] = "Jack"; } else if ( magnitude == 12) { char mag[] = "Queen"; } else if (magnitude == 13) { char mag[] = "King"; } else if (magnitude == 1) { char mag[] = "Ace"; } else if (magnitude == 10) { char mag[] = "10"; } else { mag[0] = {(char)('0' + magnitude)}; mag[1] = {'\0'}; } if (suite == 0) { printf("%s of Spades\n", mag); } else if (suite == 1) { printf("%s of Hearts\n", mag); } else if (suite == 2) { printf("%s of Diamonds\n", mag); } else if (suite == 3) { printf("%s of Clubs\n", mag); } else { printf("Error!!\n"); return 1; } }
[ "nirajmahajan007@gmail.com" ]
nirajmahajan007@gmail.com
a09e04855c67f9cefbe8b83b0a7ee9b3535c5d9d
4498a53d12a3e1611540d2130c36f36f6e9294cd
/braintrain/einstein/headers/Vector.h
22cc3127aded0fe8ae7afb68095059f76696d080
[]
no_license
haldokan/CppEdge
bec9fb92ea8a7f2dd473e7bc1f3bd97d11abf4e0
ae6a8509d41ee7b2f2c29fde00480ebec6d5fb0c
refs/heads/main
2023-02-10T02:19:20.788089
2021-01-05T17:32:23
2021-01-05T17:32:23
304,011,300
0
0
null
null
null
null
UTF-8
C++
false
false
1,280
h
#ifndef CPP_VECTOR_H #define CPP_VECTOR_H #include <initializer_list> using namespace std; namespace N { enum class Category { small, medium, large }; inline Category &operator++(Category &c) { switch (c) { case Category::small: return c = Category::medium; case Category::medium: return c = Category::large; case Category::large: return c = Category::small; } } class Vector { private: int length; double *items; Category category; public: explicit Vector(int); // no implicit conversion from int to vector Vector(int, Category); Vector(initializer_list<double>); Vector(); ~Vector(); // const signifies that this func doesn't modify its object. It can be called by const and non-const objects // however non-const funcs cannot be called by const objects (talk about simplicity!) [[nodiscard]] int get_size() const; double &operator[](int); // should never throw and exception but if it does the program will terminate by calling std::terminate() const Category get_category() noexcept; }; } #endif //CPP_VECTOR_H
[ "haldokanji@bloomberg.net" ]
haldokanji@bloomberg.net
84687d12b00ef4efff31ccb23205c6601edde2ec
e2064e3760e3e11ebcfb6c9552eb7afdfc086876
/rm/rmtest_08.cc
18df20d0ba4e27bed8e12ad37f486a1444634edb
[]
no_license
gauthamv/pdm
ae4dee5f3e6e863f5499eb8c735f14fc00f4ae28
b78aad04de4cf664559d3ef2d313ffeaac9bb17c
refs/heads/master
2021-01-10T11:16:35.450644
2015-06-12T11:46:14
2015-06-12T11:46:14
44,423,913
0
0
null
null
null
null
UTF-8
C++
false
false
1,839
cc
//#include "test_util.h" // //RC TEST_RM_8(const string &tableName, vector<RID> &rids, vector<int> &sizes) //{ // // Functions Tested for large tables: // // 1. getAttributes // // 2. insert tuple // cout << endl << "***** In RM Test Case 8 *****" << endl; // // RID rid; // void *tuple = malloc(2000); // int numTuples = 2000; // // // GetAttributes // vector<Attribute> attrs; // RC rc = rm->getAttributes(tableName, attrs); // assert(rc == success && "RelationManager::getAttributes() should not fail."); // // int nullAttributesIndicatorActualSize = getActualByteForNullsIndicator(attrs.size()); // unsigned char *nullsIndicator = (unsigned char *) malloc(nullAttributesIndicatorActualSize); // memset(nullsIndicator, 0, nullAttributesIndicatorActualSize); // //// for(unsigned i = 0; i < attrs.size(); i++) //// { //// cout << "Attr Name: " << attrs[i].name << " Type: " << (AttrType) attrs[i].type << " Len: " << attrs[i].length << endl; //// } // // // Insert 2000 tuples into table // for(int i = 0; i < numTuples; i++) // { // // Test insert Tuple // int size = 0; // memset(tuple, 0, 2000); // prepareLargeTuple(attrs.size(), nullsIndicator, i, tuple, &size); // // rc = rm->insertTuple(tableName, tuple, rid); // assert(rc == success && "RelationManager::insertTuple() should not fail."); // // rids.push_back(rid); // sizes.push_back(size); // } // cout << "***** [PASS] Test Case 8 Passed *****" << endl << endl; // free(tuple); // writeRIDsToDisk(rids); // writeSizesToDisk(sizes); // // return success; //} // //int main() //{ // vector<RID> rids; // vector<int> sizes; // // // Insert Tuple // RC rcmain = TEST_RM_8("tbl_employee4", rids, sizes); // // return rcmain; //}
[ "gautham090590@gmail.com" ]
gautham090590@gmail.com
6e14cbf967f8c3ac0b853dbc3aaf5e62638db953
6b40e9cba1dd06cd31a289adff90e9ea622387ac
/Develop/Server/GameServerOck/unittest/TestOptions.cpp
a0f56f1f6566bc83b9e30f089a81771eb8b00618
[]
no_license
AmesianX/SHZPublicDev
c70a84f9170438256bc9b2a4d397d22c9c0e1fb9
0f53e3b94a34cef1bc32a06c80730b0d8afaef7d
refs/heads/master
2022-02-09T07:34:44.339038
2014-06-09T09:20:04
2014-06-09T09:20:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,970
cpp
#include "stdafx.h" #include "AOptions.h" #include <regex> SUITE(Options) { struct TestOptions { AOptions m_options; }; TEST_FIXTURE(TestOptions, Options) { bool help; bool debug; m_options.Add(L"help", L"", help); m_options.Add(L"debug", L"", debug); CHECK(m_options.Parse(L"-help")); CHECK(help); CHECK(!debug); } TEST_FIXTURE(TestOptions, ArgumentOptions) { wstring filename; int count; m_options.Add(L"file", L"", filename); m_options.Add(L"count", L"", count); CHECK(m_options.Parse(L"-file filename -count 10")); CHECK(L"filename" == filename); CHECK_EQUAL(10, count); } TEST_FIXTURE(TestOptions, Arguments) { wstring filename; vector<wstring> fileList; m_options.Add(L"file", L"", filename); m_options.Add(L"file", L"", fileList); CHECK(m_options.Parse(L"-file first second third")); CHECK(L"first second third" == filename); ASSERT_EQUAL(3, fileList.size()); CHECK(L"first" == fileList[0]); CHECK(L"second" == fileList[1]); CHECK(L"third" == fileList[2]); } TEST_FIXTURE(TestOptions, CustomSwitch) { bool help; m_options.Add(L"help", L"", help); m_options.SetSwitch(L"/"); CHECK(m_options.Parse(L"/help")); CHECK(help); } TEST_FIXTURE(TestOptions, CustomSwitchWithRegexLetrer) { bool help; m_options.Add(L"help", L"", help); m_options.SetSwitch(L"*"); CHECK(m_options.Parse(L"*help")); CHECK(help); } TEST_FIXTURE(TestOptions, CustomSeparator) { wstring filename; m_options.Add(L"file", L"", filename); m_options.SetSeparator(L"="); CHECK(m_options.Parse(L"-file=filename")); CHECK(L"filename" == filename); } TEST_FIXTURE(TestOptions, CustomSplitter) { wstring filename; vector<wstring> fileList; m_options.Add(L"file", L"", fileList); m_options.Add(L"file", L"", filename); m_options.SetSplitter(L","); CHECK(m_options.Parse(L"-file first, second double, third")); CHECK(L"first, second double, third" == filename); ASSERT_EQUAL(3, fileList.size()); CHECK(L"first" == fileList[0]); CHECK(L"second double" == fileList[1]); CHECK(L"third" == fileList[2]); } TEST_FIXTURE(TestOptions, LongSwitchWithEtc) { wstring filename; vector<wstring> fileList; m_options.Add(L"file", L"", fileList); m_options.Add(L"file", L"", filename); m_options.SetSwitch(L"-["); m_options.SetSeparator(L"]="); m_options.SetSplitter(L".,"); CHECK(m_options.Parse(L"-[file]=first.,second double.,third")); CHECK(L"first.,second double.,third" == filename); ASSERT_EQUAL(3, fileList.size()); CHECK(L"first" == fileList[0]); CHECK(L"second double" == fileList[1]); CHECK(L"third" == fileList[2]); } TEST_FIXTURE(TestOptions, NonSwitchOption) { vector<wstring> standaloneList; vector<wstring> launchList; m_options.Add(L"standalone", L"", standaloneList); m_options.Add(L"launch", L"", launchList); m_options.SetSwitch(L""); CHECK(m_options.Parse(L"launch test localhost 109 1 1 1")); CHECK(standaloneList.empty()); ASSERT_EQUAL(6, launchList.size()); CHECK(L"test" == launchList[0]); CHECK(L"localhost" == launchList[1]); CHECK(L"109" == launchList[2]); CHECK(L"1" == launchList[3]); CHECK(L"1" == launchList[4]); CHECK(L"1" == launchList[5]); } // Reserve features //TEST_FIXTURE(TestOptions, OutputDescription) {} //TEST_FIXTURE(TestOptions, ExtraArgument) {} // app.exe extra argument -f //TEST_FIXTURE(TestOptions, ShorSwitch) {} // -fFilename //TEST_FIXTURE(TestOptions, SingleArgument) {} // -f an_argument //TEST_FIXTURE(TestOptions, DoubleQuotesArgument) {} // -file "first;second double;third" //TEST_FIXTURE(TestOptions, SetWhitespace) {} // -file first,second_double,third //TEST_FIXTURE(TestOptions, CaseSensitive) {} // -FILE firname }
[ "shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4" ]
shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4
011ddf73d78a575dd82d1f6c5045bd5b445d0439
a531acc6ed1819ec3d0f17aa990a5b079c42a1f0
/mdlink/src/base/Calendar.h
aefad5f3c93fd1f5adbc00318bd04a2fa98bbd60
[ "Apache-2.0" ]
permissive
Zzzzero/DataCore
67d49fc8c838b35a89c2aa173a1b2df5a0ace687
ca8434c0b209efc08e52f392196577b5d9a35674
refs/heads/master
2021-08-22T03:48:00.117685
2017-11-29T05:57:35
2017-11-29T05:57:35
112,545,756
1
0
null
2017-11-30T00:54:30
2017-11-30T00:54:30
null
UTF-8
C++
false
false
2,081
h
/*********************************************************************** Copyright 2017 quantOS-org 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 CALENDAR_H #define CALENDAR_H #include <chrono> #include <cstdint> #include <ctime> #include <iomanip> #include <sstream> #include <iostream> #include <map> #include <vector> #include "TimeUtil.h" using namespace jzs; using namespace std; namespace jzs { class Calendar { public: Calendar(); static Calendar* getInst(); int GetActionDayFromTradeDay(int tradeday, MillisTime time, int jzcode = -1); int GetTradeDayFromActionDay(int actionday, MillisTime time, int jzcode = -1); int GetTradeDay(MillisTime time, int jzcode = -1); int GetPreDay(int day); int GetNextDay(int day); int GetDate(); void init(); ~Calendar(); private: void GetNextDay(struct tm& td, struct tm& tm); void GetPreDay(struct tm& td, struct tm& tm); void GetNextTime(struct tm& today, struct tm& tommrow, long seconds); void GetPreTime(struct tm& today, struct tm& tommrow, long seconds); int GetWeekDay(int yymmdd); // Next work day void GetNextWorkDay(struct tm& td, struct tm& tm) { GetNextDay(td, tm); struct tm tmp; while (tm.tm_wday == 0 || tm.tm_wday == 6) { tmp = tm; GetNextDay(tmp, tm); } } std::vector<int> m_tradedays; }; } #endif
[ "zpzhxb@163.com" ]
zpzhxb@163.com
5ed8c617f7f5b1d877b62d815907c905485a0d60
cb3fe2aa64cb24d0ced9adea6242671c075992b8
/kernel/lib/kernel/vfs/DevFileSystem.cpp
7c4e371d0c59e2d2a92a98763525fe162bffe78a
[ "MIT" ]
permissive
goniz/gzOS
2f5bad243d6a80d2e65df0804161efeceeae56a2
176bfcdd06370d634a56df61b0cd7cf6c92ad9f8
refs/heads/master
2021-01-11T17:04:48.961772
2018-06-08T22:43:49
2018-06-08T22:43:49
69,507,029
3
2
null
2017-06-03T16:18:12
2016-09-28T21:56:47
C
UTF-8
C++
false
false
2,752
cpp
#include <platform/drivers.h> #include <lib/primitives/InterruptsMutex.h> #include <vfs/VirtualFileSystem.h> #include <algorithm> #include "DevFileSystem.h" static int vfs_dev_init(void) { VirtualFileSystem& vfs = VirtualFileSystem::instance(); vfs.registerFilesystem("devfs", [](const char* source, const char* destName) { auto node = std::make_shared<DevFileSystem>(std::string(destName)); return std::static_pointer_cast<VFSNode>(node); }); vfs.mkdir("/dev"); vfs.mountFilesystem("devfs", "none", "/dev"); return 0; } DECLARE_DRIVER(vfs_dev, vfs_dev_init, STAGE_SECOND); DevVFSNode::DevVFSNode(std::string&& path, FileDescriptorFactory fdf) : BasicVFSNode(VFSNode::Type::File, std::move(path)), _fdFactory(fdf) { } std::unique_ptr<FileDescriptor> DevVFSNode::open(void) { if (_fdFactory) { return _fdFactory(); } else { return nullptr; } } static const std::vector<SharedVFSNode> _empty; const std::vector<SharedVFSNode>& DevVFSNode::childNodes(void) { return _empty; } SharedVFSNode DevVFSNode::createNode(VFSNode::Type type, std::string&& path) { return nullptr; } DevFileSystem::DevFileSystem(std::string&& path) : BasicVFSNode(VFSNode::Type::Directory, std::move(path)) { } bool DevFileSystem::registerDevice(const char *deviceName, FileDescriptorFactory factory) { auto comparator = [deviceName](const SharedVFSNode& iter) -> bool { return (iter && deviceName && iter->getPathSegment() == deviceName); }; auto result = std::find_if(_devices.begin(), _devices.end(), comparator); if (result != _devices.end()) { return false; } _devices.push_back(std::make_shared<DevVFSNode>(std::string(deviceName), factory)); return true; } const std::vector<SharedVFSNode>& DevFileSystem::childNodes(void) { return _devices; } SharedVFSNode DevFileSystem::createNode(VFSNode::Type type, std::string&& path) { return nullptr; } std::unique_ptr<FileDescriptor> DevFileSystem::open(void) { return std::make_unique<DevfsIoctlFileDescriptor>(*this); } DevfsIoctlFileDescriptor::DevfsIoctlFileDescriptor(DevFileSystem& devfs) : _devfs(devfs) { } int DevfsIoctlFileDescriptor::ioctl(int cmd, va_list args) { if ((int)DevFileSystem::IoctlCommands::RegisterDevice == cmd) { auto cmdbuf = va_arg(args, DevFileSystem::IoctlRegisterDevice); // kprintf("cmdbuf: %p\n", cmdbuf); kprintf("deviceName: %p fdFactory: %p\n", cmdbuf.deviceName, cmdbuf.fdFactory); return _devfs.registerDevice(cmdbuf.deviceName, cmdbuf.fdFactory) ? 0 : -1; } return -1; } const char* DevfsIoctlFileDescriptor::type(void) const { return "DevfsIoctlFileDescriptor"; }
[ "goni1993@gmail.com" ]
goni1993@gmail.com
f0b24e1b31cccd5c8defe1fea9d96059356abf01
a28ccadc85e1d356743f5f23b7a9945c7e3ee20f
/src/main/c++/headers/tld/LearningTargets.hpp
8e09f4184cc57ab3a6858b7c74753177d80169da
[ "MIT" ]
permissive
hesitationer/OpenCVClient
2e8b2db538c92a05f3a62e5b78d04a1d23a44885
a7119b1b108b8f15090751218851b8852241d274
refs/heads/master
2021-06-11T22:29:49.622612
2017-03-09T19:37:57
2017-03-09T19:37:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
463
hpp
// // Created by dialight on 09.03.17. // #ifndef DIALIGHTTLD_LEARNINGTARGETS_HPP #define DIALIGHTTLD_LEARNINGTARGETS_HPP #include <opencv2/opencv.hpp> class LearningTargets { std::vector<cv::Mat> targets; int previewSize; int countPerColumn; public: LearningTargets(int size, int width, int height); void clear(); void add(cv::Mat &frame, cv::Rect &bb); void show(cv::Mat &frame); }; #endif //DIALIGHTTLD_LEARNINGTARGETS_HPP
[ "light_01@rambler.ru" ]
light_01@rambler.ru
bdb0ae44c6c50ae4e72991e3d22277edd59d914e
a749064d841e4faf8fed78a0ac30434da7311a06
/server/Clustering/delaunay.h
c065ac2e3351c4b176a37feab4b255f91b2d8383
[]
no_license
zyavgarov/Clustering
f51d67c8179ca7d96f704da2d6a5fdfb66380804
23d32ce543e6a59b831a5e204cff3532a59121b9
refs/heads/main
2023-07-11T14:02:26.315535
2023-07-10T14:38:36
2023-07-10T14:38:36
360,912,096
0
0
null
null
null
null
UTF-8
C++
false
false
685
h
// Created by Zyavgarov Rustam #ifndef INTERFACE4__DELAUNAY_H_ #define INTERFACE4__DELAUNAY_H_ #include "../Field.h" class delaunay { struct Edge { const Point *a, *b; Edge (const Point *a, const Point *b) : a (a), b (b) { }; }; int err_; static void delaunay_fprintf (vector<vector<bool>> &edge, int iteration); public: delaunay (); int err () const; void delaunay_base_run (vector<Edge> &baselines, vector<vector<bool>> &edge, vector<bool> &points_done, int iteration); static double delaunay_angle_to_edge (Edge &edge, int num); }; #endif //INTERFACE4__DELAUNAY_H_
[ "zyavgarov@zohomail.com" ]
zyavgarov@zohomail.com
891eb7fec54d93f10e82700f9301396e52b5142e
8a4ff466fdbe089b83e20853ee983e6872b1ae9d
/src/engine/base/shellcmd/shellcmd.cpp
1969b205b04ae6f083eeebcad6be81f530cafbbc
[]
no_license
veerwang/framework
b4339bf11174c065f452660a091f3b5cf453dbbf
3786efca82642cabd9b8716b5a5060a6513efdb9
refs/heads/master
2020-05-16T23:37:24.501478
2014-10-10T07:10:18
2014-10-10T07:10:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
574
cpp
/* * ===================================================================================== * * Filename: shellcmd.cpp * * Description: implementaton of shellcmd * * Version: 1.0 * Created: 2014年09月13日 13时51分52秒 * Revision: none * Compiler: gcc * * Author: kevin (WangWei), kevin.wang2004@hotmail.com * Organization: GNU * * ===================================================================================== */ #include "shellcmd.h" Shellcmd::Shellcmd () { } Shellcmd::~Shellcmd () { }
[ "kevin.wang2004@hotmail.com" ]
kevin.wang2004@hotmail.com
10bddbfe6d80a77f5ac321eb7f09c00f9eb04f00
9aa34c5120d7a0514943b51935b5102411d86486
/trek_client/ZoomTransition.h
c50e5c800b1da99f15657809ed2c70bbe272017e
[]
no_license
jeremykross/Trek-Browser
6fc9179302c64cf2fc26567892029018fdceee23
55c1cbe89f9ea7bcebbf8b140fd1fc1f54281ebe
refs/heads/master
2020-03-27T00:46:19.632124
2012-02-28T01:02:05
2012-02-28T01:02:05
3,565,893
1
0
null
null
null
null
UTF-8
C++
false
false
501
h
#ifndef ZOOMTRANSITION_H #define ZOOMTRANSITION_H #include <QPainter> #include <QBrush> #include <QColor> #include <QImage> #include <QPixmap> #include <QLinearGradient> #include <QGLWidget> #include "SwitchTransitionWidget.h" class ZoomTransition : public SwitchTransitionWidget { public: ZoomTransition(int duration=1000, QWidget* parent=NULL); protected slots: void update(qreal progress); protected: void paintEvent(QPaintEvent* evt); qreal mScale; }; #endif
[ "jeremy.kross@gmail.com" ]
jeremy.kross@gmail.com
a7dc63c52be25429b94be7ac8419348bc2287132
737f2d68e6dec69091b030e31ed281cfe0658f66
/2021_06_04/BSTree.h
43a6ca2750865c005a17e804ebcbb6b6a5d1b522
[]
no_license
niangeer/Jie
b0517cf6a6abfa4cc905f17c0e7408ed990f79ea
f2f37207713b729ae4bf00fe82f33989e8758256
refs/heads/main
2023-06-01T20:04:05.883583
2021-06-16T15:16:51
2021-06-16T15:16:51
315,895,149
0
0
null
null
null
null
GB18030
C++
false
false
2,954
h
#include <iostream> using namespace std; template <class K> struct BSTreeNode { K _key; BSTreeNode<K>* _left; BSTreeNode<K>* _right; BSTreeNode(const K& key = K()) :_key(key) , _left(nullptr) , _right(nullptr) {} }; template<class K> class BSTree { typedef BSTreeNode<K> Node; public: bool Insert(const K& key) { //空树 if (_root == nullptr) { _root = new Node(key); return true; } //非空时找到插入位置 Node* cur = _root; Node* parent = nullptr; while (cur) { if (key > cur->_key) { parent = cur; cur = cur->_right; } else if (key < cur->_key) { parent = cur; cur = cur->_left; } else { return false; } } Node* newNode = new Node(key); if (key > parent->_key) //大于插入右侧 parent->_right = newNode; else //小于插入左侧 parent->_left = newNode; return true; } const Node* Find(const K& key) { Node* cur = _root; while (cur) { if (key > cur->_key) cur = cur->_right; else if (key < cur->_key) cur = cur->_left; else return cur; } return nullptr; } bool Erase(const K& key) { Node* cur = _root; Node* parent = nullptr; while (cur) { if (key > cur->_key) { parent = cur; cur = cur->_right; } else if (key < cur->_key) { parent = cur; cur = cur->_left; } else { //准备删除 //1,左为空 if (nullptr == cur->_left) { //特殊情况:cur为根并且parent为nullptr if (cur == _root) _root = _root->_right; else if (parent->_left == cur) parent->_left = cur->_right; else parent->_right = cur->_right; delete cur; } //2,右为空 else if (nullptr == cur->_right) { if (cur == _root) _root = _root->_left; else if (parent->_left == cur) parent->_left = cur->_left; else parent->_right = cur->_left; delete cur; } //3,左右都不为空 else { //替代法删除 //找右子树的最小节点(最左节点),或者左子树的最大节点(最右节点) Node* subMin = cur->_right; //可能有特殊情况:右子树根就是最小节点,若smParent不能置为空,需要等于cur Node* smParent = cur; while (subMin->_left) { smParent = subMin; subMin = subMin->_left; } cur->_key = subMin->_key; if (smParent->_left == subMin) smParent->_left = subMin->_right; else //特殊情况:cur就是最小节点,此时smParent->right == subMin smParent->_right = subMin->_right; delete subMin; } return true; } } return false; } void _InOrder(Node* root) { if (nullptr == root) return; _InOrder(root->_left); cout << root->_key << " "; _InOrder(root->_right); } void InOrder() { _InOrder(_root); cout << endl; } private: Node* _root = nullptr; };
[ "898609031@qq.com" ]
898609031@qq.com
a2dacb4435f57bceda2fc03f0da55a0fd7e2fdfd
36ce40e48cefc2737e731826ad348c91cbed24e0
/shaka/test/src/media/frame_buffer_unittest.cc
d32b8896a8241ee8ce3e451fab7f2673452da50a
[ "Apache-2.0" ]
permissive
chengjingfeng/shaka-player-embedded
bca96b41b5d374c5906bb6a5f8e889428f131356
6128d3e772c1d3b0815c19fd1e4156c3da6fa0ef
refs/heads/master
2020-09-22T18:15:39.535253
2019-11-18T19:09:54
2019-11-18T19:09:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,034
cc
// Copyright 2017 Google LLC // // 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 // // https://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 "src/media/frame_buffer.h" #include <gtest/gtest.h> #include <math.h> namespace shaka { namespace media { namespace { constexpr const bool kPtsOrder = false; constexpr const bool kDtsOrder = true; std::unique_ptr<BaseFrame> MakeFrame(double start, double end, bool is_key_frame = true) { BaseFrame* ret = new BaseFrame(start, start, end - start, is_key_frame); return std::unique_ptr<BaseFrame>(ret); } } // namespace TEST(FrameBufferTest, CreatesFirstRange) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); auto ranges = buffer.GetBufferedRanges(); ASSERT_EQ(1u, ranges.size()); EXPECT_EQ(0, ranges[0].start); EXPECT_EQ(10, ranges[0].end); } TEST(FrameBufferTest, CreatesNewRangeAtStart) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(20, 30)); // Should create a new range before the original. buffer.AppendFrame(MakeFrame(0, 10)); auto ranges = buffer.GetBufferedRanges(); ASSERT_EQ(2u, ranges.size()); EXPECT_EQ(0, ranges[0].start); EXPECT_EQ(10, ranges[0].end); EXPECT_EQ(20, ranges[1].start); EXPECT_EQ(30, ranges[1].end); } TEST(FrameBufferTest, CreatesNewRangeAtEnd) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); // Should create a new range after the original. buffer.AppendFrame(MakeFrame(20, 30)); auto ranges = buffer.GetBufferedRanges(); ASSERT_EQ(2u, ranges.size()); EXPECT_EQ(0, ranges[0].start); EXPECT_EQ(10, ranges[0].end); EXPECT_EQ(20, ranges[1].start); EXPECT_EQ(30, ranges[1].end); } TEST(FrameBufferTest, CreatesNewRangeInMiddle) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); buffer.AppendFrame(MakeFrame(40, 50)); ASSERT_EQ(2u, buffer.GetBufferedRanges().size()); // Should create a new range between the two existing ranges. buffer.AppendFrame(MakeFrame(20, 30)); auto ranges = buffer.GetBufferedRanges(); ASSERT_EQ(3u, ranges.size()); EXPECT_EQ(0, ranges[0].start); EXPECT_EQ(10, ranges[0].end); EXPECT_EQ(20, ranges[1].start); EXPECT_EQ(30, ranges[1].end); EXPECT_EQ(40, ranges[2].start); EXPECT_EQ(50, ranges[2].end); } TEST(FrameBufferTest, AddsToEndOfExistingRange) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); // Should add to the exiting range. buffer.AppendFrame(MakeFrame(10, 20)); auto ranges = buffer.GetBufferedRanges(); ASSERT_EQ(1u, ranges.size()); EXPECT_EQ(0, ranges[0].start); EXPECT_EQ(20, ranges[0].end); } TEST(FrameBufferTest, AddsToMiddleOfExistingRange) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); buffer.AppendFrame(MakeFrame(10, 20)); // Should insert the frame in between the existing two. The frames should be // in pts order, even though they are overlapping. buffer.AppendFrame(MakeFrame(5, 10)); auto ranges = buffer.GetBufferedRanges(); ASSERT_EQ(1u, ranges.size()); EXPECT_EQ(0, ranges[0].start); EXPECT_EQ(20, ranges[0].end); } TEST(FrameBufferTest, AddsToBeginningOfExistingRange) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(10, 20)); // Should add to the exiting range. buffer.AppendFrame(MakeFrame(0, 10)); auto ranges = buffer.GetBufferedRanges(); ASSERT_EQ(1u, ranges.size()); EXPECT_EQ(0, ranges[0].start); EXPECT_EQ(20, ranges[0].end); } TEST(FrameBufferTest, StillAddsToExistingWithGap) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); // Should add to the exiting range. buffer.AppendFrame(MakeFrame(10.01, 20)); auto ranges = buffer.GetBufferedRanges(); ASSERT_EQ(1u, ranges.size()); EXPECT_EQ(0, ranges[0].start); EXPECT_EQ(20, ranges[0].end); } TEST(FrameBufferTest, CombinesOverlappingRanges) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); buffer.AppendFrame(MakeFrame(20, 30)); ASSERT_EQ(2u, buffer.GetBufferedRanges().size()); // Should result in combining the two ranges. buffer.AppendFrame(MakeFrame(10, 20)); auto ranges = buffer.GetBufferedRanges(); ASSERT_EQ(1u, ranges.size()); EXPECT_EQ(0, ranges[0].start); EXPECT_EQ(30, ranges[0].end); } TEST(FrameBufferTest, CombinesRangesWithSmallGap) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); buffer.AppendFrame(MakeFrame(20, 30)); ASSERT_EQ(2u, buffer.GetBufferedRanges().size()); // Should result in combining the two ranges. buffer.AppendFrame(MakeFrame(10, 19.99)); auto ranges = buffer.GetBufferedRanges(); ASSERT_EQ(1u, ranges.size()); EXPECT_EQ(0, ranges[0].start); EXPECT_EQ(30, ranges[0].end); } TEST(FrameBufferTest, UsesPtsForBufferedRanges) { // This should use the PTS of the frames for buffered ranges, even when we // are sorted on DTS. This means that the first frame in the range may not // define the time ranges for it. FrameBuffer buffer(kDtsOrder); auto makeFrame = [](double dts, double pts) { return std::unique_ptr<BaseFrame>(new BaseFrame(pts, dts, 1, true)); }; // Range 1: DTS (0, 1, 2), PTS (1, 0, 2) buffer.AppendFrame(makeFrame(0, 1)); buffer.AppendFrame(makeFrame(1, 0)); buffer.AppendFrame(makeFrame(2, 2)); // Range 2: DTS (10, 11, 12), PTS (10, 12, 11) buffer.AppendFrame(makeFrame(10, 10)); buffer.AppendFrame(makeFrame(11, 12)); buffer.AppendFrame(makeFrame(12, 11)); auto buffered = buffer.GetBufferedRanges(); ASSERT_EQ(2u, buffered.size()); EXPECT_EQ(0, buffered[0].start); EXPECT_EQ(3, buffered[0].end); EXPECT_EQ(10, buffered[1].start); EXPECT_EQ(13, buffered[1].end); } TEST(FrameBufferTest, FramesBetween) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); buffer.AppendFrame(MakeFrame(10, 20)); buffer.AppendFrame(MakeFrame(20, 30)); buffer.AppendFrame(MakeFrame(30, 40)); // buffer.AppendFrame(MakeFrame(100, 110)); buffer.AppendFrame(MakeFrame(110, 120)); buffer.AppendFrame(MakeFrame(120, 130)); ASSERT_EQ(2u, buffer.GetBufferedRanges().size()); EXPECT_EQ(0, buffer.FramesBetween(0, 0)); EXPECT_EQ(0, buffer.FramesBetween(0, 10)); EXPECT_EQ(0, buffer.FramesBetween(5, 10)); EXPECT_EQ(2, buffer.FramesBetween(0, 30)); EXPECT_EQ(3, buffer.FramesBetween(0, 100)); EXPECT_EQ(4, buffer.FramesBetween(0, 105)); EXPECT_EQ(4, buffer.FramesBetween(0, 110)); EXPECT_EQ(2, buffer.FramesBetween(5, 30)); EXPECT_EQ(2, buffer.FramesBetween(100, 200)); } TEST(FrameBufferTest, GetKeyFrameBefore_FindsFrameBefore) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); buffer.AppendFrame(MakeFrame(10, 20, false)); buffer.AppendFrame(MakeFrame(20, 30, false)); ASSERT_EQ(1u, buffer.GetBufferedRanges().size()); const BaseFrame* frame = buffer.GetKeyFrameBefore(15).get(); ASSERT_NE(nullptr, frame); EXPECT_EQ(0, frame->pts); } TEST(FrameBufferTest, GetKeyFrameBefore_FindsExactFrame) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); buffer.AppendFrame(MakeFrame(10, 20)); buffer.AppendFrame(MakeFrame(20, 30)); ASSERT_EQ(1u, buffer.GetBufferedRanges().size()); const BaseFrame* frame = buffer.GetKeyFrameBefore(10).get(); ASSERT_NE(nullptr, frame); EXPECT_EQ(10, frame->pts); } TEST(FrameBufferTest, GetKeyFrameBefore_WontReturnFutureFrames) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(10, 20)); buffer.AppendFrame(MakeFrame(20, 30)); buffer.AppendFrame(MakeFrame(30, 40)); ASSERT_EQ(1u, buffer.GetBufferedRanges().size()); const BaseFrame* frame = buffer.GetKeyFrameBefore(0).get(); EXPECT_EQ(nullptr, frame); } TEST(FrameBufferTest, GetFrameAfter_GetsNext) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); buffer.AppendFrame(MakeFrame(10, 20)); const BaseFrame* frame = buffer.GetFrameAfter(0).get(); ASSERT_NE(nullptr, frame); EXPECT_EQ(10, frame->pts); } TEST(FrameBufferTest, GetFrameAfter_GetsNextAcrossRanges) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 2)); buffer.AppendFrame(MakeFrame(2, 3)); buffer.AppendFrame(MakeFrame(10, 12)); buffer.AppendFrame(MakeFrame(12, 14)); ASSERT_EQ(2u, buffer.GetBufferedRanges().size()); const BaseFrame* frame = buffer.GetFrameAfter(2).get(); ASSERT_NE(nullptr, frame); EXPECT_EQ(10, frame->pts); } TEST(FrameBufferTest, GetFrameAfter_ReturnsNull) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); ASSERT_EQ(nullptr, buffer.GetFrameAfter(0).get()); ASSERT_EQ(nullptr, buffer.GetFrameAfter(4).get()); ASSERT_EQ(nullptr, buffer.GetFrameAfter(10).get()); ASSERT_EQ(nullptr, buffer.GetFrameAfter(12).get()); } TEST(FrameBufferTest, GetFrameNear_NextFrame) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(10, 10)); const BaseFrame* frame = buffer.GetFrameNear(0).get(); ASSERT_NE(nullptr, frame); EXPECT_EQ(10, frame->pts); } TEST(FrameBufferTest, GetFrameNear_NextFrameBetweenRanges) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 0)); buffer.AppendFrame(MakeFrame(10, 10)); ASSERT_EQ(2u, buffer.GetBufferedRanges().size()); const BaseFrame* frame = buffer.GetFrameNear(7).get(); ASSERT_NE(nullptr, frame); EXPECT_EQ(10, frame->pts); } TEST(FrameBufferTest, GetFrameNear_PastTheEnd) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); buffer.AppendFrame(MakeFrame(10, 10)); const BaseFrame* frame = buffer.GetFrameNear(12).get(); ASSERT_NE(nullptr, frame); EXPECT_EQ(10, frame->pts); } TEST(FrameBufferTest, GetFrameNear_InPastBetweenRanges) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 1)); buffer.AppendFrame(MakeFrame(1, 2)); buffer.AppendFrame(MakeFrame(10, 11)); buffer.AppendFrame(MakeFrame(11, 12)); ASSERT_EQ(2u, buffer.GetBufferedRanges().size()); const BaseFrame* frame = buffer.GetFrameNear(3).get(); ASSERT_NE(nullptr, frame); EXPECT_EQ(1, frame->pts); } TEST(FrameBufferTest, GetFrameNear_GetsNearest) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 10)); buffer.AppendFrame(MakeFrame(10.01, 10)); ASSERT_EQ(1u, buffer.GetBufferedRanges().size()); const BaseFrame* frame = buffer.GetFrameNear(10.001).get(); ASSERT_NE(nullptr, frame); EXPECT_EQ(0, frame->pts); frame = buffer.GetFrameNear(10.009).get(); ASSERT_NE(nullptr, frame); EXPECT_EQ(10.01, frame->pts); } TEST(FrameBufferTest, GetFrameNear_ReturnsNull) { // Since it returns the nearest frame always, the only case it returns null is // when there are no frames. FrameBuffer buffer(kPtsOrder); const BaseFrame* frame = buffer.GetFrameNear(0).get(); ASSERT_EQ(nullptr, frame); } TEST(FrameBufferTest, Remove_RemovesWholeRange) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 1)); buffer.AppendFrame(MakeFrame(1, 2)); buffer.AppendFrame(MakeFrame(2, 3)); // buffer.AppendFrame(MakeFrame(6, 7)); buffer.AppendFrame(MakeFrame(7, 8)); ASSERT_EQ(2u, buffer.GetBufferedRanges().size()); buffer.Remove(6, 8); EXPECT_EQ(1u, buffer.GetBufferedRanges().size()); EXPECT_EQ(nullptr, buffer.GetFrameAfter(3).get()); } TEST(FrameBufferTest, Remove_SplitsRanges) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 1)); buffer.AppendFrame(MakeFrame(1, 2)); buffer.AppendFrame(MakeFrame(2, 3)); buffer.AppendFrame(MakeFrame(3, 4)); buffer.AppendFrame(MakeFrame(4, 5)); ASSERT_EQ(1u, buffer.GetBufferedRanges().size()); buffer.Remove(2, 4); auto buffered = buffer.GetBufferedRanges(); ASSERT_EQ(2u, buffered.size()); EXPECT_EQ(0, buffered[0].start); EXPECT_EQ(2, buffered[0].end); EXPECT_EQ(4, buffered[1].start); EXPECT_EQ(5, buffered[1].end); const BaseFrame* frame = buffer.GetFrameAfter(1).get(); ASSERT_NE(nullptr, frame); EXPECT_EQ(4, frame->pts); } TEST(FrameBufferTest, Remove_RemovesPartOfRange) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 1)); buffer.AppendFrame(MakeFrame(1, 2)); buffer.AppendFrame(MakeFrame(2, 3)); buffer.AppendFrame(MakeFrame(3, 4)); buffer.AppendFrame(MakeFrame(4, 5)); ASSERT_EQ(1u, buffer.GetBufferedRanges().size()); buffer.Remove(3, 5); auto buffered = buffer.GetBufferedRanges(); ASSERT_EQ(1u, buffered.size()); EXPECT_EQ(0, buffered[0].start); EXPECT_EQ(3, buffered[0].end); EXPECT_EQ(nullptr, buffer.GetFrameAfter(2).get()); } TEST(FrameBufferTest, Remove_RemovesMultipleRanges) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 1)); buffer.AppendFrame(MakeFrame(1, 2)); buffer.AppendFrame(MakeFrame(2, 3)); // buffer.AppendFrame(MakeFrame(5, 6)); buffer.AppendFrame(MakeFrame(6, 7)); // buffer.AppendFrame(MakeFrame(10, 11)); buffer.AppendFrame(MakeFrame(11, 12)); // buffer.AppendFrame(MakeFrame(15, 16)); buffer.AppendFrame(MakeFrame(16, 17)); buffer.AppendFrame(MakeFrame(17, 18)); ASSERT_EQ(4u, buffer.GetBufferedRanges().size()); buffer.Remove(0, 7); auto buffered = buffer.GetBufferedRanges(); ASSERT_EQ(2u, buffered.size()); EXPECT_EQ(10, buffered[0].start); EXPECT_EQ(12, buffered[0].end); EXPECT_EQ(15, buffered[1].start); EXPECT_EQ(18, buffered[1].end); } TEST(FrameBufferTest, Remove_RemovesAllRanges) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 1)); buffer.AppendFrame(MakeFrame(1, 2)); buffer.AppendFrame(MakeFrame(2, 3)); // buffer.AppendFrame(MakeFrame(5, 6)); buffer.AppendFrame(MakeFrame(6, 7)); ASSERT_EQ(2u, buffer.GetBufferedRanges().size()); buffer.Remove(0, 7); EXPECT_EQ(0u, buffer.GetBufferedRanges().size()); } TEST(FrameBufferTest, Remove_RemovesNothing) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 1)); buffer.AppendFrame(MakeFrame(1, 2)); buffer.AppendFrame(MakeFrame(2, 3)); // buffer.AppendFrame(MakeFrame(5, 6)); buffer.AppendFrame(MakeFrame(6, 7)); ASSERT_EQ(2u, buffer.GetBufferedRanges().size()); buffer.Remove(10, 20); auto buffered = buffer.GetBufferedRanges(); ASSERT_EQ(2u, buffered.size()); EXPECT_EQ(0, buffered[0].start); EXPECT_EQ(3, buffered[0].end); EXPECT_EQ(5, buffered[1].start); EXPECT_EQ(7, buffered[1].end); } TEST(FrameBufferTest, Remove_SupportsInfinity) { FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(2, 3)); buffer.AppendFrame(MakeFrame(3, 4)); // buffer.AppendFrame(MakeFrame(6, 7)); buffer.AppendFrame(MakeFrame(7, 8)); ASSERT_EQ(2u, buffer.GetBufferedRanges().size()); buffer.Remove(0, HUGE_VAL /* Infinity */); EXPECT_EQ(0u, buffer.GetBufferedRanges().size()); } TEST(FrameBufferTest, Remove_RemovesUntilKeyframe) { // When removing frames, it should remove frames past the given stop until the // next keyframe; see step 3.4 of the "Coded Frame Removal Algorithm" in MSE: // https://w3c.github.io/media-source/#sourcebuffer-coded-frame-removal FrameBuffer buffer(kPtsOrder); buffer.AppendFrame(MakeFrame(0, 1)); buffer.AppendFrame(MakeFrame(1, 2)); buffer.AppendFrame(MakeFrame(2, 3, false)); buffer.AppendFrame(MakeFrame(3, 4, false)); buffer.AppendFrame(MakeFrame(6, 7)); buffer.AppendFrame(MakeFrame(7, 8)); ASSERT_EQ(2u, buffer.GetBufferedRanges().size()); buffer.Remove(0, 2); // Should actually remove [0, 4]. auto buffered = buffer.GetBufferedRanges(); ASSERT_EQ(1u, buffered.size()); EXPECT_EQ(6, buffered[0].start); EXPECT_EQ(8, buffered[0].end); } } // namespace media } // namespace shaka
[ "modmaker@google.com" ]
modmaker@google.com
6b2a81731068b14beca855ac9c6ddf31ae272b65
0f8122308db34fb0b8766c1c5423d179a04dac2c
/c++/SplineInterpolation/main.cpp
e7f2d9ac7cbe56824a3b3b7594e0d9cd9372e043
[]
no_license
asdfc321/spline-interpolation
1d0971972d21b9111fa0478d1a7682aac4f96930
6d82f6372bc804debda5bbe42061b31177fcdd33
refs/heads/master
2021-10-22T00:21:19.495341
2019-03-07T08:47:38
2019-03-07T08:47:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
689
cpp
#include <iostream> using namespace std; #include "SplineInterpolation.h" int main() { #define InputDataLen 5 #define OutputDataLen ((InputDataLen+1)*10+1) float x_i[InputDataLen] = { 1,2,3,4,5 }; float y_i[InputDataLen] = { 19.6000000000000, 121.400000000000, 212.600000000000 ,122.800000000000 ,4.80000000000000, }; float xn[OutputDataLen]; float yn[OutputDataLen]; for (int i = 0; i < OutputDataLen; i++) { xn[i] = i*0.1; // printf("%f ", xn[i]); } SplineInterpolation< InputDataLen, OutputDataLen>(x_i, y_i, xn, yn, FindPositionID_0, 0); for (int cnt = 0; cnt < OutputDataLen; cnt++) { printf("%.4f ", yn[cnt]); } printf("\n"); return 0; }
[ "SRMLabHUST@163.com" ]
SRMLabHUST@163.com
580ed5a83d773b59e8893dde00b0e588f647c518
9a66499347b20af91e33d7c5d4df9261a325a75c
/Lab 1 - Operator Overloading/Complex.cpp
dba2a503930d060320b86b3a08dcf8f84b13cc9d
[]
no_license
nerooc/OOP-PL
4268b69746278ed1d0f3373bb35132b0161666c4
220aaaaf740b63a3a951f30842636da6a1a1d671
refs/heads/master
2022-12-16T23:09:31.022158
2020-09-09T23:36:30
2020-09-09T23:36:30
294,251,678
0
0
null
null
null
null
UTF-8
C++
false
false
724
cpp
#include "Complex.h" Complex::Complex(double x, double y) : _x(x), _y(y){}; double& Complex::re(){ return _x; } double& Complex::im(){ return _y; } double const & Complex::re() const{ return _x; } double const & Complex::im() const{ return _y; } Complex Complex::operator + (const Complex& complex) const{ Complex temp{*this}; temp._x += complex._x; temp._y += complex._y; return temp; } Complex& Complex::operator ++ (){ ++_x; ++_y; return *this; } Complex Complex::operator ++ (int){ _x++; _y++; return *this; } std::ostream& operator << (std::ostream& out, const Complex& complex){ std::cout << "(" << complex._x << " + " << complex._y << "*i)"; }
[ "tomaszgajdait@gmail.com" ]
tomaszgajdait@gmail.com
42e6ed72c6cc2c35098cefa742512683b1072b2c
41194968e73ba2874847828bc7f31a41259e29b5
/xulrunner-sdk/include/nsIZipReader.h
c278564916a8a87bdd9b6533ad2ccab344278c2e
[]
no_license
snowmantw/gaia-essential
81d544d579ff4c502a75480f1fcf3a19a6e783b7
2751716dc87dea320c9c9fd2a3f82deed337ad70
refs/heads/master
2020-04-05T17:03:12.939201
2013-12-08T10:55:46
2013-12-08T10:55:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,955
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/m-cen-osx64-xr-ntly-0000000000/build/modules/libjar/nsIZipReader.idl */ #ifndef __gen_nsIZipReader_h__ #define __gen_nsIZipReader_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIUTF8StringEnumerator; /* forward declaration */ class nsIInputStream; /* forward declaration */ class nsIFile; /* forward declaration */ class nsICertificatePrincipal; /* forward declaration */ /* starting interface: nsIZipEntry */ #define NS_IZIPENTRY_IID_STR "e1c028bc-c478-11da-95a8-00e08161165f" #define NS_IZIPENTRY_IID \ {0xe1c028bc, 0xc478, 0x11da, \ { 0x95, 0xa8, 0x00, 0xe0, 0x81, 0x61, 0x16, 0x5f }} class NS_NO_VTABLE nsIZipEntry : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IZIPENTRY_IID) /* readonly attribute unsigned short compression; */ NS_IMETHOD GetCompression(uint16_t *aCompression) = 0; /* readonly attribute unsigned long size; */ NS_IMETHOD GetSize(uint32_t *aSize) = 0; /* readonly attribute unsigned long realSize; */ NS_IMETHOD GetRealSize(uint32_t *aRealSize) = 0; /* readonly attribute unsigned long CRC32; */ NS_IMETHOD GetCRC32(uint32_t *aCRC32) = 0; /* readonly attribute boolean isDirectory; */ NS_IMETHOD GetIsDirectory(bool *aIsDirectory) = 0; /* readonly attribute PRTime lastModifiedTime; */ NS_IMETHOD GetLastModifiedTime(PRTime *aLastModifiedTime) = 0; /* readonly attribute boolean isSynthetic; */ NS_IMETHOD GetIsSynthetic(bool *aIsSynthetic) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIZipEntry, NS_IZIPENTRY_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIZIPENTRY \ NS_IMETHOD GetCompression(uint16_t *aCompression); \ NS_IMETHOD GetSize(uint32_t *aSize); \ NS_IMETHOD GetRealSize(uint32_t *aRealSize); \ NS_IMETHOD GetCRC32(uint32_t *aCRC32); \ NS_IMETHOD GetIsDirectory(bool *aIsDirectory); \ NS_IMETHOD GetLastModifiedTime(PRTime *aLastModifiedTime); \ NS_IMETHOD GetIsSynthetic(bool *aIsSynthetic); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIZIPENTRY(_to) \ NS_IMETHOD GetCompression(uint16_t *aCompression) { return _to GetCompression(aCompression); } \ NS_IMETHOD GetSize(uint32_t *aSize) { return _to GetSize(aSize); } \ NS_IMETHOD GetRealSize(uint32_t *aRealSize) { return _to GetRealSize(aRealSize); } \ NS_IMETHOD GetCRC32(uint32_t *aCRC32) { return _to GetCRC32(aCRC32); } \ NS_IMETHOD GetIsDirectory(bool *aIsDirectory) { return _to GetIsDirectory(aIsDirectory); } \ NS_IMETHOD GetLastModifiedTime(PRTime *aLastModifiedTime) { return _to GetLastModifiedTime(aLastModifiedTime); } \ NS_IMETHOD GetIsSynthetic(bool *aIsSynthetic) { return _to GetIsSynthetic(aIsSynthetic); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIZIPENTRY(_to) \ NS_IMETHOD GetCompression(uint16_t *aCompression) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCompression(aCompression); } \ NS_IMETHOD GetSize(uint32_t *aSize) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSize(aSize); } \ NS_IMETHOD GetRealSize(uint32_t *aRealSize) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetRealSize(aRealSize); } \ NS_IMETHOD GetCRC32(uint32_t *aCRC32) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCRC32(aCRC32); } \ NS_IMETHOD GetIsDirectory(bool *aIsDirectory) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetIsDirectory(aIsDirectory); } \ NS_IMETHOD GetLastModifiedTime(PRTime *aLastModifiedTime) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLastModifiedTime(aLastModifiedTime); } \ NS_IMETHOD GetIsSynthetic(bool *aIsSynthetic) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetIsSynthetic(aIsSynthetic); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsZipEntry : public nsIZipEntry { public: NS_DECL_ISUPPORTS NS_DECL_NSIZIPENTRY nsZipEntry(); private: ~nsZipEntry(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsZipEntry, nsIZipEntry) nsZipEntry::nsZipEntry() { /* member initializers and constructor code */ } nsZipEntry::~nsZipEntry() { /* destructor code */ } /* readonly attribute unsigned short compression; */ NS_IMETHODIMP nsZipEntry::GetCompression(uint16_t *aCompression) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long size; */ NS_IMETHODIMP nsZipEntry::GetSize(uint32_t *aSize) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long realSize; */ NS_IMETHODIMP nsZipEntry::GetRealSize(uint32_t *aRealSize) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute unsigned long CRC32; */ NS_IMETHODIMP nsZipEntry::GetCRC32(uint32_t *aCRC32) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute boolean isDirectory; */ NS_IMETHODIMP nsZipEntry::GetIsDirectory(bool *aIsDirectory) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute PRTime lastModifiedTime; */ NS_IMETHODIMP nsZipEntry::GetLastModifiedTime(PRTime *aLastModifiedTime) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute boolean isSynthetic; */ NS_IMETHODIMP nsZipEntry::GetIsSynthetic(bool *aIsSynthetic) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: nsIZipReader */ #define NS_IZIPREADER_IID_STR "38d6d07a-8a58-4fe7-be8b-ef6472fa83ff" #define NS_IZIPREADER_IID \ {0x38d6d07a, 0x8a58, 0x4fe7, \ { 0xbe, 0x8b, 0xef, 0x64, 0x72, 0xfa, 0x83, 0xff }} class NS_NO_VTABLE nsIZipReader : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IZIPREADER_IID) /* void open (in nsIFile zipFile); */ NS_IMETHOD Open(nsIFile *zipFile) = 0; /* void openInner (in nsIZipReader zipReader, in AUTF8String zipEntry); */ NS_IMETHOD OpenInner(nsIZipReader *zipReader, const nsACString & zipEntry) = 0; /* readonly attribute nsIFile file; */ NS_IMETHOD GetFile(nsIFile * *aFile) = 0; /* void close (); */ NS_IMETHOD Close(void) = 0; /* void test (in AUTF8String aEntryName); */ NS_IMETHOD Test(const nsACString & aEntryName) = 0; /* void extract (in AUTF8String zipEntry, in nsIFile outFile); */ NS_IMETHOD Extract(const nsACString & zipEntry, nsIFile *outFile) = 0; /* nsIZipEntry getEntry (in AUTF8String zipEntry); */ NS_IMETHOD GetEntry(const nsACString & zipEntry, nsIZipEntry * *_retval) = 0; /* boolean hasEntry (in AUTF8String zipEntry); */ NS_IMETHOD HasEntry(const nsACString & zipEntry, bool *_retval) = 0; /* nsIUTF8StringEnumerator findEntries (in AUTF8String aPattern); */ NS_IMETHOD FindEntries(const nsACString & aPattern, nsIUTF8StringEnumerator * *_retval) = 0; /* nsIInputStream getInputStream (in AUTF8String zipEntry); */ NS_IMETHOD GetInputStream(const nsACString & zipEntry, nsIInputStream * *_retval) = 0; /* nsIInputStream getInputStreamWithSpec (in AUTF8String aJarSpec, in AUTF8String zipEntry); */ NS_IMETHOD GetInputStreamWithSpec(const nsACString & aJarSpec, const nsACString & zipEntry, nsIInputStream * *_retval) = 0; /* nsICertificatePrincipal getCertificatePrincipal (in AUTF8String aEntryName); */ NS_IMETHOD GetCertificatePrincipal(const nsACString & aEntryName, nsICertificatePrincipal * *_retval) = 0; /* readonly attribute uint32_t manifestEntriesCount; */ NS_IMETHOD GetManifestEntriesCount(uint32_t *aManifestEntriesCount) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIZipReader, NS_IZIPREADER_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIZIPREADER \ NS_IMETHOD Open(nsIFile *zipFile); \ NS_IMETHOD OpenInner(nsIZipReader *zipReader, const nsACString & zipEntry); \ NS_IMETHOD GetFile(nsIFile * *aFile); \ NS_IMETHOD Close(void); \ NS_IMETHOD Test(const nsACString & aEntryName); \ NS_IMETHOD Extract(const nsACString & zipEntry, nsIFile *outFile); \ NS_IMETHOD GetEntry(const nsACString & zipEntry, nsIZipEntry * *_retval); \ NS_IMETHOD HasEntry(const nsACString & zipEntry, bool *_retval); \ NS_IMETHOD FindEntries(const nsACString & aPattern, nsIUTF8StringEnumerator * *_retval); \ NS_IMETHOD GetInputStream(const nsACString & zipEntry, nsIInputStream * *_retval); \ NS_IMETHOD GetInputStreamWithSpec(const nsACString & aJarSpec, const nsACString & zipEntry, nsIInputStream * *_retval); \ NS_IMETHOD GetCertificatePrincipal(const nsACString & aEntryName, nsICertificatePrincipal * *_retval); \ NS_IMETHOD GetManifestEntriesCount(uint32_t *aManifestEntriesCount); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIZIPREADER(_to) \ NS_IMETHOD Open(nsIFile *zipFile) { return _to Open(zipFile); } \ NS_IMETHOD OpenInner(nsIZipReader *zipReader, const nsACString & zipEntry) { return _to OpenInner(zipReader, zipEntry); } \ NS_IMETHOD GetFile(nsIFile * *aFile) { return _to GetFile(aFile); } \ NS_IMETHOD Close(void) { return _to Close(); } \ NS_IMETHOD Test(const nsACString & aEntryName) { return _to Test(aEntryName); } \ NS_IMETHOD Extract(const nsACString & zipEntry, nsIFile *outFile) { return _to Extract(zipEntry, outFile); } \ NS_IMETHOD GetEntry(const nsACString & zipEntry, nsIZipEntry * *_retval) { return _to GetEntry(zipEntry, _retval); } \ NS_IMETHOD HasEntry(const nsACString & zipEntry, bool *_retval) { return _to HasEntry(zipEntry, _retval); } \ NS_IMETHOD FindEntries(const nsACString & aPattern, nsIUTF8StringEnumerator * *_retval) { return _to FindEntries(aPattern, _retval); } \ NS_IMETHOD GetInputStream(const nsACString & zipEntry, nsIInputStream * *_retval) { return _to GetInputStream(zipEntry, _retval); } \ NS_IMETHOD GetInputStreamWithSpec(const nsACString & aJarSpec, const nsACString & zipEntry, nsIInputStream * *_retval) { return _to GetInputStreamWithSpec(aJarSpec, zipEntry, _retval); } \ NS_IMETHOD GetCertificatePrincipal(const nsACString & aEntryName, nsICertificatePrincipal * *_retval) { return _to GetCertificatePrincipal(aEntryName, _retval); } \ NS_IMETHOD GetManifestEntriesCount(uint32_t *aManifestEntriesCount) { return _to GetManifestEntriesCount(aManifestEntriesCount); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIZIPREADER(_to) \ NS_IMETHOD Open(nsIFile *zipFile) { return !_to ? NS_ERROR_NULL_POINTER : _to->Open(zipFile); } \ NS_IMETHOD OpenInner(nsIZipReader *zipReader, const nsACString & zipEntry) { return !_to ? NS_ERROR_NULL_POINTER : _to->OpenInner(zipReader, zipEntry); } \ NS_IMETHOD GetFile(nsIFile * *aFile) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetFile(aFile); } \ NS_IMETHOD Close(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Close(); } \ NS_IMETHOD Test(const nsACString & aEntryName) { return !_to ? NS_ERROR_NULL_POINTER : _to->Test(aEntryName); } \ NS_IMETHOD Extract(const nsACString & zipEntry, nsIFile *outFile) { return !_to ? NS_ERROR_NULL_POINTER : _to->Extract(zipEntry, outFile); } \ NS_IMETHOD GetEntry(const nsACString & zipEntry, nsIZipEntry * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetEntry(zipEntry, _retval); } \ NS_IMETHOD HasEntry(const nsACString & zipEntry, bool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->HasEntry(zipEntry, _retval); } \ NS_IMETHOD FindEntries(const nsACString & aPattern, nsIUTF8StringEnumerator * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->FindEntries(aPattern, _retval); } \ NS_IMETHOD GetInputStream(const nsACString & zipEntry, nsIInputStream * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetInputStream(zipEntry, _retval); } \ NS_IMETHOD GetInputStreamWithSpec(const nsACString & aJarSpec, const nsACString & zipEntry, nsIInputStream * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetInputStreamWithSpec(aJarSpec, zipEntry, _retval); } \ NS_IMETHOD GetCertificatePrincipal(const nsACString & aEntryName, nsICertificatePrincipal * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCertificatePrincipal(aEntryName, _retval); } \ NS_IMETHOD GetManifestEntriesCount(uint32_t *aManifestEntriesCount) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetManifestEntriesCount(aManifestEntriesCount); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsZipReader : public nsIZipReader { public: NS_DECL_ISUPPORTS NS_DECL_NSIZIPREADER nsZipReader(); private: ~nsZipReader(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsZipReader, nsIZipReader) nsZipReader::nsZipReader() { /* member initializers and constructor code */ } nsZipReader::~nsZipReader() { /* destructor code */ } /* void open (in nsIFile zipFile); */ NS_IMETHODIMP nsZipReader::Open(nsIFile *zipFile) { return NS_ERROR_NOT_IMPLEMENTED; } /* void openInner (in nsIZipReader zipReader, in AUTF8String zipEntry); */ NS_IMETHODIMP nsZipReader::OpenInner(nsIZipReader *zipReader, const nsACString & zipEntry) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsIFile file; */ NS_IMETHODIMP nsZipReader::GetFile(nsIFile * *aFile) { return NS_ERROR_NOT_IMPLEMENTED; } /* void close (); */ NS_IMETHODIMP nsZipReader::Close() { return NS_ERROR_NOT_IMPLEMENTED; } /* void test (in AUTF8String aEntryName); */ NS_IMETHODIMP nsZipReader::Test(const nsACString & aEntryName) { return NS_ERROR_NOT_IMPLEMENTED; } /* void extract (in AUTF8String zipEntry, in nsIFile outFile); */ NS_IMETHODIMP nsZipReader::Extract(const nsACString & zipEntry, nsIFile *outFile) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIZipEntry getEntry (in AUTF8String zipEntry); */ NS_IMETHODIMP nsZipReader::GetEntry(const nsACString & zipEntry, nsIZipEntry * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean hasEntry (in AUTF8String zipEntry); */ NS_IMETHODIMP nsZipReader::HasEntry(const nsACString & zipEntry, bool *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIUTF8StringEnumerator findEntries (in AUTF8String aPattern); */ NS_IMETHODIMP nsZipReader::FindEntries(const nsACString & aPattern, nsIUTF8StringEnumerator * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIInputStream getInputStream (in AUTF8String zipEntry); */ NS_IMETHODIMP nsZipReader::GetInputStream(const nsACString & zipEntry, nsIInputStream * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIInputStream getInputStreamWithSpec (in AUTF8String aJarSpec, in AUTF8String zipEntry); */ NS_IMETHODIMP nsZipReader::GetInputStreamWithSpec(const nsACString & aJarSpec, const nsACString & zipEntry, nsIInputStream * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsICertificatePrincipal getCertificatePrincipal (in AUTF8String aEntryName); */ NS_IMETHODIMP nsZipReader::GetCertificatePrincipal(const nsACString & aEntryName, nsICertificatePrincipal * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute uint32_t manifestEntriesCount; */ NS_IMETHODIMP nsZipReader::GetManifestEntriesCount(uint32_t *aManifestEntriesCount) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif /* starting interface: nsIZipReaderCache */ #define NS_IZIPREADERCACHE_IID_STR "748050ac-3ab6-4472-bc2a-cb1564ac6a81" #define NS_IZIPREADERCACHE_IID \ {0x748050ac, 0x3ab6, 0x4472, \ { 0xbc, 0x2a, 0xcb, 0x15, 0x64, 0xac, 0x6a, 0x81 }} class NS_NO_VTABLE nsIZipReaderCache : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IZIPREADERCACHE_IID) /* void init (in unsigned long cacheSize); */ NS_IMETHOD Init(uint32_t cacheSize) = 0; /* nsIZipReader getZip (in nsIFile zipFile); */ NS_IMETHOD GetZip(nsIFile *zipFile, nsIZipReader * *_retval) = 0; /* bool isCached (in nsIFile zipFile); */ NS_IMETHOD IsCached(nsIFile *zipFile, bool *_retval) = 0; /* nsIZipReader getInnerZip (in nsIFile zipFile, in AUTF8String zipEntry); */ NS_IMETHOD GetInnerZip(nsIFile *zipFile, const nsACString & zipEntry, nsIZipReader * *_retval) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIZipReaderCache, NS_IZIPREADERCACHE_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIZIPREADERCACHE \ NS_IMETHOD Init(uint32_t cacheSize); \ NS_IMETHOD GetZip(nsIFile *zipFile, nsIZipReader * *_retval); \ NS_IMETHOD IsCached(nsIFile *zipFile, bool *_retval); \ NS_IMETHOD GetInnerZip(nsIFile *zipFile, const nsACString & zipEntry, nsIZipReader * *_retval); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIZIPREADERCACHE(_to) \ NS_IMETHOD Init(uint32_t cacheSize) { return _to Init(cacheSize); } \ NS_IMETHOD GetZip(nsIFile *zipFile, nsIZipReader * *_retval) { return _to GetZip(zipFile, _retval); } \ NS_IMETHOD IsCached(nsIFile *zipFile, bool *_retval) { return _to IsCached(zipFile, _retval); } \ NS_IMETHOD GetInnerZip(nsIFile *zipFile, const nsACString & zipEntry, nsIZipReader * *_retval) { return _to GetInnerZip(zipFile, zipEntry, _retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIZIPREADERCACHE(_to) \ NS_IMETHOD Init(uint32_t cacheSize) { return !_to ? NS_ERROR_NULL_POINTER : _to->Init(cacheSize); } \ NS_IMETHOD GetZip(nsIFile *zipFile, nsIZipReader * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetZip(zipFile, _retval); } \ NS_IMETHOD IsCached(nsIFile *zipFile, bool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsCached(zipFile, _retval); } \ NS_IMETHOD GetInnerZip(nsIFile *zipFile, const nsACString & zipEntry, nsIZipReader * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetInnerZip(zipFile, zipEntry, _retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsZipReaderCache : public nsIZipReaderCache { public: NS_DECL_ISUPPORTS NS_DECL_NSIZIPREADERCACHE nsZipReaderCache(); private: ~nsZipReaderCache(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsZipReaderCache, nsIZipReaderCache) nsZipReaderCache::nsZipReaderCache() { /* member initializers and constructor code */ } nsZipReaderCache::~nsZipReaderCache() { /* destructor code */ } /* void init (in unsigned long cacheSize); */ NS_IMETHODIMP nsZipReaderCache::Init(uint32_t cacheSize) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIZipReader getZip (in nsIFile zipFile); */ NS_IMETHODIMP nsZipReaderCache::GetZip(nsIFile *zipFile, nsIZipReader * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* bool isCached (in nsIFile zipFile); */ NS_IMETHODIMP nsZipReaderCache::IsCached(nsIFile *zipFile, bool *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsIZipReader getInnerZip (in nsIFile zipFile, in AUTF8String zipEntry); */ NS_IMETHODIMP nsZipReaderCache::GetInnerZip(nsIFile *zipFile, const nsACString & zipEntry, nsIZipReader * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #define NS_ZIPREADER_CID \ { /* 88e2fd0b-f7f4-480c-9483-7846b00e8dad */ \ 0x88e2fd0b, 0xf7f4, 0x480c, \ { 0x94, 0x83, 0x78, 0x46, 0xb0, 0x0e, 0x8d, 0xad } \ } #define NS_ZIPREADERCACHE_CID \ { /* 608b7f6f-4b60-40d6-87ed-d933bf53d8c1 */ \ 0x608b7f6f, 0x4b60, 0x40d6, \ { 0x87, 0xed, 0xd9, 0x33, 0xbf, 0x53, 0xd8, 0xc1 } \ } #endif /* __gen_nsIZipReader_h__ */
[ "snowmantw@gmail.com" ]
snowmantw@gmail.com
b447f02eb8117f50149da1e8d9cbbe342b6b5d39
2558ab11911618d8c4f9ef343d9c375975a39756
/Unit-Tests/Test-CFPP-Array.cpp
1bb63a26cf4150cc4de23bce27da39e9674ea6b2
[ "BSL-1.0" ]
permissive
BaroboRobotics/CFPP
2b8b92ea6b25315e5b4bab58d53e49b98142196c
ab7a774cb36c4581675fc291050aceaa650b4f7f
refs/heads/master
2021-01-21T03:33:47.557242
2015-06-09T12:19:59
2015-06-09T12:19:59
37,158,737
0
0
null
2015-06-09T21:13:35
2015-06-09T21:13:35
null
UTF-8
C++
false
false
1,954
cpp
/******************************************************************************* * Copyright (c) 2014, Jean-David Gadina - www.xs-labs.com / www.digidna.net * Distributed under the Boost Software License, Version 1.0. * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ******************************************************************************/ /*! * @file CFPP-Array.cpp * @copyright (c) 2014 - Jean-David Gadina - www.xs-labs.com / www.digidna.net * @abstract Unit tests for CF::Array */ #include <CF++.h> #include <GoogleMock/GoogleMock.h> using namespace testing;
[ "macmade@xs-labs.com" ]
macmade@xs-labs.com
71d05d3be29dd0b13a9e66413a0b62306c62dcd5
e8b0eb25e04dcaa532a1842017bdbbc21a0ccc4e
/921.cpp
cf404c3c046294a2bddbd7b448a2e89e77022670
[]
no_license
JonnyOu/NYOJ
98073ee3c4ba45a9731a1960616338f9232dc52e
ebb42a77eb2f48e0c05383e8f7b4d4d577380b99
refs/heads/master
2022-03-14T23:19:13.286764
2022-02-28T15:08:19
2022-02-28T15:08:19
176,429,029
2
0
null
null
null
null
UTF-8
C++
false
false
232
cpp
#include<stdio.h> int main() { int n, note; double s; while (scanf("%d", &n), n != 0) { s = n; note = n; for (int i = 2; i < 2*note; i+=2) { s += i*(1/(double)n); n--; } printf("%.2lf\n", s); } }
[ "1647063649@qq.com" ]
1647063649@qq.com
e0955bf0de16e9f24aea1e5ebd9616b7e6d998aa
2844845145012af7b7cf55bed4be87c613245baa
/cl_dll/hud_servers.cpp
e05e3e587184323fa64407b8f6da5b7338173bc5
[]
no_license
HLSources/Tyrian-GroundAssault
2ed627558e5902c63ce04d4b9e2e7237565f74f1
9411deab882dd4ae444c0e24debe5bbbff9cfc50
refs/heads/master
2023-01-31T03:30:12.157694
2020-12-03T12:32:34
2020-12-03T12:32:34
318,186,713
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
20,286
cpp
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ // // Purpose: // // $NoKeywords: $ //============================================================================= // hud_servers.cpp #include "hud.h" #include "cl_util.h" #include "hud_servers_priv.h" #include "hud_servers.h" #include "net_api.h" //#include <winsock.h> #define CALLBACK __stdcall #define WS_SWAP_SHORT(s) \ ( ( ((s) >> 8) & 0x00FF ) | \ ( ((s) << 8) & 0xFF00 ) ) static int context_id; // Default master server address in case we can't read any from woncomm.lst file #define VALVE_MASTER_ADDRESS "half-life.east.won.net" #define PORT_MASTER 27010 #define PORT_SERVER 27015 // File where we really should look for master servers #define MASTER_PARSE_FILE "valvecomm.lst" #define MAX_QUERIES 20 #define NET_API gEngfuncs.pNetAPI static CHudServers *g_pServers = NULL; /* =================== ListResponse Callback from engine =================== */ void NET_CALLBACK ListResponse( struct net_response_s *response ) { if ( g_pServers ) { g_pServers->ListResponse( response ); } } /* =================== ServerResponse Callback from engine =================== */ void NET_CALLBACK ServerResponse( struct net_response_s *response ) { if ( g_pServers ) { g_pServers->ServerResponse( response ); } } /* =================== PingResponse Callback from engine =================== */ void NET_CALLBACK PingResponse( struct net_response_s *response ) { if ( g_pServers ) { g_pServers->PingResponse( response ); } } /* =================== RulesResponse Callback from engine =================== */ void NET_CALLBACK RulesResponse( struct net_response_s *response ) { if ( g_pServers ) { g_pServers->RulesResponse( response ); } } /* =================== PlayersResponse Callback from engine =================== */ void NET_CALLBACK PlayersResponse( struct net_response_s *response ) { if ( g_pServers ) { g_pServers->PlayersResponse( response ); } } /* =================== ListResponse =================== */ void CHudServers::ListResponse( struct net_response_s *response ) { request_t *list; request_t *p; int c = 0; if ( !( response->error == NET_SUCCESS ) ) return; if ( response->type != NETAPI_REQUEST_SERVERLIST ) return; if ( response->response ) { list = ( request_t * ) response->response; while ( list ) { c++; //if ( c < 40 ) { // Copy from parsed stuff p = new request_t; p->context = -1; p->remote_address = list->remote_address; p->next = m_pServerList; m_pServerList = p; } // Move on list = list->next; } } gEngfuncs.Con_Printf( "got list\n" ); m_nQuerying = 1; m_nActiveQueries = 0; } /* =================== ServerResponse =================== */ void CHudServers::ServerResponse( struct net_response_s *response ) { char *szresponse; request_t *p; server_t *browser; int len; char sz[ 32 ]; // Remove from active list p = FindRequest( response->context, m_pActiveList ); if ( p ) { RemoveServerFromList( &m_pActiveList, p ); m_nActiveQueries--; } if ( response->error != NET_SUCCESS ) return; switch ( response->type ) { case NETAPI_REQUEST_DETAILS: if ( response->response ) { szresponse = (char *)response->response; len = strlen( szresponse ) + 100 + 1; sprintf( sz, "%i", (int)( 1000.0 * response->ping ) ); browser = new server_t; browser->remote_address = response->remote_address; browser->info = new char[ len ]; browser->ping = (int)( 1000.0 * response->ping ); strcpy( browser->info, szresponse ); NET_API->SetValueForKey( browser->info, "address", gEngfuncs.pNetAPI->AdrToString( &response->remote_address ), len ); NET_API->SetValueForKey( browser->info, "ping", sz, len ); AddServer( &m_pServers, browser ); } break; default: break; } } /* =================== PingResponse =================== */ void CHudServers::PingResponse( struct net_response_s *response ) { char sz[ 32 ]; if ( response->error != NET_SUCCESS ) return; switch ( response->type ) { case NETAPI_REQUEST_PING: sprintf( sz, "%.2f", 1000.0 * response->ping ); gEngfuncs.Con_Printf( "ping == %s\n", sz ); break; default: break; } } /* =================== RulesResponse =================== */ void CHudServers::RulesResponse( struct net_response_s *response ) { char *szresponse; if ( response->error != NET_SUCCESS ) return; switch ( response->type ) { case NETAPI_REQUEST_RULES: if ( response->response ) { szresponse = (char *)response->response; gEngfuncs.Con_Printf( "rules %s\n", szresponse ); } break; default: break; } } /* =================== PlayersResponse =================== */ void CHudServers::PlayersResponse( struct net_response_s *response ) { char *szresponse; if ( response->error != NET_SUCCESS ) return; switch ( response->type ) { case NETAPI_REQUEST_PLAYERS: if ( response->response ) { szresponse = (char *)response->response; gEngfuncs.Con_Printf( "players %s\n", szresponse ); } break; default: break; } } /* =================== CompareServers Return 1 if p1 is "less than" p2, 0 otherwise =================== */ int CHudServers::CompareServers( server_t *p1, server_t *p2 ) { const char *n1, *n2; if ( p1->ping < p2->ping ) return 1; if ( p1->ping == p2->ping ) { // Pings equal, sort by second key: hostname if ( p1->info && p2->info ) { n1 = NET_API->ValueForKey( p1->info, "hostname" ); n2 = NET_API->ValueForKey( p2->info, "hostname" ); if ( n1 && n2 ) { if ( stricmp( n1, n2 ) < 0 ) return 1; } } } return 0; } /* =================== AddServer =================== */ void CHudServers::AddServer( server_t **ppList, server_t *p ) { server_t *list; if ( !ppList || ! p ) return; m_nServerCount++; // What sort key? Ping? list = *ppList; // Head of list? if ( !list ) { p->next = NULL; *ppList = p; return; } // Put on head of list if ( CompareServers( p, list ) ) { p->next = *ppList; *ppList = p; } else { while ( list->next ) { // Insert before list next if ( CompareServers( p, list->next ) ) { p->next = list->next->next; list->next = p; return; } list = list->next; } // Just add at end p->next = NULL; list->next = p; } } /* =================== Think =================== */ void CHudServers::Think( double time ) { m_fElapsed += time; if ( !m_nRequesting ) return; if ( !m_nQuerying ) return; QueryThink(); if ( ServerListSize() > 0 ) return; m_dStarted = 0.0; m_nRequesting = 0; m_nDone = 0; m_nQuerying = 0; m_nActiveQueries = 0; } /* =================== QueryThink =================== */ void CHudServers::QueryThink( void ) { request_t *p; if ( !m_nRequesting || m_nDone ) return; if ( !m_nQuerying ) return; if ( m_nActiveQueries > MAX_QUERIES ) return; // Nothing left if ( !m_pServerList ) return; while (1)// XDM3035c: warning C4127 { p = m_pServerList; // No more in list? if ( !p ) break; // Move to next m_pServerList = m_pServerList->next; // Setup context_id p->context = context_id; // Start up query on this one NET_API->SendRequest( context_id++, NETAPI_REQUEST_DETAILS, 0, 2.0, &p->remote_address, ::ServerResponse ); // Increment active list m_nActiveQueries++; // Add to active list p->next = m_pActiveList; m_pActiveList = p; // Too many active? if ( m_nActiveQueries > MAX_QUERIES ) break; } } /* ================== ServerListSize # of servers in active query and in pending to be queried lists ================== */ int CHudServers::ServerListSize( void ) { int c = 0; request_t *p; p = m_pServerList; while ( p ) { c++; p = p->next; } p = m_pActiveList; while ( p ) { c++; p = p->next; } return c; } /* =================== FindRequest Look up a request by context id =================== */ CHudServers::request_t *CHudServers::FindRequest( int context, request_t *pList ) { request_t *p; p = pList; while ( p ) { if ( context == p->context ) return p; p = p->next; } return NULL; } /* =================== RemoveServerFromList Remote, but don't delete, item from *ppList =================== */ void CHudServers::RemoveServerFromList( request_t **ppList, request_t *item ) { request_t *p, *n; request_t *newlist = NULL; if ( !ppList ) return; p = *ppList; while ( p ) { n = p->next; if ( p != item ) { p->next = newlist; newlist = p; } p = n; } *ppList = newlist; } /* =================== ClearRequestList =================== */ void CHudServers::ClearRequestList( request_t **ppList ) { request_t *p, *n; if ( !ppList ) return; p = *ppList; while ( p ) { n = p->next; delete p; p = n; } *ppList = NULL; } /* =================== ClearServerList =================== */ void CHudServers::ClearServerList( server_t **ppList ) { server_t *p, *n; if ( !ppList ) return; p = *ppList; while ( p ) { n = p->next; delete[] p->info; delete p; p = n; } *ppList = NULL; } int CompareField( CHudServers::server_t *p1, CHudServers::server_t *p2, const char *fieldname, int iSortOrder ) { const char *sz1, *sz2; float fv1, fv2; sz1 = NET_API->ValueForKey( p1->info, fieldname ); sz2 = NET_API->ValueForKey( p2->info, fieldname ); if (sz1 == NULL || sz2 == NULL) return 0; fv1 = atof( sz1 ); fv2 = atof( sz2 ); if ( fv1 && fv2 ) { if ( fv1 > fv2 ) return iSortOrder; else if ( fv1 < fv2 ) return -iSortOrder; else return 0; } // String compare return stricmp( sz1, sz2 ); } int CALLBACK ServerListCompareFunc( CHudServers::server_t *p1, CHudServers::server_t *p2, const char *fieldname ) { if (!p1 || !p2) // No meaningful comparison return 0; return CompareField(p1, p2, fieldname, 1); } static char g_fieldname[ 256 ]; int __cdecl FnServerCompare(const void *elem1, const void *elem2 ) { CHudServers::server_t *list1, *list2; list1 = *(CHudServers::server_t **)elem1; list2 = *(CHudServers::server_t **)elem2; return ServerListCompareFunc( list1, list2, g_fieldname ); } void CHudServers::SortServers( const char *fieldname ) { server_t *p; // Create a list if ( !m_pServers ) return; strcpy( g_fieldname, fieldname ); int i; int c = 0; p = m_pServers; while ( p ) { c++; p = p->next; } server_t **pSortArray; pSortArray = new server_t *[ c ]; memset( pSortArray, 0, c * sizeof( server_t * ) ); // Now copy the list into the pSortArray: p = m_pServers; i = 0; while ( p ) { pSortArray[ i++ ] = p; p = p->next; } // Now do that actual sorting. size_t nCount = c; size_t nSize = sizeof( server_t * ); qsort( pSortArray, (size_t)nCount, (size_t)nSize, FnServerCompare ); // Now rebuild the list. m_pServers = pSortArray[0]; for ( i = 0; i < c - 1; i++ ) { pSortArray[ i ]->next = pSortArray[ i + 1 ]; } pSortArray[ c - 1 ]->next = NULL; // Clean Up. delete[] pSortArray; } /* =================== GetServer Return particular server =================== */ CHudServers::server_t *CHudServers::GetServer( int server ) { int c = 0; server_t *p; p = m_pServers; while ( p ) { if ( c == server ) return p; c++; p = p->next; } return NULL; } /* =================== GetServerInfo Return info ( key/value ) string for particular server =================== */ char *CHudServers::GetServerInfo( int server ) { server_t *p = GetServer( server ); if ( p ) { return p->info; } return NULL; } /* =================== CancelRequest Kill all pending requests in engine =================== */ void CHudServers::CancelRequest( void ) { m_nRequesting = 0; m_nQuerying = 0; m_nDone = 1; NET_API->CancelAllRequests(); } /* ================== LoadMasterAddresses Loads the master server addresses from file and into the passed in array ================== */ int CHudServers::LoadMasterAddresses( int maxservers, int *count, netadr_t *padr ) { int i; char szMaster[ 256 ]; char szMasterFile[256]; char *pbuffer = NULL; char *pstart = NULL ; netadr_t adr; char szAdr[64]; int nPort; int nCount = 0; bool bIgnore; int nDefaultPort = PORT_SERVER; // Assume default master and master file strcpy( szMaster, VALVE_MASTER_ADDRESS ); // IP:PORT string strcpy( szMasterFile, MASTER_PARSE_FILE ); // See if there is a command line override i = gEngfuncs.CheckParm( "-comm", &pstart ); if ( i && pstart ) { strcpy (szMasterFile, pstart ); } // Read them in from proper file pbuffer = (char *)gEngfuncs.COM_LoadFile( szMasterFile, 5, NULL ); // Use malloc if ( !pbuffer ) { goto finish_master; } pstart = pbuffer; while ( nCount < maxservers ) { pstart = gEngfuncs.COM_ParseFile( pstart, m_szToken ); if ( strlen(m_szToken) <= 0) break; bIgnore = true; if ( !stricmp( m_szToken, "Master" ) ) { nDefaultPort = PORT_MASTER; bIgnore = FALSE; } // Now parse all addresses between { } pstart = gEngfuncs.COM_ParseFile( pstart, m_szToken ); if ( strlen(m_szToken) <= 0 ) break; if ( stricmp ( m_szToken, "{" ) ) break; // Parse addresses until we get to "}" while ( nCount < maxservers ) { char base[256]; // Now parse all addresses between { } pstart = gEngfuncs.COM_ParseFile( pstart, m_szToken ); if (strlen(m_szToken) <= 0) break; if ( !stricmp ( m_szToken, "}" ) ) break; sprintf( base, "%s", m_szToken ); pstart = gEngfuncs.COM_ParseFile( pstart, m_szToken ); if (strlen(m_szToken) <= 0) break; if ( stricmp( m_szToken, ":" ) ) break; pstart = gEngfuncs.COM_ParseFile( pstart, m_szToken ); if (strlen(m_szToken) <= 0) break; nPort = atoi ( m_szToken ); if ( !nPort ) nPort = nDefaultPort; sprintf( szAdr, "%s:%i", base, nPort ); // Can we resolve it any better if ( !NET_API->StringToAdr( szAdr, &adr ) ) bIgnore = true; if ( !bIgnore ) { padr[ nCount++ ] = adr; } } } finish_master: if ( !nCount ) { sprintf( szMaster, VALVE_MASTER_ADDRESS ); // IP:PORT string // Convert to netadr_t if ( NET_API->StringToAdr ( szMaster, &adr ) ) { padr[ nCount++ ] = adr; } } *count = nCount; if ( pbuffer ) { gEngfuncs.COM_FreeFile( pbuffer ); } return ( nCount > 0 ) ? 1 : 0; } /* =================== RequestList Request list of game servers from master =================== */ void CHudServers::RequestList( void ) { m_nRequesting = 1; m_nDone = 0; m_dStarted = m_fElapsed; int count = 0; netadr_t adr; if ( !LoadMasterAddresses( 1, &count, &adr ) ) { gEngfuncs.Con_DPrintf( "SendRequest: Unable to read master server addresses\n" ); return; } ClearRequestList( &m_pActiveList ); ClearRequestList( &m_pServerList ); ClearServerList( &m_pServers ); m_nServerCount = 0; // Make sure networking system has started. NET_API->InitNetworking(); // Kill off left overs if any NET_API->CancelAllRequests(); // Request Server List from master NET_API->SendRequest( context_id++, NETAPI_REQUEST_SERVERLIST, 0, 5.0, &adr, ::ListResponse ); } void CHudServers::RequestBroadcastList( int clearpending ) { m_nRequesting = 1; m_nDone = 0; m_dStarted = m_fElapsed; netadr_t adr; memset( &adr, 0, sizeof( adr ) ); if ( clearpending ) { ClearRequestList( &m_pActiveList ); ClearRequestList( &m_pServerList ); ClearServerList( &m_pServers ); m_nServerCount = 0; } // Make sure to byte swap server if necessary ( using "host" to "net" conversion adr.port = WS_SWAP_SHORT(PORT_SERVER);// htons( PORT_SERVER ); XDM3033: now we don't need wsock32. dependancy // Make sure networking system has started. NET_API->InitNetworking(); if ( clearpending ) { // Kill off left overs if any NET_API->CancelAllRequests(); } adr.type = NA_BROADCAST; // Request Servers from LAN via IP NET_API->SendRequest( context_id++, NETAPI_REQUEST_DETAILS, FNETAPI_MULTIPLE_RESPONSE, 5.0, &adr, ::ServerResponse ); adr.type = NA_BROADCAST_IPX; // Request Servers from LAN via IPX ( if supported ) NET_API->SendRequest( context_id++, NETAPI_REQUEST_DETAILS, FNETAPI_MULTIPLE_RESPONSE, 5.0, &adr, ::ServerResponse ); } void CHudServers::ServerPing( int server ) { server_t *p; p = GetServer( server ); if ( !p ) return; // Make sure networking system has started. NET_API->InitNetworking(); // Request Server List from master NET_API->SendRequest( context_id++, NETAPI_REQUEST_PING, 0, 5.0, &p->remote_address, ::PingResponse ); } void CHudServers::ServerRules( int server ) { server_t *p; p = GetServer( server ); if ( !p ) return; // Make sure networking system has started. NET_API->InitNetworking(); // Request Server List from master NET_API->SendRequest( context_id++, NETAPI_REQUEST_RULES, 0, 5.0, &p->remote_address, ::RulesResponse ); } void CHudServers::ServerPlayers( int server ) { server_t *p; p = GetServer( server ); if ( !p ) return; // Make sure networking system has started. NET_API->InitNetworking(); // Request Server List from master NET_API->SendRequest( context_id++, NETAPI_REQUEST_PLAYERS, 0, 5.0, &p->remote_address, ::PlayersResponse ); } int CHudServers::isQuerying() { return m_nRequesting ? 1 : 0; } /* =================== GetServerCount Return number of servers in browser list =================== */ int CHudServers::GetServerCount( void ) { return m_nServerCount; } /* =================== CHudServers =================== */ CHudServers::CHudServers( void ) { m_nRequesting = 0; m_dStarted = 0.0; m_nDone = 0; m_pServerList = NULL; m_pServers = NULL; m_pActiveList = NULL; m_nQuerying = 0; m_nActiveQueries = 0; m_fElapsed = 0.0; m_pPingRequest = NULL; m_pRulesRequest = NULL; m_pPlayersRequest = NULL; } /* =================== ~CHudServers =================== */ CHudServers::~CHudServers( void ) { ClearRequestList( &m_pActiveList ); ClearRequestList( &m_pServerList ); ClearServerList( &m_pServers ); m_nServerCount = 0; if ( m_pPingRequest ) { delete m_pPingRequest; m_pPingRequest = NULL; } if ( m_pRulesRequest ) { delete m_pRulesRequest; m_pRulesRequest = NULL; } if ( m_pPlayersRequest ) { delete m_pPlayersRequest; m_pPlayersRequest = NULL; } } /////////////////////////////// // // PUBLIC APIs // /////////////////////////////// /* =================== ServersGetCount =================== */ int ServersGetCount( void ) { if ( g_pServers ) { return g_pServers->GetServerCount(); } return 0; } int ServersIsQuerying( void ) { if ( g_pServers ) { return g_pServers->isQuerying(); } return 0; } /* =================== ServersGetInfo =================== */ const char *ServersGetInfo( int server ) { if ( g_pServers ) { return g_pServers->GetServerInfo( server ); } return NULL; } void SortServers( const char *fieldname ) { if ( g_pServers ) { g_pServers->SortServers( fieldname ); } } /* =================== ServersShutdown =================== */ void ServersShutdown( void ) { if ( g_pServers ) { delete g_pServers; g_pServers = NULL; } } /* =================== ServersInit =================== */ void ServersInit( void ) { // Kill any previous instance ServersShutdown(); g_pServers = new CHudServers(); } /* =================== ServersThink =================== */ void ServersThink( double time ) { if ( g_pServers ) { g_pServers->Think( time ); } } /* =================== ServersCancel =================== */ void ServersCancel( void ) { if ( g_pServers ) { g_pServers->CancelRequest(); } } // Requests /* =================== ServersList =================== */ void ServersList( void ) { if ( g_pServers ) { g_pServers->RequestList(); } } void BroadcastServersList( int clearpending ) { if ( g_pServers ) { g_pServers->RequestBroadcastList( clearpending ); } } void ServerPing( int server ) { if ( g_pServers ) { g_pServers->ServerPing( server ); } } void ServerRules( int server ) { if ( g_pServers ) { g_pServers->ServerRules( server ); } } void ServerPlayers( int server ) { if ( g_pServers ) { g_pServers->ServerPlayers( server ); } }
[ "30539708+Maxxiii@users.noreply.github.com" ]
30539708+Maxxiii@users.noreply.github.com
bb1973db59f531c2f3feb28e8f739949e686f0c8
f2f17f11433e732777c031a8b2af85cc809140d9
/shared/test/common/os_interface/linux/sys_calls_linux_ult.h
fd36b5bbabb327806d9b3d08030db3488d8b9f23
[ "MIT" ]
permissive
ConnectionMaster/compute-runtime
675787c428de81abe96c969ecadd59a13150d3a2
1f6c09ba1d6ca19cd17f875c76936d194cc53885
refs/heads/master
2023-09-01T04:05:47.747499
2022-09-08T11:12:08
2022-09-09T09:50:09
183,522,897
1
0
NOASSERTION
2023-04-03T23:16:44
2019-04-25T23:20:50
C++
UTF-8
C++
false
false
722
h
/* * Copyright (C) 2021-2022 Intel Corporation * * SPDX-License-Identifier: MIT * */ #pragma once #include <iostream> #include <poll.h> namespace NEO { namespace SysCalls { extern int (*sysCallsOpen)(const char *pathname, int flags); extern ssize_t (*sysCallsPread)(int fd, void *buf, size_t count, off_t offset); extern int (*sysCallsReadlink)(const char *path, char *buf, size_t bufsize); extern int (*sysCallsIoctl)(int fileDescriptor, unsigned long int request, void *arg); extern int (*sysCallsPoll)(struct pollfd *pollFd, unsigned long int numberOfFds, int timeout); extern ssize_t (*sysCallsRead)(int fd, void *buf, size_t count); extern const char *drmVersion; } // namespace SysCalls } // namespace NEO
[ "compute-runtime@intel.com" ]
compute-runtime@intel.com
af88351118945d7deecb6590a2eb3f7883cd146b
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/231/938/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_01.cpp
1b46ca949dfdef65cf0f00a0f60c49183488e863
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
2,934
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_01.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml Template File: sources-sink-01.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using new[] and set data pointer to a small buffer * GoodSource: Allocate using new[] and set data pointer to a large buffer * Sink: swprintf * BadSink : Copy string to data using swprintf * Flow Variant: 01 Baseline * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define SNPRINTF _snwprintf #else #define SNPRINTF swprintf #endif namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_01 { #ifndef OMITBAD void bad() { wchar_t * data; data = NULL; /* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */ data = new wchar_t[50]; data[0] = L'\0'; /* null terminate */ { wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ SNPRINTF(data, 100, L"%s", source); printWLine(data); delete [] data; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { wchar_t * data; data = NULL; /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = new wchar_t[100]; data[0] = L'\0'; /* null terminate */ { wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ SNPRINTF(data, 100, L"%s", source); printWLine(data); delete [] data; } } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_01; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
6f32b32bff907e0eb65c5db17c269fc3a82a0384
b74e96c9a0741fe8376123b7f604dea46c21a6a4
/9-1.cpp
e7d5f366568569d2f8c548057dd0ed9360d5f81b
[]
no_license
ddt-sawa/meikai_mid_cpp_sawa
e7fc2c27618207213e3d7135196c9a789d001056
b51e1c1ef7853c462d93bd6b1a7a6df4997c86f8
refs/heads/master
2020-03-24T20:57:57.929410
2018-09-13T11:33:15
2018-09-13T11:33:15
143,006,294
0
0
null
2018-09-20T09:28:05
2018-07-31T11:39:39
C++
UTF-8
C++
false
false
520
cpp
/*演習9-1 char型に特殊化した挿入子を作成せよ。表示する文字を単一引用符'で囲んで表示する(例えば、['A','C'と表示する])こと。*/ #include<iostream> #include<string> #include"9-1_twin.h" using namespace std; int main() { //テンプレート実引数をchar型に指定したTwinClass型オブジェクトを定義 TwinClass<char> testTwinObject('A', 'Z'); //char型に特殊化した挿入子を用いてオブジェクト表示を確認 cout << testTwinObject; }
[ "ddt.sawa@gmail.com" ]
ddt.sawa@gmail.com
bce88ae5af6ed0ead4fa292e03f67b24ef61d967
b6607ecc11e389cc56ee4966293de9e2e0aca491
/acm.kbtu.kz/Programming langs/19/19.cpp
218f92400d07e83f20801371146786cdadc46b25
[]
no_license
BekzhanKassenov/olymp
ec31cefee36d2afe40eeead5c2c516f9bf92e66d
e3013095a4f88fb614abb8ac9ba532c5e955a32e
refs/heads/master
2022-09-21T10:07:10.232514
2021-11-01T16:40:24
2021-11-01T16:40:24
39,900,971
5
0
null
null
null
null
UTF-8
C++
false
false
352
cpp
#include <iostream> #include <cstdio> #include <vector> using namespace std; int main() { int n; cin >> n; vector <int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] == a[j]) { cout << i + 1 << ' ' << j + 1; return 0; } cout << "0 0"; return 0; }
[ "bekzhan.kassenov@nu.edu.kz" ]
bekzhan.kassenov@nu.edu.kz
2d3ffb8044f122ee98fbd4c8ce018caf2f8ff500
c32ee8ade268240a8064e9b8efdbebfbaa46ddfa
/Libraries/m2sdk/ue/sys/anim/C_TKeyStorage_TPL_CFF01850.h
eefc660bc403f50fe82bb734eb2b276d7300f205
[]
no_license
hopk1nz/maf2mp
6f65bd4f8114fdeb42f9407a4d158ad97f8d1789
814cab57dc713d9ff791dfb2a2abeb6af0e2f5a8
refs/heads/master
2021-03-12T23:56:24.336057
2015-08-22T13:53:10
2015-08-22T13:53:10
41,209,355
19
21
null
2015-08-31T05:28:13
2015-08-22T13:56:04
C++
UTF-8
C++
false
false
704
h
// auto-generated file (rttidump-exporter by h0pk1nz) #pragma once #include <ue/sys/anim/C_KeyStorage.h> namespace ue { namespace sys { namespace anim { /** ue::sys::anim::C_TKeyStorage<ue::game::cutscenes::C_AeRadio::S_RadioAction *> (VTable=0x01E5F140) */ class C_TKeyStorage_TPL_CFF01850 : public C_KeyStorage { public: virtual void vfn_0001_850AD388() = 0; virtual void vfn_0002_850AD388() = 0; virtual void vfn_0003_850AD388() = 0; virtual void vfn_0004_850AD388() = 0; virtual void vfn_0005_850AD388() = 0; virtual void vfn_0006_850AD388() = 0; virtual void vfn_0007_850AD388() = 0; virtual void vfn_0008_850AD388() = 0; }; } // namespace anim } // namespace sys } // namespace ue
[ "hopk1nz@gmail.com" ]
hopk1nz@gmail.com
d2cb5b16c701d6c328547ce9641e94b56212c099
28bf7793cde66074ac6cbe2c76df92bd4803dab9
/answers/tushartangri/Day11/Question2.cpp
aa5812dee66371aaf773a1726027fe8bae78235d
[ "MIT" ]
permissive
Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021
2dee33e057ba22092795a6ecc6686a9d31607c9d
66c7d85025481074c93cfda7853b145c88a30da4
refs/heads/main
2023-05-29T10:33:31.795738
2021-06-10T14:57:30
2021-06-10T14:57:30
348,153,476
22
135
MIT
2021-06-10T14:57:31
2021-03-15T23:37:26
Java
UTF-8
C++
false
false
728
cpp
#include <stdio.h> #include<string.h> int num(char *str, char *substr, int n, int k) { int res=0,i,j; for(i=0;i<=n-k;i++) { for(j=0;j<k;j++) if(str[i+j]!=substr[j]) break; if(j==k) { res++; j=0; } } return res; } int main() { char str[100]; int m, n,k,i,j; printf("Enter a String: "); gets(str); n=strlen(str); printf("Enter no of Substring: "); scanf("%d",&k); char substr[k][100]; int a[k]; for(j=0;j<k;j++) { printf("Enter subscript no. %d ", j+1); scanf("%s",substr[j]); a[j]=strlen(substr[j]); printf("%d\n", num(str, substr[j],n,a[j])); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
7f1e80862812ae7b1c65236bdcb6463b300eb6a5
2016a1082c18106be742dd6582b1ddb0b1f5e1ee
/todoapp/app/src/main/cpp/native-lib.cpp
5e40d4970eb600e85e9dd0a116ed99e5c52b3dd5
[]
no_license
manhhieu1412/android-architecture
59cc32c6bd595fc18ad10f972ded74e0528576ec
c40cbdd784d2594c67b154293486b85a11904f70
refs/heads/master
2021-06-24T15:53:32.546128
2020-07-29T15:25:19
2020-07-29T15:25:19
102,622,269
0
0
null
null
null
null
UTF-8
C++
false
false
265
cpp
#include <jni.h> #include <string> extern "C" JNIEXPORT jstring JNICALL Java_vn_com_vng_todoapp_MainActivity_stringFromJNI( JNIEnv* env, jobject /* this */) { std::string hello = "Hello from C++"; return env->NewStringUTF(hello.c_str()); }
[ "hieuvm@vng.com.vn" ]
hieuvm@vng.com.vn
80ff97cb8e015a592fc40b0481a09040d990fe73
eb1fd998d748b5679c8b2c5fb95abe5d6b79a629
/clientthread.h
6eab680d9eb459507a192ec1a8c2d1a349b8ce19
[]
no_license
oevermann/flaming-robot
c5c26c759fa8a5b302a9cfc9a7d5bfa0725e961d
80485e3454c2d718d7249c7c781878513918510d
refs/heads/master
2021-01-01T18:12:50.287516
2012-12-19T21:21:13
2012-12-19T21:21:13
6,809,528
1
0
null
null
null
null
UTF-8
C++
false
false
424
h
#ifndef CLIENTTHREAD_H #define CLIENTTHREAD_H #include <QThread> #include <QTcpSocket> #include "daten.h" class ClientThread : public QThread { Q_OBJECT public: explicit ClientThread(QTcpSocket* socket,Daten *data,QObject *parent = 0); ~ClientThread(); void run(); void stop(); void sendMessage(); private: QTcpSocket *socket; bool execute; Daten *data; }; #endif // CLIENTTHREAD_H
[ "foevermann@gmx.de" ]
foevermann@gmx.de
1bf77700ee391912cb2740b203273abc9b4e32ea
a89a30a000a6c7eef6853aacbe051985f1965d6a
/project_euler/44/1.cpp
ad77fb2d154a4e0f170264fe4533db0e856290b7
[]
no_license
ak795/acm
9edd7d18ddb6efeed8184b91489005aec7425caa
81787e16e23ce54bf956714865b7162c0188eb3a
refs/heads/master
2021-01-15T19:36:00.052971
2012-02-06T02:25:23
2012-02-06T02:25:23
44,054,046
1
0
null
2015-10-11T13:53:25
2015-10-11T13:53:23
null
UTF-8
C++
false
false
956
cpp
#include <iostream> #include <vector> using namespace std; int fac3(int n) { int result = 1; for (int i=0; i<n; i++) { result *= 3; } return result; } bool check(int n, int& a, int& b) { int x = n*(3*n-1)/2; x *= 2; // cout << x << endl; int t = 1; int f = 0; while ((f=fac3(t)) < x) { // cout << "ffffff: "<< f << endl; if ((x%(f-1) == 0) && ((x/(f-1)-1)%3 == 0) && ((a=(x/(f-1)-1)/3) > n)) { b = a + t; // cout << m << endl; return true; } t++; } return false; } int main() { int n = 1; int a = 1; int b = 1; int t1 = 1; int t2 = 1; while (true) { // if (n > 100) break; cout << n-1 << " a: " << a << " b: " << b<< endl; if (check(n, a, b) && check(a, t1, t2) && (b == t1)) { cout << a << endl; cout << n*(3*n-1)/2; break; } n++; } // cout <<check(7,m) << endl; // cout << m << endl; }
[ "rock.spartacus@gmail.com" ]
rock.spartacus@gmail.com
62d9fb8e1b52bc652cb8b5d06460b6f567af1b80
0df147022b4d450c707295e5b5f23d06f61bcbcf
/client/include/file_list/file_list_model_proxy.h
3aeb484ffe33c3a77262cf0b1e05ebda16589132
[]
no_license
IronTony-Stark/Explorer
636b7784edd285d4894fee10de70158501589ab0
ab5436634911f84b7570fd0ff4ec0276735a59cc
refs/heads/master
2023-02-16T14:16:09.247173
2021-01-11T15:54:49
2021-01-11T15:54:49
328,715,334
3
0
null
null
null
null
UTF-8
C++
false
false
555
h
// // Created by Iron Tony on 20/12/2020. // #ifndef EXPLORERSERVER_FILE_MODEL_PROXY_H #define EXPLORERSERVER_FILE_MODEL_PROXY_H #include <QSortFilterProxyModel> #include "file.h" class FileListModelProxy : public QSortFilterProxyModel { Q_OBJECT public: explicit FileListModelProxy(QObject* parent = nullptr); void setShowHidden(bool); void invalidate(); protected: bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override; private: bool mShowHidden; }; #endif //EXPLORERSERVER_FILE_MODEL_PROXY_H
[ "lifegamecom1@gmail.com" ]
lifegamecom1@gmail.com
86f39d9fc8efde90ac7e20ddc276357992e352ce
c733192c3d57931fc4e12e3c3568f9ef69d923f7
/src/qt/paymentserver.cpp
328989dc1bab94265e96f9f715c0469355d6ea71
[ "MIT" ]
permissive
MasterNodesME/mnme
1f34595747a2f0dbb44cca6fd04de77ef2c919f0
744e8f9dfe603bdeafe78ca7a7dcb47a1d57bf0b
refs/heads/main
2023-04-14T17:14:03.878890
2021-04-28T17:15:17
2021-04-28T17:15:17
362,399,490
0
2
null
null
null
null
UTF-8
C++
false
false
25,237
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The PIVX developers // Copyright (c) 2019-2020 The MasterWin developers // Copyright (c) 2021-2021 The MasterNodesME developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "paymentserver.h" #include "bitcoinunits.h" #include "guiutil.h" #include "optionsmodel.h" #include "base58.h" #include "chainparams.h" #include "ui_interface.h" #include "util.h" #include "wallet.h" #include <cstdlib> #include <openssl/x509.h> #include <openssl/x509_vfy.h> #include <QApplication> #include <QByteArray> #include <QDataStream> #include <QDateTime> #include <QDebug> #include <QFile> #include <QFileOpenEvent> #include <QHash> #include <QList> #include <QLocalServer> #include <QLocalSocket> #include <QNetworkAccessManager> #include <QNetworkProxy> #include <QNetworkReply> #include <QNetworkRequest> #include <QSslCertificate> #include <QSslError> #include <QSslSocket> #include <QStringList> #include <QTextDocument> #include <QUrlQuery> using namespace boost; using namespace std; const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds const QString BITCOIN_IPC_PREFIX("masternodesme:"); // BIP70 payment protocol messages const char* BIP70_MESSAGE_PAYMENTACK = "PaymentACK"; const char* BIP70_MESSAGE_PAYMENTREQUEST = "PaymentRequest"; // BIP71 payment protocol media types const char* BIP71_MIMETYPE_PAYMENT = "application/masternodesme-payment"; const char* BIP71_MIMETYPE_PAYMENTACK = "application/masternodesme-paymentack"; const char* BIP71_MIMETYPE_PAYMENTREQUEST = "application/masternodesme-paymentrequest"; // BIP70 max payment request size in bytes (DoS protection) const qint64 BIP70_MAX_PAYMENTREQUEST_SIZE = 50000; struct X509StoreDeleter { void operator()(X509_STORE* b) { X509_STORE_free(b); } }; struct X509Deleter { void operator()(X509* b) { X509_free(b); } }; namespace // Anon namespace { std::unique_ptr<X509_STORE, X509StoreDeleter> certStore; } // // Create a name that is unique for: // testnet / non-testnet // data directory // static QString ipcServerName() { QString name("MasterNodesMEQt"); // Append a simple hash of the datadir // Note that GetDataDir(true) returns a different path // for -testnet versus main net QString ddir(QString::fromStdString(GetDataDir(true).string())); name.append(QString::number(qHash(ddir))); return name; } // // We store payment URIs and requests received before // the main GUI window is up and ready to ask the user // to send payment. static QList<QString> savedPaymentRequests; static void ReportInvalidCertificate(const QSslCertificate& cert) { qDebug() << QString("%1: Payment server found an invalid certificate: ").arg(__func__) << cert.serialNumber() << cert.subjectInfo(QSslCertificate::CommonName) << cert.subjectInfo(QSslCertificate::DistinguishedNameQualifier) << cert.subjectInfo(QSslCertificate::OrganizationalUnitName); } // // Load OpenSSL's list of root certificate authorities // void PaymentServer::LoadRootCAs(X509_STORE* _store) { // Unit tests mostly use this, to pass in fake root CAs: if (_store) { certStore.reset(_store); return; } // Normal execution, use either -rootcertificates or system certs: certStore.reset(X509_STORE_new()); // Note: use "-system-" default here so that users can pass -rootcertificates="" // and get 'I don't like X.509 certificates, don't trust anybody' behavior: QString certFile = QString::fromStdString(GetArg("-rootcertificates", "-system-")); if (certFile.isEmpty()) return; // Empty store QList<QSslCertificate> certList; if (certFile != "-system-") { certList = QSslCertificate::fromPath(certFile); // Use those certificates when fetching payment requests, too: QSslSocket::setDefaultCaCertificates(certList); } else certList = QSslSocket::systemCaCertificates(); int nRootCerts = 0; const QDateTime currentTime = QDateTime::currentDateTime(); foreach (const QSslCertificate& cert, certList) { if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) { ReportInvalidCertificate(cert); continue; } // Blacklisted certificate if (cert.isBlacklisted()) { ReportInvalidCertificate(cert); continue; } QByteArray certData = cert.toDer(); const unsigned char* data = (const unsigned char*)certData.data(); std::unique_ptr<X509, X509Deleter> x509(d2i_X509(0, &data, certData.size())); if (x509 && X509_STORE_add_cert(certStore.get(), x509.get())) { // Note: X509_STORE increases the reference count to the X509 object, // we still have to release our reference to it. ++nRootCerts; } else { ReportInvalidCertificate(cert); continue; } } qWarning() << "PaymentServer::LoadRootCAs : Loaded " << nRootCerts << " root certificates"; // Project for another day: // Fetch certificate revocation lists, and add them to certStore. // Issues to consider: // performance (start a thread to fetch in background?) // privacy (fetch through tor/proxy so IP address isn't revealed) // would it be easier to just use a compiled-in blacklist? // or use Qt's blacklist? // "certificate stapling" with server-side caching is more efficient } // // Sending to the server is done synchronously, at startup. // If the server isn't already running, startup continues, // and the items in savedPaymentRequest will be handled // when uiReady() is called. // // Warning: ipcSendCommandLine() is called early in init, // so don't use "emit message()", but "QMessageBox::"! // void PaymentServer::ipcParseCommandLine(int argc, char* argv[]) { for (int i = 1; i < argc; i++) { QString arg(argv[i]); if (arg.startsWith("-")) continue; // If the masternodesme: URI contains a payment request, we are not able to detect the // network as that would require fetching and parsing the payment request. // That means clicking such an URI which contains a testnet payment request // will start a mainnet instance and throw a "wrong network" error. if (arg.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // masternodesme: URI { savedPaymentRequests.append(arg); SendCoinsRecipient r; if (GUIUtil::parseBitcoinURI(arg, &r) && !r.address.isEmpty()) { CBitcoinAddress address(r.address.toStdString()); if (address.IsValid(Params(CBaseChainParams::MAIN))) { SelectParams(CBaseChainParams::MAIN); } else if (address.IsValid(Params(CBaseChainParams::TESTNET))) { SelectParams(CBaseChainParams::TESTNET); } } } else if (QFile::exists(arg)) // Filename { savedPaymentRequests.append(arg); PaymentRequestPlus request; if (readPaymentRequestFromFile(arg, request)) { if (request.getDetails().network() == "main") { SelectParams(CBaseChainParams::MAIN); } else if (request.getDetails().network() == "test") { SelectParams(CBaseChainParams::TESTNET); } } } else { // Printing to debug.log is about the best we can do here, the // GUI hasn't started yet so we can't pop up a message box. qWarning() << "PaymentServer::ipcSendCommandLine : Payment request file does not exist: " << arg; } } } // // Sending to the server is done synchronously, at startup. // If the server isn't already running, startup continues, // and the items in savedPaymentRequest will be handled // when uiReady() is called. // bool PaymentServer::ipcSendCommandLine() { bool fResult = false; foreach (const QString& r, savedPaymentRequests) { QLocalSocket* socket = new QLocalSocket(); socket->connectToServer(ipcServerName(), QIODevice::WriteOnly); if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT)) { delete socket; socket = NULL; return false; } QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << r; out.device()->seek(0); socket->write(block); socket->flush(); socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT); socket->disconnectFromServer(); delete socket; socket = NULL; fResult = true; } return fResult; } PaymentServer::PaymentServer(QObject* parent, bool startLocalServer) : QObject(parent), saveURIs(true), uriServer(0), netManager(0), optionsModel(0) { // Verify that the version of the library that we linked against is // compatible with the version of the headers we compiled against. GOOGLE_PROTOBUF_VERIFY_VERSION; // Install global event filter to catch QFileOpenEvents // on Mac: sent when you click masternodesme: links // other OSes: helpful when dealing with payment request files (in the future) if (parent) parent->installEventFilter(this); QString name = ipcServerName(); // Clean up old socket leftover from a crash: QLocalServer::removeServer(name); if (startLocalServer) { uriServer = new QLocalServer(this); if (!uriServer->listen(name)) { // constructor is called early in init, so don't use "emit message()" here QMessageBox::critical(0, tr("Payment request error"), tr("Cannot start masternodesme: click-to-pay handler")); } else { connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection())); connect(this, SIGNAL(receivedPaymentACK(QString)), this, SLOT(handlePaymentACK(QString))); } } } PaymentServer::~PaymentServer() { google::protobuf::ShutdownProtobufLibrary(); } // // OSX-specific way of handling masternodesme: URIs and // PaymentRequest mime types // bool PaymentServer::eventFilter(QObject* object, QEvent* event) { // clicking on masternodesme: URIs creates FileOpen events on the Mac if (event->type() == QEvent::FileOpen) { QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event); if (!fileEvent->file().isEmpty()) handleURIOrFile(fileEvent->file()); else if (!fileEvent->url().isEmpty()) handleURIOrFile(fileEvent->url().toString()); return true; } return QObject::eventFilter(object, event); } void PaymentServer::initNetManager() { if (!optionsModel) return; if (netManager != NULL) delete netManager; // netManager is used to fetch paymentrequests given in masternodesme: URIs netManager = new QNetworkAccessManager(this); QNetworkProxy proxy; // Query active SOCKS5 proxy if (optionsModel->getProxySettings(proxy)) { netManager->setProxy(proxy); qDebug() << "PaymentServer::initNetManager : Using SOCKS5 proxy" << proxy.hostName() << ":" << proxy.port(); } else qDebug() << "PaymentServer::initNetManager : No active proxy server found."; connect(netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(netRequestFinished(QNetworkReply*))); connect(netManager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&)), this, SLOT(reportSslErrors(QNetworkReply*, const QList<QSslError>&))); } void PaymentServer::uiReady() { initNetManager(); saveURIs = false; foreach (const QString& s, savedPaymentRequests) { handleURIOrFile(s); } savedPaymentRequests.clear(); } void PaymentServer::handleURIOrFile(const QString& s) { if (saveURIs) { savedPaymentRequests.append(s); return; } if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // masternodesme: URI { QUrlQuery uri((QUrl(s))); if (uri.hasQueryItem("r")) // payment request URI { QByteArray temp; temp.append(uri.queryItemValue("r")); QString decoded = QUrl::fromPercentEncoding(temp); QUrl fetchUrl(decoded, QUrl::StrictMode); if (fetchUrl.isValid()) { qDebug() << "PaymentServer::handleURIOrFile : fetchRequest(" << fetchUrl << ")"; fetchRequest(fetchUrl); } else { qWarning() << "PaymentServer::handleURIOrFile : Invalid URL: " << fetchUrl; emit message(tr("URI handling"), tr("Payment request fetch URL is invalid: %1").arg(fetchUrl.toString()), CClientUIInterface::ICON_WARNING); } return; } else // normal URI { SendCoinsRecipient recipient; if (GUIUtil::parseBitcoinURI(s, &recipient)) { CBitcoinAddress address(recipient.address.toStdString()); if (!address.IsValid()) { emit message(tr("URI handling"), tr("Invalid payment address %1").arg(recipient.address), CClientUIInterface::MSG_ERROR); } else emit receivedPaymentRequest(recipient); } else emit message(tr("URI handling"), tr("URI cannot be parsed! This can be caused by an invalid MasterNodesME address or malformed URI parameters."), CClientUIInterface::ICON_WARNING); return; } } if (QFile::exists(s)) // payment request file { PaymentRequestPlus request; SendCoinsRecipient recipient; if (!readPaymentRequestFromFile(s, request)) { emit message(tr("Payment request file handling"), tr("Payment request file cannot be read! This can be caused by an invalid payment request file."), CClientUIInterface::ICON_WARNING); } else if (processPaymentRequest(request, recipient)) emit receivedPaymentRequest(recipient); return; } } void PaymentServer::handleURIConnection() { QLocalSocket* clientConnection = uriServer->nextPendingConnection(); while (clientConnection->bytesAvailable() < (int)sizeof(quint32)) clientConnection->waitForReadyRead(); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); QDataStream in(clientConnection); in.setVersion(QDataStream::Qt_4_0); if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) { return; } QString msg; in >> msg; handleURIOrFile(msg); } // // Warning: readPaymentRequestFromFile() is used in ipcSendCommandLine() // so don't use "emit message()", but "QMessageBox::"! // bool PaymentServer::readPaymentRequestFromFile(const QString& filename, PaymentRequestPlus& request) { QFile f(filename); if (!f.open(QIODevice::ReadOnly)) { qWarning() << QString("PaymentServer::%1: Failed to open %2").arg(__func__).arg(filename); return false; } // BIP70 DoS protection if (f.size() > BIP70_MAX_PAYMENTREQUEST_SIZE) { qWarning() << QString("PaymentServer::%1: Payment request %2 is too large (%3 bytes, allowed %4 bytes).") .arg(__func__) .arg(filename) .arg(f.size()) .arg(BIP70_MAX_PAYMENTREQUEST_SIZE); return false; } QByteArray data = f.readAll(); return request.parse(data); } bool PaymentServer::processPaymentRequest(PaymentRequestPlus& request, SendCoinsRecipient& recipient) { if (!optionsModel) return false; if (request.IsInitialized()) { const payments::PaymentDetails& details = request.getDetails(); // Payment request network matches client network? if (details.network() != Params().NetworkIDString()) { emit message(tr("Payment request rejected"), tr("Payment request network doesn't match client network."), CClientUIInterface::MSG_ERROR); return false; } // Expired payment request? if (details.has_expires() && (int64_t)details.expires() < GetTime()) { emit message(tr("Payment request rejected"), tr("Payment request has expired."), CClientUIInterface::MSG_ERROR); return false; } } else { emit message(tr("Payment request error"), tr("Payment request is not initialized."), CClientUIInterface::MSG_ERROR); return false; } recipient.paymentRequest = request; recipient.message = GUIUtil::HtmlEscape(request.getDetails().memo()); request.getMerchant(certStore.get(), recipient.authenticatedMerchant); QList<std::pair<CScript, CAmount> > sendingTos = request.getPayTo(); QStringList addresses; foreach (const PAIRTYPE(CScript, CAmount) & sendingTo, sendingTos) { // Extract and check destination addresses CTxDestination dest; if (ExtractDestination(sendingTo.first, dest)) { // Append destination address addresses.append(QString::fromStdString(CBitcoinAddress(dest).ToString())); } else if (!recipient.authenticatedMerchant.isEmpty()) { // Insecure payments to custom masternodesme addresses are not supported // (there is no good way to tell the user where they are paying in a way // they'd have a chance of understanding). emit message(tr("Payment request rejected"), tr("Unverified payment requests to custom payment scripts are unsupported."), CClientUIInterface::MSG_ERROR); return false; } // Extract and check amounts CTxOut txOut(sendingTo.second, sendingTo.first); if (txOut.IsDust(::minRelayTxFee)) { emit message(tr("Payment request error"), tr("Requested payment amount of %1 is too small (considered dust).").arg(BitcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), sendingTo.second)), CClientUIInterface::MSG_ERROR); return false; } recipient.amount += sendingTo.second; } // Store addresses and format them to fit nicely into the GUI recipient.address = addresses.join("<br />"); if (!recipient.authenticatedMerchant.isEmpty()) { qDebug() << "PaymentServer::processPaymentRequest : Secure payment request from " << recipient.authenticatedMerchant; } else { qDebug() << "PaymentServer::processPaymentRequest : Insecure payment request to " << addresses.join(", "); } return true; } void PaymentServer::fetchRequest(const QUrl& url) { QNetworkRequest netRequest; netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTREQUEST); netRequest.setUrl(url); netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str()); netRequest.setRawHeader("Accept", BIP71_MIMETYPE_PAYMENTREQUEST); netManager->get(netRequest); } void PaymentServer::fetchPaymentACK(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction) { const payments::PaymentDetails& details = recipient.paymentRequest.getDetails(); if (!details.has_payment_url()) return; QNetworkRequest netRequest; netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTACK); netRequest.setUrl(QString::fromStdString(details.payment_url())); netRequest.setHeader(QNetworkRequest::ContentTypeHeader, BIP71_MIMETYPE_PAYMENT); netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str()); netRequest.setRawHeader("Accept", BIP71_MIMETYPE_PAYMENTACK); payments::Payment payment; payment.set_merchant_data(details.merchant_data()); payment.add_transactions(transaction.data(), transaction.size()); // Create a new refund address, or re-use: QString account = tr("Refund from %1").arg(recipient.authenticatedMerchant); std::string strAccount = account.toStdString(); set<CTxDestination> refundAddresses = wallet->GetAccountAddresses(strAccount); if (!refundAddresses.empty()) { CScript s = GetScriptForDestination(*refundAddresses.begin()); payments::Output* refund_to = payment.add_refund_to(); refund_to->set_script(&s[0], s.size()); } else { CPubKey newKey; if (wallet->GetKeyFromPool(newKey)) { CKeyID keyID = newKey.GetID(); wallet->SetAddressBook(keyID, strAccount, "refund"); CScript s = GetScriptForDestination(keyID); payments::Output* refund_to = payment.add_refund_to(); refund_to->set_script(&s[0], s.size()); } else { // This should never happen, because sending coins should have // just unlocked the wallet and refilled the keypool. qWarning() << "PaymentServer::fetchPaymentACK : Error getting refund key, refund_to not set"; } } int length = payment.ByteSize(); netRequest.setHeader(QNetworkRequest::ContentLengthHeader, length); QByteArray serData(length, '\0'); if (payment.SerializeToArray(serData.data(), length)) { netManager->post(netRequest, serData); } else { // This should never happen, either. qWarning() << "PaymentServer::fetchPaymentACK : Error serializing payment message"; } } void PaymentServer::netRequestFinished(QNetworkReply* reply) { reply->deleteLater(); // BIP70 DoS protection if (reply->size() > BIP70_MAX_PAYMENTREQUEST_SIZE) { QString msg = tr("Payment request %1 is too large (%2 bytes, allowed %3 bytes).") .arg(reply->request().url().toString()) .arg(reply->size()) .arg(BIP70_MAX_PAYMENTREQUEST_SIZE); qWarning() << QString("PaymentServer::%1:").arg(__func__) << msg; emit message(tr("Payment request DoS protection"), msg, CClientUIInterface::MSG_ERROR); return; } if (reply->error() != QNetworkReply::NoError) { QString msg = tr("Error communicating with %1: %2") .arg(reply->request().url().toString()) .arg(reply->errorString()); qWarning() << "PaymentServer::netRequestFinished: " << msg; emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR); return; } QByteArray data = reply->readAll(); QString requestType = reply->request().attribute(QNetworkRequest::User).toString(); if (requestType == BIP70_MESSAGE_PAYMENTREQUEST) { PaymentRequestPlus request; SendCoinsRecipient recipient; if (!request.parse(data)) { qWarning() << "PaymentServer::netRequestFinished : Error parsing payment request"; emit message(tr("Payment request error"), tr("Payment request cannot be parsed!"), CClientUIInterface::MSG_ERROR); } else if (processPaymentRequest(request, recipient)) emit receivedPaymentRequest(recipient); return; } else if (requestType == BIP70_MESSAGE_PAYMENTACK) { payments::PaymentACK paymentACK; if (!paymentACK.ParseFromArray(data.data(), data.size())) { QString msg = tr("Bad response from server %1") .arg(reply->request().url().toString()); qWarning() << "PaymentServer::netRequestFinished : " << msg; emit message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR); } else { emit receivedPaymentACK(GUIUtil::HtmlEscape(paymentACK.memo())); } } } void PaymentServer::reportSslErrors(QNetworkReply* reply, const QList<QSslError>& errs) { Q_UNUSED(reply); QString errString; foreach (const QSslError& err, errs) { qWarning() << "PaymentServer::reportSslErrors : " << err; errString += err.errorString() + "\n"; } emit message(tr("Network request error"), errString, CClientUIInterface::MSG_ERROR); } void PaymentServer::setOptionsModel(OptionsModel* optionsModel) { this->optionsModel = optionsModel; } void PaymentServer::handlePaymentACK(const QString& paymentACKMsg) { // currently we don't futher process or store the paymentACK message emit message(tr("Payment acknowledged"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL); } X509_STORE* PaymentServer::getCertStore() { return certStore.get(); }
[ "" ]
555e9769d807d8122ce16d4e1070e0fb4c4f5ea2
19907e496cfaf4d59030ff06a90dc7b14db939fc
/POC/oracle_dapp/node_modules/wrtc/third_party/webrtc/include/chromium/src/content/browser/renderer_host/input/web_input_event_util.h
b7963a38e28b064ddc733b9db907403a854a6400
[ "BSD-2-Clause" ]
permissive
ATMatrix/demo
c10734441f21e24b89054842871a31fec19158e4
e71a3421c75ccdeac14eafba38f31cf92d0b2354
refs/heads/master
2020-12-02T20:53:29.214857
2017-08-28T05:49:35
2017-08-28T05:49:35
96,223,899
8
4
null
2017-08-28T05:49:36
2017-07-04T13:59:26
JavaScript
UTF-8
C++
false
false
863
h
// Copyright 2013 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_RENDERER_HOST_INPUT_WEB_INPUT_EVENT_UTIL_H_ #define CONTENT_BROWSER_RENDERER_HOST_INPUT_WEB_INPUT_EVENT_UTIL_H_ #include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "content/common/content_export.h" #include "third_party/WebKit/public/web/WebInputEvent.h" #include "ui/events/keycodes/keyboard_codes.h" namespace ui { enum class DomCode; struct GestureEventData; struct GestureEventDetails; } namespace content { int WebEventModifiersToEventFlags(int modifiers); blink::WebInputEvent::Modifiers DomCodeToWebInputEventModifiers( ui::DomCode code); } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_INPUT_WEB_INPUT_EVENT_UTIL_H_
[ "steven.jun.liu@qq.com" ]
steven.jun.liu@qq.com
79e9fa188978f5ae197c72b38ce101937b920f4d
083cffea6f6cbbb9c13a5f450e6da17bfaebe9b4
/CustomOperators/main.cpp
23ef67da97617f61b312db8b79a84f4f47e887b8
[]
no_license
MohammadRaziei/Cpp-Custom-Operators
63ac70cb5aa31922e357896df8a9c3abb132dcb3
4d12303682c302537a1b7b5a2b6c91eeb07c7e8c
refs/heads/master
2022-11-26T20:03:34.359466
2020-08-09T16:38:04
2020-08-09T16:38:04
285,821,690
6
0
null
null
null
null
UTF-8
C++
false
false
1,835
cpp
#include <QCoreApplication> #include <algorithm> #include <iostream> #include <string> #include <typeinfo> #include <vector> #include "CustomOperators.h" #define show(x) \ std::cout << ">> " << #x << " : \n\t[TYPE] " << typeName(x) << "\n\t"; \ print(x); \ std::cout << std::endl; template <typename T> std::string typeName(const T &v) { std::string typeStr = typeid(v).name(); std::string alloc = ",class std::allocator<"; std::size_t found = typeStr.find(alloc); if (found != std::string::npos) typeStr = typeStr.substr(0, found) + ">"; size_t pos = std::string::npos; std::string classStr = "class "; // Search for the substring in string in a loop untill nothing is found while ((pos = typeStr.find(classStr)) != std::string::npos) { typeStr.erase(pos, classStr.length()); } return typeStr; } template <typename T> void print(const std::vector<T> &a) { std::copy(a.begin(), a.end(), std::ostream_iterator<T>(std::cout, ", ")); std::cout << "\b\b " << std::endl; } template <typename T> void print(const T &a) { std::cout << a << std::endl; } /////////////////////////////////////////////////////// int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); std::vector<int> vectInt{1, 2, 3}; std::vector<float> vectFloat{0.5, 1.5, -0.5}; std::vector<float> vectDouble{0.5, 7.5, 9.5}; std::vector<std::complex<float>> vectCompFloat{{0.5, 1}, {1.5, 2}, {-0.5, 3}}; show(vectInt); show(vectFloat); show(vectCompFloat); show(vectDouble); show(vectInt + vectCompFloat); show(vectFloat / vectCompFloat); show(vectDouble - 0.5); show(vectInt *= vectInt); show(vectInt *= 2); show(vectInt[1]); return app.exec(); }
[ "mohammadraziei1375@gmail.com" ]
mohammadraziei1375@gmail.com
91f64952db3bcbcc3be08b3e0f2d9f6ed3ffaf68
92e67b30497ffd29d3400e88aa553bbd12518fe9
/assignment2/part6/Re=110/74.8/uniform/time
be8215ea1be0f5be51fc8009284ee596836fa045
[]
no_license
henryrossiter/OpenFOAM
8b89de8feb4d4c7f9ad4894b2ef550508792ce5c
c54b80dbf0548b34760b4fdc0dc4fb2facfdf657
refs/heads/master
2022-11-18T10:05:15.963117
2020-06-28T15:24:54
2020-06-28T15:24:54
241,991,470
0
0
null
null
null
null
UTF-8
C++
false
false
823
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "74.8/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 74.799999999997894; name "74.8"; index 1496; deltaT 0.05; deltaT0 0.05; // ************************************************************************* //
[ "henry.rossiter@utexas.edu" ]
henry.rossiter@utexas.edu
8d645b45973d97b371b27e59708859289286093c
ef1360311214b04c7f394c2bbd3670ec49a01ef3
/ISTbd-21/Gryaznov E.A/lab 6/lab6.3.cpp
50ce0d9d16e289430e787e0ea5dfda9d2a79a90b
[]
no_license
Qui-Gon173/AiSD-2020
64ac282ee8ff9b931cef5a9593f531b2436cf6e7
5a07321590c047cd8add2563a67a7381db37277e
refs/heads/master
2023-02-17T00:14:06.089644
2021-01-15T16:07:23
2021-01-15T16:07:23
303,781,723
7
21
null
2021-01-15T16:07:25
2020-10-13T17:33:14
C++
UTF-8
C++
false
false
550
cpp
#include <iostream> using namespace std; int main() { setlocale(LC_ALL, "ru"); int x = 10; int y = 10; int *xptr = &x; int *yptr = &y; //сравниваем указатели if (xptr == yptr) cout << "Указатели равны\n"; else cout << "Указатели неравны\n"; //сравниваем значения, на которое указывает указатель if (*xptr == *yptr) { cout << "Значения равны\n"; } else { cout << "Значения неравны\n"; } return 0; }
[ "gryaznov.z@bk.ru" ]
gryaznov.z@bk.ru
577911b792d9360c33f0ba9ba979a49dc3b47703
e0eeceb2fee7a7df6ba15dd50836f0854a7c2c3f
/cpp/app/src/main/cpp/include/core/PipelineBase.h
ce492f0f0689d4579e69f680ffc05833060e6746
[ "Apache-2.0" ]
permissive
Bob1562021/hms-av-pipeline-demo
6791a0183bc281e35c47fa630da6ec6312a938f9
9f822deb28d408c2edd3462c57cbdd169996f906
refs/heads/master
2023-07-22T15:39:36.498560
2021-08-26T01:47:19
2021-08-26T01:47:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,104
h
/* * Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved. * Description: header file of PipelineBase */ #ifndef PIPELINE_BASE_H #define PIPELINE_BASE_H #include <condition_variable> #include <cstddef> #include <cstdio> #include <memory> #include <set> #include "core/INode.h" #include "core/IPipeline.h" #include "core/Writer.h" #include "base/MsgQueueThread.h" #include "base/MediaMeta.h" #include "base/MMListener.h" #include "base/ElapsedTimer.h" #include "core/SourceNode.h" #include "core/SinkNode.h" #include "core/FilterNode.h" #include "GraphParser.h" namespace AVPipeline { struct PipelineParamRefBase : HolderBase { PipelineParamRefBase(int msg, int param1, int param2, const INode *sender, const MediaParcelSP param) : mMsg(msg), mSender(sender), mParam(param), mParam1(param1), mParam2(param2) {} PipelineParamRefBase(int msg, const MediaBufferSP buffer, MediaType type, const INode *sender) : mMsg(msg), mBuffer(buffer), mMediaType(type), mSender(sender) {} int mMsg { 0 }; MediaBufferSP mBuffer { nullptr }; MediaType mMediaType { MT_MAX }; const INode *mSender { nullptr }; MediaParcelSP mParam { nullptr }; int mParam1 { 0 }; int mParam2 { 0 }; }; struct PipelineBase : IPipeline, MsgQueueThread, INode::NodeListener, GraphParser, std::enable_shared_from_this<PipelineBase> { static PipelineSP Create(PipelineBase *pipeline, std::weak_ptr<PipelineListener> listenerReceive); RetCode Prepare(bool isAsync) override; RetCode Start() override; RetCode Stop() override; RetCode Pause() override; RetCode Resume() override; RetCode Reset() override; RetCode Flush() override; RetCode GetState(INode::State &state) const override; RetCode SetParameter(const MediaMetaSP &) override; RetCode GetParameter(MediaMetaSP &) const override; RetCode WriteBuffer(const MediaBufferSP &buffer, MediaType type) override; void SetListener(std::weak_ptr<PipelineListener> listener) override; static void DebugMsgInfo(int event, int param1, const char *_sender = nullptr); ~PipelineBase() override = default; protected: // can be override by subclass virtual RetCode DoInit() { return OK; } virtual void DoDeInit() {} virtual RetCode DoSetParameter(const MediaMetaSP &) { return OK; } virtual RetCode DoGetParameter(MediaMeta *) const; virtual RetCode DoStart() { return OK; } virtual RetCode DoResume() { return OK; } virtual RetCode DoStop() { return OK; } virtual RetCode DoPause() { return OK; } virtual RetCode DoPrepare() { return OK; } virtual RetCode DoReset() { return OK; } virtual RetCode DoFlush() { return OK; } virtual RetCode DoRegisterHandlers() { return OK; } virtual void DoNodeMessage(const MediaMetaSP &, uint32_t) { } virtual std::string GetGraphPath() { return mGraphPath; } virtual RetCode DoEosEvent() { return OK; } struct NodeInfo; virtual NodeSP DoAddNode(NodeInfo &); protected: // can not be override explicit PipelineBase(bool isAsync = true); virtual RetCode DoPrepareGraph(); void OnMessage(int msg, int param1, int param2, MediaParcelSP obj, const INode *sender) override final; void OnBuffer(int event, MediaBufferSP obj, MediaType type, const INode *sender) override final; NodeSP AddNode(NodeSP &up, int downId, std::map<int, GraphNodeInfo> &graph) final; std::vector<NodeSP> GetSourceNode() const override final; size_t GetSinkNodeSize() const override; std::vector<NodeSP> GetSinkNode(MediaType type) const override final; RetCode Notify(int msg, int param1, int param2, MediaParcelSP obj) const; RetCode Notify(MediaBufferSP buffer, MediaType type) const; RetCode LoadSourceNode(const std::string &libName, const std::string &mime); void SetState(INode::State &source, INode::State target); void SetErrorCode(uint32_t target); RetCode ProcessMessage(MsgType msg, bool isAsync); RetCode DoSetPipelineState(INode::Event event); bool DoCheckNodesState(const INode::Event &event, INode::State &stateTarget, const INode *sender); RetCode WaitNodeStateDone(INode::State &source, INode::State target, int64_t timeoutUs = -1); void Dump(); protected: struct NodeInfo { NodeInfo(NodeSP &comp, NodeType nt, MediaType mt, std::string mime, std::string libName = {}) : mNode(comp), mNodeType(nt), mMediaType(mt), mMime(mime), mLibName(libName) {} NodeSP mNode { nullptr }; NodeType mNodeType { NodeType::NT_MAX }; MediaType mMediaType { MediaType::MT_MAX }; std::string mMime {}; std::string mLibName {}; INode::State mState { INode::State::UNINITIALIZED }; INode::State mStateOverlay { INode::State::UNINITIALIZED }; private: NodeInfo() = delete; }; private: DECLARE_HANDLER(OnPrepare); DECLARE_HANDLER(OnSetParameter); DECLARE_HANDLER(OnGetParameter); DECLARE_HANDLER(OnStart); DECLARE_HANDLER(OnResume); DECLARE_HANDLER(OnPause); DECLARE_HANDLER(OnStop); DECLARE_HANDLER(OnFlush); DECLARE_HANDLER(OnReset); DECLARE_HANDLER(OnWriteBuffer); RetCode Init() override; void DeInit() override; static void Destroy(PipelineBase *pipeline); RetCode RegisterHandlers(); void OnPipelineNotify(const MediaMetaSP &msg, uint32_t rspId); void OnNodeMessage(const MediaMetaSP &msg, uint32_t rspId); void SetPipelineState(INode::Event event, uint32_t rspId); static INode::State Event2State(INode::Event event); INode::State &GetNodeStateMode(INode::Event event, std::size_t i); INode::State &GetPipelineStateMode(INode::Event event); RetCode WaitPipelineStateDone(INode::Event event, INode::State target, int64_t timeoutUs = -1); DISALLOW_COPY_AND_ASSIGN(PipelineBase); protected: friend struct GraphParser; std::weak_ptr<PipelineListener> mListenerSend; bool mIsAsync { true }; INode::State mState { INode::State::UNINITIALIZED }; INode::State mStateOverlay { INode::State::MAX_COUNT }; // help for Seek/flush/reset status check std::vector<NodeInfo> mNodes; mutable std::mutex mLock; std::condition_variable mCondition; uint32_t mErrorCode { 0 }; // setup the error code from msg handler thread MediaMetaSP mMediaMeta { nullptr }; using StateAction = std::function<void()>; std::shared_ptr<MsgQueueThread> mNodeEventThread { nullptr }; std::thread::id mNodeEventThreadId {}; std::string mCoreXmlPath { CORE_XML_PATH }; std::string mGraphPath {}; std::set<std::string> mEosStream; bool mIsResetDone{false}; bool mNodePrepareSyncMode{true}; std::size_t mSourceIndex{UINT32_MAX}; std::size_t mSinkClockIndex{UINT32_MAX}; // the sink node to get current playback position std::size_t mVideoSinkIndex{UINT32_MAX}; std::string mVideoMime{}; std::string mAudioMime{}; }; // PipelineBase #define CHECK_AND_REPORT_RETURN_VOID(CHECK_VALUE, NOTIFY_EVENT) \ do { \ if (CHECK_VALUE) { \ INFO("error %d", NOTIFY_EVENT); \ Notify(INode::EVENT_ERROR, NOTIFY_EVENT, 0, nullptr); \ return; \ } \ } while (0) #define CHECK_AND_REPORT_RETURN(CHECK_VALUE, NOTIFY_EVENT, RETURN_VALUE) \ do { \ if (CHECK_VALUE) { \ INFO("%s check failed, error %d", #CHECK_VALUE, NOTIFY_EVENT); \ Notify(INode::EVENT_ERROR, NOTIFY_EVENT, 0, nullptr); \ return RETURN_VALUE; \ } \ } while (0) } // namespace AVPipeline #endif // PIPELINE_BASE_H
[ "meixu@huawei.com" ]
meixu@huawei.com
dfc7355afe03bb9dfe19c4fcaea578e7e21e723d
0d79c4be8e471163a9ab248ced1b38292b82e4b2
/367div2/B.cpp
c1ddb37813e2a85c874402ffc3bdccf8dea9a9d4
[]
no_license
KhusainovAydar/codeforces
c2969022c6d9c3a9bd0e5bc524a9c2b57fb152fb
922db9f3147aff6ccbcf4e5d0981a66355703f6b
refs/heads/master
2020-05-05T01:19:55.869594
2019-04-05T02:39:17
2019-04-05T02:39:17
179,599,612
0
0
null
null
null
null
UTF-8
C++
false
false
1,223
cpp
#include <bits/stdc++.h> #define fi first #define se second #define endl '\n' #define pb push_back #define INF 1000000000 #define y1 kek //#define pi 3.1415926535897932384626433832795 #define eps 0.0000000001 //#d efine double long double //#define int ll using namespace std; typedef long long ll; int main() { ios_base::sync_with_stdio(false); srand((unsigned int)time(NULL)); /*#if __APPLE__ freopen("/Users/macbook/Documents/cpp/cpp/input.txt", "r", stdin); freopen("/Users/macbook/Documents/cpp/cpp/output.txt", "w", stdout); #else freopen("permutation2.in", "r", stdin); freopen("permutation2.out", "w", stdout); #endif*/ int n; cin >> n; vector< int > a; for (int i = 0; i < n; i++) { int x; cin >> x; a.push_back(x); } sort(a.begin(), a.end()); vector<int> pref_sum = a; int q; cin >> q; for (int i = 0; i < q; i++) { int x; cin >> x; int l = -1, r = n; while (r - l > 1) { int m = (r + l) >> 1; if (pref_sum[m] <= x) { l = m; } else { r = m; } } cout << l + 1 << endl; } }
[ "aikhusainov@edu.hse.ru" ]
aikhusainov@edu.hse.ru
5fef3132b7ba5093f4438b425542e6fd78c17b26
a12d46936ffad88476229811ac2feb39c29b6f2d
/DxRpgProject/src/Util/CsvMapReader.h
68cff766101b0d82f6a83f4f0100312d79eb668b
[ "BSD-3-Clause", "MIT" ]
permissive
sujiniku/DxRpg
95c60f8aa35774ddd2dc95f1927bfaff51448be2
22c9d95f2ff06bcdbeae42fa99c295a8ec0ebcde
refs/heads/master
2020-03-27T12:57:10.579522
2017-08-05T19:31:39
2017-08-05T19:31:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
320
h
#pragma once #include "StdCommon.h" namespace Util { class CsvMapReader { public: CsvMapReader(); ~CsvMapReader() { } void load(const char *filename); int getMapData(int x, int y); private: int size_; char *data_; int mapSize_; int mapData_[YBlock * XBlock]; }; }
[ "ava1anche_eco@yahoo.co.jp" ]
ava1anche_eco@yahoo.co.jp
f270441e782a70299b2f3a22977f33872d9380b0
229b94e496baa382a5a9f0a495c0b13e3ce854d7
/special/greateIdea/809_ExpressiveWords.cpp
b893cf706f722f8097085a9d0d9df6e8a8e9afb9
[]
no_license
GorillaSX/DataStructureAndAlgorithm
5fcff909bb9e6bec721425458e5155a7e3a99193
88261763c71afbdb9eefffe8a455c98ef6776458
refs/heads/master
2021-07-02T21:50:49.631324
2019-02-11T14:53:44
2019-02-11T14:53:44
119,570,646
0
0
null
null
null
null
UTF-8
C++
false
false
4,133
cpp
/* Sometimes people repeat letters to represent extra feeling, such as "hello" -> "heeellooo", "hi" -> "hiiii". Here, we have groups, of adjacent letters that are all the same character, and adjacent characters to the group are different. A group is extended if that group is length 3 or more, so "e" and "o" would be extended in the first example, and "i" would be extended in the second example. As another example, the groups of "abbcccaaaa" would be "a", "bb", "ccc", and "aaaa"; and "ccc" and "aaaa" are the extended groups of that string. For some given string S, a query word is stretchy if it can be made to be equal to S by extending some groups. Formally, we are allowed to repeatedly choose a group (as defined above) of characters c, and add some number of the same character c to it so that the length of the group is 3 or more. Note that we cannot extend a group of size one like "h" to a group of size two like "hh" - all extensions must leave the group extended - ie., at least 3 characters long. Given a list of query words, return the number of words that are stretchy. Example: Input: S = "heeellooo" words = ["hello", "hi", "helo"] Output: 1 Explanation: We can extend "e" and "o" in the word "hello" to get "heeellooo". We can't extend "helo" to get "heeellooo" because the group "ll" is not extended. Notes: 0 <= len(S) <= 100. 0 <= len(words) <= 100. 0 <= len(words[i]) <= 100. S and all words in words consist only of lowercase letters */ class Solution { public: pair<string, vector<int>> compress(string word) { pair<string, vector<int>> result; int start = 0; vector<int> counts; string rep = ""; for(int i = 0;i < word.size();i++) { if(word[i] != word[start]) { rep += word[start]; counts.push_back(i - start); start = i; } } rep += word[start]; counts.push_back(word.size() - start); return make_pair(rep, counts); } int expressiveWords(string S, vector<string>& words) { pair<string, vector<int>> reps = compress(S); int count = 0; for(auto word : words) { pair<string, vector<int>> curs = compress(word); if(curs.first == reps.first) { int find = true; for(int i = 0;i < curs.second.size();i++) { if((reps.second[i] < 3 and reps.second[i] != curs.second[i]) or (reps.second[i] >= 3 and curs.second[i] > reps.second[i])) { find = false; break; } } if(find) count++; } } return count; } }; class Solution { public: vector<pair<char, int>> compress(string word) { vector<pair<char, int>> result; int start = 0; for(int i = 0;i < word.size();i++) { if(word[i] != word[start]) { result.push_back(make_pair(word[start], i - start)); start = i; } } result.push_back(make_pair(word[start], word.size() - start)); return result; } int expressiveWords(string S, vector<string>& words) { vector<pair<char,int>> reps = compress(S); int count = 0; for(auto word : words) { vector<pair<char, int>> curs = compress(word); if(curs.size() == reps.size()) { int find = true; for(int i = 0;i < curs.size();i++) { if(reps[i].first != curs[i].first or (reps[i].second < 3 and reps[i].second != curs[i].second) or (reps[i].second >= 3 and curs[i].second > reps[i].second)) { find = false; break; } } if(find) count++; } } return count; } };
[ "songxin@udel.edu" ]
songxin@udel.edu
f6b3c5415989da0a09d37cc21da3b3d80814bd10
5158b0f288752708b736afb05843748faa1916b5
/Lab 7/RegionalHospital/HospitalUnit.cpp
05261687f4fb2b1d0085c64a25b4318a0ba6ee49
[]
no_license
programming-653501/LinaKovalevskaya
ccccdedeaa904858087ac7e00a9b57b18a9cf933
026d2949ca7e0b0ed57d90085e8f81af1220869f
refs/heads/master
2021-01-19T10:57:00.996397
2017-05-30T19:53:46
2017-05-30T19:53:46
82,222,682
0
0
null
null
null
null
UTF-8
C++
false
false
17,363
cpp
#include "HospitalUnit.h" HospitalUnit::HospitalUnit(const char* name, int unitNo, int capacity) { strncpy_s(name_, name, MAX_HOSPITAL_UNIT_NAME_LENGTH); unitNo_ = unitNo; capacity_ = capacity; initializeMedicalWorkersArray(); initializeDiagnosisDatabase(); initializePatientsList(); } void HospitalUnit::initializePatientsList() { currentPatientsAmount_ = 0; patientsListTail_ = patientsList_ = NULL; } void HospitalUnit::initializeDiagnosisDatabase() { availableDiagnosisDatabaseSize_ = INITIAL_DIAGNOSIS_DATABASE_SIZE; currentDiagnosisDatabaseSize_ = 0; diagnosisDatabase_ = NULL; } void HospitalUnit::initializeMedicalWorkersArray() { availableMedicalWorkersAmount_ = INITIAL_MEDICAL_WORKERS_AMOUNT; currentMedicalWorkersAmount_ = 0; medicalWorkers_ = NULL; } HospitalUnit::HospitalUnit() { initializeMedicalWorkersArray(); initializeDiagnosisDatabase(); initializePatientsList(); } void HospitalUnit::createUnitDirectory(const char* hospitalDirectory) { formUnitDirectoryPath(hospitalDirectory); if (!_mkdir(unitDirectoryPath_)) { printf("Directory %s was successfully created.\n", unitDirectoryPath_); } else { printf("Can not create directory %s.\n", unitDirectoryPath_); exit(1); } } void HospitalUnit::formUnitDirectoryPath(const char* hospitalDirectory) { formSubdirectoryPath(unitDirectoryPath_, hospitalDirectory, name_); } void HospitalUnit::formDataFilePath() { formInnerFilePath(dataFilePath_, unitDirectoryPath_, name_); } void HospitalUnit::formMedicalWorkersFilePath() { formInnerFilePath(medicalWorkersFilePath_, unitDirectoryPath_, DEFAULT_MEDICAL_WORKERS_FILE_NAME); } void HospitalUnit::formDiagnosisDatabaseFilePath() { formInnerFilePath(diagnosisDatabaseFilePath_, unitDirectoryPath_, DEFAULT_DIAGNOSIS_DATABASE_FILE_NAME); } void HospitalUnit::formPatientsListFilePath() { formInnerFilePath(patientsListFilePath_, unitDirectoryPath_, DEFAULT_PATIENTS_FILE_NAME); } void HospitalUnit::formInnerFilesPath() { formDataFilePath(); formMedicalWorkersFilePath(); formDiagnosisDatabaseFilePath(); formPatientsListFilePath(); } void HospitalUnit::writeToDataFile() { FILE* stream = NULL; stream = openStreamForWriting(stream, dataFilePath_); if (stream == NULL) return; fwrite(name_, sizeof(char), MAX_HOSPITAL_UNIT_NAME_LENGTH, stream); fwrite(&unitNo_, sizeof(int), 1, stream); fwrite(&capacity_, sizeof(int), 1, stream); fwrite(&currentMedicalWorkersAmount_, sizeof(int), 1, stream); fwrite(&availableMedicalWorkersAmount_, sizeof(int), 1, stream); fwrite(&currentDiagnosisDatabaseSize_, sizeof(int), 1, stream); fwrite(&availableDiagnosisDatabaseSize_, sizeof(int), 1, stream); fwrite(medicalWorkersFilePath_, sizeof(char), _MAX_PATH, stream); fwrite(diagnosisDatabaseFilePath_, sizeof(char), _MAX_PATH, stream); fwrite(patientsListFilePath_, sizeof(char), _MAX_PATH, stream); closeStream(stream, dataFilePath_); } void HospitalUnit::readFromDataFile() { FILE* stream = NULL; stream = openStreamForReading(stream, dataFilePath_); if (stream == NULL) return; fread(name_, sizeof(char), MAX_HOSPITAL_UNIT_NAME_LENGTH, stream); fread(&unitNo_, sizeof(int), 1, stream); fread(&capacity_, sizeof(int), 1, stream); fread(&currentMedicalWorkersAmount_, sizeof(int), 1, stream); fread(&availableMedicalWorkersAmount_, sizeof(int), 1, stream); fread(&currentDiagnosisDatabaseSize_, sizeof(int), 1, stream); fread(&availableDiagnosisDatabaseSize_, sizeof(int), 1, stream); fread(medicalWorkersFilePath_, sizeof(char), _MAX_PATH, stream); fread(diagnosisDatabaseFilePath_, sizeof(char), _MAX_PATH, stream); fread(patientsListFilePath_, sizeof(char), _MAX_PATH, stream); closeStream(stream, dataFilePath_); } void HospitalUnit::increaseMedicalWorkersAvailableAmount() { MedicalWorker* buffer = new MedicalWorker[availableMedicalWorkersAmount_ * DYNAMIC_ARRAY_FACTOR]; for (int i = 0; i < currentMedicalWorkersAmount_; i++) buffer[i] = medicalWorkers_[i]; delete[] medicalWorkers_; medicalWorkers_ = buffer; availableMedicalWorkersAmount_ *= DYNAMIC_ARRAY_FACTOR; } void HospitalUnit::addMedicalWorker(MedicalWorker* medicalWorker) { if (medicalWorkers_ == NULL) medicalWorkers_ = new MedicalWorker[availableMedicalWorkersAmount_]; if (currentMedicalWorkersAmount_ >= availableMedicalWorkersAmount_) increaseMedicalWorkersAvailableAmount(); medicalWorkers_[currentMedicalWorkersAmount_] = *medicalWorker; currentMedicalWorkersAmount_++; } void HospitalUnit::addMedicalWorker(const char* name, const char* surname, const char* post, const char* speciality) { MedicalWorker buffer(unitNo_, currentMedicalWorkersAmount_ + 1, name, surname, post, speciality); addMedicalWorker(&buffer); } HospitalUnit::~HospitalUnit() { delete medicalWorkers_; delete diagnosisDatabase_; removePatientsList(); } void HospitalUnit::writeMedicalWorkersToFile() { FILE* stream = NULL; stream = openStreamForWriting(stream, medicalWorkersFilePath_); if (stream == NULL) return; fwrite(medicalWorkers_, sizeof(MedicalWorker), availableMedicalWorkersAmount_, stream); closeStream(stream, medicalWorkersFilePath_); } void HospitalUnit::readMedicalWorkersFromFile() { FILE* stream = NULL; stream = openStreamForReading(stream, medicalWorkersFilePath_); if (stream == NULL) return; medicalWorkers_ = new MedicalWorker[availableMedicalWorkersAmount_]; fread(medicalWorkers_, sizeof(MedicalWorker), availableMedicalWorkersAmount_, stream); closeStream(stream, medicalWorkersFilePath_); } void HospitalUnit::printMedicalWorkers() { for (int i = 0; i < currentMedicalWorkersAmount_; i++) medicalWorkers_[i].printInformation(); } void HospitalUnit::increaseDiagnosisDatabaseSize() { Diagnosis* buffer = new Diagnosis[availableDiagnosisDatabaseSize_*DYNAMIC_ARRAY_FACTOR]; for (int i = 0; i < availableDiagnosisDatabaseSize_; i++) buffer[i] = diagnosisDatabase_[i]; delete[] diagnosisDatabase_; diagnosisDatabase_ = buffer; availableDiagnosisDatabaseSize_ *= DYNAMIC_ARRAY_FACTOR; } void HospitalUnit::addDiagnosisToDatabase(const char* diagnosis) { if (diagnosisDatabase_ == NULL) diagnosisDatabase_ = new Diagnosis[INITIAL_DIAGNOSIS_DATABASE_SIZE]; if (currentDiagnosisDatabaseSize_ >= availableDiagnosisDatabaseSize_) increaseDiagnosisDatabaseSize(); diagnosisDatabase_[currentDiagnosisDatabaseSize_] = Diagnosis(diagnosis, unitNo_, currentDiagnosisDatabaseSize_ + 1); currentDiagnosisDatabaseSize_++; } void HospitalUnit::printDiagnosisDatabase() { for (int i = 0; i < currentDiagnosisDatabaseSize_; i++) printf("%d %d %s", diagnosisDatabase_[i].hospitalUnitNo_, diagnosisDatabase_[i].key_, diagnosisDatabase_[i].diagnosis_); } void HospitalUnit::writeDiagnosisDatabaseToFile() { FILE* stream = NULL; stream = openStreamForWriting(stream, diagnosisDatabaseFilePath_); if (stream == NULL) return; fwrite(diagnosisDatabase_, sizeof(Diagnosis), availableDiagnosisDatabaseSize_, stream); closeStream(stream, diagnosisDatabaseFilePath_); } void HospitalUnit::readDiagnosisDatabaseFromFile() { FILE* stream = NULL; stream = openStreamForReading(stream, diagnosisDatabaseFilePath_); if (stream == NULL) return; diagnosisDatabase_ = new Diagnosis[availableDiagnosisDatabaseSize_]; fread(diagnosisDatabase_, sizeof(Diagnosis), availableDiagnosisDatabaseSize_, stream); closeStream(stream, diagnosisDatabaseFilePath_); } void HospitalUnit::removePatientsList() { PatientsListItem* buffer; while (patientsList_ != NULL) { buffer = patientsList_; patientsList_ = patientsList_->next; delete buffer; } } void HospitalUnit::addPatientToList(Patient* patient) { PatientsListItem* patientsListItem = new PatientsListItem(*patient); patientsListItem->previous = patientsListItem->next = NULL; if (patientsList_ == NULL) patientsList_ = patientsListTail_ = patientsListItem; else { patientsListTail_->next = patientsListItem; patientsListItem->previous = patientsListTail_; patientsListTail_ = patientsListItem; } currentPatientsAmount_++; } MedicalWorker* HospitalUnit::findFreeMedicalWorkerSomehow() { int minPatientsAmount = medicalWorkers_[0].currentPatientsAmount_, minPatientsAmountIndex = 0; for (int i = 0; i < currentMedicalWorkersAmount_; i++) { if (minPatientsAmount > medicalWorkers_[i].currentPatientsAmount_) { minPatientsAmount = medicalWorkers_[i].currentPatientsAmount_; minPatientsAmountIndex = i; } } return medicalWorkers_ + minPatientsAmountIndex; } void HospitalUnit::addPatientToList(ReceptionPatientForm& receptionPatientForm, int diagnosisKey) { int medicalWorkerNo = (findFreeMedicalWorkerSomehow())->medicalWorkerNo_; addPatientToMedicalWorker(medicalWorkerNo); Patient buffer(unitNo_, receptionPatientForm, medicalWorkerNo); buffer.makeDiagnosis(diagnosisKey); addPatientToList(&buffer); } PatientsListItem* HospitalUnit::findPatientInList(int patientNo) { PatientsListItem* buffer = patientsList_; while (buffer != NULL && buffer->patient.patientNo_ != patientNo) buffer = buffer->next; if (buffer == NULL) printf("\nCan not find a patient with such patientNo.\n"); return buffer; } void HospitalUnit::removePatientFromList(int patientNo) { PatientsListItem* patientsListItem = findPatientInList(patientNo); removePatientFromMedicalWorker(getPatientAttendingMedicalWorkerNo(patientsListItem)); removePatientFromList(patientsListItem); } int HospitalUnit::getPatientAttendingMedicalWorkerNo(PatientsListItem* patientsListItem) { if (patientsListItem == NULL) return 0; return patientsListItem->patient.medicalWorkerId_; } void HospitalUnit::removePatientFromList(PatientsListItem* patientsListItem) { if (patientsListItem == NULL) return; if (patientsListItem->previous != NULL) patientsListItem->previous->next = patientsListItem->next; else patientsList_ = patientsListItem->next; if (patientsListItem->next != NULL) patientsListItem->next->previous = patientsListItem->previous; else patientsListTail_ = patientsListItem->previous; currentPatientsAmount_--; delete patientsListItem; } void HospitalUnit::writePatientsListToFile() { FILE* stream = NULL; stream = openStreamForWriting(stream, patientsListFilePath_); if (stream == NULL) return; Patient::writeIdCounterToFile(stream); fwrite(&currentPatientsAmount_, sizeof(int), 1, stream); writePatientsListToFile(stream); closeStream(stream, patientsListFilePath_); } void HospitalUnit::writePatientsListToFile(FILE* stream) { if (stream == NULL) return; PatientsListItem* buffer = new PatientsListItem; buffer = patientsList_; while (buffer != NULL) { buffer->patient.writeToFile(stream); buffer = buffer->next; } delete buffer; } void HospitalUnit::readPatientsListFromFile() { FILE* stream = NULL; stream = openStreamForReading(stream, patientsListFilePath_); Patient::readIdCounterFromFile(stream); readPatientsListFromFile(stream); closeStream(stream, patientsListFilePath_); } void HospitalUnit::readPatientsListFromFile(FILE* stream) { if (stream == NULL) return; int restoredCurrentPatientsAmount; fread(&restoredCurrentPatientsAmount, sizeof(int), 1, stream); for (int i = 0; i < restoredCurrentPatientsAmount; i++) { Patient buffer; buffer.readFromFile(stream); addPatientToList(&buffer); } } void HospitalUnit::printPatientsList() { PatientsListItem* buffer = new PatientsListItem; buffer = patientsList_; while (buffer != NULL) { printPatientMedicalRecords(buffer); buffer = buffer->next; } delete buffer; } const char* HospitalUnit::getDiagnosis(PatientsListItem* patientsListItem) { return diagnosisDatabase_[patientsListItem->patient.diagnosisKey_ - 1].diagnosis_; } bool HospitalUnit::isFull() { return currentPatientsAmount_ >= capacity_ ? true : false; } void HospitalUnit::addPatientToMedicalWorker(int medicalWorkerNo) { medicalWorkers_[medicalWorkerNo - 1].increaseCurrentPatientsAmount(); } void HospitalUnit::removePatientFromMedicalWorker(int medicalWorkerNo) { if (medicalWorkerNo <= 0) return; medicalWorkers_[medicalWorkerNo - 1].decreaseCurrentPatientsAmount(); } void HospitalUnit::givePrescriptionsToPatient(int id) { PatientsListItem* buffer = findPatientInList(id); if (buffer == NULL) return; givePrescriptionsToPatient(buffer); } void HospitalUnit::removePrescriptionsFromPatient(int id) { PatientsListItem* buffer = findPatientInList(id); if (buffer == NULL) return; removePrescriptionsFromPatient(buffer); } void HospitalUnit::givePrescriptionsToPatient(PatientsListItem* patientsListItem) { char buf[MAX_PRESCRIPTION_LENGTH]; char choice = 0; while (choice != '0') { my_fflush(); printf("Prescription to recommend: "); if (!my_fgets(buf, MAX_PRESCRIPTION_LENGTH)) my_fflush(); patientsListItem->patient.addPrescriptionToList(buf); printf("Press '0' to exit or any other key to go on.\t"); scanf_s("%c", &choice); } } void HospitalUnit::removePrescriptionsFromPatient(PatientsListItem* patientsListItem) { char buf[MAX_PRESCRIPTION_LENGTH]; char choice = 0; while (choice != '0') { my_fflush(); printf("Prescription to cancel: "); if (!my_fgets(buf, MAX_PRESCRIPTION_LENGTH)) my_fflush(); patientsListItem->patient.removePrescriptionFromList(buf); printf("Press '0' to exit or any other key to go on.\t"); scanf_s("%c", &choice); } } float HospitalUnit::getAverageWorkloadPerMedicalWorker() { return (float)currentPatientsAmount_ / currentMedicalWorkersAmount_; } void HospitalUnit::printPatientMedicalRecords(PatientsListItem* patientsListItem) { if (patientsListItem == NULL) return; printf("\nMedical Records:\n"); printf("\nNo%d\t", patientsListItem->patient.patientNo_); patientsListItem->patient.printReceptionForm(); printf("\nDiagnosis: %s", getDiagnosis(patientsListItem)); printf("\nAttending medical worker:\t"); printMedicalWorker(getPatientAttendingMedicalWorkerNo(patientsListItem)); patientsListItem->patient.printPrescriptionsList(); } void HospitalUnit::printPatientMedicalRecords(int patientNo) { PatientsListItem* buffer = findPatientInList(patientNo); printPatientMedicalRecords(buffer); } void HospitalUnit::printInformation() { printf("\nNo%d %s", unitNo_, name_); printf("\nCapacity: %d\tNumber of medical workers: %d", capacity_, currentMedicalWorkersAmount_); printf("\nCurrent number of patients in %s: %d", name_, currentPatientsAmount_); printf("\nAverage workload per medical worker: %.2f", getAverageWorkloadPerMedicalWorker()); } void HospitalUnit::printMedicalWorker(int medicalWorkerNo) { medicalWorkers_[medicalWorkerNo - 1].printInformation(); } void HospitalUnit::workWithUnit() { printInvitation(); char choice = 0; bool flag = false; while (!flag) { my_fflush(); printf("\nYour choice:\t"); scanf_s("%c", &choice); switch (choice) { case '1': printInformation(); break; case '2': printMedicalWorkers(); break; case '3': printDiagnosisDatabase(); break; case '4': printPatientsList(); break; case '5': choosePatient(); printInvitation(); break; case EXIT_KEY: flag = true; my_fflush(); break; } } } void HospitalUnit::printInvitation() { printf("\n\nHOSPITAL UNIT\nPress key:"); printf("\n1 - view information about %s", name_); printf("\n2 - view information about current medical workers"); printf("\n3 - view %s diagnosis database", name_); printf("\n4 - view list of current patients"); printf("\n5 - work with one of the patients"); printf("\n0 - exit\n"); } void HospitalUnit::choosePatient() { printf("\nChoose the patient you would like to work with:\n"); printf("Enter patient's No:\t"); int patientNo; enterNaturalNumber(&patientNo); workWithPatient(patientNo); } void HospitalUnit::showWorkWithPatientInvitation() { printf("\n\nWORK WITH PATIENT\nPress key:"); printf("\n1 - view patient's medical records"); printf("\n2 - discharge patient"); printf("\n3 - give prescriptions to patient", name_); printf("\n4 - cancel some of the patient's prescriptions"); printf("\n0 - exit\n"); } void HospitalUnit::workWithPatient(int patientNo) { showWorkWithPatientInvitation(); char choice = 0; bool flag = false; while (!flag) { my_fflush(); printf("Your choice:\t"); scanf_s("%c", &choice); switch (choice) { case '1': printPatientMedicalRecords(patientNo); break; case '2': removePatientFromList(patientNo); break; case '3': my_fflush(); givePrescriptionsToPatient(patientNo); showWorkWithPatientInvitation(); break; case '4': my_fflush(); removePrescriptionsFromPatient(patientNo); showWorkWithPatientInvitation(); break; case EXIT_KEY: flag = true; break; } } } Date& HospitalUnit::findNearestDischargeDate() { PatientsListItem* buffer = new PatientsListItem; Date nearestDischargeDate = patientsList_->patient.getDischargeDate(); buffer = patientsList_; while (buffer != NULL) { nearestDischargeDate = Date::chooseEarlierDate(nearestDischargeDate, buffer->patient.getDischargeDate()); buffer = buffer->next; } delete buffer; return nearestDischargeDate; } const char* HospitalUnit::getDiagnosis(int diagnosisKey) { return diagnosisDatabase_[diagnosisKey - 1].diagnosis_; }
[ "heike3291@gmail.com" ]
heike3291@gmail.com
bb8de8af2c428ef63682f2335c1ff66ec35c8ce8
dd949f215d968f2ee69bf85571fd63e4f085a869
/subarchitectures/vision.sa/branches/spring-school-2011-DEPRECATED/src/c++/vision/components/VisualMediator/VisualMediator.h
91fc5d7a3d16b1d27b09c953ffd00b93c9eab556
[]
no_license
marc-hanheide/cogx
a3fd395805f1b0ad7d713a05b9256312757b37a9
cb9a9c9cdfeba02afac6a83d03b7c6bb778edb95
refs/heads/master
2022-03-16T23:36:21.951317
2013-12-10T23:49:07
2013-12-10T23:49:07
219,460,352
1
2
null
null
null
null
UTF-8
C++
false
false
4,215
h
/** * @author Alen Vrecko * @date July 2009 * * A component the filters out persistent VisualObjects. */ #ifndef OBJECT_ANALYZER_H #define OBJECT_ANALYZER_H #define UPD_THR_DEFAULT 5 #include <vector> #include <string> #include <queue> #include <map> #include <algorithm> #include <boost/interprocess/sync/named_semaphore.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <cast/architecture/ManagedComponent.hpp> #include <../../VisionUtils.h> #include <VisionData.hpp> #include <BindingWorkingMemoryWriter.hpp> #include <BindingWorkingMemoryReader.hpp> #include <BinderEssentials.hpp> #include <BeliefModels.hpp> #include <DomainModel.hpp> namespace cast { class VisualMediator : public binder::BindingWorkingMemoryWriter, public binder::BindingWorkingMemoryReader { private: /** * Time and update thresholds *(part of the ROI persistency criteria) */ int updateThr; bool doDisplay; /** * Name of the binder subarchitecture */ std::string m_bindingSA; /** * Name of the binder subarchitecture */ std::string m_salientObjID; bool first; /** * status of VisualObject persistency */ enum VisualObjectStatus { OBJECT, PROXY, DELETED }; /** * VisualObject data, contains also data used to evaluate VisualObject persistency */ struct VisualObjectData { cdl::WorkingMemoryAddress addr; VisualObjectStatus status; std::string proxyId; cdl::CASTTime addedTime; cdl::CASTTime lastUpdateTime; cdl::CASTTime deleteTime; }; std::map<std::string, VisualObjectData>VisualObjectMap; std::map<std::string, cast::WorkingMemoryChangeReceiver*>TaskFilterMap; std::queue<std::string> proxyToAdd; std::queue<std::string> proxyToDelete; std::queue<std::string> proxyToUpdate; boost::interprocess::named_semaphore* queuesNotEmpty; /** * callback function called whenever a new VisualObject appears */ void newVisualObject(const cdl::WorkingMemoryChange & _wmc); /** * callback function called whenever a VisualObject changes */ void updatedVisualObject(const cdl::WorkingMemoryChange & _wmc); /** * callback function called whenever a VisualObject is deleted */ void deletedVisualObject(const cdl::WorkingMemoryChange & _wmc); /** * callback function called whenever a Belief changes */ void updatedBelief(const cdl::WorkingMemoryChange & _wmc); /** * callback function called whenever a learning task is overwritten */ void updatedLearningTask(const cdl::WorkingMemoryChange & _wmc); // bool unionRef(beliefmodels::domainmodel::cogx::SuperFormulaPtr f, std::string &unionID); bool unionRef(beliefmodels::adl::FormulaPtr f, std::string &unionID); bool findAsserted(beliefmodels::adl::FormulaPtr fp, std::vector<beliefmodels::domainmodel::cogx::Color> &colors, std::vector<beliefmodels::domainmodel::cogx::Shape> &shapes, std::vector<float> &colorDist, std::vector<float> &shapeDist); bool AttrAgent(beliefmodels::adl::AgentStatusPtr ags); void addFeatureListToProxy(binder::autogen::core::ProxyPtr proxy, VisionData::IntSeq labels, VisionData::DoubleSeq distribution); void compileAndSendLearnTask(std::string visualObjID, const std::string beliefID, std::vector<beliefmodels::domainmodel::cogx::Color> &colors, std::vector<beliefmodels::domainmodel::cogx::Shape> &shapes, std::vector<float> &colorDist, std::vector<float> &shapeDist); void removeLearnedAssertions(beliefmodels::adl::FormulaPtr fp, VisionData::VisualLearnerLearningTaskPtr task); void checkDistribution4Clarification(std::string proxyID, VisionData::IntSeq labels, VisionData::DoubleSeq distribution); protected: /** * called by the framework to configure our component */ virtual void configure(const std::map<std::string,std::string> & _config); /** * called by the framework after configuration, before run loop */ virtual void start(); /** * called by the framework to start compnent run loop */ virtual void runComponent(); public: virtual ~VisualMediator() {} }; } #endif /* vim:set fileencoding=utf-8 sw=2 ts=4 noet:vim*/
[ "michaelz@9dca7cc1-ec4f-0410-aedc-c33437d64837" ]
michaelz@9dca7cc1-ec4f-0410-aedc-c33437d64837
96b60487b789e3230f9efde0a543e41ca2cb8975
8bd4a52406539c481bfb0126272e5689af2ec9d6
/main.cpp
2ebc8fbf805d3a28c22d8f5c79dbdc7f52f2afbd
[]
no_license
MosasoM/SUW
cddd5a24dcba111d90b780c976117cf947f940f2
3c36dd3318bf91baff21ca5f34ed4d90cbd23415
refs/heads/master
2020-05-20T00:49:24.476979
2019-05-14T02:34:25
2019-05-14T02:34:25
185,295,699
0
0
null
null
null
null
UTF-8
C++
false
false
2,874
cpp
#include <opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <stdlib.h> #include <iostream> int main(int argc, char *argv[]) { double ellipse_center_x; double ellipse_center_y;//楕円の中心座標の初期位置 double angle;//楕円の初期角度 double ellipse_length; int num1; int num2; ellipse_center_x = 500; ellipse_center_y = 500; angle = 0; ellipse_length = 20; for (int i = 0 ; i < 100000 ; i++) { cv::Mat img = cv::Mat::zeros(1000, 1000, CV_8UC3); if(ellipse_center_x < 100 || ellipse_center_x > 900 || ellipse_center_y < 100 || ellipse_center_y > 900){ while (ellipse_center_x < 100 || ellipse_center_x > 900 || ellipse_center_y < 100 || ellipse_center_y > 900) { //フレームから出そうになった時に方向転換する num2 = rand() % 3;//0,1,2,の中からランダムに数字を取る angle = angle + 180 + (num2 - 1) * 30 ; ellipse_center_x = ellipse_center_x - 10 * cos(angle * 3.141592 / 180); ellipse_center_y = ellipse_center_y - 10 * sin(angle * 3.141592 / 180); } } else{ num1 = rand() % 7;//0,1,2,3,4,5,6の中からランダムに数字を取る angle = angle + (num1 - 3) * 10; ellipse_center_x = ellipse_center_x - 10 * cos(angle * 3.141592 / 180); ellipse_center_y = ellipse_center_y - 10 * sin(angle * 3.141592 / 180);//ランダムで方向転換しながら進む } cv::ellipse(img, cv::Point(ellipse_center_x, ellipse_center_y), cv::Size(ellipse_length, 10), angle, 0, 360, cv::Scalar(200,0,0), -1, 3); double connect_point_x; double connect_point_y; connect_point_x = ellipse_center_x + ellipse_length * cos(angle * 3.141592 / 180); connect_point_y = ellipse_center_y + ellipse_length * sin(angle * 3.141592 / 180); //魚の胴体と尾っぽの部分のつなぎ点 cv::Point pt[3]; //任意の3点を配列に入れる pt[0] = cv::Point(connect_point_x, connect_point_y); pt[1] = cv::Point(connect_point_x + 15 * cos((angle + 45) * 3.141592 / 180), connect_point_y + 15 * sin((angle + 45) * 3.141592 / 180)); pt[2] = cv::Point(connect_point_x + 15 * cos((angle - 45) * 3.141592 / 180), connect_point_y + 15 * sin((angle - 45) * 3.141592 / 180)); //魚の尾っぽの部分 cv::fillConvexPoly(img, pt, 3, cv::Scalar(200,0,0) ); cv::namedWindow("drawing", cv::WINDOW_AUTOSIZE|cv::WINDOW_FREERATIO); cv::imshow("drawing", img); cv::waitKey(100); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
fb55283fedad8e6d78d9383b831ec6ff1211903c
47de9c88b957dc66c46769f40103d5147b00b7c9
/codeforces/1272/A.cpp
fd28f848001807debad10f98d3532107b4dae88f
[]
no_license
autul2017831021/Codeforces_Atcoder_Solved_Problems
1027a606b3cb5be80e57fcfbcfa0327ebd47bd95
b95e432718c9393f8a781fa56c2ed65f082274f5
refs/heads/master
2023-07-02T02:23:58.307782
2021-03-01T13:00:00
2021-07-31T15:40:28
329,067,317
1
0
null
null
null
null
UTF-8
C++
false
false
663
cpp
#include<bits/stdc++.h> using namespace std; long long bal(long long a,long long b,long long c) { return abs(a-b)+abs(a-c)+abs(b-c); } main() { int t; cin>>t; while(t--) { long long a,b,c,ans=0,ax,bx,cx; cin>>a>>b>>c; ans=bal(a,b,c); for(long long aa=-1;aa<=1;aa++) { for(long long bb=-1;bb<=1;bb++) { for(long long cc=-1;cc<=1;cc++) { ax=aa+a; bx=bb+b; cx=cc+c; ans=min(ans,bal(ax,bx,cx)); } } } cout<<ans<<endl; } }
[ "alexiautul@gmail.com" ]
alexiautul@gmail.com
7ad791ba74bcdfe40ba105bbec95de94f27219e1
68df74deb602f3f1ab270777e615796f10caeaa5
/12/12_4.cpp
2193c3aef37368aab8063cb6f17e3854d20691b6
[]
no_license
nanohaikaros/cpp_learn
88d726f05a22703426a2910184ab8535203f4f91
31a96d6666ceed5f12089fd63174d530798c0b16
refs/heads/master
2020-05-30T11:32:48.484164
2019-06-21T01:28:52
2019-06-21T01:28:52
189,705,452
0
0
null
null
null
null
UTF-8
C++
false
false
987
cpp
#include <iostream> using namespace std; class Date { private: int day, month, year; string dateInString; public: Date(int inMonth, int inDay, int inYear) : month(inMonth), day(inDay), year(inYear){}; Date operator + (int daysToAdd) { // binary addition Date newDate(month, day + daysToAdd, year); return newDate; } Date operator - (int daysToSub) { // binary subtraction return Date(month, day - daysToSub, year); } void DisplayDate() { cout << month << " / " << day << " / " << year << endl; } }; int main() { Date Holiday(12, 25, 2016); cout << "Holiday on: "; Holiday.DisplayDate(); Date PreviousHoliday(Holiday - 19); cout << "Precious holiday on: "; PreviousHoliday.DisplayDate(); Date NextHoliday(Holiday + 6); cout << "Next holiday on: "; NextHoliday.DisplayDate(); return 0; }
[ "1371689491@qq.com" ]
1371689491@qq.com
c716ac800cbe990e7e5eca9db5c898bfbb535206
195507851a9c21f30d1e0418513271748028aa92
/src/appleseed/renderer/modeling/surfaceshader/constantsurfaceshader.cpp
db021019418ecdfe0570ae85a066549fef3f7ab4
[ "MIT" ]
permissive
laizy/appleseed
0ff8ffed272d1c5723f9e8f29c1eb9b34da4448c
ddf210795102bad15f7b6ffe40a8ef0207a08035
refs/heads/master
2021-01-17T16:53:48.614187
2013-06-27T20:34:53
2013-06-27T20:34:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,090
cpp
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "constantsurfaceshader.h" // appleseed.renderer headers. #include "renderer/global/globaltypes.h" #include "renderer/kernel/shading/shadingcontext.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/kernel/shading/shadingresult.h" #include "renderer/modeling/input/inputarray.h" #include "renderer/modeling/surfaceshader/surfaceshader.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/image/colorspace.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/containers/specializedarrays.h" using namespace foundation; using namespace std; namespace renderer { namespace { // // Constant color surface shader. // const char* Model = "constant_surface_shader"; class ConstantSurfaceShader : public SurfaceShader { public: ConstantSurfaceShader( const char* name, const ParamArray& params) : SurfaceShader(name, params) { m_inputs.declare("color", InputFormatSpectralIlluminance); m_inputs.declare("color_multiplier", InputFormatScalar, "1.0"); m_inputs.declare("alpha_multiplier", InputFormatScalar, "1.0"); const string alpha_source = m_params.get_optional<string>("alpha_source", "color"); if (alpha_source == "color") m_alpha_source = AlphaSourceColor; else if (alpha_source == "material") m_alpha_source = AlphaSourceMaterial; else { RENDERER_LOG_ERROR( "invalid value \"%s\" for parameter \"alpha_source\", " "using default value \"color\".", alpha_source.c_str()); m_alpha_source = AlphaSourceColor; } } virtual void release() OVERRIDE { delete this; } virtual const char* get_model() const OVERRIDE { return Model; } virtual void evaluate( SamplingContext& sampling_context, const ShadingContext& shading_context, const ShadingPoint& shading_point, ShadingResult& shading_result) const OVERRIDE { // Evaluate the shader inputs. InputValues values; m_inputs.evaluate( shading_context.get_texture_cache(), shading_point.get_uv(0), &values); shading_result.m_color_space = ColorSpaceSpectral; shading_result.m_color = values.m_color; // This surface shader can override alpha. if (m_alpha_source == AlphaSourceColor) shading_result.m_alpha = values.m_alpha; // Apply multipliers. shading_result.m_color *= static_cast<float>(values.m_color_multiplier); shading_result.m_alpha *= static_cast<float>(values.m_alpha_multiplier); } private: DECLARE_INPUT_VALUES(InputValues) { Spectrum m_color; Alpha m_alpha; double m_color_multiplier; double m_alpha_multiplier; }; enum AlphaSource { AlphaSourceColor, AlphaSourceMaterial }; AlphaSource m_alpha_source; }; } // // ConstantSurfaceShaderFactory class implementation. // const char* ConstantSurfaceShaderFactory::get_model() const { return Model; } const char* ConstantSurfaceShaderFactory::get_human_readable_model() const { return "Constant"; } DictionaryArray ConstantSurfaceShaderFactory::get_widget_definitions() const { DictionaryArray definitions; definitions.push_back( Dictionary() .insert("name", "color") .insert("label", "Color") .insert("widget", "entity_picker") .insert("entity_types", Dictionary() .insert("color", "Colors") .insert("texture_instance", "Textures")) .insert("use", "required") .insert("default", "")); definitions.push_back( Dictionary() .insert("name", "alpha_source") .insert("label", "Alpha Source") .insert("widget", "dropdown_list") .insert("dropdown_items", Dictionary() .insert("Alpha channel of the color", "color") .insert("Alpha map of the material", "material")) .insert("use", "optional") .insert("default", "color")); definitions.push_back( Dictionary() .insert("name", "color_multiplier") .insert("label", "Color Multiplier") .insert("widget", "entity_picker") .insert("entity_types", Dictionary().insert("texture_instance", "Textures")) .insert("default", "1.0") .insert("use", "optional")); definitions.push_back( Dictionary() .insert("name", "alpha_multiplier") .insert("label", "Alpha Multiplier") .insert("widget", "entity_picker") .insert("entity_types", Dictionary().insert("texture_instance", "Textures")) .insert("default", "1.0") .insert("use", "optional")); return definitions; } auto_release_ptr<SurfaceShader> ConstantSurfaceShaderFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<SurfaceShader>( new ConstantSurfaceShader(name, params)); } } // namespace renderer
[ "beaune@aist.enst.fr" ]
beaune@aist.enst.fr
14120ef768380a7b13d92b36a103a0d31f91e4f9
0934782cc900ef32616d3c5204bca05b2aa34032
/SDK/RC_Foliage_parameters.hpp
310a3cd9d8b723b335bc3dc17cda35c505894de7
[]
no_license
igromanru/RogueCompany-SDK-9-24-2020
da959376e5464e505486cf0df01fff71dde212cf
fcab8fd45cf256c6f521d94f295e2a76701c411d
refs/heads/master
2022-12-18T05:30:30.039119
2020-09-25T01:12:25
2020-09-25T01:12:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,411
hpp
#pragma once // RogueCompany (4.24) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function Foliage.FoliageStatistics.FoliageOverlappingSphereCount struct UFoliageStatistics_FoliageOverlappingSphereCount_Params { class UObject** WorldContextObject; // (Parm, ZeroConstructor, IsPlainOldData) class UStaticMesh** StaticMesh; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData) struct FVector* CenterPosition; // (Parm, ZeroConstructor, IsPlainOldData) float* Radius; // (Parm, ZeroConstructor, IsPlainOldData) int ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function Foliage.FoliageStatistics.FoliageOverlappingBoxCount struct UFoliageStatistics_FoliageOverlappingBoxCount_Params { class UObject** WorldContextObject; // (Parm, ZeroConstructor, IsPlainOldData) class UStaticMesh** StaticMesh; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData) struct FBox* Box; // (Parm, ZeroConstructor, IsPlainOldData) int ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function Foliage.InteractiveFoliageActor.CapsuleTouched struct AInteractiveFoliageActor_CapsuleTouched_Params { class UPrimitiveComponent** OverlappedComp; // (Parm, ZeroConstructor, InstancedReference, IsPlainOldData) class AActor** Other; // (Parm, ZeroConstructor, IsPlainOldData) class UPrimitiveComponent** OtherComp; // (Parm, ZeroConstructor, InstancedReference, IsPlainOldData) int* OtherBodyIndex; // (Parm, ZeroConstructor, IsPlainOldData) bool* bFromSweep; // (Parm, ZeroConstructor, IsPlainOldData) struct FHitResult* OverlapInfo; // (ConstParm, Parm, OutParm, ReferenceParm, IsPlainOldData) }; // Function Foliage.ProceduralFoliageSpawner.Simulate struct UProceduralFoliageSpawner_Simulate_Params { int* NumSteps; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "60810131+frankie-11@users.noreply.github.com" ]
60810131+frankie-11@users.noreply.github.com
eac82a3116b7dc12973447b53d7fafdf04443e53
d971f9ee0d93e967be86f67a605911c75efcda6c
/cpp/alignment/tests/test_alignment.cpp
8f42324b1f284dda97b04ad0b77d515e583d406e
[]
no_license
zhuchcn/genomic-algorithms
0ea11e4935239f4f17e30982d7c426395747ace1
7a75b5f3b39b551bdd1ad738681f3fabe3cb1127
refs/heads/master
2020-07-04T06:48:42.687874
2020-03-01T21:47:27
2020-03-01T21:47:27
202,193,044
0
0
null
null
null
null
UTF-8
C++
false
false
1,198
cpp
#define CATCH_CONFIG_MAIN #include "../../catch/catch.hpp" #include "../NeedlemanWunsch.h" #include "../SmithWaterman.h" #include <iostream> #include <string> #include <limits> #include <exception> TEST_CASE("Testing Needleman Wunsch alignment", "[NeedlemanWunsch]") { SECTION("Testing two equal strings") { NeedlemanWunsch a ("AAGCTCGGTGGCGAAGTC", "AAGCTCGGTGGCGAAGTC"); a.printAlignment(); auto matrix = a.matrix(); REQUIRE(matrix.back().back() == 18); } } TEST_CASE("Testing Smith Watterman alignment", "[SmithWatterman]") { SECTION("Testing two equal strings") { SmithWaterman a ( "CTCTAAGCTCGGTGGCGAAGTCGTCA", "GTCCCCCCCCAGTAAGCTAGGGGCGACAGTG" ); a.printAlignment(); auto matrix = a.matrix(); REQUIRE(matrix.back().back() == 10); } } TEST_CASE("Testing semi-global alignment", "[SemiGlobalAlignment]") { SECTION("Testing two equal strings") { SmithWaterman a ( "AAGCTAGGGGCGACAGTG", "CTTTGCAAGCTCGGTGGCGAAGTCGTCA" ); a.printAlignment(); auto matrix = a.matrix(); REQUIRE(matrix.back().back() == 9); } }
[ "zhuchcn@gmail.com" ]
zhuchcn@gmail.com
1bf4890b4acb691c04d38c729b4bb3a01df8580f
99488b8c4d67a5432dff3021f27aaae36c86d0ea
/codeforces/1353/E.cpp
5b4f83842c62b06cd40de248159db2b16d75ee97
[]
no_license
Pratims10/CodeForces-Submissions
e1a2a8892547fca6e9e89ceb328cb84f80e86a1b
506af8b80a41e0310ea09ec3bb3f0c076f8b8cd8
refs/heads/master
2023-02-06T23:31:24.431536
2018-08-27T17:29:00
2020-12-21T08:08:09
323,261,045
0
0
null
null
null
null
UTF-8
C++
false
false
790
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long int ll n,k; ll dp[1000001]; string s; ll cnt[1000001]={0}; ll func(ll ind) { if(ind>=n) return 0; if(dp[ind]!=-1) return dp[ind]; ll ret=cnt[n-1]-cnt[ind]; if(s[ind]=='1') ret=min(ret,cnt[min(n-1,ind+k-1)]-cnt[ind]+func(ind+k)); else ret=min(ret,1+cnt[min(n-1,ind+k-1)]-cnt[ind]+func(ind+k)); return dp[ind]=ret; } int main() { ll i,j,m,t; cin>>t; while(t--) { cin>>n>>k; cin>>s; if(s[0]=='1') cnt[0]=1; else cnt[0]=0; for(i=1;i<n;i++) if(s[i]=='1') cnt[i]=cnt[i-1]+1; else cnt[i]=cnt[i-1]; for(i=0;i<=n;i++) dp[i]=-1; ll ans=n; for(i=n-1;i>=0;i--) func(i); for(i=0;i<n;i++) { ll x; if(i==0) x=dp[i]; else x=dp[i]+cnt[i-1]; ans=min(ans,x); } cout<<ans<<endl; } }
[ "pratimsarkar23@gmail.com" ]
pratimsarkar23@gmail.com
ccf4ee2bf2cf5595c6431fd3d16c48b07fc52ade
23e393f8c385a4e0f8f3d4b9e2d80f98657f4e1f
/WNP/01_WNP_소켓입출력모델/02_WSAAsyncSelect모델/3_Sample White/1_WhiteServer/a.cpp
1d5bd87e99ac6e6f77eb1dd8f545f5552273c354
[]
no_license
IgorYunusov/Mega-collection-cpp-1
c7c09e3c76395bcbf95a304db6462a315db921ba
42d07f16a379a8093b6ddc15675bf777eb10d480
refs/heads/master
2020-03-24T10:20:15.783034
2018-06-12T13:19:05
2018-06-12T13:19:05
142,653,486
3
1
null
2018-07-28T06:36:35
2018-07-28T06:36:35
null
UHC
C++
false
false
3,488
cpp
// user.chol.com/~downboard/async.txt 복사해 오세요. #define WIN32_LEAN_AND_MEAN #include <winsock2.h> #include <windows.h> #pragma comment(lib, "ws2_32.lib") struct LINE { POINTS ptFrom; POINTS ptTo; }; LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { static SOCKET listen_socket, link_socket; static POINTS ptFrom; switch( msg ) { case WM_LBUTTONDOWN: ptFrom = MAKEPOINTS(lParam); return 0; case WM_MOUSEMOVE: if ( wParam & MK_LBUTTON ) { POINTS pt = MAKEPOINTS(lParam); HDC hdc = GetDC( hwnd ); MoveToEx( hdc, ptFrom.x, ptFrom.y, 0); LineTo ( hdc, pt.x, pt.y ); ReleaseDC( hwnd, hdc ); // client로 보낸다. LINE line; line.ptFrom = ptFrom; line.ptTo = pt; send( link_socket, (char*)&line, sizeof(line), 0); ptFrom = pt; } return 0; case WM_USER+100: { WORD event = WSAGETSELECTEVENT( lParam ); WORD error = WSAGETSELECTERROR( lParam ); switch( event ) { case FD_CLOSE: SetWindowText( hwnd, "접속이 끊어 졌습니다."); closesocket( link_socket ); return 0; case FD_READ: { // data 도착 - 읽어 낸다. LINE line; recv( link_socket, (char*)&line, sizeof(line), 0); HDC hdc = GetDC( hwnd ); MoveToEx( hdc, line.ptFrom.x, line.ptFrom.y, 0); LineTo ( hdc, line.ptTo.x, line.ptTo.y); ReleaseDC( hwnd, hdc ); } return 0; case FD_ACCEPT: { SOCKADDR_IN addr; int size = sizeof( addr ); link_socket = accept( listen_socket, (SOCKADDR*)&addr, &size); // 대기 소켓을 닫는다.(1:1 통신) closesocket( listen_socket); SetWindowText( hwnd, "접속 되었습니다."); // 연결된 소켓을 비동기 소켓으로 변경한다. WSAAsyncSelect( link_socket, hwnd, WM_USER+100, FD_READ | FD_CLOSE ); } break; } break; } return 0; case WM_CREATE: { listen_socket = socket( AF_INET, SOCK_STREAM, 0 ); // socket 을 비동기 소켓으로 변경한다. WSAAsyncSelect( listen_socket, hwnd, WM_USER+100, FD_ACCEPT); SOCKADDR_IN addr; addr.sin_family = AF_INET; addr.sin_port = htons( 6000 ); addr.sin_addr.s_addr = INADDR_ANY; bind( listen_socket, (SOCKADDR*)&addr, sizeof(addr)); listen( listen_socket, 5); } return 0; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc( hwnd, msg, wParam, lParam); } int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd ) { WSADATA wsadata; if ( WSAStartup( MAKEWORD(2,2), &wsadata) != 0 ) { MessageBox( 0, "Error", "", MB_OK); return 0; } ATOM atom; WNDCLASS wc; HWND hwnd; MSG msg; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground= (HBRUSH)GetStockObject( WHITE_BRUSH ); wc.hCursor = LoadCursor( 0, IDC_ARROW ); wc.hIcon = LoadIcon( 0, IDI_APPLICATION); wc.hInstance = hInstance; wc.lpfnWndProc = WndProc; wc.lpszClassName= "First"; wc.lpszMenuName = 0; wc.style = 0; atom = RegisterClass(&wc); if ( atom == 0 ) { MessageBox( 0, "Fail To RegisterClass", "Error", MB_OK); return 0; } hwnd = CreateWindowEx( 0, "first", "Hello", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT,0, 0, 0, hInstance, 0); ShowWindow( hwnd, nShowCmd); UpdateWindow( hwnd ); while ( GetMessage( &msg, 0, 0, 0) ) { TranslateMessage(&msg); DispatchMessage( &msg); } WSACleanup(); return 0; }
[ "wyrover@gmail.com" ]
wyrover@gmail.com
1a51e01748aec9ac1c6a0685ab8ba66e6e0af3cd
655202725f7b5eac7bd45a415b333042cd33ef6b
/Graphics/ConstantBufferTypeAndID.h
9bbd4c1b6db04a487e848be2174edf962e4bf843
[]
no_license
BarabasGitHub/DogDealer
8c6aac914b1dfa54b6e89b0a3727a83d4ab61706
41b7d6bdbc6b9c2690695612ff8828f08b1403c7
refs/heads/master
2022-12-08T04:25:50.257398
2022-11-19T19:31:07
2022-11-19T19:31:07
121,017,925
1
2
null
null
null
null
UTF-8
C++
false
false
819
h
#pragma once #include "ConstantBufferTypes.h" #include "IDs.h" #include <tuple> // for std::tie namespace Graphics { struct ConstantBufferTypeAndID { ConstantBufferType type; ConstantBufferID id; ConstantBufferTypeAndID() = default; ConstantBufferTypeAndID( ConstantBufferType type, ConstantBufferID id) : type( type ), id(id) {} }; inline bool operator<( ConstantBufferTypeAndID const & first, ConstantBufferTypeAndID const & second ) { return std::tie( first.id, first.type ) < std::tie( second.id, second.type ); } inline bool operator==( ConstantBufferTypeAndID const & first, ConstantBufferTypeAndID const & second ) { return std::tie( first.id, first.type ) == std::tie( second.id, second.type ); } }
[ "mailbasvandenberg@gmail.com" ]
mailbasvandenberg@gmail.com
262da4187d05b888014abe9d78449bba50ea3904
4256dcd0abe17c5359ca1363cd4d0dce5dc9f850
/CollegeTimeTableView.cpp
6e2c23b5278658fe142376a92907501469843de1
[]
no_license
milindoka/CollegeTimeTable
83c58cf210ec1a561736f46f1ea9697c2f45c008
70f7e3c8d17a1cfd48e39975c1129b32a6f55377
refs/heads/master
2021-01-10T06:34:44.544948
2016-02-15T04:14:32
2016-02-15T04:14:32
51,728,746
4
1
null
null
null
null
UTF-8
C++
false
false
76,223
cpp
// CollegeTimeTableView.cpp : implementation of the CCollegeTimeTableView class // //#pragma warning(disable:4089) #include "stdafx.h" #include "CollegeTimeTable.h" #include "CollegeTimeTableDoc.h" #include "CollegeTimeTableView.h" #include "CollegeName.h" //#include <afxcoll.h> #include "FindReplace.h" #include "SwapDlg.h" #include "MultiDisableDlg.h" #include "Continue.h" #include "Wizard1Dlg.h" #include "Wizard2.h" #include "ExpNameDlg.h" #include "helpsheet.h" //#include "afxtempl.h" #define ROWS 300 // no. of rows in master #define COLS 7 // no.of cols in master #define RO 30 // no. of rows in individual/class #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //////////////////////// CString IArr[150][RO][COLS]; int cc[150],dc[150],gc[150]; CFindReplace FR; CSwapDlg SDlg; CMultiDisableDlg mdd; CWizard1Dlg wiz; CWizard2 wiz2; CExpNameDlg expand; int DispIndexIndi=0; int DispIndexClas=0; int cellcount; int TotalTrs=0; COLORREF YELLOW=RGB(255,255,160); COLORREF WHITE=RGB(255,255,255); COLORREF RED=RGB(255,200,200); COLORREF GREEN=RGB(200,255,200); COLORREF BLACK=RGB(0,0,0); int GlobalGapCount,GlobalClashCount,GlobalDubCount; CContinue cont; void pop(int ttt) { CString tmp; tmp.Format("%d",ttt); AfxMessageBox(tmp); } /////////Page Description Class /////////////// class CPage {public : CUIntArray Line;//stores line no.s of master that can be accomodated on single page // first index is line of lecture time public : CPage() {} ~CPage(){} CPage& CPage::operator=(const CPage& ss){ Line.RemoveAll(); return *this;} /// This dummy overloaded operator is required in order to add an empty element }; class CPrintPage {public : CStringArray Codes; /// Individuals or classes that can be accommodated ////on a single page public : CPrintPage(){} ~CPrintPage(){} CPrintPage& CPrintPage::operator=(const CPrintPage& ss){ Codes.RemoveAll(); return *this;} /// This dummy overloaded operator is required in order to add an empty element }; CArray <CPrintPage,CPrintPage&> ClassOrIndPageArray; // array containg print page //description for ind or class CArray <CPage,CPage&> PageArray; ////array containg print description for master ///////////////////////////////////////////////////////////////////////////// // CCollegeTimeTableView IMPLEMENT_DYNCREATE(CCollegeTimeTableView, CFormView) BEGIN_MESSAGE_MAP(CCollegeTimeTableView, CFormView) //{{AFX_MSG_MAP(CCollegeTimeTableView) ON_COMMAND(ID_EDIT_COPY, OnEditCopy) ON_COMMAND(ID_EDIT_CUT, OnEditCut) ON_COMMAND(ID_EDIT_PASTE, OnEditPaste) ON_COMMAND(ID_EDIT_UNDO, OnEditUndo) ON_BN_CLICKED(IDC_GENERATE, OnGenerate) ON_COMMAND(ID_FILE_PRINTTYPECLASSES, OnFilePrinttypeclasses) ON_COMMAND(ID_FILE_PRINTTYPEINDIVIDUALS, OnFilePrinttypeindividuals) ON_COMMAND(ID_FILE_PRINTTYPEMASTER, OnFilePrinttypemaster) ON_COMMAND(ID_FILE_SEVAS, OnFileSevas) ON_COMMAND(ID_FILE_SEV, OnFileSev) ON_COMMAND(ID_FILE_LOAD, OnFileLoad) ON_COMMAND(ID_FILENU, OnFilenu) ON_COMMAND(ID_SET_COLLEGENAME, OnSetCollegename) ON_COMMAND(ID_EDIT_INSERTROW, OnEditInsertrow) ON_COMMAND(ID_EDIT_DELETEROW, OnEditDeleterow) ON_COMMAND(ID_APP_EXIT, OnAppExit) ON_WM_TIMER() ON_COMMAND(ID_FILE_PRINTCURRENT, OnFilePrintcurrent) ON_COMMAND(ID_EDIT_FINDANDREPLACE, OnEditFindandreplace) ON_COMMAND(ID_EDIT_SWAPTEACHERS, OnEditSwapteachers) ON_COMMAND(ID_EDIT_DISABLECELL, OnEditDisablecell) ON_COMMAND(ID_TOOLS_DISPLAYGAPREPORT, OnToolsDisplaygapreport) ON_COMMAND(ID_TOOLS_AUTOREDUCEGAPS, OnToolsAutoreducegaps) ON_COMMAND(ID_TOOLS_DISPLAYCLASHREPORT, OnToolsDisplayclashreport) ON_COMMAND(ID_EDIT_DISABLEMULTIPLECELLS, OnEditDisablemultiplecells) ON_COMMAND(ID_EDIT_ENABLEALLCELLS, OnEditEnableallcells) ON_COMMAND(ID_TOOLS_TIMETABLEWIZARD, OnToolsTimetablewizard) ON_COMMAND(ID_TOOLS_TIMETABLEWIZARDSTEPII, OnToolsTimetablewizardstepII) ON_COMMAND(ID_SET_FULLNAMES, OnSetFullnames) ON_COMMAND(ID_EDIT_DEFREEZE_ON_STRING, OnEditDefreezeOnString) ON_COMMAND(ID_EDIT_SELECTMAKEBLUECELLSCONTAINGGIVENSTRING, OnEditSelectOnGivenString) ON_COMMAND(ID_TOOLS_DISPLAYNEXTINDIVIDUAL, OnToolsDisplaynextindividual) ON_COMMAND(ID_TOOLS_DISPLAYPREVINDIVIDUAL, OnToolsDisplayprevindividual) ON_COMMAND(ID_TOOLS_REFRESHTEACHERANDCLASSLISTS, OnToolsRefreshteacherandclasslists) ON_COMMAND(ID_TOOLS_DISPLAYNEXTCLASS, OnToolsDisplaynextclass) ON_COMMAND(ID_TOOLS_DISPLAYPREVCLASS, OnToolsDisplayprevclass) ON_COMMAND(ID_TOOLS_SHOWALLCOUNTS, OnToolsShowallcounts) ON_COMMAND(ID_HELP_HOWTOUSETIMETABLE, OnHelpHowtousetimetable) ON_MESSAGE(WM_USER,OnDisplay) ON_COMMAND(ID_HELP_LOADSAMPETIMETABLE, OnHelpLoadsampetimetable) //}}AFX_MSG_MAP // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CFormView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CFormView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CFormView::OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCollegeTimeTableView construction/destruction CCollegeTimeTableView* g_GetView() { return (CCollegeTimeTableView*)((CFrameWnd*)AfxGetApp()->m_pMainWnd)->GetActiveView(); } void MyGlobalFunc() { g_GetView()->Bye(); } void CCollegeTimeTableView::Bye() { //MessageBox("Bye"); OnAppExit(); } CCollegeTimeTableView::CCollegeTimeTableView() : CFormView(CCollegeTimeTableView::IDD) { //{{AFX_DATA_INIT(CCollegeTimeTableView) m_search = _T(""); //}}AFX_DATA_INIT // TODO: add construction code here } CCollegeTimeTableView::~CCollegeTimeTableView() { } void CCollegeTimeTableView::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); //{{AFX_DATA_MAP(CCollegeTimeTableView) DDX_Text(pDX, IDC_SEARCHBOX, m_search); //}}AFX_DATA_MAP } BOOL CCollegeTimeTableView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CFormView::PreCreateWindow(cs); } void CCollegeTimeTableView::OnInitialUpdate() { college="COLLEGE NAME"; CString wdays[]={"MON","TUE","WED","THU","FRI","SAT"}; LinesPerPage=46; PrintType=0; tcodes.SetSize(150); //// initial 150 teachers to avoid freq. mem alloc AllClasses.SetSize(20); PageArray.SetSize(100); /// 100 pages, large enough to avoid mem alloc CRect rect(0,0,509,630); m_master.Create(rect,this, 21111); m_master.SetRowCount(ROWS); m_master.SetColumnCount(COLS); m_master.SetFixedRowCount(); //m_master.SetFixedColumnCount(); for(int i=1;i<7;i++) { m_master.SetColumnWidth(i,68); m_master.SetItemText(0,i,wdays[i-1]); m_master.SetItemFormat(0,i-1,ES_CENTER | ES_UPPERCASE); } m_master.SetItemText(0,0,"MASTER"); m_master.SetItemFormat(0,6,ES_CENTER | ES_UPPERCASE); CRect rect1(509,80,1018,580); m_indiv.Create(rect1,this, 21112); m_indiv.SetEditable(FALSE); m_indiv.SetRowCount(RO); m_indiv.SetColumnCount(7); m_indiv.SetFixedRowCount(); //m_indiv.SetFixedColumnCount(); for(i=1;i<7;i++) { m_indiv.SetColumnWidth(i,68); m_indiv.SetItemText(0,i,wdays[i-1]); m_indiv.SetItemFormat(0,i-1,ES_CENTER | ES_UPPERCASE | ES_READONLY); } m_indiv.SetColumnWidth(6,68); m_indiv.SetItemFormat(0,6,ES_CENTER | ES_UPPERCASE); m_indiv.SetColumnWidth(0,84); CFormView::OnInitialUpdate(); GetParentFrame()->RecalcLayout(); ResizeParentToFit(); curfilename="Untitled"; CFrameWnd* pfr=GetParentFrame(); pfr->SetWindowText("College Time Table : "+curfilename); DuplicateData(DataBefore); cxScr = GetSystemMetrics(SM_CXSCREEN)/2 - 150; cyScr = GetSystemMetrics(SM_CYSCREEN)/2; } ///////////////////////////////////////////////////////////////////////////// // CCollegeTimeTableView printing BOOL CCollegeTimeTableView::OnPreparePrinting(CPrintInfo* pInfo) { switch(PrintType) // 0 for master, 1 for individual, 2 for class { //case 2: OnPrepareMasterPrint(pInfo);break; case 3: OnPrepareSinglePrint(pInfo);break; } return DoPreparePrinting(pInfo); } void CCollegeTimeTableView::OnPrepareSinglePrint(CPrintInfo* pInfo) { } void CCollegeTimeTableView::OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo) { //int Heightmm=pDC->GetDeviceCaps(VERTSIZE); //pop(Heightmm); ///double fff; //fff=Heightmm/6.46; //LinesPerPage=int(fff); switch(PrintType) // 0 for master, 1 for individual, 2 for class {case 0: DoPaginationForIndi(pDC,pInfo);break; case 1: DoPaginationForClass(pDC,pInfo);break; case 2: DoPaginationForMaster(pDC,pInfo);break; case 3: OnPrepareSinglePrint(pInfo);break; } } void CCollegeTimeTableView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) {CFrameWnd* pfr=GetParentFrame(); pfr->SetWindowText("College Time Table : "+curfilename); } void CCollegeTimeTableView::OnPrint(CDC* pDC, CPrintInfo* pInfo) {int lastindex; CString temp; for(lastindex=ROWS-1;lastindex>0;lastindex--) {temp=m_master.GetItemText(lastindex,0);if(!temp.IsEmpty()) break;} if(lastindex<=0) return; /////Empty Master !!!! switch(PrintType) // 0 for master, 1 for individual, 2 for class 3 for single current {case 0: PrintIndividual(pDC,pInfo);break; case 1: PrintClass(pDC,pInfo);break; case 2: PrintMaster(pDC,pInfo);break; case 3: PrintSingle(pDC,pInfo);break; } } void CCollegeTimeTableView::PrintSingle(CDC* pDC, CPrintInfo* pInfo) { //UpdateData(TRUE); int i,j; CString temp; if(m_search.IsEmpty()) return; for(i=1;i<ROWS;i++) for(j=0;j<COLS;j++) { temp=m_master.GetItemText(i,j); if(temp.IsEmpty()) continue; if(temp.Find(m_search)!=-1) { if(j==0) {GenerateClass(m_search); PrintOneClass(pDC); return;} else { GenerateIndividual(m_search); PrintOne(pDC);return;} } } } void CCollegeTimeTableView::GetParallelLectureList(CString str,CStringArray &arr) { arr.RemoveAll(); int idx; while((idx=str.Find(','))!=-1) {arr.Add(str.Left(idx)); str=str.Mid(idx+1); } arr.Add(str); } ///////////////////////////////////////////////////////////////////////////// // CCollegeTimeTableView diagnostics #ifdef _DEBUG void CCollegeTimeTableView::AssertValid() const { CFormView::AssertValid(); } void CCollegeTimeTableView::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } CCollegeTimeTableDoc* CCollegeTimeTableView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CCollegeTimeTableDoc))); return (CCollegeTimeTableDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CCollegeTimeTableView message handlers LONG CCollegeTimeTableView::OnDisplay(UINT wParam, LONG lparam) { CCellID cid=m_master.GetFocusCell(); int row=cid.row; int col=cid.col; CString temp=m_master.GetItemText(row,col); if(col==0) //if any class is selected {GenerateClass(temp);m_search=temp;UpdateData(FALSE);} ///otherwise it is individual display else { temp=PickTeacherCode(temp); m_search=temp;UpdateData(FALSE);GenerateIndividual(temp); } return TRUE; } void CCollegeTimeTableView::OnEditCopy() {m_master.OnEditCopy();} void CCollegeTimeTableView::OnEditCut() {m_master.OnEditCut();RefreshFormat();} void CCollegeTimeTableView::OnEditPaste() {m_master.SetFocus(); m_master.OnEditPaste(); RefreshFormat(); } void CCollegeTimeTableView::OnEditUndo() { // TODO: Add your command handler code here } CString CCollegeTimeTableView::PickTeacherCode(CString str)//return teacher code as XY {int left=str.Find('('); int rite=str.Find(')'); if(left>rite) return ""; return str.Mid(left+1,rite-left-1); } CString CCollegeTimeTableView::PickTeacherCode2(CString &str)//return teacher code and CUT {int left=str.Find('('); // the string int rite=str.Find(')'); if(left>rite) return ""; CString temp=str.Mid(left+1,rite-left-1); CString temp2=str.Mid(rite+1); str=temp2; return temp; } CString CCollegeTimeTableView::PickLectureTime(int row) { CString temp; for(int i=row;i>=1;i--) // go through leftmost time column upwards {temp=m_master.GetItemText(i,0); if(temp.IsEmpty()) continue; if(temp[0]>='0' && temp[0]<='9') return temp; } return "?"; } void CCollegeTimeTableView::SetGapAndClashCount(int lasttimerow) {int i,j,k; int first,last; gapcount=0;dubcount=0; CString temp,temp1; for(j=1;j<7;j++) ////through all six colums { first=last=0; for(i=1;i<=lasttimerow;i++) ///first nonempty row index; {temp=m_indiv.GetItemText(i,j); if(temp.IsEmpty() || temp=="RECESS") continue; else {first=i;break;} } for(i=lasttimerow;i>0;i--) ///last non-empty row index {temp=m_indiv.GetItemText(i,j); if(temp.IsEmpty() || temp=="RECESS") continue; else {last=i; break;} } if(first==0) continue; ////last has to be zero ////now count gaps and also count double lectures for(i=first;i<=last;i++) {temp=m_indiv.GetItemText(i,j); if(temp.IsEmpty() || temp=="RECESS") {gapcount++;continue;} for(k=i+1;k<=last;k++) {temp1=m_indiv.GetItemText(k,j); if(temp==temp1) dubcount++; } } } } void CCollegeTimeTableView::GenerateIndividual(CString tcode) {int i,j,k,lastidx,syze; clashcount=0; gapcount=0; dubcount=0; CString temp,temp2,temp3="("+tcode+")",temp4,temptime,tempclash; CString timearr[RO]; //Max RO lectures per day for an individual, index 1 to RO-1 CStringArray entry; CUIntArray count; int TotalLectures=0; ///Workload, 0 in the beginning for(i=1;i<RO;i++) /// Clean Individual timetable Area for(j=0;j<7;j++) {m_indiv.SetItemText(i,j,""); m_indiv.SetItemBkColour(i,j,WHITE); m_indiv.RedrawCell(i,j); } m_indiv.SetItemText(0,0,""); m_indiv.RedrawCell(0,0); //clean topleft corner if(tcode.IsEmpty()) return; lastidx=1; for(i=1;i<ROWS;i++) ///Collect All Lecture Timings i.e all numerics in col 0 {temp=m_master.GetItemText(i,0); if(temp.IsEmpty()) continue; if(temp[0]>='0' && temp[0]<='9') { timearr[lastidx]=temp; if(j<RO-1) lastidx++; else break;} } /// timearr contains all lecture timings if(lastidx+1<RO) lastidx+=1; for(i=1;i<=lastidx;i++) {m_indiv.SetItemText(i,0,timearr[i]); m_indiv.RedrawCell(i,0);} int rowindex=0; for(i=1;i<ROWS;i++) for(j=1;j<COLS;j++) {temp=m_master.GetItemText(i,j); if(temp.IsEmpty()) continue; k=temp.Find(temp3); ///find (tcode) , teachercode encluding brackets if(temp.Find("//")!=-1) { temptime=PickLectureTime(i); for(rowindex=1;rowindex<RO;rowindex++) if(timearr[rowindex]==temptime) { m_indiv.SetItemText(rowindex,3,"RECESS"); m_indiv.RedrawCell(rowindex,3); break; } } if(k!=-1) /// if (tcode) found { temptime=PickLectureTime(i); for(rowindex=1;rowindex<RO;rowindex++) if(timearr[rowindex]==temptime) { temp4=m_indiv.GetItemText(rowindex,j);//Get spot to check clash temp2=m_master.GetItemText(i,0); // get class temp2+="-"+temp.Mid(k-3,3); //attach subject if(temp4.IsEmpty()) ///cell empty so no clash m_indiv.SetItemText(rowindex,j,temp2); else //clash occurs {temp4+=","; temp4+=temp2; m_indiv.SetItemText(rowindex,j,temp4); m_indiv.SetItemBkColour(rowindex,j,RED);//red clashcount++; } m_indiv.RedrawCell(rowindex,j); //refresh class entry /// now add this entry to splitting chart //// i.e lecture entry & corresponding count syze=entry.GetSize(); if(syze==-1) { entry.Add(temp2); count.Add(1); ///this is first entry TotalLectures++; continue; } BOOL found=FALSE; // Set found=false for(int k=0;k<syze;k++) if(entry[k]==temp2) { count[k]++; found=TRUE; TotalLectures++;break; } //if entry already there count++ ////otherwise add entry and set count=1 for it if(!found) {entry.Add(temp2);count.Add(1);TotalLectures++;} } } } SetGapAndClashCount(lastidx); tempclash.Format("Clash Count : %d",clashcount); SetDlgItemText(IDC_CLASHCOUNT,tempclash); tempclash.Format("Double Count : %d",dubcount); SetDlgItemText(IDC_DUBCOUNT,tempclash); //MessageBox(tempclash); tempclash.Format("Gap Count : %d",gapcount); SetDlgItemText(IDC_GAPCOUNT,tempclash); syze=entry.GetSize(); if(syze==0) return; for(k=0;k<syze;k++) {m_indiv.SetItemText(lastidx+k/3,1+2*(k%3),entry[k]); m_indiv.RedrawCell(lastidx+k/3,1+2*(k%3)); temp.Format("%2d",count[k]); m_indiv.SetItemText(lastidx+k/3,2+2*(k%3),temp); m_indiv.RedrawCell(lastidx+k/3,2+2*(k%3)); } temp.Format(" - %d",TotalLectures); tcode+=temp; m_indiv.SetItemText(0,0,tcode); m_indiv.RedrawCell(0,0); } void CCollegeTimeTableView::RefreshFormat() { int i,j; CString temp; for (i=1;i<ROWS;i++) for(j=0;j<COLS;j++) { temp=m_master.GetItemText(i,j); if(temp[0]>='0' && temp[0]<='9') { m_master.SetItemBkColour(i,j,GREEN);m_master.RedrawCell(i,j);continue;} if(m_master.GetItemBkColour(i,j)==YELLOW) ; //do nothing else m_master.SetItemBkColour(i,j,WHITE); m_master.RedrawCell(i,j);continue; } } void CCollegeTimeTableView::GenerateClass(CString classcode) //for ex FYJC-I {int i,j,k,l,syze,lastidx,paralect; CString temp; CStringArray entry; CStringArray arr; CUIntArray count; CString timearr[RO],temptime; //Max RO lectures per day index 1 to RO-1 j=1; for(i=1;i<RO;i++) /// Clean Individual timetable Area for(j=0;j<7;j++) {m_indiv.SetItemText(i,j,""); m_indiv.SetItemBkColour(i,j,WHITE); m_indiv.RedrawCell(i,j); } m_indiv.SetItemText(0,0,""); m_indiv.RedrawCell(0,0); //clean topleft corner if(classcode.IsEmpty()) return; if(classcode[0]>='0' && classcode[0]<='9') return; ///it is time entry NOT class j=1; for(i=1;i<ROWS;i++) ///Collect All Lecture Timings i.e numerics in col 0 {temp=m_master.GetItemText(i,0); if(temp.IsEmpty()) continue; if(temp[0]>='0' && temp[0]<='9') { timearr[j]=temp; if(j<RO-1) j++; else break;} } for(i=1;i<RO;i++) {m_indiv.SetItemText(i,0,timearr[i]); m_indiv.RedrawCell(i,0);} m_indiv.SetItemText(0,0,classcode); m_indiv.RedrawCell(0,0); int rowindex=0; for(i=1;i<ROWS;i++) { temp=m_master.GetItemText(i,0); if(temp==classcode) /// include this entry {temptime=PickLectureTime(i); for(rowindex=1;rowindex<RO;rowindex++) /// if(timearr[rowindex]==temptime) for(j=1;j<7;j++) { m_indiv.SetItemText(rowindex,j,m_master.GetItemText(i,j)); m_indiv.RedrawCell(rowindex,j); //refresh class entry } } for(j=1;j<7;j++) { temp=m_master.GetItemText(i,j); if(temp.Find("//")!=-1) { temptime=PickLectureTime(i); for(rowindex=1;rowindex<RO;rowindex++) if(timearr[rowindex]==temptime) { m_indiv.SetItemText(rowindex,3,"RECESS"); m_indiv.RedrawCell(rowindex,3); break; } } } } ///Now fill Lecture Count Chart int TotalLectures=0; BOOL found; for(lastidx=RO-1;lastidx>0;lastidx--) {temp=m_indiv.GetItemText(lastidx,0); if(!temp.IsEmpty()) break; }///Get Last Time-Rowo of index of Indiv in lastidx //Now traverse all non-time cells for(i=1;i<=lastidx;i++) for(j=1;j<7;j++) {temp=m_indiv.GetItemText(i,j); if(temp.IsEmpty()) continue; GetParallelLectureList(temp,arr); paralect=arr.GetUpperBound(); if(paralect==-1) {MessageBox("Error in Class Generation"); return;} for(k=0;k<=paralect;k++) {//arr[k].TrimLeft();arr[k].TrimRight(); if(arr[k].IsEmpty()) continue; syze=entry.GetUpperBound(); if(syze==-1) { entry.Add(arr[k]); count.Add(1); ///this is first entry TotalLectures++; continue; } //check repeat count found=FALSE; for(l=0;l<=syze;l++) if(entry[l]==arr[k]) {found=TRUE; break;} if(found){ count[l]++;TotalLectures++;} else {entry.Add(arr[k]); count.Add(1);TotalLectures++;} } } lastidx+=2; syze=entry.GetSize(); if(syze==0) return; for(k=0;k<syze;k++) {m_indiv.SetItemText(lastidx+k/3,1+2*(k%3),entry[k]); m_indiv.RedrawCell(lastidx+k/3,1+2*(k%3)); temp.Format("%2d",count[k]); m_indiv.SetItemText(lastidx+k/3,2+2*(k%3),temp); m_indiv.RedrawCell(lastidx+k/3,2+2*(k%3)); } temp.Format(" - %d",TotalLectures); classcode+=temp; m_indiv.SetItemText(0,0,classcode); m_indiv.RedrawCell(0,0); } void CCollegeTimeTableView::OnGenerate() {UpdateData(TRUE); int i,j; CString temp; if(m_search.IsEmpty()) return; for(i=1;i<ROWS;i++) for(j=0;j<COLS;j++) {temp=m_master.GetItemText(i,j); if(temp.IsEmpty()) continue; if(temp.Find(m_search)!=-1) { if(j==0) GenerateClass(m_search); else { GenerateIndividual(m_search); } return; } } } void CCollegeTimeTableView::DisplayGrid(CPoint tl,CPoint br,int rows,int cols,CDC* pDC) { CPen pPen,*pPenold; pPen.CreatePen(PS_SOLID,1,BLACK); pPenold=pDC->SelectObject(&pPen); int xn=(br.x-tl.x)/cols; int yn=(br.y-tl.y)/rows; for(int i=0;i<=cols;i++) { pDC->MoveTo(tl.x+i*xn,tl.y); pDC->LineTo(tl.x+i*xn,br.y); } for(i=0;i<=rows;i++) {pDC->MoveTo(tl.x,tl.y+i*yn); pDC->LineTo(br.x,tl.y+i*yn); } pDC->SelectObject(pPenold); // pDC->SelectObject(pOldBrush); } void CCollegeTimeTableView::CentreText(int y,CString str,CDC* pDC) {CSize tt; tt=pDC->GetTextExtent(str); int xx=70+(700-tt.cx)/2; pDC->TextOut(xx,y,str); } void CCollegeTimeTableView::PrintMaster(CDC* pDC, CPrintInfo* pInfo) { int j,k,height,maxheight; UINT line; CString temp; CStringArray arr; CFont fon; CFont* oldfont; fon.CreateFont(18,8,0,0,FW_BOLD,0,0,0,ANSI_CHARSET,OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH | FF_SWISS,"COURIER NEW"); oldfont=pDC->SelectObject(&fon); pDC->SetMapMode(MM_LOENGLISH); pDC->SetBkMode(TRANSPARENT); CPoint PP(70,-25); CPoint QQ(771,-25); CPoint tempPP,tempQQ; if(pInfo->m_nCurPage==1) CentreText(-25,college,pDC); int LineCounter=0; UINT lastline=PageArray[(pInfo->m_nCurPage)-1].Line.GetUpperBound();/// for(line=0;line<=lastline;line++) { maxheight=1; for(j=0;j<7;j++) { tempPP=PP;//tempQQ=QQ; temp=m_master.GetItemText(PageArray[(pInfo->m_nCurPage)-1].Line[line],j); if(temp[0]>='0' && temp[0]<='9') {PP.Offset(0,-25); pDC->TextOut(74+100,PP.y-2," MON"); pDC->TextOut(74+200,PP.y-2," TUE"); pDC->TextOut(74+300,PP.y-2," WED"); pDC->TextOut(74+400,PP.y-2," THU"); pDC->TextOut(74+500,PP.y-2," FRI"); pDC->TextOut(74+600,PP.y-2," SAT"); tempPP=PP;QQ.Offset(0,-25); /////create blank space between lecture blocks } GetParallelLectureList(temp,arr);// in CStringarray arr height=arr.GetSize(); if(height<1) height=1; if(height>maxheight) maxheight=height; for(k=0;k<height;k++) {pDC->TextOut(74+j*100,PP.y-2,arr[k]); PP.Offset(0,-25); } PP=tempPP;//Reset to normal lecture line } //end of j=0 loop QQ.Offset(0,-25*maxheight); DisplayGrid(PP,QQ,1,7,pDC); PP.Offset(0,-25*maxheight); } /// end of line=0 loop pDC->SelectObject(&oldfont); } /// end of PrintMaster fn void CCollegeTimeTableView::DoPaginationForMaster(CDC* pDC,CPrintInfo* pInfo) {pInfo->SetMinPage(1); CString temp;//,temp2; CStringArray arr; arr.SetSize(20); //// for parallel lecture splitting in diff strings int height,maxheight,i,j; int LineCounter=0,PageIndex=0; PageArray.RemoveAll(); ////// Reset Page Description Array CPage tempage; PageArray.Add(tempage); for(int lastindex=ROWS-1;lastindex>0;lastindex--) {temp=m_master.GetItemText(lastindex,0); if(!temp.IsEmpty()) break;} if(lastindex<=0) return; /////Empty Master !!!! if(lastindex<1) lastindex=1; for(i=1;i<=lastindex;i++) ////// Preapre Page Description {maxheight=1; temp=m_master.GetItemText(i,0); if(temp.IsEmpty()) continue; //temp2=m_master.GetItemText(i,1); //if( if(temp[0]>='0' && temp[0]<='9') maxheight=2; // for lecture time skip one line for(j=1;j<7;j++) {temp=m_master.GetItemText(i,j); GetParallelLectureList(temp,arr);// Get Parallel lectures in CStringarray arr height=arr.GetSize(); if(height<1) height=1; if(height>maxheight) maxheight=height; ///max cell height,>1 for parallel lectures } if((LineCounter+maxheight)<LinesPerPage) /// check whether line(s) fit in page {LineCounter+=maxheight; //if yes, include lines PageArray[PageIndex].Line.Add(i); continue; ///go for more lines on page } PageIndex++; /// otherwise Page is Full, go for next page PageArray.Add(tempage);///Create Empty Page Struct LineCounter=maxheight; /// include current line(s) PageArray[PageIndex].Line.Add(i); } pInfo->SetMaxPage(PageIndex+1);///Max Page no. can now be set } ///////------------------------------------------------------------------------ /////// Printing Individual Time Tables ///////------------------------------------------------------------------------ void CCollegeTimeTableView::Fill_AllIndividuals_in_tcodesArray() { CString temp,temp2; tcodes.RemoveAll(); ////Reset teacher codes list CStringArray paralist; /// collect all sharing(llel) lecture entries BOOL found; int i,j,k,l,paratotal; for(i=1;i<ROWS;i++) ///traverse through master for(j=1;j<7;j++) {temp=m_master.GetItemText(i,j); if(temp.IsEmpty()) continue; GetParallelLectureList(temp,paralist); paratotal=paralist.GetUpperBound(); if(paratotal==-1) { MessageBox("Improper Entry"); continue;} for(k=0;k<=paratotal;k++) {temp2=PickTeacherCode(paralist[k]); found=FALSE; for(l=0;l<tcodes.GetSize();l++) if(tcodes[l]==temp2){found=TRUE;break;} if(!found) tcodes.Add(temp2); } } int II=tcodes.GetSize(); for(j=1;j<II;j++) for(i=0;i<j;i++) if(tcodes[i]>tcodes[j]) {temp=tcodes[i];tcodes[i]=tcodes[j];tcodes[j]=temp;} if(tcodes[0].IsEmpty()) tcodes.RemoveAt(0); } void CCollegeTimeTableView::PrintOneClass(CDC* pDC) {int i,j,k,height,maxheight,lastindex,firstindex; // UINT codeidx; CString temp; CStringArray arr; arr.SetSize(20); CFont fon; CFont* oldfont; fon.CreateFont(18,8,0,0,FW_BOLD,0,0,0,ANSI_CHARSET,OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH | FF_SWISS,"COURIER NEW"); oldfont=pDC->SelectObject(&fon); pDC->SetMapMode(MM_LOENGLISH); pDC->SetBkMode(TRANSPARENT); CPoint PP(70,-5); CPoint QQ(771,-5); CPoint tempPP,tempQQ; int LineCounter=0; for(firstindex=0;firstindex<RO;firstindex++) for(j=1;j<7;j++) /// Get first non-empty row index {temp=m_indiv.GetItemText(firstindex,j);if(!temp.IsEmpty()) goto GotFirstIndex; } GotFirstIndex : if(firstindex>RO-1)firstindex=RO-1; for(lastindex=RO-1;lastindex>=firstindex;lastindex--) /// Get last time-cell index {temp=m_indiv.GetItemText(lastindex,0);if(!temp.IsEmpty()) break;} CentreText(PP.y,college,pDC); PP.Offset(0,-25); QQ.Offset(0,-25); for(i=firstindex;i<=lastindex;i++) { maxheight=1; for(j=0;j<7;j++) { tempPP=PP;tempQQ=QQ; temp=m_indiv.GetItemText(i,j); GetParallelLectureList(temp,arr);// in CStringarray arr height=arr.GetSize(); if(height<1) height=1; if(height>maxheight) maxheight=height; for(k=0;k<height;k++) {pDC->TextOut(74+j*100,PP.y-2,arr[k]); PP.Offset(0,-25); } PP=tempPP;//Reset to normal lecture line }///end loop for(j=0 QQ.Offset(0,-25*maxheight); DisplayGrid(PP,QQ,1,7,pDC); PP.Offset(0,-25*maxheight); } ///end loop for(codeidx=0 PP.Offset(0,-25); QQ.Offset(0,-25); //} ///end of loop for(i=0 pDC->SelectObject(&oldfont); } void CCollegeTimeTableView::PrintOne(CDC* pDC) { int j,k; CString temp,temp1,temp3; int lastindex,firstindex; CFont fon; CFont* oldfont; fon.CreateFont(18,8,0,0,FW_BOLD,0,0,0,ANSI_CHARSET,OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH | FF_SWISS,"COURIER NEW"); oldfont=pDC->SelectObject(&fon); pDC->SetMapMode(MM_LOENGLISH); pDC->SetBkMode(TRANSPARENT); pDC->SelectStockObject(NULL_BRUSH); CPoint PP(70,-5); CPoint QQ(771,-30); int ee=expand.ExpandedNames.GetSize(); if(ee>0) for(j=0;j<ee;j++) if (expand.ExpandedNames[j].Left(2)==m_search) {temp3=expand.ExpandedNames[j].Mid(2); break;} temp=college; temp+=" : "; temp+=temp3; temp1.Format(" : [CC:%d][GC:%d][DC:%d]",clashcount,gapcount,dubcount); temp+=temp1; pDC->TextOut(PP.x,PP.y,temp); for(firstindex=1;firstindex<RO;firstindex++) for(j=1;j<7;j++) /// Get first non-empty row index {temp=m_indiv.GetItemText(firstindex,j);if(!temp.IsEmpty()) goto GotFirstNonemptyRow; } GotFirstNonemptyRow : if(firstindex>RO-1) firstindex=RO-1; for(lastindex=RO-1;lastindex>0;lastindex--) /// Get last time-cell index { temp=m_indiv.GetItemText(lastindex,0);if(!temp.IsEmpty()) break;} int lastindex1=lastindex; for(j=lastindex;j>0;j--) for(k=1;k<7;k++) { temp=m_indiv.GetItemText(j,k); if(!temp.IsEmpty()) goto lastcell;} lastcell : lastindex=j; int LineCounter=0; PP.Offset(0,-25); QQ.Offset(0,-25); pDC->TextOut(74+100,PP.y-2," MON"); pDC->TextOut(74+200,PP.y-2," TUE"); pDC->TextOut(74+300,PP.y-2," WED"); pDC->TextOut(74+400,PP.y-2," THU"); pDC->TextOut(74+500,PP.y-2," FRI"); pDC->TextOut(74+600,PP.y-2," SAT"); DisplayGrid(PP,QQ,1,7,pDC); pDC->TextOut(74,PP.y-2,m_indiv.GetItemText(0,0)); for(j=firstindex;j<=lastindex;j++) { PP.Offset(0,-25); QQ.Offset(0,-25); for(k=0;k<7;k++) { temp=m_indiv.GetItemText(j,k); pDC->TextOut(74+k*100,PP.y-2,temp);//print cell text } DisplayGrid(PP,QQ,1,7,pDC); ///Print each row with enclosing grid } //// now print lecture counts QQ.Offset(0,-12); ///keep some spacing PP.Offset(0,-30); //// slight lower the top-left for count box BOOL FirstLine=TRUE; //PP=QQ; //lastindex+=2;///locate lecture count part in individual lastindex=lastindex1+2;///locate lecture count part in individual for(j=lastindex;j<RO;j++) { temp=m_indiv.GetItemText(j,1); if(temp.IsEmpty()) break; ///if end of counts then stop if(!FirstLine) QQ.Offset(0,-25); //else next line, no spacing for top table temp1=m_indiv.GetItemText(j,2); temp=temp+" -"+temp1;///make one convenient string to print pDC->TextOut(74+1*100,QQ.y-2,temp);//print cell text temp=m_indiv.GetItemText(j,3); if(temp.IsEmpty()) break;///if end of counts temp1=m_indiv.GetItemText(j,4); temp=temp+" -"+temp1;///make one convenient string to print pDC->TextOut(74+3*100,QQ.y-2,temp);//print cell text temp=m_indiv.GetItemText(j,5); if(temp.IsEmpty()) break;///if end of counts temp1=m_indiv.GetItemText(j,6); temp=temp+" -"+temp1;///make one convenient string to print pDC->TextOut(74+5*100,QQ.y-2,temp);//print cell text FirstLine=FALSE; ///now allow next line spacing on top } QQ.Offset(0,-25); //next line DisplayGrid(PP,QQ,1,1,pDC); QQ.Offset(0,-25); ///leave gap between two individuals PP.y=QQ.y; QQ.Offset(0,-25); // } ///end of loop codeidx = 0... pDC->SelectObject(&oldfont); } void CCollegeTimeTableView::PrintIndividual(CDC* pDC,CPrintInfo* pInfo) { int j,k,ee; UINT codeidx; CString temp,temp1,temp3; int lastindex,firstindex; CFont fon; CFont* oldfont; fon.CreateFont(18,8,0,0,FW_BOLD,0,0,0,ANSI_CHARSET,OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH | FF_SWISS,"COURIER NEW"); oldfont=pDC->SelectObject(&fon); pDC->SetMapMode(MM_LOENGLISH); pDC->SetBkMode(TRANSPARENT); pDC->SelectStockObject(NULL_BRUSH); CPoint PP(70,-3); CPoint QQ(771,-28); ee=expand.ExpandedNames.GetSize(); int LineCounter=0; UINT lastcode=ClassOrIndPageArray[(pInfo->m_nCurPage)-1].Codes.GetUpperBound();/// for(codeidx=0;codeidx<=lastcode;codeidx++) { temp3=ClassOrIndPageArray[(pInfo->m_nCurPage)-1].Codes[codeidx]; GenerateIndividual(temp3); if(ee>0) for(j=0;j<ee;j++) if (expand.ExpandedNames[j].Left(2)==temp3) {temp3=expand.ExpandedNames[j].Mid(2); break;} temp=college; temp+=" : "; temp+=temp3; temp1.Format(" : [CC:%d][GC:%d][DC:%d]",clashcount,gapcount,dubcount); temp+=temp1; pDC->TextOut(PP.x,PP.y,temp); for(firstindex=1;firstindex<RO;firstindex++) for(j=1;j<7;j++) /// Get first non-empty row index {temp=m_indiv.GetItemText(firstindex,j);if(!temp.IsEmpty()) goto GotFirstNonempty; } GotFirstNonempty : if(firstindex>RO-1) firstindex=RO-1; for(lastindex=RO-1;lastindex>0;lastindex--) /// Get last time-cell index { temp=m_indiv.GetItemText(lastindex,0);if(!temp.IsEmpty()) break;} int lastindex1=lastindex; for(j=lastindex;j>0;j--) for(k=1;k<7;k++) { temp=m_indiv.GetItemText(j,k); if(!temp.IsEmpty()) goto lastcell;} lastcell : lastindex=j; //CentreText(PP.y,college,pDC); PP.Offset(0,-25); QQ.Offset(0,-25); pDC->TextOut(74+100,PP.y-2," MON"); pDC->TextOut(74+200,PP.y-2," TUE"); pDC->TextOut(74+300,PP.y-2," WED"); pDC->TextOut(74+400,PP.y-2," THU"); pDC->TextOut(74+500,PP.y-2," FRI"); pDC->TextOut(74+600,PP.y-2," SAT"); DisplayGrid(PP,QQ,1,7,pDC); pDC->TextOut(74,PP.y-2,m_indiv.GetItemText(0,0)); for(j=firstindex;j<=lastindex;j++) { PP.Offset(0,-25); QQ.Offset(0,-25); for(k=0;k<7;k++) { temp=m_indiv.GetItemText(j,k); pDC->TextOut(74+k*100,PP.y-2,temp);//print cell text } DisplayGrid(PP,QQ,1,7,pDC); ///Print each row with enclosing grid } BOOL FirstLine=TRUE; lastindex=lastindex1+2;///locate lecture count part in individual for(j=lastindex;j<RO;j++) { temp=m_indiv.GetItemText(j,1); if(temp.IsEmpty()) break; ///if end of counts then stop if(!FirstLine) QQ.Offset(0,-25); //else next line, no spacing for top table temp1=m_indiv.GetItemText(j,2); temp=temp+" -"+temp1;///make one convenient string to print pDC->TextOut(74+1*100,QQ.y-2,temp);//print cell text temp=m_indiv.GetItemText(j,3); if(temp.IsEmpty()) break;///if end of counts temp1=m_indiv.GetItemText(j,4); temp=temp+" -"+temp1;///make one convenient string to print pDC->TextOut(74+3*100,QQ.y-2,temp);//print cell text temp=m_indiv.GetItemText(j,5); if(temp.IsEmpty()) break;///if end of counts temp1=m_indiv.GetItemText(j,6); temp=temp+" -"+temp1;///make one convenient string to print pDC->TextOut(74+5*100,QQ.y-2,temp);//print cell text FirstLine=FALSE; ///now allow next line spacing on top } QQ.Offset(0,-25); //next line DisplayGrid(PP,QQ,1,1,pDC); QQ.Offset(0,-25); ///leave gap between two individuals PP.y=QQ.y; QQ.Offset(0,-25); } ///end of loop codeidx = 0... pDC->SelectObject(&oldfont); } ///////------------------------------------------------ /////// Printing Class Time Tables ///////------------------------------------------------ void CCollegeTimeTableView::DoPaginationForClass(CDC* pDC,CPrintInfo* pInfo) {//LinesPerPage=46; CString temp; pInfo->SetMinPage(1); int i,j,k,l,rowheight,height,lastindex,LineCounter,ClassHeight; BOOL found; CStringArray arr; /// array to store parallel lectures arr.SetSize(20); /// max 20 lectures before mem allocation /// Collect All Classes (***Do not Allow Duplicates) ClassOrIndPageArray.RemoveAll(); ////// Reset Page Description Array CPrintPage tempage; ClassOrIndPageArray.Add(tempage); /// now PageIndex is 0 (for first page) int PageIndex=0; for(i=1;i<ROWS;i++) /// All classes are in the first column of the master {temp=m_master.GetItemText(i,0); if(temp.IsEmpty()) continue; /// skip empty cells if(temp[0]>='0' && temp[0]<='9') continue; /// and also skip time cells k=AllClasses.GetSize(); if(k==0) {AllClasses.Add(temp);continue;} ///initial entry found=FALSE; for(j=0;j<k;j++) if(temp==AllClasses[j]) {found=TRUE; break;} ///// if no duplicate class found then add if(!found) AllClasses.Add(temp); } ///start pagination for class printouts k=AllClasses.GetSize(); LineCounter=0; ///initialize line count, it should be maximum but < LinesPerPage for(i=0;i<k;i++) { GenerateClass(AllClasses[i]); for(lastindex=RO-1;lastindex>0;lastindex--) {temp=m_indiv.GetItemText(lastindex,0); if(temp.IsEmpty()) continue; else break; } //if(lastindex<=0) return; /////Empty Class !!!! ClassHeight=1; for(j=1;j<=lastindex;j++) { rowheight=1; for(l=1;l<7;l++) {temp=m_indiv.GetItemText(j,l);///Examine each cell for height if(temp.IsEmpty()) continue; ///Height will be >1 for sharing lectures GetParallelLectureList(temp,arr);// Get Parallel lectures in CStringarray arr height=arr.GetSize(); if(height<1) {rowheight=1;break;} if(height>rowheight) rowheight=height; ///max cell height,>1 for parallel lectures }///end of l=1 loop ClassHeight+=rowheight; }////end of j=1 loop ClassHeight+=3;///for college title + Weekday line + Seperation LineCounter+=ClassHeight; //pop(LineCounter); if(LineCounter<LinesPerPage) {//LineCounter+=ClassHeight; /// this class time table fits in page // CString tmp; // tmp.Format("%d",LineCounter); //MessageBox(tmp); ClassOrIndPageArray[PageIndex].Codes.Add(AllClasses[i]); LineCounter++; continue; ///Add line before next class & go for more classes } //{CString tmp; //tmp.Format("%d",LineCounter); //MessageBox(tmp);} /// otherwise Page is Full, go for next page ClassOrIndPageArray.Add(tempage);///Create Empty Page Struct LineCounter=ClassHeight; /// Set Line Counter for the next page PageIndex++; ClassOrIndPageArray[PageIndex].Codes.Add(AllClasses[i]); ///Add class // pop(PageIndex); ////loop ends...go for more classes.... top of loop } pInfo->SetMaxPage(PageIndex+1); /// set maximum page count //pop(PageIndex); } void CCollegeTimeTableView::PrintClass(CDC* pDC,CPrintInfo* pInfo) { int i,j,k,height,maxheight,lastindex; UINT codeidx; CString temp; CStringArray arr; arr.SetSize(20); //pop(pInfo->m_nCurPage); CFont fon; CFont* oldfont; fon.CreateFont(18,8,0,0,FW_BOLD,0,0,0,ANSI_CHARSET,OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH | FF_SWISS,"COURIER NEW"); oldfont=pDC->SelectObject(&fon); pDC->SetMapMode(MM_LOENGLISH); pDC->SetBkMode(TRANSPARENT); CPoint PP(70,-3); CPoint QQ(771,-3); CPoint tempPP,tempQQ; int LineCounter=0; UINT lastcode=ClassOrIndPageArray[(pInfo->m_nCurPage)-1].Codes.GetUpperBound();/// for(codeidx=0;codeidx<=lastcode;codeidx++) { GenerateClass(ClassOrIndPageArray[(pInfo->m_nCurPage)-1].Codes[codeidx]); for(lastindex=RO-1;lastindex>0;lastindex--) /// Get last time-cell index {temp=m_indiv.GetItemText(lastindex,0);if(!temp.IsEmpty()) break;} CentreText(PP.y,college,pDC); PP.Offset(0,-25); QQ.Offset(0,-25); for(i=0;i<=lastindex;i++) { maxheight=1; for(j=0;j<7;j++) { tempPP=PP;tempQQ=QQ; temp=m_indiv.GetItemText(i,j); GetParallelLectureList(temp,arr);// in CStringarray arr height=arr.GetSize(); if(height<1) height=1; if(height>maxheight) maxheight=height; if(i==0 || j==0) maxheight=1; for(k=0;k<height;k++) {pDC->TextOut(74+j*100,PP.y-2,arr[k]); PP.Offset(0,-25); } PP=tempPP;//Reset to normal lecture line }///end loop for(j=0 QQ.Offset(0,-25*maxheight); DisplayGrid(PP,QQ,1,7,pDC); //MessageBox("!"); PP.Offset(0,-25*maxheight); } ///end loop for(codeidx=0 PP.Offset(0,-25); QQ.Offset(0,-25); } ///end of loop for(i=0 pDC->SelectObject(&oldfont); } //end classprint void CCollegeTimeTableView::OnFilePrinttypeclasses() { PrintType=1; PostMessage(WM_COMMAND,ID_FILE_PRINT,0); } void CCollegeTimeTableView::OnFilePrinttypeindividuals() { PrintType=0; PostMessage(WM_COMMAND,ID_FILE_PRINT,0); } void CCollegeTimeTableView::OnFilePrinttypemaster() {PrintType=2; PostMessage(WM_COMMAND,ID_FILE_PRINT,0); } void CCollegeTimeTableView::OnFileSevas() { // TODO: Add your command handler code here CFileDialog cfd(FALSE,"tit","*.tit"); CString filename; if(cfd.DoModal()==IDOK) { CString token="TimeTable"; //college="College Name"; CString filepath=cfd.GetPathName(); filename=cfd.GetFileName(); CFile thefile; CFileException exc; thefile.Open(filepath,CFile::modeCreate | CFile::modeWrite,&exc); CArchive archive(&thefile,CArchive::store); int i,j; int totnames=expand.ExpandedNames.GetSize(); CString temp; COLORREF tempcolour; archive<<token <<college; //// college name for (i=1;i<ROWS;i++) for(j=0;j<COLS;j++) { temp=m_master.GetItemText(i,j); tempcolour=m_master.GetItemBkColour(i,j); archive<<temp<<tempcolour; } archive <<totnames; //// total expanded names for(i=0;i<totnames;i++) archive<<expand.ExpandedNames[i]; curpath=filepath; curfilename=filename; CFrameWnd* pfr=GetParentFrame(); pfr->SetWindowText("College Time Table : "+filename); } DuplicateData(DataBefore); } void CCollegeTimeTableView::OnFileSev() {if(curpath.IsEmpty()) { OnFileSevas(); return;} m_master.Down(); CString token="TimeTable"; CFile thefile; CFileException exc; thefile.Open(curpath,CFile::modeCreate | CFile::modeWrite,&exc); CArchive archive(&thefile,CArchive::store); int i,j; int totnames=expand.ExpandedNames.GetSize(); CString temp; COLORREF tempcolour; archive<<token <<college; for (i=1;i<ROWS;i++) for(j=0;j<COLS;j++) { temp=m_master.GetItemText(i,j); tempcolour=m_master.GetItemBkColour(i,j); archive<<temp<<tempcolour; } archive<<totnames; //// total expanded names for(i=0;i<totnames;i++) archive<<expand.ExpandedNames[i]; DuplicateData(DataBefore); DisplayToolTip(); SetTimer(1,3000,NULL); } void CCollegeTimeTableView::OnFileLoad() { // TODO: Add your command handler code here CFileDialog cfd(TRUE,"tit","*.tit"); if(cfd.DoModal()==IDOK) { CString token; CString filepath=cfd.GetPathName(); CString filename=cfd.GetFileName(); CFile thefile; CFileException exc; thefile.Open(filepath,CFile::modeRead,&exc); CArchive archive(&thefile,CArchive::load); int i,j,totnames; CString temp; COLORREF colref; archive>>token >>college; for (i=1;i<ROWS;i++) for(j=0;j<COLS;j++) { archive>>temp; archive>>colref; m_master.SetItemText(i,j,temp); m_master.SetItemBkColour(i,j,colref); } expand.ExpandedNames.RemoveAll(); archive >> totnames; //// total expanded names for(i=0;i<totnames;i++) { archive>>temp;expand.ExpandedNames.Add(temp);} RefreshFormat(); OnToolsRefreshteacherandclasslists(); archive.Close(); thefile.Close(); curpath=filepath; curfilename=filename; CFrameWnd* pfr=GetParentFrame(); pfr->SetWindowText("College Time Table : "+filename); DuplicateData(DataBefore); } RefreshFormat(); } void CCollegeTimeTableView::OnFilenu() { int i,j; for(i=1;i<RO;i++) /// Clean Individual timetable Area for(j=0;j<7;j++) {m_indiv.SetItemText(i,j,""); m_indiv.SetItemBkColour(i,j,WHITE); m_indiv.RedrawCell(i,j); } m_indiv.SetItemText(0,0,""); m_indiv.RedrawCell(0,0); //clean topleft corner for(i=1;i<ROWS;i++) /// Clean Master timetable Area for(j=0;j<7;j++) {m_master.SetItemText(i,j,""); m_master.SetItemBkColour(i,j,WHITE); m_master.RedrawCell(i,j); } curpath=""; curfilename="Untitled"; CFrameWnd* pfr=GetParentFrame(); pfr->SetWindowText("College Time Table : "+curfilename); } void CCollegeTimeTableView::OnSetCollegename() {CCollegeName ccn; ccn.m_collegename=college; if(ccn.DoModal()==IDOK) {college=ccn.m_collegename;} } void CCollegeTimeTableView::OnEditInsertrow() {CCellID cid; cid=m_master.GetFocusCell(); //CString tmp; // tmp.Format("%d",cid.row); //MessageBox(tmp); if(cid.row==-1) return; int i,j; CString tmp; for(i=ROWS-1;i>=cid.row;i--) for(j=0;j<7;j++) { tmp=m_master.GetItemText(i,j); m_master.SetItemText(i+1,j,tmp); m_master.RedrawCell(i+1,j); } for(j=0;j<7;j++) ///make current row empty {m_master.SetItemText(cid.row,j,""); m_master.RedrawCell(cid.row,j); } RefreshFormat(); } void CCollegeTimeTableView::OnEditDeleterow() {CCellID cid; cid=m_master.GetFocusCell(); //CString tmp; // tmp.Format("%d",cid.row); //MessageBox(tmp); if(cid.row==-1) return; int i,j; CString tmp; for(i=cid.row;i<ROWS-1;i++) for(j=0;j<7;j++) { tmp=m_master.GetItemText(i+1,j); m_master.SetItemText(i,j,tmp); m_master.RedrawCell(i,j); } for(j=0;j<7;j++) ///make last row empty {m_master.SetItemText(ROWS-1,j,""); m_master.RedrawCell(ROWS-1-1,j); } RefreshFormat(); } void CCollegeTimeTableView::DuplicateData(CString &Str) /// Backup Master Before or After {CString temp; Str.Empty(); int i,j; for(i=1;i<ROWS;i++) for(j=0;j<COLS;j++) {temp=m_master.GetItemText(i,j); Str+=temp; } //MessageBox(Str); } void CCollegeTimeTableView::OnAppExit() { int ans; DuplicateData(DataAfter); //MessageBox(DataAfter); if(DataBefore!=DataAfter) { ans=MessageBox("Time Table Modified. Save Changes ?","College Time Table",MB_YESNOCANCEL | MB_ICONQUESTION); if(ans==IDNO) goto quit; if(ans==IDCANCEL) return; OnFileSev(); goto quit; ////PostMeExitInstance(); } quit : PostMessage(WM_QUIT); //OnFileExit(); } BOOL CCollegeTimeTableView::PreTranslateMessage(MSG* pMsg) { if (pMsg->message == WM_KEYDOWN && (pMsg->wParam == VK_RETURN)) { //CWnd* pdlg=GetDlgItem(IDC_SEARCHBOX); //pdlg->GetWindowText(m_search); OnGenerate(); return TRUE; } return CFormView::PreTranslateMessage(pMsg); } void CCollegeTimeTableView::DisplayToolTip() { CString m_text=" The Time Table File Has Been Updated "; if (!bToolTip) { unsigned int uid = 0; // for ti initialization // CREATE A TOOLTIP WINDOW hwndTT = CreateWindowEx(WS_EX_TOPMOST, TOOLTIPS_CLASS, NULL, TTS_NOPREFIX | TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL ); // INITIALIZE MEMBERS OF THE TOOLINFO STRUCTURE //changing tool tip font //Great idea and it works. The code is: //CToolTipCtrl tool; //tool.Create(this); //CFont *f = tool.GetFont(); //LOGFONT pLogFont; //f-&gt;GetLogFont(&pLogFont); //m_fontText.CreateFontIndirect(&pLogFont); //Thank you ti.cbSize = sizeof(TOOLINFO); ti.uFlags = TTF_TRACK; ti.hwnd = NULL; ti.hinst = NULL; ti.uId = uid; ti.lpszText = (LPSTR)(LPCSTR) m_text; // ToolTip control will cover the whole window ti.rect.left = 0; ti.rect.top = 0; ti.rect.right = 0; ti.rect.bottom = 0; // SEND AN ADDTOOL MESSAGE TO THE TOOLTIP CONTROL WINDOW ::SendMessage(hwndTT, TTM_ADDTOOL, 0, (LPARAM) (LPTOOLINFO) &ti); ::SendMessage(hwndTT, TTM_TRACKPOSITION, 0, (LPARAM)(DWORD) MAKELONG(cxScr,cyScr)); ::SendMessage(hwndTT, TTM_TRACKACTIVATE, true, (LPARAM)(LPTOOLINFO) &ti); bToolTip=TRUE; } else { ::SendMessage(hwndTT, TTM_TRACKACTIVATE, false, (LPARAM)(LPTOOLINFO) &ti); bToolTip=FALSE; } } void CCollegeTimeTableView::OnTimer(UINT nIDEvent) { if(nIDEvent==1) { DisplayToolTip(); KillTimer(1); } CFormView::OnTimer(nIDEvent); } void CCollegeTimeTableView::OnFilePrintcurrent() {PrintType=3; PostMessage(WM_COMMAND,ID_FILE_PRINT,0); } void CCollegeTimeTableView::OnEditFindandreplace() { CString temp; int totaloccur=0; again : if(FR.DoModal()==IDOK) { if(FR.m_find.IsEmpty() || FR.m_replace.IsEmpty()) { MessageBox("Empty String"); goto again;} totaloccur=FR_WithoutPrompt(FR.m_find,FR.m_replace); } temp.Format("Replaced %d Occurrences",totaloccur); MessageBox(temp); } int CCollegeTimeTableView::FR_WithoutPrompt(CString one,CString two) { int occur; CString temp; int totaloccur=0; int i,j; for(i=1;i<ROWS;i++) for(j=0;j<7;j++) {temp=m_master.GetItemText(i,j); occur=0; occur=temp.Replace(one,two); if(occur) { m_master.SetItemText(i,j,temp); totaloccur+=occur; m_master.RedrawCell(i,j); } } return totaloccur; } void CCollegeTimeTableView::OnEditSwapteachers() { CString temp; CString t1="("; CString t2="("; again: if(SDlg.DoModal()==IDOK) { if(SDlg.m_tea1.IsEmpty() || SDlg.m_tea2.IsEmpty()) { MessageBox("Empty String"); goto again;} t1+=SDlg.m_tea1; t1+=")"; t2+=SDlg.m_tea2; t2+=")"; FR_WithoutPrompt(t1,"@!#@"); FR_WithoutPrompt(t2,t1); FR_WithoutPrompt("@!#@",t2); temp.Format("Swapped %s and %s", SDlg.m_tea1,SDlg.m_tea2); MessageBox(temp); } } void CCollegeTimeTableView::OnEditDisablecell() { CCellID cid=m_master.GetFocusCell(); COLORREF TEMP=m_master.GetItemBkColour(cid.row,cid.col); if(TEMP==YELLOW) TEMP=WHITE; else TEMP=YELLOW; m_master.SetItemBkColour(cid.row,cid.col,TEMP); m_master.RedrawCell(cid.row,cid.col); DisableBlueCells(); } void CCollegeTimeTableView::GetGlobalGapCount() {int i,j; GlobalGapCount=0; GlobalClashCount=0; GlobalDubCount=0; CString temp; Fill_AllIndividuals_in_tcodesArray(); // tcodes array contains all teacher names j=tcodes.GetSize(); for(i=0;i<j;i++) {FastGenerateIndi(i); GlobalGapCount+=gapcount; GlobalClashCount+=clashcount; GlobalDubCount+=dubcount; } //GapString.Format("Gap Count : %d , Continue ?",GlobalGapCount); } void CCollegeTimeTableView::OnToolsDisplaygapreport() { CStringArray GapRecord; int i,j,maxindex; GlobalGapCount=0; CString temp,dispstr; Fill_AllIndividuals_in_tcodesArray(); // tcodes array contains all teacher names j=tcodes.GetSize(); for(i=0;i<j;i++) {FastGenerateIndi(i); temp.Format("[%02d : %s]",gapcount,tcodes[i]); GapRecord.Add(temp); //dispstr+=temp; GlobalGapCount+=gapcount; } ///sort gaprecords maxindex=GapRecord.GetUpperBound(); for(i=0;i<maxindex;i++) for(j=i+1;j<=maxindex;j++) if(GapRecord[i]>GapRecord[j]) {temp=GapRecord[i]; GapRecord[i]=GapRecord[j]; GapRecord[j]=temp; } for(i=0;i<=maxindex;i++) {dispstr+=GapRecord[i];if((i+1)%10==0) dispstr+="\n";} temp.Format("\n\nGlobal Gap Count : %d",GlobalGapCount); dispstr+=temp; MessageBox(dispstr); } int CCollegeTimeTableView::CreateClashReport() {int i,j; GlobalClashCount=0; CString temp; ClashString.Empty(); Fill_AllIndividuals_in_tcodesArray(); // tcodes array contains all teacher names j=tcodes.GetSize(); for(i=0;i<j;i++) {FastGenerateIndi(i); if(clashcount==0) continue; temp.Format("[%02d : %s]",clashcount,tcodes[i]); ClashString+=temp; GlobalClashCount+=clashcount; if((i+1)%10==0) ClashString+="\n"; } temp.Format("\n\nGlobal Clash Count : %d",GlobalClashCount); ClashString+=temp; return GlobalClashCount; } void CCollegeTimeTableView::OnToolsDisplayclashreport() {CreateClashReport(); MessageBox(ClashString); } void CCollegeTimeTableView::OnEditDisablemultiplecells() { mdd.m_freezmsg="Enter String to Freeze Multiple Cells"; if(mdd.DoModal()!=IDOK) return; int i,j; CString temp; if(mdd.m_mdstring.IsEmpty()) return; for(i=1;i<ROWS;i++) for(j=0;j<COLS;j++) {temp=m_master.GetItemText(i,j); if(temp.IsEmpty()) continue; if(temp.Find(mdd.m_mdstring)!=-1) ///string found, make YELLOW { m_master.SetItemBkColour(i,j,YELLOW);m_master.RedrawCell(i,j);} } //RefreshFormat(); } void CCollegeTimeTableView::OnEditEnableallcells() {int i,j; COLORREF tempcolour; for(i=1;i<ROWS;i++) for(j=0;j<COLS;j++) { tempcolour=m_master.GetItemBkColour(i,j); if(tempcolour==YELLOW) {m_master.SetItemBkColour(i,j,WHITE); m_master.RedrawCell(i,j); } } } void CCollegeTimeTableView::DisableBlueCells() { int i,j; COLORREF tempcolour; UINT cellstate; for(i=1;i<ROWS;i++) for(j=0;j<COLS;j++) { cellstate=m_master.GetItemState(i,j); if(cellstate==GVNI_SELECTED || cellstate==GVIS_DROPHILITED) { tempcolour=m_master.GetItemBkColour(i,j); if(tempcolour==YELLOW) m_master.SetItemBkColour(i,j,WHITE); else m_master.SetItemBkColour(i,j,YELLOW); m_master.SetItemState(i,j,0); m_master.RedrawCell(i,j); } } } void CCollegeTimeTableView::DoPaginationForIndi(CDC* pDC, CPrintInfo* pInfo) { int test; CString temp,temp1; pInfo->SetMinPage(1); int i,j,k,l,height,lastindex,lastime,LineCounter; ClassOrIndPageArray.RemoveAll(); ////// Reset Page Description Array CPrintPage tempage; ///// To add empty object ClassOrIndPageArray.Add(tempage); /// now PageIndex is 0 (for first page) int PageIndex=0; Fill_AllIndividuals_in_tcodesArray(); // tcodes array contains all teacher names ///start pagination for individual printouts k=tcodes.GetSize(); LineCounter=0; ///initialize line count, it should be maximum but < LinesPerPage for(i=0;i<k;i++) { GenerateIndividual(tcodes[i]); for(lastindex=RO-1;lastindex>0;lastindex--) {temp=m_indiv.GetItemText(lastindex,1); if(temp.IsEmpty()) continue; else break; } if(lastindex<=0) continue; /////Empty Indi !!!! ///find last time cell for(lastime=RO-1;lastime>0;lastime--) {temp=m_indiv.GetItemText(lastindex,0); if(temp.IsEmpty()) continue; else break; } for(j=lastime;j>0;j--) for(l=1;l<7;l++) { temp=m_indiv.GetItemText(j,l); if(!temp.IsEmpty()) goto stop;} stop : lastindex=lastindex - lastime + j; height=lastindex+1; ///seperation, recess, title-SIWS, Weekday line //{ // CString tmp; // tmp.Format("%d",height); // MessageBox(tmp); // } test=LineCounter+height; //pop(test); if(test<LinesPerPage) {LineCounter+=height; /// this individual time table fits in page //pop(LineCounter); //pop(LinesPerPage); ClassOrIndPageArray[PageIndex].Codes.Add(tcodes[i]); LineCounter++; continue; ///Add line before next indi & go for more indi's } /// otherwise Page is Full, go for next page ClassOrIndPageArray.Add(tempage);///Create Empty Page Struct PageIndex++; ClassOrIndPageArray[PageIndex].Codes.Add(tcodes[i]); ///Add indi to next page LineCounter=height; /// Set Line Counter for the next page ////loop ends...go for more individuals... top of loop } pInfo->SetMaxPage(PageIndex+1); /// set maximum page count } void CCollegeTimeTableView::OnToolsTimetablewizard() { CString temp; int times,classes,i,j,rowcounter=1; if(wiz.DoModal()==IDOK) { times=wiz.timeslots.GetSize(); classes=wiz.classslots.GetSize(); for(i=0;i<times;i++) { m_master.SetItemText(rowcounter,0,wiz.timeslots[i]); m_master.SetItemBkColour(rowcounter,0,GREEN); m_master.RedrawCell(rowcounter,0); rowcounter++; for(j=0;j<classes;j++) {m_master.SetItemText(rowcounter,0,wiz.classslots[j]); m_master.RedrawCell(rowcounter,0); rowcounter++; } rowcounter++; ///sepearation by an empty row } } } void CCollegeTimeTableView::OnToolsTimetablewizardstepII() {int i,j,lecturecounter; CString tempclass,tempentry; while(wiz2.DoModal()==IDOK) ///Keep allocating lectures {lecturecounter=wiz2.m_noflectures; for(i=2;i<ROWS;i++) {if(lecturecounter<=0) break; tempclass=m_master.GetItemText(i,0); if(tempclass==wiz2.m_curclass) for(j=1;j<7;j++) { if(lecturecounter<=0) break; tempentry=m_master.GetItemText(i,j); if(tempentry.IsEmpty()) { m_master.SetItemText(i,j,wiz2.m_sub_tr); m_master.RedrawCell(i,j); lecturecounter--; } } } } } void CCollegeTimeTableView::OnSetFullnames() { if(expand.ExpandedNames.GetSize()<=0) { int i, tcodesize; Fill_AllIndividuals_in_tcodesArray(); tcodesize=tcodes.GetSize(); if(tcodesize>0) for(i=0;i<tcodesize;i++) expand.ExpandedNames.Add(tcodes[i]); else expand.ExpandedNames.Add(""); } expand.DoModal(); } void CCollegeTimeTableView::OnEditDefreezeOnString() { mdd.m_freezmsg="Enter String to DeFreeze Multiple Cells"; if(mdd.DoModal()!=IDOK) return; int i,j; CString temp; if(mdd.m_mdstring.IsEmpty()) return; for(i=1;i<ROWS;i++) for(j=0;j<COLS;j++) {temp=m_master.GetItemText(i,j); if(temp.IsEmpty()) continue; if(temp.Find(mdd.m_mdstring)!=-1) ///string found, make YELLOW { m_master.SetItemBkColour(i,j,WHITE); m_master.RedrawCell(i,j);} } } void CCollegeTimeTableView::OnEditSelectOnGivenString() {mdd.m_freezmsg="Enter String to Select Multiple Cells"; if(mdd.DoModal()!=IDOK) return; int i,j; CString temp; if(mdd.m_mdstring.IsEmpty()) return; for(i=1;i<ROWS;i++) for(j=0;j<COLS;j++) {temp=m_master.GetItemText(i,j); if(temp.IsEmpty()) continue; if(temp.Find(mdd.m_mdstring)!=-1) ///string found, make YELLOW {m_master.SetItemState(i,j,GVIS_SELECTED); m_master.RedrawCell(i,j);} } } void CCollegeTimeTableView::OnToolsDisplaynextindividual() { if(DispIndexIndi>tcodes.GetUpperBound()) DispIndexIndi=0; GenerateIndividual(tcodes[DispIndexIndi]); m_search=tcodes[DispIndexIndi]; UpdateData(FALSE); DispIndexIndi++; } void CCollegeTimeTableView::OnToolsDisplayprevindividual() { if(DispIndexIndi<0) DispIndexIndi=tcodes.GetUpperBound(); GenerateIndividual(tcodes[DispIndexIndi]); m_search=tcodes[DispIndexIndi]; UpdateData(FALSE); DispIndexIndi--; } void CCollegeTimeTableView::OnToolsRefreshteacherandclasslists() { Fill_AllIndividuals_in_tcodesArray(); Fill_AllClassesArray(); DispIndexIndi=DispIndexClas=0; } void CCollegeTimeTableView::OnToolsDisplaynextclass() { if(DispIndexClas>AllClasses.GetUpperBound()) DispIndexClas=0; GenerateClass(AllClasses[DispIndexClas]); m_search=AllClasses[DispIndexClas]; UpdateData(FALSE); DispIndexClas++; } void CCollegeTimeTableView::OnToolsDisplayprevclass() { if(DispIndexClas<0) DispIndexClas=AllClasses.GetUpperBound(); GenerateClass(AllClasses[DispIndexClas]); m_search=AllClasses[DispIndexClas]; UpdateData(FALSE); DispIndexClas--; } void CCollegeTimeTableView::Fill_AllClassesArray() {int i,j,k; AllClasses.RemoveAll(); CString temp; BOOL found; for(i=1;i<ROWS;i++) /// All classes are in the first column of the master {temp=m_master.GetItemText(i,0); if(temp.IsEmpty()) continue; /// skip empty cells if(temp[0]>='0' && temp[0]<='9') continue; /// and also skip time cells k=AllClasses.GetSize(); if(k==0) {AllClasses.Add(temp);continue;} ///initial entry found=FALSE; for(j=0;j<k;j++) if(temp==AllClasses[j]) {found=TRUE; break;} ///// if no duplicate class found then add if(!found) AllClasses.Add(temp); } int II=AllClasses.GetSize(); for(j=1;j<II;j++) for(i=0;i<j;i++) if(AllClasses[i]>AllClasses[j]) {temp=AllClasses[i];AllClasses[i]=AllClasses[j];AllClasses[j]=temp;} } void CCollegeTimeTableView::FastGenerateIndi(int ti) /// teacher index in tcodes two letter Tr code { if(tcodes[ti].IsEmpty()) return; int i,j,k,lastidx,syze; clashcount=0; gapcount=0; dubcount=0; CString temp,temp2,temp3="("+tcodes[ti]+")",temp4,temptime,tempclash; CString timearr[RO]; //Max RO lectures per day for an individual, index 1 to RO-1 CStringArray entry; CUIntArray count; int TotalLectures=0; ///Workload, 0 in the beginning for(i=1;i<RO;i++) /// Clean Individual timetable Area for(j=0;j<7;j++) {IArr[ti][i][j]=""; //m_indiv.SetItemBkColour(i,j,WHITE); //m_indiv.RedrawCell(i,j); } IArr[ti][0][0]=""; //clean topleft corner lastidx=1; for(i=1;i<ROWS;i++) ///Collect All Lecture Timings i.e all numerics in col 0 {temp=m_master.GetItemText(i,0); if(temp.IsEmpty()) continue; if(temp[0]>='0' && temp[0]<='9') { timearr[lastidx]=temp; if(j<RO-1) lastidx++; else break;} } /// timearr contains all lecture timings if(lastidx+1<RO) lastidx+=1; for(i=1;i<=lastidx;i++) IArr[ti][i][0]=timearr[i]; int rowindex=0; for(i=1;i<ROWS;i++) for(j=1;j<COLS;j++) {temp=m_master.GetItemText(i,j); if(temp.IsEmpty()) continue; k=temp.Find(temp3); ///find (tcode) , teachercode encluding brackets if(temp.Find("//")!=-1) { temptime=PickLectureTime(i); for(rowindex=1;rowindex<RO;rowindex++) if(timearr[rowindex]==temptime) { IArr[ti][rowindex][3]="RECESS"; break; } } if(k!=-1) /// if (tcode) found { temptime=PickLectureTime(i); for(rowindex=1;rowindex<RO;rowindex++) if(timearr[rowindex]==temptime) { temp4=IArr[ti][rowindex][j]; temp2=m_master.GetItemText(i,0); // get class temp2+="-"+temp.Mid(k-3,3); //attach subject if(temp4.IsEmpty()) ///cell empty so no clash IArr[ti][rowindex][j]=temp2; else //clash occurs {temp4+=","; temp4+=temp2; IArr[ti][rowindex][j]=temp4; //m_indiv.SetItemText(rowindex,j,temp4); //m_indiv.SetItemBkColour(rowindex,j,RED);//red clashcount++; } //m_indiv.RedrawCell(rowindex,j); //refresh class entry /// now add this entry to splitting chart //// i.e lecture entry & corresponding count syze=entry.GetSize(); if(syze==-1) { entry.Add(temp2); count.Add(1); ///this is first entry TotalLectures++; continue; } BOOL found=FALSE; // Set found=false for(int k=0;k<syze;k++) if(entry[k]==temp2) { count[k]++; found=TRUE; TotalLectures++;break; } //if entry already there count++ ////otherwise add entry and set count=1 for it if(!found) {entry.Add(temp2);count.Add(1);TotalLectures++;} } } } FastSetGapAndDoubleCount(lastidx,ti); } void CCollegeTimeTableView::FastSetGapAndDoubleCount(int lasttimerow,int ti) {int i,j,k; int first,last; gapcount=0;dubcount=0; CString temp,temp1; for(j=1;j<7;j++) ////through all six colums { first=last=0; for(i=1;i<=lasttimerow;i++) ///first nonempty row index; {//temp=m_indiv.GetItemText(i,j); temp=IArr[ti][i][j]; if(temp.IsEmpty() || temp=="RECESS") continue; else {first=i;break;} } for(i=lasttimerow;i>0;i--) ///last non-empty row index {//temp=m_indiv.GetItemText(i,j); temp=IArr[ti][i][j]; if(temp.IsEmpty() || temp=="RECESS") continue; else {last=i; break;} } if(first==0) continue; ////last has to be zero ////now count gaps and also count double lectures for(i=first;i<=last;i++) {//temp=m_indiv.GetItemText(i,j); temp=IArr[ti][i][j]; if(temp.IsEmpty() || temp=="RECESS") {gapcount++;continue;} for(k=i+1;k<=last;k++) {//temp1=m_indiv.GetItemText(k,j); temp1=IArr[ti][k][j]; if(temp==temp1) dubcount++; } } } } void CCollegeTimeTableView::FastShow(int ti) {int j; FastGenerateIndi(ti); /// two letter Tr code for(int i=0;i<RO;i++) for(j=0;j<COLS;j++) {m_indiv.SetItemText(i,j,IArr[ti][i][j]); m_indiv.RedrawCell(i,j); } } void CCollegeTimeTableView::OnToolsAutoreducegaps() {int i,j,lastnonemtpyrow; CString temp; lastnonemtpyrow=2; for(i=ROWS;i>=2;i--) ///Get last non empty row {temp=m_master.GetItemText(i,0); if(temp.IsEmpty()) continue; else break; } lastnonemtpyrow=i; //pop(lastnonemtpyrow); //pop(lastnonemtpyrow); BOOL bEND=FALSE; Again: cellcount=(lastnonemtpyrow-1)*6; bEND=FALSE; //pop(cellcount); CFrameWnd * pFrame = (CFrameWnd *)(AfxGetApp()->m_pMainWnd); COLORREF tempcolour; for(i=2;i<=lastnonemtpyrow;i++) { for(j=1;j<COLS;j++) { cellcount--; temp.Format("Global Clash Count : %d Global Double Count : %d Global Gap Count : %d [Remaining Cells : %04d] - Press ESC To Stop",GlobalClashCount,GlobalDubCount,GlobalGapCount,cellcount); pFrame->SetMessageText(temp); tempcolour=m_master.GetItemBkColour(i,j); if(tempcolour==YELLOW) continue; temp=m_master.GetItemText(i,j); if(temp.IsEmpty()) continue; ReduceGapForCell(i,j); } GetGlobalGapCount(); CreateClashReport(); if(cont.DoModal()!=IDOK) { bEND=TRUE; break;} } RefreshFormat(); if(bEND) return; else goto Again; } void CCollegeTimeTableView::ReduceGapForCell(int Ox,int Oy) { COLORREF tempcolour; CString Entry1,Entry2,X,Y,sourceClass,currentClass,temp; int i,j,SgcBefore,SccBefore,TgcBefore,TccBefore,SccAfter,SgcAfter,SdcBefore,SdcAfter,TdcBefore; int TgcAfter,TccAfter,TdcAfter; //int currentR=11,currentC=1; Entry1=m_master.GetItemText(Ox,Oy); if(Entry1.IsEmpty()) return; sourceClass=m_master.GetItemText(Ox,0); ////get class to ensure class exchange only if(sourceClass.IsEmpty()) return; CFrameWnd * pFrame = (CFrameWnd *)(AfxGetApp()->m_pMainWnd); SgcBefore=SccBefore=SdcBefore=0; temp=Entry1; while((X=PickTeacherCode2(temp))!="") ////consume all parallel tr codes { tcodes[0]=X; FastGenerateIndi(0); SgcBefore+=gapcount; /// if(X.GetLength()!=2) return; SccBefore+=clashcount; SdcBefore+=dubcount; } //MessageBox(X); for(i=2;i<ROWS;i++) for(j=1;j<COLS;j++) { tempcolour=m_master.GetItemBkColour(i,j); if(tempcolour==YELLOW) continue; currentClass=m_master.GetItemText(i,0); if(currentClass!=sourceClass) continue; ///class mismatch ! cannot exchange Entry2=m_master.GetItemText(i,j); if(Entry2.IsEmpty()) continue; TgcBefore=TccBefore=TdcBefore=0; temp=Entry2; while((Y=PickTeacherCode2(temp))!="") { tcodes[0]=Y; FastGenerateIndi(0); TgcBefore+=gapcount; TccBefore+=clashcount; TdcBefore+=dubcount; } /////Now Exchange Cells m_master.SetItemText(Ox,Oy,Entry2); m_master.SetItemText(i,j,Entry1); temp=Entry1; SgcAfter=SccAfter=SdcAfter=0; while((X=PickTeacherCode2(temp))!="") { tcodes[0]=X; FastGenerateIndi(0); SgcAfter+=gapcount; /// if(X.GetLength()!=2) return; SccAfter+=clashcount; SdcAfter+=dubcount; } temp=Entry2; TgcAfter=TccAfter=TdcAfter=0; while((Y=PickTeacherCode2(temp))!="") {tcodes[0]=Y; FastGenerateIndi(0); TgcAfter+=gapcount; TccAfter+=clashcount; TdcAfter+=dubcount; } if(SccAfter+TccAfter<SccBefore+TccBefore) goto NoRestore; ///clash decreased if(SccAfter+TccAfter>SccBefore+TccBefore) goto RestoreChange; ///clash increased if(SdcAfter+TdcAfter<SdcBefore+TdcBefore) goto NoRestore; if(SdcAfter+TdcAfter>SdcBefore+TdcBefore) goto RestoreChange; ///double increased if(SgcAfter+TgcAfter>SgcBefore+TgcBefore) goto RestoreChange; /// gap increased // ////No restore i.e changes conformed, /// Now pick changed cell content from (ox,oy) to exchange with all one by one NoRestore: GetGlobalGapCount(); //CreateClashReport(); //temp.Format("Global Clash Count : %d Global Double Count : %d Global Gap Count : %d [Remaining Cells : %d]",GlobalClashCount,GlobalDubCount,GlobalGapCount,cellcount); //pFrame->SetMessageText(temp); Entry1=m_master.GetItemText(Ox,Oy); if(Entry1.IsEmpty()) return; sourceClass=m_master.GetItemText(Ox,0); ////get class to ensure class exchange only SgcBefore=SccBefore=SdcBefore=0; temp=Entry1; while((X=PickTeacherCode2(temp))!="") { tcodes[0]=X; FastGenerateIndi(0); SgcBefore+=gapcount; /// if(X.GetLength()!=2) return; SccBefore+=clashcount; SdcBefore+=dubcount; } continue; RestoreChange: m_master.SetItemText(Ox,Oy,Entry1); m_master.SetItemText(i,j,Entry2); } } void CCollegeTimeTableView::OnToolsShowallcounts() {CString temp; GetGlobalGapCount(); CFrameWnd * pFrame = (CFrameWnd *)(AfxGetApp()->m_pMainWnd); temp.Format("Global Clash Count : %d Global Double Count : %d Global Gap Count : %d",GlobalClashCount,GlobalDubCount,GlobalGapCount); pFrame->SetMessageText(temp); } void CCollegeTimeTableView::OnHelpHowtousetimetable() { CHelpSheet propSheet("College Time Table Help", this, 0); propSheet.m_psh.dwFlags |= PSH_NOAPPLYNOW; //// remove apply button int result = propSheet.DoModal(); } void CCollegeTimeTableView::OnHelpLoadsampetimetable() { OnFilenu(); CString Load[36][7]={ {"12:30-01:10"}, {"FY-A","ENG(MN)","ECO(CD)","SEP(AB)","SEP(AB)","ECO(CD)","SEP(AB)"}, {"FY-B","ACS(EF)","MAR(IJ),HIN(KL)","MAR(IJ),HIN(KL)","ORC(GH)","SEP(AB)","MAR(IJ),HIN(KL)"}, {"SY-A","ORC(GH)","ACS(EF)","ACS(EF)","ECO(CD)","ACS(EF)","ACS(EF)"}, {"SY-B","SEP(AB)","ENG(MN)","ORC(GH)","ENG(MN)","ORC(GH)","ORC(GH)"}, {""}, {"01:10-01:50"}, {"FY-A","MAR(IJ),HIN(KL)","ECO(CD)","MAR(IJ),HIN(KL)","ENG(MN)","ENG(MN)","MAR(IJ),HIN(KL)"}, {"FY-B","SEP(AB)","ACS(EF)","SEP(AB)","SEP(AB)","ACS(EF)","ACS(EF)"}, {"SY-A","ACS(EF)","ENG(MN)","ORC(GH)","ORC(GH)","ORC(GH)","ORC(GH)"}, {"SY-B","ORC(GH)","MAR(IJ),HIN(KL)","ECO(CD)","ECO(CD)","SEP(AB)","SEP(AB)"}, {""}, {"01:50-02:30"}, {"FY-A","ECO(CD)","ACS(EF)","ORC(GH)","ORC(GH)","MAR(IJ),HIN(KL)","ORC(GH)"}, {"FY-B","ENG(MN)","ECO(CD)","ECO(CD)","MAR(IJ),HIN(KL)","ORC(GH)","ENG(MN)"}, {"SY-A","SEP(AB)","ORC(GH)","ENG(MN)","ENG(MN)","SEP(AB)","MAR(IJ),HIN(KL)"}, {"SY-B","MAR(IJ),HIN(KL)","SEP(AB)","SEP(AB)","SEP(AB)","ACS(EF)","ACS(EF)"}, {""}, {"03:00-03:40"}, {"FY-A","ORC(GH)","MAR(IJ),HIN(KL)","MAR(IJ),HIN(KL)","ACS(EF)","ORC(GH)","ACS(EF)"}, {"FY-B","MAR(IJ),HIN(KL)","ACS(EF)","ACS(EF)","ENG(MN)","MAR(IJ),HIN(KL)","ECO(CD)"}, {"SY-A","ENG(MN)","SEP(AB)","SEP(AB)","ECO(CD)","ECO(CD)","SEP(AB)"}, {"SY-B","ECO(CD)","ORC(GH)","ENG(MN)","ORC(GH)","ENG(MN)","ENG(MN)"}, {""}, {"03:40-04:20"}, {"FY-A","SEP(AB)","ORC(GH)","ACS(EF)","ENG(MN)","SEP(AB)","ENG(MN)"}, {"FY-B","ECO(CD)","SEP(AB)","ORC(GH)","ECO(CD)","ECO(CD)","SEP(AB)"}, {"SY-A","MAR(IJ),HIN(KL)","ECO(CD)","ECO(CD)","ACS(EF)","ENG(MN)","ECO(CD)"}, {"SY-B","ACS(EF)","ACS(EF)","MAR(IJ),HIN(KL)","MAR(IJ),HIN(KL)","MAR(IJ),HIN(KL)","MAR(IJ),HIN(KL)"}, {""}, {"04:20-05:00"} , {"FY-A","ACS(EF)","ENG(MN)","ECO(CD)","ECO(CD)","ACS(EF)","SEP(AB)"}, {"FY-B","ORC(GH)","ORC(GH)","ENG(MN)","ENG(MN)","ENG(MN)","ORC(GH)"}, {"SY-A","SEP(AB)","MAR(IJ),HIN(KL)","MAR(IJ),HIN(KL)","MAR(IJ),HIN(KL)","MAR(IJ),HIN(KL)","ENG(MN)"}, {"SY-B","ENG(MN)","ECO(CD)","ACS(EF)","ACS(EF)","ECO(CD)","ECO(CD)"}, {""}, }; for (int i=1;i<=36;i++) for(int j=0;j<=7;j++) m_master.SetItemText(i,j,Load[i-1][j]); RefreshFormat(); }
[ "oak445@gmail.com" ]
oak445@gmail.com