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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ed75dc7f0e2c3b8a28429497c8f9d3f0f18deb06 | 076d02e99d65c64b2fd32006e964471ae1982bf0 | /logger.hpp | c698b17d7dca1588a84dbc5c9418c86b0595277b | [
"WTFPL"
] | permissive | pingwindyktator/cpp_sandbox | bd1690231458fe1961adb8b615a9444c18bece21 | 815a80f826aa0ea718389ebda0f8e6513a051de1 | refs/heads/master | 2021-04-29T22:25:16.371297 | 2018-07-29T14:20:22 | 2018-07-29T14:20:22 | 121,636,345 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,373 | hpp | #pragma once
#include "macroOverloading.hpp"
#include <iomanip>
#include <iostream>
#include <sstream>
namespace sandbox {
namespace details {
template <class CharT, class Traits>
class logger_helper : boost::noncopyable
{
public:
using os_t = std::basic_ostream<CharT, Traits>;
using ss_t = std::basic_stringstream<CharT, Traits>;
logger_helper(os_t& os)
: os(os)
{
}
~logger_helper()
{
os << get_ss().rdbuf() << '\n';
os.flush();
}
ss_t& get_ss() const { return ss; }
private:
mutable ss_t ss{};
os_t& os;
};
template <class CharT, class Traits>
std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const logger_helper<CharT, Traits>& helper)
{
return helper.get_ss();
}
}
}
// clang-format off
#define LOG(...) VFUNC(LOG, __VA_ARGS__)
#define LOG1(os) os << sandbox::details::logger_helper<decltype(os)::char_type, decltype(os)::traits_type>{os} \
<< '[' << std::setw(12) << std::left << sandbox::get_current_datetime_str() << ']' \
<< '[' << __FILENAME__ << ":" << std::setw(3) << std::left << __LINE__ << ']' \
<< '[' << __FUNC_NAME__ << "]\t"
#define LOG0() LOG1(std::cout)
#define BARK() { LOG(); }
// clang-format on
| [
"ja2222ja@gmail.com"
] | ja2222ja@gmail.com |
f400952dc8eb5d10f339fe4ef4e7b4d5bd021508 | 89273186f1772c05fc716125e9a4e96e42507d1d | /DWDM/dectree.cpp | 89f74691e9d4b56217507eb622b273364c59a2b6 | [] | no_license | Avi-ab007/Semester | 10aa5e4f60280598ddcccb4d9a17237f2c4ca778 | 289eed63367b6da6919c7fa396efb389d6012dbc | refs/heads/master | 2020-03-12T11:14:51.418401 | 2019-04-02T15:54:39 | 2019-04-02T15:54:39 | 130,591,866 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,058 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <map>
#include <math.h>
#include <float.h>
#include <cstdlib>
#include <iomanip>
using namespace std;
typedef vector<string> vs;
typedef vector<vs> vvs;
typedef vector<int> vi;
typedef map<string, int> msi;
typedef vector<double> vd;
struct node // struct node defines the structure of a node of the decision tree
{
string splitOn; // Stores which attribute to split on at a particular node
string label; // Stores the class label for leaf nodes. For nodes that are not leaf nodes, it stores the value of the attribute of the parent's' split
bool isLeaf; // boolean flag for leaf nodes
vector<string> childrenValues; // Stores the values of the childrens' attributes
vector<node*> children; // Stores pointers to the children of a node
};
void parse(string&, vvs&); // Parses a single line from the input file and stores the information into a vector of vector of strings
void printAttributeTable(vvs&); // For debugging purposes only. Prints a data table
vvs pruneTable(vvs&, string&, string); // Prunes a table based on a column/attribute's name and the value of that attribute. Removes that column and all instances that have that value for that column
node* buildDecisionTree(vvs&, node*, vvs&); // Builds the decision tree based on the table it is passed
bool isHomogeneous(vvs&); // Returns true if all instances in a subtable at a node have the same class label
vi countDistinct(vvs&, int); // Returns a vector of integers containing the counts of all the various values of an attribute/column
string decideSplittingColumn(vvs&); // Returns the column on which to split on. Decision of column is based on entropy
int returnColumnIndex(string&, vvs&); // Returns the index of a column in a subtable
bool tableIsEmpty(vvs&); // Returns true if a subtable is empty
void printDecisionTree(node*); // For degubbing purposes only. Recursively prints decision tree
string testDataOnDecisionTree(vs&, node*, vvs&, string); // Runs a single instance of the test data through the decision tree. Returns the predicted class label
int returnIndexOfVector(vs&, string); // Returns the index of a string in a vector of strings
double printPredictionsAndCalculateAccuracy(vs&, vs&); // Outputs the predictions to file and returns the accuracy of the classification
vvs generateTableInfo(vvs &dataTable); // Generates information about the table in a vector of vector of stings
string returnMostFrequentClass(vvs &dataTable); // Returns the most frequent class from the training data. This class is used as the default class during the testing phase
void parse(string& someString, vvs &attributeTable)
{
int attributeCount = 0;
vs vectorOfStrings;
while (someString.length() != 0 && someString.find(',') != string::npos)
{
size_t pos;
string singleAttribute;
pos = someString.find_first_of(',');
singleAttribute = someString.substr(0, pos);
vectorOfStrings.push_back(singleAttribute);
someString.erase(0, pos+1);
}
vectorOfStrings.push_back(someString);
attributeTable.push_back(vectorOfStrings);
vectorOfStrings.clear();
}
/*
* Prints a vector of vector of strings
* For debugging purposes only.
*/
void printAttributeTable(vvs &attributeTable)
{
int inner, outer;
for (outer = 0; outer < attributeTable.size(); outer++) {
for (inner = 0; inner < attributeTable[outer].size(); inner++) {
cout << attributeTable[outer][inner] << "\t";
}
cout << endl;
}
}
/*
* Prunes a table based on a column/attribute's name
* and value of that attribute. Removes that column
* and all rows that have that value for that column.
*/
vvs pruneTable(vvs &attributeTable, string &colName, string value)
{
int iii, jjj;
vvs prunedTable;
int column = -1;
vs headerRow;
for (iii = 0; iii < attributeTable[0].size(); iii++) {
if (attributeTable[0][iii] == colName) {
column = iii;
break;
}
}
for (iii = 0; iii < attributeTable[0].size(); iii++) {
if (iii != column) {
headerRow.push_back(attributeTable[0][iii]);
}
}
prunedTable.push_back(headerRow);
for (iii = 0; iii < attributeTable.size(); iii++) {
vs auxRow;
if (attributeTable[iii][column] == value) {
for (jjj = 0; jjj < attributeTable[iii].size(); jjj++) {
if(jjj != column) {
auxRow.push_back(attributeTable[iii][jjj]);
}
}
prunedTable.push_back(auxRow);
}
}
return prunedTable;
}
/*
* Recursively builds the decision tree based on
* the data that it is passed and tha table info.
*/
node* buildDecisionTree(vvs &table, node* nodePtr, vvs &tableInfo)
{
if (tableIsEmpty(table)) {
return NULL;
}
if (isHomogeneous(table)) {
nodePtr->isLeaf = true;
nodePtr->label = table[1][table[1].size()-1];
return nodePtr;
} else {
string splittingCol = decideSplittingColumn(table);
nodePtr->splitOn = splittingCol;
int colIndex = returnColumnIndex(splittingCol, tableInfo);
int iii;
for (iii = 1; iii < tableInfo[colIndex].size(); iii++) {
node* newNode = (node*) new node;
newNode->label = tableInfo[colIndex][iii];
nodePtr->childrenValues.push_back(tableInfo[colIndex][iii]);
newNode->isLeaf = false;
newNode->splitOn = splittingCol;
vvs auxTable = pruneTable(table, splittingCol, tableInfo[colIndex][iii]);
nodePtr->children.push_back(buildDecisionTree(auxTable, newNode, tableInfo));
}
}
return nodePtr;
}
/*
* Returns true if all rows in a subtable
* have the same class label.
* This means that that node's class label
* has been decided.
*/
bool isHomogeneous(vvs &table)
{
int iii;
int lastCol = table[0].size() - 1;
string firstValue = table[1][lastCol];
for (iii = 1; iii < table.size(); iii++) {
if (firstValue != table[iii][lastCol]) {
return false;
}
}
return true;
}
/*
* Returns a vector of integers containing the counts
* of all the various values of an attribute/column.
*/
vi countDistinct(vvs &table, int column)
{
vs vectorOfStrings;
vi counts;
bool found = false;
int foundIndex;
for (int iii = 1; iii < table.size(); iii++) {
for (int jjj = 0; jjj < vectorOfStrings.size(); jjj++) {
if (vectorOfStrings[jjj] == table[iii][column]) {
found = true;
foundIndex = jjj;
break;
} else {
found = false;
}
}
if (!found) {
counts.push_back(1);
vectorOfStrings.push_back(table[iii][column]);
} else {
counts[foundIndex]++;
}
}
int sum = 0;
for (int iii = 0; iii < counts.size(); iii++) {
sum += counts[iii];
}
counts.push_back(sum);
return counts;
}
/*
* Decides which column to split on
* based on entropy. Returns the column
* with the least entropy.
*/
string decideSplittingColumn(vvs &table)
{
int column, iii;
double minEntropy = DBL_MAX;
int splittingColumn = 0;
vi entropies;
for (column = 0; column < table[0].size() - 1; column++) {
string colName = table[0][column];
msi tempMap;
vi counts = countDistinct(table, column);
vd attributeEntropy;
double columnEntropy = 0.0;
for (iii = 1; iii < table.size()-1; iii++) {
double entropy = 0.0;
if (tempMap.find(table[iii][column]) != tempMap.end()) { // IF ATTRIBUTE IS ALREADY FOUND IN A COLUMN, UPDATE IT'S FREQUENCY
tempMap[table[iii][column]]++;
} else { // IF ATTRIBUTE IS FOUND FOR THE FIRST TIME IN A COLUMN, THEN PROCESS IT AND CALCULATE IT'S ENTROPY
tempMap[table[iii][column]] = 1;
vvs tempTable = pruneTable(table, colName, table[iii][column]);
vi classCounts = countDistinct(tempTable, tempTable[0].size()-1);
int jjj, kkk;
for (jjj = 0; jjj < classCounts.size(); jjj++) {
double temp = (double) classCounts[jjj];
entropy -= (temp/classCounts[classCounts.size()-1])*(log(temp/classCounts[classCounts.size()-1]) / log(2));
}
attributeEntropy.push_back(entropy);
entropy = 0.0;
}
}
for (iii = 0; iii < counts.size() - 1; iii++) {
columnEntropy += ((double) counts[iii] * (double) attributeEntropy[iii]);
}
columnEntropy = columnEntropy / ((double) counts[counts.size() - 1]);
if (columnEntropy <= minEntropy) {
minEntropy = columnEntropy;
splittingColumn = column;
}
}
return table[0][splittingColumn];
}
/*
* Returns an integer which is the
* index of a column passed as a string
*/
int returnColumnIndex(string &columnName, vvs &tableInfo)
{
int iii;
for (iii = 0; iii < tableInfo.size(); iii++) {
if (tableInfo[iii][0] == columnName) {
return iii;
}
}
return -1;
}
/*
* Returns true if the table is empty
* returns false otherwise
*/
bool tableIsEmpty(vvs &table)
{
return (table.size() == 1);
}
/*
* Recursively prints the decision tree
* For debugging purposes only
*/
void printDecisionTree(node* nodePtr)
{
if(nodePtr == NULL) {
return;
}
if (!nodePtr->children.empty()) {
cout << " Value: " << nodePtr->label << endl;
cout << "Split on: " << nodePtr->splitOn;
int iii;
for (iii = 0; iii < nodePtr->children.size(); iii++) {
cout << "\t";
printDecisionTree(nodePtr->children[iii]);
}
return;
} else {
cout << "Predicted class = " << nodePtr->label;
return;
}
}
/*
* Takes a row and traverses that row through
* the decision tree to find out the
* predicted class label. If none is found
* returns the default class label which is
* the class label with the highest frequency.
*/
string testDataOnDecisionTree(vs &singleLine, node* nodePtr, vvs &tableInfo, string defaultClass)
{
string prediction;
while (!nodePtr->isLeaf && !nodePtr->children.empty()) {
int index = returnColumnIndex(nodePtr->splitOn, tableInfo);
string value = singleLine[index];
int childIndex = returnIndexOfVector(nodePtr->childrenValues, value);
nodePtr = nodePtr->children[childIndex];
if (nodePtr == NULL) {
prediction = defaultClass;
break;
}
prediction = nodePtr->label;
}
return prediction;
}
/*
* Returns an integer which is the index
* of a string in a vector of strings
*/
int returnIndexOfVector(vs &stringVector, string value)
{
int iii;
for (iii = 0; iii < stringVector.size(); iii++) {
if (stringVector[iii] == value) {
return iii;
}
}
return -1;
}
/*
* Outputs the predictions to file
* and returns the accuracy of the classification
*/
double printPredictionsAndCalculateAccuracy(vs &givenData, vs &predictions)
{
ofstream outputFile;
outputFile.open("decisionTreeOutput.txt");
int correct = 0;
outputFile << setw(3) << "#" << setw(16) << "Given Class" << setw(31) << right << "Predicted Class" << endl;
outputFile << "--------------------------------------------------" << endl;
for (int iii = 0; iii < givenData.size(); iii++) {
outputFile << setw(3) << iii+1 << setw(16) << givenData[iii];
if (givenData[iii] == predictions[iii]) {
correct++;
outputFile << " ------------ ";
} else {
outputFile << " xxxxxxxxxxxx ";
}
outputFile << predictions[iii] << endl;
}
outputFile << "--------------------------------------------------" << endl;
outputFile << "Total number of instances in test data = " << givenData.size() << endl;
outputFile << "Number of correctly predicted instances = " << correct << endl;
outputFile.close();
return (double) correct/50 * 100;
}
/*
* Returns a vvs which contains information about
* the data table. The vvs contains the names of
* all the columns and the values that each
* column can take
*/
vvs generateTableInfo(vvs &dataTable)
{
vvs tableInfo;
for (int iii = 0; iii < dataTable[0].size(); iii++) {
vs tempInfo;
msi tempMap;
for (int jjj = 0; jjj < dataTable.size(); jjj++) {
if (tempMap.count(dataTable[jjj][iii]) == 0) {
tempMap[dataTable[jjj][iii]] = 1;
tempInfo.push_back(dataTable[jjj][iii]);
} else {
tempMap[dataTable[jjj][iii]]++;
}
}
tableInfo.push_back(tempInfo);
}
return tableInfo;
}
/*
* Returns the most frequent class from the training data
* This class will be used as the default class label
*/
string returnMostFrequentClass(vvs &dataTable)
{
msi trainingClasses; // Stores the classlabels and their frequency
for (int iii = 1; iii < dataTable.size(); iii++) {
if (trainingClasses.count(dataTable[iii][dataTable[0].size()-1]) == 0) {
trainingClasses[dataTable[iii][dataTable[0].size()-1]] = 1;
} else {
trainingClasses[dataTable[iii][dataTable[0].size()-1]]++;
}
}
msi::iterator mapIter;
int highestClassCount = 0;
string mostFrequentClass;
for (mapIter = trainingClasses.begin(); mapIter != trainingClasses.end(); mapIter++) {
if (mapIter->second >= highestClassCount) {
highestClassCount = mapIter->second;
mostFrequentClass = mapIter->first;
}
}
return mostFrequentClass;
}
int main(int argc, const char *argv[])
{
ifstream inputFile; // Input file stream
string singleInstance; // Single line read from the input file
vvs dataTable; // Input data in the form of a vector of vector of strings
inputFile.open("train.dat");
if (!inputFile) // If input file does not exist, print error and exit
{
cerr << "Error: Training data file not found!" << endl;
exit(-1);
}
/*
* Decision tree training phase
* In this phase, the training data is read
* from the file and stored into a vvs using
* the parse() function. The generateTableInfo()
* function extracts the attribute (column) names
* and also the values that each column can take.
* This information is also stored in a vvs.
* buildDecisionTree() function recursively
* builds trains the decision tree.
*/
while (getline(inputFile, singleInstance)) // Read from file, parse and store data
{
parse(singleInstance, dataTable);
}
inputFile.close(); // Close input file
vvs tableInfo = generateTableInfo(dataTable); // Stores all the attributes and their values in a vector of vector of strings named tableInfo
node* root = new node; // Declare and assign memory for the root node of the Decision Tree
root = buildDecisionTree(dataTable, root, tableInfo); // Recursively build and train decision tree
string defaultClass = returnMostFrequentClass(dataTable); // Stores the most frequent class in the training data. This is used as the default class label
dataTable.clear(); // clear dataTable of training data to store testing data
/*
* Decision tree testing phase
* In this phase, the testing is read
* from the file, parsed and stored.
* Each row in the table is made to
* traverse down the decision tree
* till a class label is found.
*/
inputFile.clear();
inputFile.open("test.dat"); // Open test file
if (!inputFile) // Exit if test file is not found
{
cerr << "Error: Testing data file not found!" << endl;
exit(-1);
}
while (getline(inputFile, singleInstance)) // Store test data in a table
{
parse(singleInstance, dataTable);
}
vs predictedClassLabels; // Stores the predicted class labels for each row
vs givenClassLabels; // Stores the given class labels in the test data
for (int iii = 1; iii < dataTable.size(); iii++) // Store given class labels in vector of strings named givenClassLabels
{
string data = dataTable[iii][dataTable[0].size()-1];
givenClassLabels.push_back(data);
}
for (int iii = 1; iii < dataTable.size(); iii++) // Predict class labels based on the decision tree
{
string someString = testDataOnDecisionTree(dataTable[iii], root, tableInfo, defaultClass);
predictedClassLabels.push_back(someString);
}
dataTable.clear();
/* Print output */
ofstream outputFile;
outputFile.open("decisionTreeOutput.txt", ios::app);
outputFile << endl << "--------------------------------------------------" << endl;
double accuracy = printPredictionsAndCalculateAccuracy(givenClassLabels, predictedClassLabels); // calculate accuracy of classification
outputFile << "Accuracy of decision tree classifier = " << accuracy << "%"; // Print out accuracy to console
return 0;
} | [
"[avinash.ab007@gmail.com]"
] | [avinash.ab007@gmail.com] |
416c727bd21a4c5f2d865ea2053a88393d109ea2 | c164deecf14db1b3f09e9e89dcaf45c993a35897 | /include/lwiot/bmpsensor.h | 51325774b63c95c2b5c75947c5b474e94100f432 | [
"Apache-2.0"
] | permissive | michelmegens/lwIoT | 16135aadc53079b03b49cef002daf5df19f94cd2 | 345d7d7705b1c2f639c4b19fe608ae54e3b7cde1 | refs/heads/master | 2021-10-15T23:19:00.065109 | 2018-10-02T13:17:20 | 2018-10-02T13:17:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | h | /*
* BMP base header.
*
* @author Michel Megens
* @email dev@bietje.net
*/
#pragma once
#include <lwiot/lwiot.h>
#include <lwiot/types.h>
#include <lwiot/log.h>
#include <lwiot/i2cbus.h>
namespace lwiot
{
class BmpSensor {
public:
explicit BmpSensor(uint8_t addr, I2CBus& bus);
virtual ~BmpSensor() = default;
protected:
virtual uint32_t read24(uint8_t reg);
virtual uint16_t read16(uint8_t reg);
virtual uint8_t read8(uint8_t reg);
virtual int16_t readS16(uint8_t reg);
uint16_t read16_LE(uint8_t reg);
int16_t readS16_LE(uint8_t reg);
virtual void write(uint8_t reg, uint8_t value);
private:
uint8_t _addr;
I2CBus& _bus;
bool read(uint8_t reg, uint8_t *rv, size_t num);
};
}
| [
"dev@bietje.net"
] | dev@bietje.net |
c525d5d0b06542f09226702449609067a8185461 | d23d36fd5b4e6851fef68940b15ed625677a576b | /作业10-1和2/作业10-1和2/作业10-1和2View.h | c3bb8ea1deb9437433f28ee71a2d360093f6ff14 | [] | no_license | DJQ0926/test | 0d5fd731edef513e08b1169578e70fe9139d7d05 | e9a755ac66750e14bbb870d211531d91a92fc2ee | refs/heads/master | 2021-02-15T23:03:21.681207 | 2020-07-05T09:51:20 | 2020-07-05T09:51:20 | 244,942,227 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,416 | h |
// 作业10-1和2View.h : C作业101和2View 类的接口
//
#pragma once
class C作业101和2Set;
class C作业101和2View : public CRecordView
{
protected: // 仅从序列化创建
C作业101和2View();
DECLARE_DYNCREATE(C作业101和2View)
public:
#ifdef AFX_DESIGN_TIME
enum{ IDD = IDD_MY1012_FORM };
#endif
C作业101和2Set* m_pSet;
// 特性
public:
C作业101和2Doc* GetDocument() const;
// 操作
public:
// 重写
public:
virtual CRecordset* OnGetRecordset();
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
virtual void OnInitialUpdate(); // 构造后第一次调用
// 实现
public:
virtual ~C作业101和2View();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// 生成的消息映射函数
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnEnChangeEdit2();
afx_msg void OnEnChangeEdit1();
long ID;
CString name;
CString number;
CString age;
CString phone;
afx_msg void OnBnClickedButton1();
afx_msg void OnEnChangeEdit3();
void foo(CImage& img, int &sx, int &sy, int &w, int &h);
afx_msg void OnEnChangeEdit5();
};
#ifndef _DEBUG // 作业10-1和2View.cpp 中的调试版本
inline C作业101和2Doc* C作业101和2View::GetDocument() const
{ return reinterpret_cast<C作业101和2Doc*>(m_pDocument); }
#endif
| [
"964158009@qq.com"
] | 964158009@qq.com |
ad55ca19ec2c43cd3787d12f9d3531c7f42ae762 | c0be1b5248ffb2801c6191d55fe385969cb802ef | /media/materials/programs/StdFxMaterial/JoyCodec.inc | 2f0ead7f5d1a0d9599d2220210cc5fb632fa495c | [] | no_license | zephyroal/BloodrainPlan | cd98610d25d5f545c13879c1c4108d2bbdf1f44c | 807f85ceca421ec6e84cd9b4e644f4c30dc44755 | refs/heads/master | 2016-09-16T09:40:46.165096 | 2013-11-22T11:57:42 | 2013-11-22T11:57:42 | 27,374,206 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,475 | inc | #ifndef _JoyCodec_INC_
#define _JoyCodec_INC_
#ifndef CODEC_KEY
#define CODEC_KEY 256.f
#endif
/*
编码函数, 把一个R8G8B8A8的值转到一个float32位中,越往后精度越低
*/
void encode(in float4 color, out float codec)
{
codec = color.x +
color.y * (1 / CODEC_KEY) +
color.z * (1 / (CODEC_KEY * CODEC_KEY)) +
color.w * (1 / (CODEC_KEY * CODEC_KEY * CODEC_KEY));
}
/*
* 编码2个RGB8到1个RGB16中
*/
float3 encodeRGB8_16( in float3 iColorLow, in float3 iColorHigh )
{
return floor(iColorLow*255)+(min(iColorHigh, 0.99));
}
void decodeRGB16_8( in float3 iColor, out float3 oColorLow, out float3 oColorHi )
{
float3 tmp = floor( iColor );
oColorLow = tmp / 255.f;
oColorHi = iColor - tmp ;
}
/*
解码函数,从一个float32的数中得到R8G8B8A8某一位的值,越往后精度越低,解码速度越慢
*/
void decode_R(in float codec, out float r) //R8
{
r = floor(codec);
}
void decode_G(in float codec, out float g) //G8
{
codec = (codec - floor(codec)) * CODEC_KEY;
g = floor(codec);
}
void decode_B(in float codec, out float b) //B8
{
codec = (codec - floor(codec)) * CODEC_KEY;
codec = (codec - floor(codec)) * CODEC_KEY;
b = floor(codec);
}
void decode_A(in float codec, out float a) //A8
{
codec = (codec - floor(codec)) * CODEC_KEY;
codec = (codec - floor(codec)) * CODEC_KEY;
codec = (codec - floor(codec)) * CODEC_KEY;
a = floor(codec);
}
void decode_RG(in float codec, out float2 color) //R8G8
{
color.x = floor(codec);
codec = (codec - color.x) * CODEC_KEY;
color.y = floor(codec);
}
void decode_RGB(in float codec, out float3 color) //R8G8B8
{
color.x = floor(codec);
codec = (codec - color.x) * CODEC_KEY;
color.y = floor(codec);
codec = (codec - color.y) * CODEC_KEY;
color.z = floor(codec);
}
void decode_RGBA(in float codec, out float4 color) //R8G8B8A8
{
color.x = floor(codec);
codec = (codec - color.x) * CODEC_KEY;
color.y = floor(codec);
codec = (codec - color.y) * CODEC_KEY;
color.z = floor(codec);
codec = (codec - color.z) * CODEC_KEY;
color.w = floor(codec);
}
float2 encode_normal( float3 n )
{
half p = sqrt(n.z*8+8);
return n.xy/p + 0.5;
}
float3 decode_normal( float2 enc )
{
half2 fenc = enc*4-2;
half f = dot(fenc,fenc);
half g = sqrt(1-f/4);
half3 n;
n.xy = fenc*g;
n.z = 1-f/2;
return n;
}
#endif | [
"zephyroal@localhost"
] | zephyroal@localhost |
7b06470e0f7cf23922a3d6ec469fd1e285795e18 | 543d6087dfeefe917a94ec84f02139a2c97aebd9 | /archive/08.2016/TS/1569.cpp | 8ce1c91000755e89e27e937c10d98d809d71d650 | [] | no_license | rrkarim/neerc | c99947099915a00a6a532a1d878ea54f97be9538 | 68718698dd2acd39c333c898bf856a09d225abfd | refs/heads/master | 2021-09-01T12:04:05.061830 | 2017-12-26T22:05:17 | 2017-12-26T22:05:17 | 62,803,353 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,578 | cpp | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:16777216")
#define MAX_CHAR 256
#define MAXN 1000005
#define INF 1000000
#define pi 3.14159265358979323846
using namespace std;
typedef long long ll;
int n, m, maxn1, maxn2, x, y;
vector <vector <int> > g, new_graph;
pair <int, int> pd[10005];
map <pair <int, int>, int> mp;
int used[105], us[105], ans = 1000000, index = -1, dist, dist_in = -1, st;
vector <int> res, edges;
int dfs(int s, int k) {
if(k > dist) {
dist = k;
dist_in = s;
}
us[s] = 1;
for(int i = 0; i < new_graph[s].size(); ++i) {
int to = new_graph[s][i];
if(!us[to]) dfs(to, k + 1);
}
}
int diameter(int in) {
memset(us, 0, sizeof us);
dist = 0, dist_in = -1;
dfs(in, 0);
dist = 0;
memset(us, 0, sizeof us);
dfs(dist_in, 0);
if(dist < ans) {
ans = dist;
res.clear();
for(int i = 1; i <= n; ++i) {
for(int j = 0; j < new_graph[i].size(); ++j) {
if(new_graph[i][j] <= i) continue;
res.push_back(mp[{i, new_graph[i][j]}]);
}
}
}
return dist;
}
int bfs(int s, queue <int> q, int c) {
new_graph.clear(); new_graph.resize(n + 1);
if(c == 1) {
new_graph[pd[s].first].push_back(pd[s].second);
new_graph[pd[s].second].push_back(pd[s].first);
}
while(!q.empty()) {
int top = q.front(); q.pop();
for(int j = 0; j < g[top].size(); ++j) {
int to = g[top][j];
if(!used[to]) {
q.push(to);
used[to] = 1;
new_graph[top].push_back(to), new_graph[to].push_back(top);
}
}
}
if(c == 1) return diameter(pd[s].first);
return diameter(s);
}
int main() {
cin >> n >> m;
g.resize(n + 2); new_graph.resize(n + 2);
for(int i = 0; i < m; ++i) {
cin >> x >> y;
g[x].push_back(y), g[y].push_back(x);
pd[i] = {x,y}, mp[{x,y}] = mp[{y,x}] = i;
}
for(int i = 1; i <= n; ++i) {
memset(used, 0, sizeof used);
queue<int> q; q.push(i); used[i] = 1;
int x = bfs(i, q, 0);
}
for(int i = 0; i < m; ++i) {
memset(used,0,sizeof used);
queue<int> q;
q.push(pd[i].first);
q.push(pd[i].second);
used[pd[i].first] = used[pd[i].second] = 1;
int x = bfs(i, q, 1);
if(x < ans) {
ans = x;
}
}
for(int i = 0; i < res.size(); ++i) {
cout << pd[res[i]].first << " " << pd[res[i]].second << endl;
}
}
| [
"rkerimov@std.qu.edu.az"
] | rkerimov@std.qu.edu.az |
5ddea4d1c62da2a238c1c9d3f66716f77b7e63fd | 63b07643f25cd6de4a2d1e48ecbcd1f4c9417a18 | /include/aveExotico.h | e6a84a50a3d2b690198a6349b13198974460188e | [] | no_license | jonathan-julio/LP1_AP3-master | d42f3bf9e9d75fec245f33228b2c73bb3968e43a | 665a5d3b0aa4314436bb620f12a79213e3e04ccb | refs/heads/master | 2020-09-12T20:31:06.204377 | 2019-11-22T04:35:53 | 2019-11-22T04:35:53 | 222,545,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | h | #define _GLIBCXX_USE_CXX11_ABI 0
#ifndef AVEEXOTICO_H
#define AVEEXOTICO_H
#include <iostream>
#include <vector>
#include <string>
#include <ctime>
#include <iterator>
#include <algorithm>
#include "animal.h"
#include "ave.h"
#include "animalExotico.h"
#include "animalSilvestre.h"
using namespace std;
class Ave_exotico:public Ave, public Animal_exotico{
public:
Ave_exotico();
Ave_exotico(int id_a,string classe,string nome_c,char sexo,double tamanho, string dieta, int funcionario, string nome_B, double tamanhoDoBico, double envergaduraAsas, string paisOrigem, string autorizacaoIbama);
~Ave_exotico();
friend ostream& operator << (ostream &o, Ave_exotico &animal_);
};
#endif // AVEEXOTICO_H | [
"jonathan.julio@ufrn.edu.br"
] | jonathan.julio@ufrn.edu.br |
a6883ddbdbb1f3b017097363d96d717e8ec3006b | 6df25e954b76561627ec01a079fc94e19f0173e3 | /Laba15/Laba15 Client/Laba15 Client/main.cpp | 108e2bec98240d0f008c7644348314f6ffe5dc58 | [] | no_license | MChuduk/OS2 | 5bda136f7a378f9264d3801f9ad20a9c32c7b79d | 0b05b39abbaff0039a816f47ef3b588313de673f | refs/heads/master | 2022-12-16T09:00:58.252154 | 2020-09-24T06:54:54 | 2020-09-24T06:54:54 | 298,192,262 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 4,613 | cpp | #include <iostream>
#include <stdio.h>
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <winsock2.h>
#pragma comment(lib, "Ws2_32.lib")
void task1();
void task2();
void task3();
int main()
{
setlocale(LC_CTYPE, "Rus");
std::cout << "КЛИЕНТ" << std::endl;
//task1();
//task2();
task3();
return 0;
}
void task1()
{
int retVal = 0;
WSADATA wsaData;
WORD ver = MAKEWORD(2, 2);
WSAStartup(ver, (LPWSADATA)&wsaData);
LPHOSTENT hostEnt;
hostEnt = gethostbyname("localhost");
SOCKADDR_IN serverInfo;
serverInfo.sin_family = PF_INET;
serverInfo.sin_addr = *((LPIN_ADDR)*hostEnt->h_addr_list);
serverInfo.sin_port = htons(1111);
//Создаем сокет
SOCKET clientSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSock == SOCKET_ERROR)
{
std::cout << "Ошибка создания сокета." << std::endl;
WSACleanup();
return;
}
retVal = connect(clientSock, (LPSOCKADDR)&serverInfo, sizeof(serverInfo));
if (retVal == SOCKET_ERROR)
{
std::cout << "Ошибка поключения к серверу." << std::endl;
WSACleanup();
return;
}
std::cout << "Подключено к серверу успешно." << std::endl;
while (true)
{
char str[80];
std::cout << "Отправить сообщение: ";
std::cin >> str;
retVal = send(clientSock, str, sizeof(str), 0);
if (retVal == SOCKET_ERROR)
{
std::cout << "Ошибка отправки сообщения." << std::endl;
WSACleanup();
return;
}
if (!strcmp(str, "exit"))
break;
}
closesocket(clientSock);
WSACleanup();
}
void task2()
{
int retVal = 0;
WSADATA wsaData;
WORD ver = MAKEWORD(2, 2);
WSAStartup(ver, (LPWSADATA)&wsaData);
LPHOSTENT hostEnt;
hostEnt = gethostbyname("localhost");
SOCKADDR_IN serverInfo;
serverInfo.sin_family = PF_INET;
serverInfo.sin_addr = *((LPIN_ADDR)*hostEnt->h_addr_list);
serverInfo.sin_port = htons(1111);
//Создаем сокет
SOCKET clientSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSock == SOCKET_ERROR)
{
std::cout << "Ошибка создания сокета." << std::endl;
WSACleanup();
return;
}
retVal = connect(clientSock, (LPSOCKADDR)&serverInfo, sizeof(serverInfo));
if (retVal == SOCKET_ERROR)
{
std::cout << "Ошибка поключения к серверу." << std::endl;
WSACleanup();
return;
}
std::cout << "Подключено к серверу успешно." << std::endl;
char str[80];
retVal = recv(clientSock, str, sizeof(str), 0);
if (retVal == SOCKET_ERROR)
{
std::cout << "Ошибка получения сообщения" << std::endl;
WSACleanup();
return;
}
std::cout << "Полученное сообщение: " << str << std::endl;
system("pause");
closesocket(clientSock);
WSACleanup();
}
void task3()
{
int retVal = 0;
WSADATA wsaData;
WORD ver = MAKEWORD(2, 2);
WSAStartup(ver, (LPWSADATA)&wsaData);
LPHOSTENT hostEnt;
hostEnt = gethostbyname("localhost");
SOCKADDR_IN serverInfo;
serverInfo.sin_family = PF_INET;
serverInfo.sin_addr = *((LPIN_ADDR)*hostEnt->h_addr_list);
serverInfo.sin_port = htons(1111);
//Создаем сокет
SOCKET clientSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSock == SOCKET_ERROR)
{
std::cout << "Ошибка создания сокета." << std::endl;
WSACleanup();
return;
}
retVal = connect(clientSock, (LPSOCKADDR)&serverInfo, sizeof(serverInfo));
if (retVal == SOCKET_ERROR)
{
std::cout << "Ошибка поключения к серверу." << std::endl;
WSACleanup();
return;
}
std::cout << "Подключено к серверу успешно." << std::endl;
char str[80] = "Сообщение1337";
send(clientSock, str, sizeof(str), 0);
std::cout << "Отправлено: " << str << std::endl;
Sleep(5000);
recv(clientSock, str, sizeof(str), 0);
std::cout << "Получено: " << str << std::endl;
Sleep(5000);
send(clientSock, str, sizeof(str), 0);
std::cout << "Отправлено: " << str << std::endl;
system("pause");
closesocket(clientSock);
WSACleanup();
} | [
"greatchuduk@gmail.com"
] | greatchuduk@gmail.com |
75c20731408836f5fab98c9a892a04b73fda179a | 4d623ea7a585e58e4094c41dc212f60ba0aec5ea | /A_Saitama_Destroys_Hotel.cpp | 0de94b4ab95a1fcc759917f3acfd7954f6d5bdf3 | [] | no_license | akshit-04/CPP-Codes | 624aadeeec35bf608ef4e83f1020b7b54d992203 | ede0766d65df0328f7544cadb3f8ff0431147386 | refs/heads/main | 2023-08-30T13:28:14.748412 | 2021-11-19T12:04:43 | 2021-11-19T12:04:43 | 429,779,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 769 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define For(i,n) for(int i=0;i<n;i++)
#define VI vector<int>
#define fast ios_base::sync_with_stdio(0); cin.tie(0)
int main()
{
fast;
int t=1;
//cin>>t;
while(t--)
{
int n,tf;
cin>>n>>tf;
VI a(tf+1);
For(i,tf+1)
a[i]=0;
while(n--)
{
int f,t;
cin>>f>>t;
a[f]=max(t,a[f]);
}
//sort(v.begin(),v.end(),greater<int>());
int sum=0;
for(int i=tf;i>0;i--)
{
if(a[i]>sum)
{
sum+=(a[i]-sum);
}
sum+=1;
}
cout<<sum;
}
return 0;
} | [
"ishu.akshitgarg@gmail.com"
] | ishu.akshitgarg@gmail.com |
238134f4fbc3fa7a445fc285ed752c6f59c7e0fc | dec5b424b90e0eb2c2cc56e85f7352491c23ea7b | /bin/cpp/main/src/__files__.cpp | f2af611887663ec398f47a2772486e02397ec1f6 | [] | no_license | TylerMcKenzie/git_branch_dependency | ea09a3218b02a1dd61604ecbb1c961c621257748 | f14c5036000febb22c985caa0ca4d125f2dd85ef | refs/heads/master | 2020-05-26T16:57:32.920120 | 2019-10-28T19:27:49 | 2019-10-28T19:27:49 | 188,307,368 | 0 | 0 | null | 2019-10-28T19:27:04 | 2019-05-23T21:12:54 | C++ | UTF-8 | C++ | false | true | 4,718 | cpp | // Generated by Haxe 4.0.0+ef18b627e
#include <hxcpp.h>
namespace hx {
const char *__hxcpp_all_files[] = {
#ifdef HXCPP_DEBUGGER
"/home/vagrant/haxe_20191025230916_ef18b627e/std/StringTools.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/Date.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/EReg.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/Reflect.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/Std.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/StringBuf.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/Sys.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/Type.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/haxe/ds/StringMap.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/sys/FileSystem.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/sys/io/File.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/sys/io/FileInput.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/sys/io/FileOutput.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/sys/io/Process.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/SysTools.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/format/JsonParser.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/format/JsonPrinter.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/io/Bytes.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/io/BytesBuffer.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/io/Eof.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/io/Input.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/io/Output.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/io/Path.hx",
"?",
"Main.hx",
"app/App.hx",
"app/model/DependencyModel.hx",
"app/util/Formatter.hx",
#endif
0 };
const char *__hxcpp_all_files_fullpath[] = {
#ifdef HXCPP_DEBUGGER
"/home/vagrant/haxe_20191025230916_ef18b627e/std/StringTools.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/Date.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/EReg.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/Reflect.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/Std.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/StringBuf.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/Sys.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/Type.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/haxe/ds/StringMap.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/sys/FileSystem.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/sys/io/File.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/sys/io/FileInput.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/sys/io/FileOutput.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/cpp/_std/sys/io/Process.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/SysTools.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/format/JsonParser.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/format/JsonPrinter.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/io/Bytes.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/io/BytesBuffer.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/io/Eof.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/io/Input.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/io/Output.hx",
"/home/vagrant/haxe_20191025230916_ef18b627e/std/haxe/io/Path.hx",
"?",
"/home/vagrant/code/release/tyler-stuff/haxe/haxe_cmd/git_branch_dependency/src/Main.hx",
"/home/vagrant/code/release/tyler-stuff/haxe/haxe_cmd/git_branch_dependency/src/app/App.hx",
"/home/vagrant/code/release/tyler-stuff/haxe/haxe_cmd/git_branch_dependency/src/app/model/DependencyModel.hx",
"/home/vagrant/code/release/tyler-stuff/haxe/haxe_cmd/git_branch_dependency/src/app/util/Formatter.hx",
#endif
0 };
const char *__hxcpp_all_classes[] = {
#ifdef HXCPP_DEBUGGER
"Date",
"EReg",
"Reflect",
"Std",
"StringBuf",
"haxe.SysTools",
"StringTools",
"Sys",
"Type",
"app.App",
"app.model.DependencyModel",
"app.util.Formatter",
"haxe.ds.StringMap",
"haxe.format.JsonParser",
"haxe.format.JsonPrinter",
"haxe.io.Bytes",
"haxe.io.BytesBuffer",
"haxe.io.Eof",
"haxe.io.Input",
"haxe.io.Output",
"haxe.io.Path",
"src.Main",
"sys.FileSystem",
"sys.io.File",
"sys.io.FileInput",
"sys.io.FileOutput",
"sys.io._Process.Stdin",
"sys.io._Process.Stdout",
"sys.io.Process",
#endif
0 };
} // namespace hx
void __files__boot() { __hxcpp_set_debugger_info(hx::__hxcpp_all_classes, hx::__hxcpp_all_files_fullpath); }
| [
"tylrmckenz@gmail.com"
] | tylrmckenz@gmail.com |
b000b47d0a044c675367bd5c2c9c9de241b35212 | 9a7bb05a62c25d7146184d333cfe791a2f594ea1 | /src/app/storageprovider.h | 7c34a4f7e77b39604775febeaab45d2015a0f2a1 | [] | no_license | cmacq2/factorkey | a8c39f13fb2f6fbf7124b245e0c4788a7d646391 | 67bc6cf6524ae2b011ebbecebe6a3243a7e42910 | refs/heads/master | 2020-04-12T09:03:45.131358 | 2017-11-30T20:38:39 | 2017-12-02T10:15:30 | 54,341,537 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,127 | h | #ifndef FACTORKEY_APP_STORAGEPROVIDER_H
#define FACTORKEY_APP_STORAGEPROVIDER_H
#include "otp/storage/storageprovider.h"
#include <QDir>
#include <QFileInfo>
#include <QString>
namespace otp
{
namespace app
{
namespace storage
{
class StorageBuilder
{
public:
StorageBuilder();
otp::storage::StorageProvider * build(void) const;
void setSecretsDomain(const QString& domain = QString());
void setDbConnectionName(const QString& connectionName = QString());
void setDbName(const QString& name);
void setDbDirectory(const QDir& dir);
void setDbFile(const QFileInfo& dbFile);
void setDbFile(const QString& dbFile);
void setParent(QObject * parent);
private:
QString m_secretsDomain;
QString m_dbConnectionName;
QString m_dbName;
QDir m_dir;
bool m_dirSet;
QObject * m_parent;
};
}
}
}
#endif
| [
"jm.ouwerkerk@gmail.com"
] | jm.ouwerkerk@gmail.com |
af5191885f842822c4135ad553b376fd0c919527 | d60968b7b1cd9c3e5fead62b6842204b9a473c5d | /hierarchy_determination/comparison1/task.h | 2478096516b9df80b32bb54da6f1220b987d0972 | [] | no_license | MrZhang1994/crowdsensing | 7df53823a5bddb3f849c64ff058807fd2ba61d95 | 8a774bc4652a98a6cf44555ea2ba894d223b9a4c | refs/heads/master | 2020-12-09T19:37:34.944470 | 2020-10-24T12:50:09 | 2020-10-24T12:50:09 | 233,399,541 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 642 | h | #ifndef _TASK_H_
#define _TASK_H
#include <vector>
using namespace std;
class task_t
{
public:
vector<float> attr; // attribution of sensors (a_n)
vector<float> attr_weight; // weight of each attribution (w_n)
int sensor_num; // required number of sensors (s_n')
vector<bool> area; // required sensing areas (m_n)
float threshold; // similarity threshold (b_n)
// Initialize a task randomly.
task_t(int attr_size, int sensor_num, int area_size, float threshold);
// Show all information of this task. (debug)
void print_task();
};
#endif | [
"noreply@github.com"
] | noreply@github.com |
dba9275370e8cc14c9c28b7b3c3b24d9d0a9887a | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_5/Z6.1+dmb.ld+dmb.st+po.c.cbmc_out.cpp | 888eccf6b25ddf0fd4712f54daa79e8ebee99748 | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 36,386 | cpp | // Global variabls:
// 0:vars:3
// 3:atom_2_X0_1:1
// Local global variabls:
// 0:thr0:1
// 1:thr1:1
// 2:thr2:1
#define ADDRSIZE 4
#define LOCALADDRSIZE 3
#define NTHREAD 4
#define NCONTEXT 5
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// Declare arrays for intial value version in contexts
int local_mem[LOCALADDRSIZE];
// Dumping initializations
local_mem[0+0] = 0;
local_mem[1+0] = 0;
local_mem[2+0] = 0;
int cstart[NTHREAD];
int creturn[NTHREAD];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NTHREAD*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NTHREAD*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NTHREAD*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NTHREAD*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NTHREAD*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NTHREAD*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NTHREAD*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NTHREAD*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NTHREAD*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NTHREAD];
int cdy[NTHREAD];
int cds[NTHREAD];
int cdl[NTHREAD];
int cisb[NTHREAD];
int caddr[NTHREAD];
int cctrl[NTHREAD];
int r0= 0;
char creg_r0;
char creg__r0__1_;
int r1= 0;
char creg_r1;
int r2= 0;
char creg_r2;
int r3= 0;
char creg_r3;
int r4= 0;
char creg_r4;
int r5= 0;
char creg_r5;
char creg__r5__2_;
int r6= 0;
char creg_r6;
char creg__r6__2_;
int r7= 0;
char creg_r7;
int r8= 0;
char creg_r8;
int r9= 0;
char creg_r9;
char creg__r9__1_;
int r10= 0;
char creg_r10;
char old_cctrl= 0;
char old_cr= 0;
char old_cdy= 0;
char old_cw= 0;
char new_creg= 0;
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
buff(3,0) = 0;
pw(3,0) = 0;
cr(3,0) = 0;
iw(3,0) = 0;
cw(3,0) = 0;
cx(3,0) = 0;
is(3,0) = 0;
cs(3,0) = 0;
crmax(3,0) = 0;
buff(3,1) = 0;
pw(3,1) = 0;
cr(3,1) = 0;
iw(3,1) = 0;
cw(3,1) = 0;
cx(3,1) = 0;
is(3,1) = 0;
cs(3,1) = 0;
crmax(3,1) = 0;
buff(3,2) = 0;
pw(3,2) = 0;
cr(3,2) = 0;
iw(3,2) = 0;
cw(3,2) = 0;
cx(3,2) = 0;
is(3,2) = 0;
cs(3,2) = 0;
crmax(3,2) = 0;
buff(3,3) = 0;
pw(3,3) = 0;
cr(3,3) = 0;
iw(3,3) = 0;
cw(3,3) = 0;
cx(3,3) = 0;
is(3,3) = 0;
cs(3,3) = 0;
crmax(3,3) = 0;
cl[3] = 0;
cdy[3] = 0;
cds[3] = 0;
cdl[3] = 0;
cisb[3] = 0;
caddr[3] = 0;
cctrl[3] = 0;
cstart[3] = get_rng(0,NCONTEXT-1);
creturn[3] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(0+2,0) = 0;
mem(3+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
mem(0,1) = meminit(0,1);
co(0,1) = coinit(0,1);
delta(0,1) = deltainit(0,1);
mem(0,2) = meminit(0,2);
co(0,2) = coinit(0,2);
delta(0,2) = deltainit(0,2);
mem(0,3) = meminit(0,3);
co(0,3) = coinit(0,3);
delta(0,3) = deltainit(0,3);
mem(0,4) = meminit(0,4);
co(0,4) = coinit(0,4);
delta(0,4) = deltainit(0,4);
co(1,0) = 0;
delta(1,0) = -1;
mem(1,1) = meminit(1,1);
co(1,1) = coinit(1,1);
delta(1,1) = deltainit(1,1);
mem(1,2) = meminit(1,2);
co(1,2) = coinit(1,2);
delta(1,2) = deltainit(1,2);
mem(1,3) = meminit(1,3);
co(1,3) = coinit(1,3);
delta(1,3) = deltainit(1,3);
mem(1,4) = meminit(1,4);
co(1,4) = coinit(1,4);
delta(1,4) = deltainit(1,4);
co(2,0) = 0;
delta(2,0) = -1;
mem(2,1) = meminit(2,1);
co(2,1) = coinit(2,1);
delta(2,1) = deltainit(2,1);
mem(2,2) = meminit(2,2);
co(2,2) = coinit(2,2);
delta(2,2) = deltainit(2,2);
mem(2,3) = meminit(2,3);
co(2,3) = coinit(2,3);
delta(2,3) = deltainit(2,3);
mem(2,4) = meminit(2,4);
co(2,4) = coinit(2,4);
delta(2,4) = deltainit(2,4);
co(3,0) = 0;
delta(3,0) = -1;
mem(3,1) = meminit(3,1);
co(3,1) = coinit(3,1);
delta(3,1) = deltainit(3,1);
mem(3,2) = meminit(3,2);
co(3,2) = coinit(3,2);
delta(3,2) = deltainit(3,2);
mem(3,3) = meminit(3,3);
co(3,3) = coinit(3,3);
delta(3,3) = deltainit(3,3);
mem(3,4) = meminit(3,4);
co(3,4) = coinit(3,4);
delta(3,4) = deltainit(3,4);
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !34, metadata !DIExpression()), !dbg !43
// br label %label_1, !dbg !44
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !42), !dbg !45
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !35, metadata !DIExpression()), !dbg !46
// call void @llvm.dbg.value(metadata i64 2, metadata !38, metadata !DIExpression()), !dbg !46
// store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !47
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l19_c3
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l19_c3
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 2;
mem(0,cw(1,0)) = 2;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// call void (...) @dmbld(), !dbg !48
// dumbld: Guess
cdl[1] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdl[1] >= cdy[1]);
ASSUME(cdl[1] >= cr(1,0+0));
ASSUME(cdl[1] >= cr(1,0+1));
ASSUME(cdl[1] >= cr(1,0+2));
ASSUME(cdl[1] >= cr(1,3+0));
ASSUME(creturn[1] >= cdl[1]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !39, metadata !DIExpression()), !dbg !49
// call void @llvm.dbg.value(metadata i64 1, metadata !41, metadata !DIExpression()), !dbg !49
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !50
// ST: Guess
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l21_c3
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l21_c3
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 1;
mem(0+1*1,cw(1,0+1*1)) = 1;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
ASSUME(creturn[1] >= cw(1,0+1*1));
// ret i8* null, !dbg !51
ret_thread_1 = (- 1);
goto T1BLOCK_END;
T1BLOCK_END:
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !54, metadata !DIExpression()), !dbg !62
// br label %label_2, !dbg !44
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !61), !dbg !64
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !55, metadata !DIExpression()), !dbg !65
// call void @llvm.dbg.value(metadata i64 2, metadata !57, metadata !DIExpression()), !dbg !65
// store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !47
// ST: Guess
iw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l27_c3
old_cw = cw(2,0+1*1);
cw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l27_c3
// Check
ASSUME(active[iw(2,0+1*1)] == 2);
ASSUME(active[cw(2,0+1*1)] == 2);
ASSUME(sforbid(0+1*1,cw(2,0+1*1))== 0);
ASSUME(iw(2,0+1*1) >= 0);
ASSUME(iw(2,0+1*1) >= 0);
ASSUME(cw(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cw(2,0+1*1) >= old_cw);
ASSUME(cw(2,0+1*1) >= cr(2,0+1*1));
ASSUME(cw(2,0+1*1) >= cl[2]);
ASSUME(cw(2,0+1*1) >= cisb[2]);
ASSUME(cw(2,0+1*1) >= cdy[2]);
ASSUME(cw(2,0+1*1) >= cdl[2]);
ASSUME(cw(2,0+1*1) >= cds[2]);
ASSUME(cw(2,0+1*1) >= cctrl[2]);
ASSUME(cw(2,0+1*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+1*1) = 2;
mem(0+1*1,cw(2,0+1*1)) = 2;
co(0+1*1,cw(2,0+1*1))+=1;
delta(0+1*1,cw(2,0+1*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+1*1));
// call void (...) @dmbst(), !dbg !48
// dumbst: Guess
cds[2] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cds[2] >= cdy[2]);
ASSUME(cds[2] >= cw(2,0+0));
ASSUME(cds[2] >= cw(2,0+1));
ASSUME(cds[2] >= cw(2,0+2));
ASSUME(cds[2] >= cw(2,3+0));
ASSUME(creturn[2] >= cds[2]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !58, metadata !DIExpression()), !dbg !68
// call void @llvm.dbg.value(metadata i64 1, metadata !60, metadata !DIExpression()), !dbg !68
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !50
// ST: Guess
iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l29_c3
old_cw = cw(2,0+2*1);
cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l29_c3
// Check
ASSUME(active[iw(2,0+2*1)] == 2);
ASSUME(active[cw(2,0+2*1)] == 2);
ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(cw(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cw(2,0+2*1) >= old_cw);
ASSUME(cw(2,0+2*1) >= cr(2,0+2*1));
ASSUME(cw(2,0+2*1) >= cl[2]);
ASSUME(cw(2,0+2*1) >= cisb[2]);
ASSUME(cw(2,0+2*1) >= cdy[2]);
ASSUME(cw(2,0+2*1) >= cdl[2]);
ASSUME(cw(2,0+2*1) >= cds[2]);
ASSUME(cw(2,0+2*1) >= cctrl[2]);
ASSUME(cw(2,0+2*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+2*1) = 1;
mem(0+2*1,cw(2,0+2*1)) = 1;
co(0+2*1,cw(2,0+2*1))+=1;
delta(0+2*1,cw(2,0+2*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+2*1));
// ret i8* null, !dbg !51
ret_thread_2 = (- 1);
goto T2BLOCK_END;
T2BLOCK_END:
// Dumping thread 3
int ret_thread_3 = 0;
cdy[3] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[3] >= cstart[3]);
T3BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !73, metadata !DIExpression()), !dbg !83
// br label %label_3, !dbg !46
goto T3BLOCK1;
T3BLOCK1:
// call void @llvm.dbg.label(metadata !82), !dbg !85
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !75, metadata !DIExpression()), !dbg !86
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !49
// LD: Guess
old_cr = cr(3,0+2*1);
cr(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM _l35_c15
// Check
ASSUME(active[cr(3,0+2*1)] == 3);
ASSUME(cr(3,0+2*1) >= iw(3,0+2*1));
ASSUME(cr(3,0+2*1) >= 0);
ASSUME(cr(3,0+2*1) >= cdy[3]);
ASSUME(cr(3,0+2*1) >= cisb[3]);
ASSUME(cr(3,0+2*1) >= cdl[3]);
ASSUME(cr(3,0+2*1) >= cl[3]);
// Update
creg_r0 = cr(3,0+2*1);
crmax(3,0+2*1) = max(crmax(3,0+2*1),cr(3,0+2*1));
caddr[3] = max(caddr[3],0);
if(cr(3,0+2*1) < cw(3,0+2*1)) {
r0 = buff(3,0+2*1);
ASSUME((!(( (cw(3,0+2*1) < 1) && (1 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,1)> 0));
ASSUME((!(( (cw(3,0+2*1) < 2) && (2 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,2)> 0));
ASSUME((!(( (cw(3,0+2*1) < 3) && (3 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,3)> 0));
ASSUME((!(( (cw(3,0+2*1) < 4) && (4 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,4)> 0));
} else {
if(pw(3,0+2*1) != co(0+2*1,cr(3,0+2*1))) {
ASSUME(cr(3,0+2*1) >= old_cr);
}
pw(3,0+2*1) = co(0+2*1,cr(3,0+2*1));
r0 = mem(0+2*1,cr(3,0+2*1));
}
ASSUME(creturn[3] >= cr(3,0+2*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !77, metadata !DIExpression()), !dbg !86
// %conv = trunc i64 %0 to i32, !dbg !50
// call void @llvm.dbg.value(metadata i32 %conv, metadata !74, metadata !DIExpression()), !dbg !83
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !78, metadata !DIExpression()), !dbg !89
// call void @llvm.dbg.value(metadata i64 1, metadata !80, metadata !DIExpression()), !dbg !89
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !52
// ST: Guess
iw(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l36_c3
old_cw = cw(3,0);
cw(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l36_c3
// Check
ASSUME(active[iw(3,0)] == 3);
ASSUME(active[cw(3,0)] == 3);
ASSUME(sforbid(0,cw(3,0))== 0);
ASSUME(iw(3,0) >= 0);
ASSUME(iw(3,0) >= 0);
ASSUME(cw(3,0) >= iw(3,0));
ASSUME(cw(3,0) >= old_cw);
ASSUME(cw(3,0) >= cr(3,0));
ASSUME(cw(3,0) >= cl[3]);
ASSUME(cw(3,0) >= cisb[3]);
ASSUME(cw(3,0) >= cdy[3]);
ASSUME(cw(3,0) >= cdl[3]);
ASSUME(cw(3,0) >= cds[3]);
ASSUME(cw(3,0) >= cctrl[3]);
ASSUME(cw(3,0) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,0) = 1;
mem(0,cw(3,0)) = 1;
co(0,cw(3,0))+=1;
delta(0,cw(3,0)) = -1;
ASSUME(creturn[3] >= cw(3,0));
// %cmp = icmp eq i32 %conv, 1, !dbg !53
creg__r0__1_ = max(0,creg_r0);
// %conv1 = zext i1 %cmp to i32, !dbg !53
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !81, metadata !DIExpression()), !dbg !83
// store i32 %conv1, i32* @atom_2_X0_1, align 4, !dbg !54, !tbaa !55
// ST: Guess
iw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l38_c15
old_cw = cw(3,3);
cw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l38_c15
// Check
ASSUME(active[iw(3,3)] == 3);
ASSUME(active[cw(3,3)] == 3);
ASSUME(sforbid(3,cw(3,3))== 0);
ASSUME(iw(3,3) >= creg__r0__1_);
ASSUME(iw(3,3) >= 0);
ASSUME(cw(3,3) >= iw(3,3));
ASSUME(cw(3,3) >= old_cw);
ASSUME(cw(3,3) >= cr(3,3));
ASSUME(cw(3,3) >= cl[3]);
ASSUME(cw(3,3) >= cisb[3]);
ASSUME(cw(3,3) >= cdy[3]);
ASSUME(cw(3,3) >= cdl[3]);
ASSUME(cw(3,3) >= cds[3]);
ASSUME(cw(3,3) >= cctrl[3]);
ASSUME(cw(3,3) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,3) = (r0==1);
mem(3,cw(3,3)) = (r0==1);
co(3,cw(3,3))+=1;
delta(3,cw(3,3)) = -1;
ASSUME(creturn[3] >= cw(3,3));
// ret i8* null, !dbg !59
ret_thread_3 = (- 1);
goto T3BLOCK_END;
T3BLOCK_END:
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// %thr2 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !105, metadata !DIExpression()), !dbg !135
// call void @llvm.dbg.value(metadata i8** %argv, metadata !106, metadata !DIExpression()), !dbg !135
// %0 = bitcast i64* %thr0 to i8*, !dbg !69
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !69
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !107, metadata !DIExpression()), !dbg !137
// %1 = bitcast i64* %thr1 to i8*, !dbg !71
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !71
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !111, metadata !DIExpression()), !dbg !139
// %2 = bitcast i64* %thr2 to i8*, !dbg !73
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !73
// call void @llvm.dbg.declare(metadata i64* %thr2, metadata !112, metadata !DIExpression()), !dbg !141
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !113, metadata !DIExpression()), !dbg !142
// call void @llvm.dbg.value(metadata i64 0, metadata !115, metadata !DIExpression()), !dbg !142
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !76
// ST: Guess
iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l47_c3
old_cw = cw(0,0+2*1);
cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l47_c3
// Check
ASSUME(active[iw(0,0+2*1)] == 0);
ASSUME(active[cw(0,0+2*1)] == 0);
ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(cw(0,0+2*1) >= iw(0,0+2*1));
ASSUME(cw(0,0+2*1) >= old_cw);
ASSUME(cw(0,0+2*1) >= cr(0,0+2*1));
ASSUME(cw(0,0+2*1) >= cl[0]);
ASSUME(cw(0,0+2*1) >= cisb[0]);
ASSUME(cw(0,0+2*1) >= cdy[0]);
ASSUME(cw(0,0+2*1) >= cdl[0]);
ASSUME(cw(0,0+2*1) >= cds[0]);
ASSUME(cw(0,0+2*1) >= cctrl[0]);
ASSUME(cw(0,0+2*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+2*1) = 0;
mem(0+2*1,cw(0,0+2*1)) = 0;
co(0+2*1,cw(0,0+2*1))+=1;
delta(0+2*1,cw(0,0+2*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !116, metadata !DIExpression()), !dbg !144
// call void @llvm.dbg.value(metadata i64 0, metadata !118, metadata !DIExpression()), !dbg !144
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !78
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l48_c3
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l48_c3
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !119, metadata !DIExpression()), !dbg !146
// call void @llvm.dbg.value(metadata i64 0, metadata !121, metadata !DIExpression()), !dbg !146
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !80
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l49_c3
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l49_c3
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// store i32 0, i32* @atom_2_X0_1, align 4, !dbg !81, !tbaa !82
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l50_c15
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l50_c15
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !86
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call5 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !87
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %call6 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !88
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[3] >= cdy[0]);
// %3 = load i64, i64* %thr0, align 8, !dbg !89, !tbaa !90
r2 = local_mem[0];
// %call7 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !92
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %4 = load i64, i64* %thr1, align 8, !dbg !93, !tbaa !90
r3 = local_mem[1];
// %call8 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !94
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// %5 = load i64, i64* %thr2, align 8, !dbg !95, !tbaa !90
r4 = local_mem[2];
// %call9 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !96
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[3]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !123, metadata !DIExpression()), !dbg !160
// %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !98
// LD: Guess
old_cr = cr(0,0);
cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l60_c12
// Check
ASSUME(active[cr(0,0)] == 0);
ASSUME(cr(0,0) >= iw(0,0));
ASSUME(cr(0,0) >= 0);
ASSUME(cr(0,0) >= cdy[0]);
ASSUME(cr(0,0) >= cisb[0]);
ASSUME(cr(0,0) >= cdl[0]);
ASSUME(cr(0,0) >= cl[0]);
// Update
creg_r5 = cr(0,0);
crmax(0,0) = max(crmax(0,0),cr(0,0));
caddr[0] = max(caddr[0],0);
if(cr(0,0) < cw(0,0)) {
r5 = buff(0,0);
ASSUME((!(( (cw(0,0) < 1) && (1 < crmax(0,0)) )))||(sforbid(0,1)> 0));
ASSUME((!(( (cw(0,0) < 2) && (2 < crmax(0,0)) )))||(sforbid(0,2)> 0));
ASSUME((!(( (cw(0,0) < 3) && (3 < crmax(0,0)) )))||(sforbid(0,3)> 0));
ASSUME((!(( (cw(0,0) < 4) && (4 < crmax(0,0)) )))||(sforbid(0,4)> 0));
} else {
if(pw(0,0) != co(0,cr(0,0))) {
ASSUME(cr(0,0) >= old_cr);
}
pw(0,0) = co(0,cr(0,0));
r5 = mem(0,cr(0,0));
}
ASSUME(creturn[0] >= cr(0,0));
// call void @llvm.dbg.value(metadata i64 %6, metadata !125, metadata !DIExpression()), !dbg !160
// %conv = trunc i64 %6 to i32, !dbg !99
// call void @llvm.dbg.value(metadata i32 %conv, metadata !122, metadata !DIExpression()), !dbg !135
// %cmp = icmp eq i32 %conv, 2, !dbg !100
creg__r5__2_ = max(0,creg_r5);
// %conv10 = zext i1 %cmp to i32, !dbg !100
// call void @llvm.dbg.value(metadata i32 %conv10, metadata !126, metadata !DIExpression()), !dbg !135
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !128, metadata !DIExpression()), !dbg !164
// %7 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !102
// LD: Guess
old_cr = cr(0,0+1*1);
cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l62_c12
// Check
ASSUME(active[cr(0,0+1*1)] == 0);
ASSUME(cr(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cr(0,0+1*1) >= 0);
ASSUME(cr(0,0+1*1) >= cdy[0]);
ASSUME(cr(0,0+1*1) >= cisb[0]);
ASSUME(cr(0,0+1*1) >= cdl[0]);
ASSUME(cr(0,0+1*1) >= cl[0]);
// Update
creg_r6 = cr(0,0+1*1);
crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1));
caddr[0] = max(caddr[0],0);
if(cr(0,0+1*1) < cw(0,0+1*1)) {
r6 = buff(0,0+1*1);
ASSUME((!(( (cw(0,0+1*1) < 1) && (1 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,1)> 0));
ASSUME((!(( (cw(0,0+1*1) < 2) && (2 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,2)> 0));
ASSUME((!(( (cw(0,0+1*1) < 3) && (3 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,3)> 0));
ASSUME((!(( (cw(0,0+1*1) < 4) && (4 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,4)> 0));
} else {
if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) {
ASSUME(cr(0,0+1*1) >= old_cr);
}
pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1));
r6 = mem(0+1*1,cr(0,0+1*1));
}
ASSUME(creturn[0] >= cr(0,0+1*1));
// call void @llvm.dbg.value(metadata i64 %7, metadata !130, metadata !DIExpression()), !dbg !164
// %conv14 = trunc i64 %7 to i32, !dbg !103
// call void @llvm.dbg.value(metadata i32 %conv14, metadata !127, metadata !DIExpression()), !dbg !135
// %cmp15 = icmp eq i32 %conv14, 2, !dbg !104
creg__r6__2_ = max(0,creg_r6);
// %conv16 = zext i1 %cmp15 to i32, !dbg !104
// call void @llvm.dbg.value(metadata i32 %conv16, metadata !131, metadata !DIExpression()), !dbg !135
// %8 = load i32, i32* @atom_2_X0_1, align 4, !dbg !105, !tbaa !82
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l64_c12
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r7 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r7 = buff(0,3);
ASSUME((!(( (cw(0,3) < 1) && (1 < crmax(0,3)) )))||(sforbid(3,1)> 0));
ASSUME((!(( (cw(0,3) < 2) && (2 < crmax(0,3)) )))||(sforbid(3,2)> 0));
ASSUME((!(( (cw(0,3) < 3) && (3 < crmax(0,3)) )))||(sforbid(3,3)> 0));
ASSUME((!(( (cw(0,3) < 4) && (4 < crmax(0,3)) )))||(sforbid(3,4)> 0));
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r7 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i32 %8, metadata !132, metadata !DIExpression()), !dbg !135
// %and = and i32 %conv16, %8, !dbg !106
creg_r8 = max(creg__r6__2_,creg_r7);
r8 = (r6==2) & r7;
// call void @llvm.dbg.value(metadata i32 %and, metadata !133, metadata !DIExpression()), !dbg !135
// %and17 = and i32 %conv10, %and, !dbg !107
creg_r9 = max(creg__r5__2_,creg_r8);
r9 = (r5==2) & r8;
// call void @llvm.dbg.value(metadata i32 %and17, metadata !134, metadata !DIExpression()), !dbg !135
// %cmp18 = icmp eq i32 %and17, 1, !dbg !108
creg__r9__1_ = max(0,creg_r9);
// br i1 %cmp18, label %if.then, label %if.end, !dbg !110
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg__r9__1_);
if((r9==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([106 x i8], [106 x i8]* @.str.1, i64 0, i64 0), i32 noundef 67, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !111
// unreachable, !dbg !111
r10 = 1;
goto T0BLOCK_END;
T0BLOCK2:
// %9 = bitcast i64* %thr2 to i8*, !dbg !114
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !114
// %10 = bitcast i64* %thr1 to i8*, !dbg !114
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !114
// %11 = bitcast i64* %thr0 to i8*, !dbg !114
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !114
// ret i32 0, !dbg !115
ret_thread_0 = 0;
goto T0BLOCK_END;
T0BLOCK_END:
ASSUME(meminit(0,1) == mem(0,0));
ASSUME(coinit(0,1) == co(0,0));
ASSUME(deltainit(0,1) == delta(0,0));
ASSUME(meminit(0,2) == mem(0,1));
ASSUME(coinit(0,2) == co(0,1));
ASSUME(deltainit(0,2) == delta(0,1));
ASSUME(meminit(0,3) == mem(0,2));
ASSUME(coinit(0,3) == co(0,2));
ASSUME(deltainit(0,3) == delta(0,2));
ASSUME(meminit(0,4) == mem(0,3));
ASSUME(coinit(0,4) == co(0,3));
ASSUME(deltainit(0,4) == delta(0,3));
ASSUME(meminit(1,1) == mem(1,0));
ASSUME(coinit(1,1) == co(1,0));
ASSUME(deltainit(1,1) == delta(1,0));
ASSUME(meminit(1,2) == mem(1,1));
ASSUME(coinit(1,2) == co(1,1));
ASSUME(deltainit(1,2) == delta(1,1));
ASSUME(meminit(1,3) == mem(1,2));
ASSUME(coinit(1,3) == co(1,2));
ASSUME(deltainit(1,3) == delta(1,2));
ASSUME(meminit(1,4) == mem(1,3));
ASSUME(coinit(1,4) == co(1,3));
ASSUME(deltainit(1,4) == delta(1,3));
ASSUME(meminit(2,1) == mem(2,0));
ASSUME(coinit(2,1) == co(2,0));
ASSUME(deltainit(2,1) == delta(2,0));
ASSUME(meminit(2,2) == mem(2,1));
ASSUME(coinit(2,2) == co(2,1));
ASSUME(deltainit(2,2) == delta(2,1));
ASSUME(meminit(2,3) == mem(2,2));
ASSUME(coinit(2,3) == co(2,2));
ASSUME(deltainit(2,3) == delta(2,2));
ASSUME(meminit(2,4) == mem(2,3));
ASSUME(coinit(2,4) == co(2,3));
ASSUME(deltainit(2,4) == delta(2,3));
ASSUME(meminit(3,1) == mem(3,0));
ASSUME(coinit(3,1) == co(3,0));
ASSUME(deltainit(3,1) == delta(3,0));
ASSUME(meminit(3,2) == mem(3,1));
ASSUME(coinit(3,2) == co(3,1));
ASSUME(deltainit(3,2) == delta(3,1));
ASSUME(meminit(3,3) == mem(3,2));
ASSUME(coinit(3,3) == co(3,2));
ASSUME(deltainit(3,3) == delta(3,2));
ASSUME(meminit(3,4) == mem(3,3));
ASSUME(coinit(3,4) == co(3,3));
ASSUME(deltainit(3,4) == delta(3,3));
ASSERT(r10== 0);
}
| [
"tuan-phong.ngo@it.uu.se"
] | tuan-phong.ngo@it.uu.se |
405edb57a33dc571afc6acbcdea840072bb35006 | 52cbf6068b0005d64172460ff7082e4c71f89e5e | /c++/617_merge_two_binary_trees.cpp | 8da9ca0f27bb919d526e719f918c3d202d9e5ea4 | [] | no_license | hatlonely/leetcode-2018 | d2efe08b86871735b1c48697adb9347501df7c08 | 57217059f04898cb41b76682e94f401ee4839d05 | refs/heads/master | 2021-12-09T02:03:38.983512 | 2021-10-31T03:52:23 | 2021-10-31T03:52:23 | 144,447,729 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 547 | cpp | #include <gtest/gtest.h>
#include <iostream>
#include "treenode.hpp"
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if (t1 == nullptr) {
return t2;
}
if (t2 == nullptr) {
return t1;
}
t1->val += t2->val;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
return t1;
}
};
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | [
"hatlonely@gmail.com"
] | hatlonely@gmail.com |
f86669711a6cb5cbbab200383d52425c4e125c7c | d1e2c8c580e7624019786b267cea24e092863819 | /signupwindow.cpp | 1cb0a7f7d0cc97ee63953767f22200d8d430e9ac | [] | no_license | FigueroaCode/Scribble | 893716f75eebac80b071b1ffcfe5c1650de6de2d | 84d7defce62e634c411dbb0e3b8e03792616b184 | refs/heads/master | 2021-01-22T22:43:58.518139 | 2017-04-21T16:41:13 | 2017-04-21T16:41:13 | 85,568,410 | 1 | 3 | null | 2017-04-15T18:38:04 | 2017-03-20T11:20:52 | C++ | UTF-8 | C++ | false | false | 1,287 | cpp | #include "signupwindow.h"
#include "ui_signupwindow.h"
#include "mainwindow.h"
#include "registerwindow.h"
#include <QDir>
#include <QMessageBox>
#include "getdirectorywindow.h"
#include <QFileInfo>
#include <QFile>
SignUpWindow::SignUpWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::SignUpWindow)
{
ui->setupUi(this);
dirPath = "";
QString pathname = QDir::homePath()+"/StateInfo/Directory_Path.txt";
if(QFileInfo::exists(pathname)){
QFile file(pathname);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
dirPath = file.readAll();
file.close();
}else{
GetDirectoryWindow window;
window.setModal(true);
window.exec();
}
}
SignUpWindow::~SignUpWindow()
{
delete ui;
}
void SignUpWindow::on_signInBtn_clicked()
{
//TODO:Need to check if they already set their project directory using database
// --close Window--
close();
// ----Open Main Window if sign in successful----
MainWindow window;
window.setModal(true);
window.exec();
}
void SignUpWindow::on_signUpBtn_clicked()
{
// --close Window--
close();
// ----Open Register Window----
RegisterWindow window;
window.setModal(true);
window.exec();
}
| [
"debrianfigueroa@gmail.com"
] | debrianfigueroa@gmail.com |
3433ddf0c4a587781017168b2c28049c8f6725a0 | b0ba659ac7dd2f52c5c7f17d8c7f3f138c992730 | /test/CFcoding/OthersQuestions/presearon-round-3/3.cpp | 9930915dc20d2ff0c60475608cc7a30be9f90be7 | [] | no_license | CutIce/kraken | ee0fb6872901a9d2ae57792b45f503793e11fefc | 37e3076d804bcd00a58a7a2dd9c4291c4961198c | refs/heads/master | 2023-02-25T04:50:25.687233 | 2021-02-01T01:50:09 | 2021-02-01T01:50:09 | 254,654,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 334 | cpp | #include <bits/stdc++.h>
using namespace std;
const int mo = 1e9 + 7;
int power(int x, int m) {
int nowans = 1;
while(m) {
if(m & 1)nowans = 1ll * nowans * x % mo;
x = 1ll * x * x % mo;
m >>= 1;
}
return nowans;
}
int main() {
int n;
scanf("%d", &n);
int ans = 1ll * n * power(2, n - 1) % mo;
printf("%d\n", ans);
}
| [
"1031941295@qq.com"
] | 1031941295@qq.com |
36a0990228c4d75b29fc0fcff409bedf53626d50 | af684bcf962b88e2bbc46d8dd96df320f8769d98 | /NeiGin/srcExt/NeiCore/src/Log.h | cc0403a839bc625cdc2c9f88f51764fa7aa046b0 | [] | no_license | neithy/NeiGinPublic | 08aa733fa34675e93acb7a0e9856a46c339014d2 | f955d6d6a9c26a42383508a6b359a3cf5c575a5f | refs/heads/master | 2020-09-30T18:12:27.083154 | 2020-01-13T02:32:12 | 2020-01-13T02:32:12 | 227,344,818 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,579 | h | #pragma once
#include "Export.h"
#include "spdlog/spdlog.h"
#define nei_debug(...) {Nei::Logger::getInstance().debug(__VA_ARGS__);}
#define nei_info(...) {Nei::Logger::getInstance().info(__VA_ARGS__);}
#define nei_log nei_info
#define nei_warning(...) {Nei::Logger::getInstance().warning(__VA_ARGS__);}
#define nei_error(...) {Nei::Logger::getInstance().error(__VA_ARGS__);__debugbreak();}
#define nei_fatal(...) {Nei::Logger::getInstance().error(__VA_ARGS__);__debugbreak();exit(-1);}
#define nei_warning_once(...) {static bool once=true; if(once){once = false;nei_warning(__VA_ARGS__); } }
#define nei_nyi { nei_error("Not yet implemented");}
#if defined(DEBUG) || defined(RELEASE_ASSERT)
#define nei_assertm(exp, msg) {if (!(exp)) nei_error("Assert failed: {}",msg); }
#define nei_assert(exp) nei_assertm(exp,#exp)
#else
#define nei_assert(exp)
#define nei_assertm(exp, msg)
#endif
namespace Nei {
class NEICORE_EXPORT Logger {
public:
Logger();
template <typename... Args>
void debug(Args ...args) {
spdlog::debug(args...);
}
template <typename... Args>
void info(Args ...args) {
spdlog::info(args...);
}
template <typename... Args>
void error(Args ...args) {
spdlog::error(args...);
}
template <typename... Args>
void warning(Args ...args) {
spdlog::warn(args...);
}
template <typename... Args>
void fatal(Args ...args) {
spdlog::error(args...);
exit(-1);
}
static auto& getInstance() { return instance; }
protected:
static Logger instance;
};
}
| [
"neithy.cz@gmail.com"
] | neithy.cz@gmail.com |
6b4ce49e85d69adcd63ab0cd0ed7aeb1020448cb | c0faf45174c54e903bc8e11daea57ab830338957 | /Lab12_Table_redo/main.cpp | 6da08379bbaad201793bb4f16d2bdfe0d2316e88 | [] | no_license | jwalter229/CS3304 | 53992c32d4ce10f4a681c7446aede96e6ba077b7 | fbc2c4741b9d4f94b21b3a883488a7f27148cce6 | refs/heads/master | 2020-03-26T22:09:23.922493 | 2018-08-20T15:37:26 | 2018-08-20T15:37:26 | 145,435,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,706 | cpp | #include <iostream>
#include "table1.h"
#include <cassert>
using namespace std;
using namespace main_savitch_12A;
struct record_type
{
int key;
string value;
};
int main() {
table<record_type> t1;
//same hash worst case
for(int i=0; i<1024; i++) {
record_type r1;
r1.key=i*1024;
r1.value="This is value for key " + to_string(i);
t1.insert(r1);
}
assert(t1.size()==1024);
for(int i=0; i<1024; i++) {
t1.remove(i*1024);
record_type myR;
bool found;
t1.find(i,found,myR);
assert(!found);
}
assert(t1.size()==0);
//double duplicates of each
for(int i=0; i<2048; i+=2) {
record_type r1;
r1.key=i;
r1.value="This is value for key " + to_string(r1.key);
t1.insert(r1);
record_type myR;
bool found;
t1.find(i,found,myR);
assert(found);
}
assert(t1.size()==1024);
for(int i=0; i<2048; i+=2) {
t1.remove(i);
record_type myR;
bool found;
t1.find(i,found,myR);
assert(!found);
}
assert(t1.size()==0);
//best case
for(int i=0; i<1024; i++) {
record_type r1;
r1.key=i;//200 unique numbers
r1.value="This is value for key " + to_string(r1.key);
t1.insert(r1);
record_type myR;
bool found;
t1.find(i,found,myR);
assert(found);
}
assert(t1.size()==1024);
for(int i=0; i<1024; i++) {
t1.remove(i);
record_type myR;
bool found;
t1.find(i,found,myR);
assert(!found);
}
assert(t1.size()==0);
cout<<"All Test passed";
return 0;
}
| [
"jwalter229@gmail.com"
] | jwalter229@gmail.com |
81151c875474c65325477cef1b62cef5e7afbd6c | 7b4b089b84df2f4cd721cc7d7bc79b36cb3f526f | /Cliente-BdD/src/ipc/ExclusiveLockFile.cpp | 030075dbba75c25d5c39f5e50c2d5ce949a1454c | [] | no_license | juanmanuelbouvier/Concurrente-TP2 | ea948c39c297c87b3c71903944236514ae9c4134 | caad0e12c65ddef472baaf9a2b2d237727557c70 | refs/heads/master | 2021-01-21T17:57:38.278972 | 2017-06-22T02:37:38 | 2017-06-22T02:37:38 | 92,003,830 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,389 | cpp |
#include "../../include/ipc/ExclusiveLockFile.h"
ExclusiveLockFile :: ExclusiveLockFile ( const string nombre ) {
this->nombre = nombre;
this->fl.l_type = F_WRLCK;
this->fl.l_whence = SEEK_SET;
this->fl.l_start = 0;
this->fl.l_len = 0;
crearDirectorioSiNoExiste(nombre);
this->fd = open ( this->nombre.c_str(),O_CREAT|O_WRONLY,0777 );
}
int ExclusiveLockFile :: tomarLock () {
this->fl.l_type = F_WRLCK;
return fcntl ( this->fd,F_SETLKW,&(this->fl) );
}
int ExclusiveLockFile :: liberarLock () {
this->fl.l_type = F_UNLCK;
return fcntl ( this->fd,F_SETLK,&(this->fl) );
}
ssize_t ExclusiveLockFile :: escribir ( const void* buffer,const ssize_t buffsize ) const {
lseek ( this->fd,0,SEEK_END );
return write ( this->fd,buffer,buffsize );
}
ssize_t ExclusiveLockFile :: remplazar ( const void* buffer,const ssize_t buffsize ) const {
lseek ( this->fd,0,SEEK_SET );
return write ( this->fd,buffer,buffsize );
}
ExclusiveLockFile :: ~ExclusiveLockFile () {
close ( this->fd );
}
int ExclusiveLockFile::crearDirectorioSiNoExiste(string rutaCompletaArchivo) {
string path = rutaCompletaArchivo.substr(0, rutaCompletaArchivo.find_last_of("\\/"));
DIR* dir = opendir(path.c_str());
if (dir) {
return closedir(dir);
}
else if (ENOENT == errno) {
return mkdir(path.c_str(), 0777);
}
} | [
"juanmabouvier@gmail.com"
] | juanmabouvier@gmail.com |
2cabf7d257b151e15ea96fc8cb70896d4c5a0460 | f8517de40106c2fc190f0a8c46128e8b67f7c169 | /AllJoyn/Samples/MyLivingRoom/Models/org.alljoyn.ControlPanel/PropertyProducer.cpp | e30612e4caf15861c1a5de32ae8de05354117ae7 | [
"MIT"
] | permissive | ferreiramarcelo/samples | eb77df10fe39567b7ebf72b75dc8800e2470108a | 4691f529dae5c440a5df71deda40c57976ee4928 | refs/heads/develop | 2023-06-21T00:31:52.939554 | 2021-01-23T16:26:59 | 2021-01-23T16:26:59 | 66,746,116 | 0 | 0 | MIT | 2023-06-19T20:52:43 | 2016-08-28T02:48:20 | C | UTF-8 | C++ | false | false | 12,471 | cpp | #include "pch.h"
using namespace concurrency;
using namespace Microsoft::WRL;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Devices::AllJoyn;
using namespace org::alljoyn::ControlPanel;
std::map<alljoyn_busobject, WeakReference*> PropertyProducer::SourceObjects;
std::map<alljoyn_interfacedescription, WeakReference*> PropertyProducer::SourceInterfaces;
PropertyProducer::PropertyProducer(AllJoynBusAttachment^ busAttachment)
: m_busAttachment(busAttachment),
m_sessionListener(nullptr),
m_busObject(nullptr),
m_sessionPort(0),
m_sessionId(0)
{
m_weak = new WeakReference(this);
ServiceObjectPath = ref new String(L"/Service");
m_signals = ref new PropertySignals();
m_busAttachmentStateChangedToken.Value = 0;
}
PropertyProducer::~PropertyProducer()
{
UnregisterFromBus();
delete m_weak;
}
void PropertyProducer::UnregisterFromBus()
{
if ((nullptr != m_busAttachment) && (0 != m_busAttachmentStateChangedToken.Value))
{
m_busAttachment->StateChanged -= m_busAttachmentStateChangedToken;
m_busAttachmentStateChangedToken.Value = 0;
}
if (nullptr != SessionPortListener)
{
alljoyn_busattachment_unbindsessionport(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), m_sessionPort);
alljoyn_sessionportlistener_destroy(SessionPortListener);
SessionPortListener = nullptr;
}
if (nullptr != BusObject)
{
alljoyn_busattachment_unregisterbusobject(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject);
alljoyn_busobject_destroy(BusObject);
BusObject = nullptr;
}
if (nullptr != SessionListener)
{
alljoyn_sessionlistener_destroy(SessionListener);
SessionListener = nullptr;
}
}
bool PropertyProducer::OnAcceptSessionJoiner(_In_ alljoyn_sessionport sessionPort, _In_ PCSTR joiner, _In_ const alljoyn_sessionopts opts)
{
UNREFERENCED_PARAMETER(sessionPort); UNREFERENCED_PARAMETER(joiner); UNREFERENCED_PARAMETER(opts);
return true;
}
void PropertyProducer::OnSessionJoined(_In_ alljoyn_sessionport sessionPort, _In_ alljoyn_sessionid id, _In_ PCSTR joiner)
{
UNREFERENCED_PARAMETER(joiner);
// We initialize the Signals object after the session has been joined, because it needs
// the session id.
m_signals->Initialize(BusObject, id);
m_sessionPort = sessionPort;
m_sessionId = id;
alljoyn_sessionlistener_callbacks callbacks =
{
AllJoynHelpers::SessionLostHandler<PropertyProducer>,
AllJoynHelpers::SessionMemberAddedHandler<PropertyProducer>,
AllJoynHelpers::SessionMemberRemovedHandler<PropertyProducer>
};
SessionListener = alljoyn_sessionlistener_create(&callbacks, m_weak);
alljoyn_busattachment_setsessionlistener(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), id, SessionListener);
}
void PropertyProducer::OnSessionLost(_In_ alljoyn_sessionid sessionId, _In_ alljoyn_sessionlostreason reason)
{
if (sessionId == m_sessionId)
{
AllJoynSessionLostEventArgs^ args = ref new AllJoynSessionLostEventArgs(static_cast<AllJoynSessionLostReason>(reason));
SessionLost(this, args);
}
}
void PropertyProducer::OnSessionMemberAdded(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
{
if (sessionId == m_sessionId)
{
auto args = ref new AllJoynSessionMemberAddedEventArgs(AllJoynHelpers::MultibyteToPlatformString(uniqueName));
SessionMemberAdded(this, args);
}
}
void PropertyProducer::OnSessionMemberRemoved(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
{
if (sessionId == m_sessionId)
{
auto args = ref new AllJoynSessionMemberRemovedEventArgs(AllJoynHelpers::MultibyteToPlatformString(uniqueName));
SessionMemberRemoved(this, args);
}
}
void PropertyProducer::BusAttachmentStateChanged(_In_ AllJoynBusAttachment^ sender, _In_ AllJoynBusAttachmentStateChangedEventArgs^ args)
{
if (args->State == AllJoynBusAttachmentState::Connected)
{
QStatus result = AllJoynHelpers::CreateProducerSession<PropertyProducer>(m_busAttachment, m_weak);
if (ER_OK != result)
{
StopInternal(result);
return;
}
}
else if (args->State == AllJoynBusAttachmentState::Disconnected)
{
StopInternal(ER_BUS_STOPPING);
}
}
void PropertyProducer::CallMetadataChangedSignalHandler(_In_ const alljoyn_interfacedescription_member* member, _In_ alljoyn_message message)
{
auto source = SourceInterfaces.find(member->iface);
if (source == SourceInterfaces.end())
{
return;
}
auto producer = source->second->Resolve<PropertyProducer>();
if (producer->Signals != nullptr)
{
auto callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message)));
auto eventArgs = ref new PropertyMetadataChangedReceivedEventArgs();
eventArgs->MessageInfo = callInfo;
producer->Signals->CallMetadataChangedReceived(producer->Signals, eventArgs);
}
}
void PropertyProducer::CallValueChangedSignalHandler(_In_ const alljoyn_interfacedescription_member* member, _In_ alljoyn_message message)
{
auto source = SourceInterfaces.find(member->iface);
if (source == SourceInterfaces.end())
{
return;
}
auto producer = source->second->Resolve<PropertyProducer>();
if (producer->Signals != nullptr)
{
auto callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message)));
auto eventArgs = ref new PropertyValueChangedReceivedEventArgs();
eventArgs->MessageInfo = callInfo;
producer->Signals->CallValueChangedReceived(producer->Signals, eventArgs);
}
}
QStatus PropertyProducer::AddMethodHandler(_In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_methodhandler_ptr handler)
{
alljoyn_interfacedescription_member member;
if (!alljoyn_interfacedescription_getmember(interfaceDescription, methodName, &member))
{
return ER_BUS_INTERFACE_NO_SUCH_MEMBER;
}
return alljoyn_busobject_addmethodhandler(
m_busObject,
member,
handler,
m_weak);
}
QStatus PropertyProducer::AddSignalHandler(_In_ alljoyn_busattachment busAttachment, _In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_signalhandler_ptr handler)
{
alljoyn_interfacedescription_member member;
if (!alljoyn_interfacedescription_getmember(interfaceDescription, methodName, &member))
{
return ER_BUS_INTERFACE_NO_SUCH_MEMBER;
}
return alljoyn_busattachment_registersignalhandler(busAttachment, handler, member, NULL);
}
QStatus PropertyProducer::OnPropertyGet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _Inout_ alljoyn_msgarg value)
{
UNREFERENCED_PARAMETER(interfaceName);
if (0 == strcmp(propertyName, "Version"))
{
auto task = create_task(Service->GetVersionAsync(nullptr));
auto result = task.get();
if (AllJoynStatus::Ok != result->Status)
{
return static_cast<QStatus>(result->Status);
}
return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "q", result->Version));
}
if (0 == strcmp(propertyName, "States"))
{
auto task = create_task(Service->GetStatesAsync(nullptr));
auto result = task.get();
if (AllJoynStatus::Ok != result->Status)
{
return static_cast<QStatus>(result->Status);
}
return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "u", result->States));
}
if (0 == strcmp(propertyName, "OptParams"))
{
auto task = create_task(Service->GetOptParamsAsync(nullptr));
auto result = task.get();
if (AllJoynStatus::Ok != result->Status)
{
return static_cast<QStatus>(result->Status);
}
return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "a{qv}", result->OptParams));
}
if (0 == strcmp(propertyName, "Value"))
{
auto task = create_task(Service->GetValueAsync(nullptr));
auto result = task.get();
if (AllJoynStatus::Ok != result->Status)
{
return static_cast<QStatus>(result->Status);
}
return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "v", result->Value));
}
return ER_BUS_NO_SUCH_PROPERTY;
}
QStatus PropertyProducer::OnPropertySet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg value)
{
UNREFERENCED_PARAMETER(interfaceName);
if (0 == strcmp(propertyName, "Value"))
{
Platform::Object^ argument;
TypeConversionHelpers::GetAllJoynMessageArg(value, "v", &argument);
auto task = create_task(Service->SetValueAsync(nullptr, argument));
return static_cast<QStatus>(task.get());
}
return ER_BUS_NO_SUCH_PROPERTY;
}
void PropertyProducer::Start()
{
if (nullptr == m_busAttachment)
{
StopInternal(ER_FAIL);
return;
}
QStatus result = AllJoynHelpers::CreateInterfaces(m_busAttachment, c_PropertyIntrospectionXml);
if (result != ER_OK)
{
StopInternal(result);
return;
}
result = AllJoynHelpers::CreateBusObject<PropertyProducer>(m_weak);
if (result != ER_OK)
{
StopInternal(result);
return;
}
alljoyn_interfacedescription interfaceDescription = alljoyn_busattachment_getinterface(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), "org.alljoyn.ControlPanel.Property");
if (interfaceDescription == nullptr)
{
StopInternal(ER_FAIL);
return;
}
alljoyn_busobject_addinterface_announced(BusObject, interfaceDescription);
result = AddSignalHandler(
AllJoynHelpers::GetInternalBusAttachment(m_busAttachment),
interfaceDescription,
"MetadataChanged",
[](const alljoyn_interfacedescription_member* member, PCSTR srcPath, alljoyn_message message) { UNREFERENCED_PARAMETER(srcPath); CallMetadataChangedSignalHandler(member, message); });
if (result != ER_OK)
{
StopInternal(result);
return;
}
result = AddSignalHandler(
AllJoynHelpers::GetInternalBusAttachment(m_busAttachment),
interfaceDescription,
"ValueChanged",
[](const alljoyn_interfacedescription_member* member, PCSTR srcPath, alljoyn_message message) { UNREFERENCED_PARAMETER(srcPath); CallValueChangedSignalHandler(member, message); });
if (result != ER_OK)
{
StopInternal(result);
return;
}
SourceObjects[m_busObject] = m_weak;
SourceInterfaces[interfaceDescription] = m_weak;
result = alljoyn_busattachment_registerbusobject(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject);
if (result != ER_OK)
{
StopInternal(result);
return;
}
m_busAttachmentStateChangedToken = m_busAttachment->StateChanged += ref new TypedEventHandler<AllJoynBusAttachment^,AllJoynBusAttachmentStateChangedEventArgs^>(this, &PropertyProducer::BusAttachmentStateChanged);
m_busAttachment->Connect();
}
void PropertyProducer::Stop()
{
StopInternal(AllJoynStatus::Ok);
}
void PropertyProducer::StopInternal(int32 status)
{
UnregisterFromBus();
Stopped(this, ref new AllJoynProducerStoppedEventArgs(status));
}
int32 PropertyProducer::RemoveMemberFromSession(_In_ String^ uniqueName)
{
return alljoyn_busattachment_removesessionmember(
AllJoynHelpers::GetInternalBusAttachment(m_busAttachment),
m_sessionId,
AllJoynHelpers::PlatformToMultibyteString(uniqueName).data());
}
PCSTR org::alljoyn::ControlPanel::c_PropertyIntrospectionXml = "<interface name=\"org.alljoyn.ControlPanel.Property\">"
" <property name=\"Version\" type=\"q\" access=\"read\" />"
" <property name=\"States\" type=\"u\" access=\"read\" />"
" <property name=\"OptParams\" type=\"a{qv}\" access=\"read\" />"
" <property name=\"Value\" type=\"v\" access=\"readwrite\" />"
" <signal name=\"MetadataChanged\" />"
" <signal name=\"ValueChanged\" type=\"v\" />"
"</interface>"
;
| [
"artemz@microsoft.com"
] | artemz@microsoft.com |
2494839771935131d51d45294ddfd89a0951d368 | 07adbe63c171e036e19b31b5e43d84f853c85fd7 | /debugger/xtalhighlighter.h | a1dffbb5c568d4b465196bed025a2c892e65b9d7 | [
"Zlib",
"MIT"
] | permissive | jamesu/xtal-language | ccab2e9dff74b8ccc8d7ce61cc5ffa5fa2b918b0 | c90c41fe28d37514907501503b3f8dd075909812 | refs/heads/master | 2016-09-05T12:01:10.131598 | 2013-11-14T06:30:08 | 2013-11-14T06:30:08 | 34,965,315 | 0 | 1 | null | null | null | null | SHIFT_JIS | C++ | false | false | 841 | h | #ifndef XTALHIGHLIGHTER_H
#define XTALHIGHLIGHTER_H
#include <QtGui>
#include <QPlainTextEdit>
#include <QObject>
/**
* \brief Xtalのシンタックスハイライタ
*/
class XtalHighlighter : public QSyntaxHighlighter{
Q_OBJECT
public:
XtalHighlighter(QTextDocument *parent = 0);
protected:
void highlightBlock(const QString &text);
private:
struct HighlightingRule{
QRegExp pattern;
QTextCharFormat format;
};
QVector<HighlightingRule> highlightingRules_;
QRegExp commentStartExpression_;
QRegExp commentEndExpression_;
QTextCharFormat keywordFormat_;
QTextCharFormat classFormat_;
QTextCharFormat singlelineCommentFormat_;
QTextCharFormat multilineCommentFormat_;
QTextCharFormat quotationFormat_;
QTextCharFormat numberFormat_;
};
#endif // XTALHIGHLIGHTER_H
| [
"dofixx@2a538ec3-9d2e-0410-833a-dbe6a5d41180"
] | dofixx@2a538ec3-9d2e-0410-833a-dbe6a5d41180 |
f1e6a11c79e138c173a5b60a6cf0142bcfb43227 | b3505199d1dc87c93efb7523c60c6ce8b1353e3e | /Important Algorithm (Dip Vai)/Important Algorithms BY DIP VAI/Dp variation/Montonous Queue + Convext Hull Trick/Commando_APIO2010.cpp | f44e66f31205f84f7d918b5da29d78a5ed5e2fb8 | [] | no_license | habibrahmanbd/Code-Lab | ee3fee907fd364d693cb733aa20e50aef17e360d | e22635aba137c73fb0d25dd9df75667dd1b1d74f | refs/heads/master | 2021-01-02T23:08:51.674572 | 2019-01-17T16:57:27 | 2019-01-17T16:57:27 | 99,474,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,271 | cpp | /**
APIO 2010 Commando
You are the commander of a troop ofnsoldiers, numbered from 1 to n.
For the battle ahead, you plan to divide thesensoldiers into several com-mando units.
To promote unity and boost morale, each unit will
consist of
a contiguous sequence of soldiers of the form (i, i+1, . . . , i+k).
Each soldieri has a battle effectiveness ratingx
i
. Originally, the battle
effectivenessxof a commando unit (i, i+1, . . . , i+k) was computed by adding
up the individual battle effectiveness of the soldiers in the unit. In other
words,x=x
i +x
i+1+· · · +x
i+k
.
However, years of glorious victories have led you to conclude that the
battle effectiveness of a unit should be adjusted as follows: the adjusted
effectivenessx
0
is computed by using the equation x
0
=ax
2
+bx+c, where a,
b, care known coefficients(a <0),xis the original effectiveness of the unit.
Your task as commander is to divide your soldiers into commando units
in order to maximize the sum of the adjusted effectiveness of all the units.
For instance, suppose you have 4 soldiers,x
1
= 2, x
2
= 2, x
3
= 3, x
4
= 4.
Further, let the coefficients for the equation to adjust the battle effectiveness
of a unit bea=−1,b = 10,c=−20. In this case, the best solution is to
divide the soldiers into three commando units: The first unit contains soldiers
1 and 2, the second unit contains soldier 3, and the third unit contains soldier
4. The battle effectiveness of the three units are 4, 3, 4 respectively, and the
adjusted effectiveness are 4, 1, 4 respectively. The total adjusted effectiveness
for this grouping is 9 and it can be checked that no better solution is possible.
Input format
The input consists of three lines. The first line contains a positive integer
n, the total number of soldiers. The second line contains 3 integers a, b,
andc, the coefficients for the equation to adjust the battle effectiveness of
a commando unit. The last line containsnintegers x
1
, x
2
, . . . , x
n
, sepa-rated by spaces, representing the battle effectiveness of soldiers 1, 2, . . . ,n,
respectively.
Output format
A single line with an integer indicating the maximum adjusted effectiveness
achievable.
*/
//#pragma comment(linker, "/STACK:60000000")
#include <iostream>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <set>
#include <cmath>
#include <cstring>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <stdlib.h>
#include <vector>
#include <iomanip>
#include <ctime>
#include <assert.h>
using namespace std;
//Type Definition
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<vi>vvi;
typedef vector<string> vs;
typedef map<string,int> msi;
typedef map<int,int>mii;
#define ERR 1e-9
#define PI 3.141592653589793
#define REP(i,n) for (i=0;i<n;i++)
#define FOR(i,p,k) for (i=p; i<k;i++)
#define FOREACH(it,x) for(__typeof((x).begin()) it=(x.begin()); it!=(x).end(); ++it)
#define Sort(x) sort(x.begin(),x.end())
#define Reverse(x) reverse(x.begin(),x.end())
#define MP(a,b) make_pair(a,b)
#define Clear(x,with) memset(x,with,sizeof(x))
#define SZ(x) (int)x.size()
#define pb push_back
#define popcount(i) __builtin_popcount(i)
#define gcd(a,b) __gcd(a,b)
#define lcm(a,b) ((a)*((b)/gcd(a,b)))
#define two(X) (1<<(X))
#define twoL(X) (((ll)(1))<<(X))
#define setBit(mask,i) (mask|two(i))
#define contain(S,X) (((S)&two(X))!=0)
#define fs first
#define sc second
#define CS c_str()
#define EQ(a,b) (fabs(a-b)<ERR)
#define Unique(store) store.resize(unique(store.begin(),store.end())-store.begin());
#define Find(x,y) ((int)x.find(y))
//For debugging
#define debug_array(a,n) for(ll i=0;i<n;i++) cerr<<a[i]<<" "; cerr<<endl;
#define debug_matrix(mat,row,col) for(ll i=0;i<row;i++) {for(ll j=0;j<col;j++) cerr<<mat[i][j]<<" ";cerr<<endl;}
#define debug(args...) {dbg,args; cerr<<endl;}
struct debugger{template<typename T> debugger& operator , (const T& v){cerr<<v<<"\t"; return *this; }}dbg;
//Important Functions
template<class T> void setmax(T &a, T b) { if(a < b) a = b; }
template<class T> void setmin(T &a, T b) { if(b < a) a = b; }
template<class T> T Abs(T x) {return x > 0 ? x : -x;}
template<class T> inline T sqr(T x){return x*x;}
template<class T> inline T Mod(T n,T m) {return (n%m+m)%m;} //For Positive Negative No.
template<class T> string toString(T n){ostringstream oss;oss<<n;oss.flush();return oss.str();}
ll toInt(string s){ll r=0;istringstream sin(s);sin>>r;return r;}
bool isVowel(char ch){ch=tolower(ch);if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')return true;return false;}
bool isUpper(char c){return c>='A' && c<='Z';}
bool isLower(char c){return c>='a' && c<='z';}
ll Pow(ll B,ll P){ ll R=1; while(P>0) {if(P%2==1) R=(R*B);P/=2;B=(B*B);}return R;}
ll BigMod(ll B,ll P,ll M){ ll R=1; while(P>0) {if(P%2==1){R=(R*B)%M;}P/=2;B=(B*B)%M;} return R;}
void binprint(ll mask,ll n){ll i;string s="";do{s+=(mask%2+'0');mask/=2;}while(mask);Reverse(s);s=string(max(n-SZ(s),0LL),'0')+s;for(i=SZ(s)-n;i<SZ(s);i++) printf("%c",s[i]);printf("\n");}
//void ASCII_Chart(){ll i,j,k;printf("ASCII Chart:(30-129)\n");FOR(i,30,50){REP(j,5){k=i+j*20;printf("%3d---> '%c' ",k,k);}printf("\n");}}
//int month[]={-1,31,28,31,30,31,30,31,31,30,31,30,31}; //Not Leap Year
//int dx[]={1,0,-1,0};int dy[]={0,1,0,-1}; //4 Direction
//int dx[]={1,1,0,-1,-1,-1,0,1};int dy[]={0,1,1,1,0,-1,-1,-1};//8 direction
//int dx[]={2,1,-1,-2,-2,-1,1,2};int dy[]={1,2,2,1,-1,-2,-2,-1};//Knight Direction
//int dx[]={-1,-1,+0,+1,+1,+0};int dy[]={-1,+1,+2,+1,-1,-2}; //Hexagonal Direction
//#include<conio.h> //for using getch();
//struct edge{ int cost,node; edge(int _cost=0,int _node=0){cost=_cost;node=_node;}bool operator<(const edge &b)const {return cost>b.cost;}}; // Min Priority Queue
//bool comp(edge a,edge b){ return a.cost < b.cost;} //Asc Sort by cost
#define INF (1<<28)
#define SIZE 1100000
ll dp[SIZE],arr[SIZE],sum[SIZE];
vector<ll>M,B;
int pointer;
//Returns true if either line l1 or line l3 is always better than line l2
bool bad(int l1,int l2,int l3)
{
/*
intersection(l1,l2) has x-coordinate (b1-b2)/(m2-m1)
intersection(l1,l3) has x-coordinate (b1-b3)/(m3-m1)
set the former greater than the latter, and cross-multiply to
eliminate division
*/
return (B[l3]-B[l1])*(M[l1]-M[l2])<(B[l2]-B[l1])*(M[l1]-M[l3]);
}
void add(long long m,long long b)
{
//First, let's add it to the end
M.push_back(m);
B.push_back(b);
//If the penultimate is now made irrelevant between the antepenultimate
//and the ultimate, remove it. Repeat as many times as necessary
while (M.size()>=3&&bad(M.size()-3,M.size()-2,M.size()-1))
{
M.erase(M.end()-2);
B.erase(B.end()-2);
}
}
//Returns the minimum y-coordinate of any intersection between a given vertical
//line and the lower envelope
long long query(long long x)
{
//If we removed what was the best line for the previous query, then the
//newly inserted line is now the best for that query
if (pointer>=M.size())
pointer=M.size()-1;
//Any better line must be to the right, since query values are
//non-decreasing
while (pointer<M.size()-1 && M[pointer+1]*x+B[pointer+1]>M[pointer]*x+B[pointer]) // Max Value wanted...
pointer++;
return M[pointer]*x+B[pointer];
}
int main()
{
freopen("commando10.in","r",stdin);
freopen("commando10.out","w",stdout);
int i,j,test,Case=1;
ll N,a,b,c;
while(scanf("%lld",&N)==1)
{
scanf("%lld %lld %lld",&a,&b,&c);
for(i=1;i<=N;i++) scanf("%lld",&arr[i]);
Clear(sum,0);
for(i=1;i<=N;i++) sum[i]=sum[i-1]+arr[i];
Clear(dp,0);
dp[1]=a*sum[1]*sum[1]+b*sum[1]+c;
add(-2*a*sum[1],dp[1]+a*sum[1]*sum[1]-b*sum[1]); //here a is negative
for(i=2;i<=N;i++)
{
dp[i]=a*sum[i]*sum[i]+b*sum[i]+c;
dp[i]=max(dp[i],query(sum[i])+a*sum[i]*sum[i]+b*sum[i]+c);
add(-2*a*sum[i],dp[i]+a*sum[i]*sum[i]-b*sum[i]);
}
printf("%lld\n",dp[N]);
}
return 0;
}
| [
"bdhabib94@gmail.com"
] | bdhabib94@gmail.com |
7d34cddfa6fdb5c59ed035e600d8b38aebaf7c47 | 3e1ac5a6f5473c93fb9d4174ced2e721a7c1ff4c | /build/iOS/Preview/include/Fuse.FileSystem.FileSystemModule.h | 0b16d2112c3a88d60a355ed2352aca51fe4fcdd9 | [] | no_license | dream-plus/DreamPlus_popup | 49d42d313e9cf1c9bd5ffa01a42d4b7c2cf0c929 | 76bb86b1f2e36a513effbc4bc055efae78331746 | refs/heads/master | 2020-04-28T20:47:24.361319 | 2019-05-13T12:04:14 | 2019-05-13T12:04:14 | 175,556,703 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,742 | h | // This file was generated based on /usr/local/share/uno/Packages/Fuse.FileSystem/1.9.0/FileSystemModule.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Scripting.IModuleProvider.h>
#include <Fuse.Scripting.NativeModule.h>
#include <Uno.IDisposable.h>
namespace g{namespace Fuse{namespace FileSystem{struct FileSystemModule;}}}
namespace g{namespace Fuse{namespace FileSystem{struct FileSystemOperations;}}}
namespace g{namespace Fuse{namespace FileSystem{struct Nothing;}}}
namespace g{namespace Fuse{namespace Scripting{struct Array;}}}
namespace g{namespace Fuse{namespace Scripting{struct Context;}}}
namespace g{namespace Fuse{namespace Scripting{struct Object;}}}
namespace g{namespace Uno{namespace Collections{struct Dictionary;}}}
namespace g{namespace Uno{namespace IO{struct FileSystemInfo;}}}
namespace g{namespace Uno{namespace Threading{struct Future1;}}}
namespace g{namespace Uno{namespace Time{struct ZonedDateTime;}}}
namespace g{
namespace Fuse{
namespace FileSystem{
// public sealed class FileSystemModule :43
// {
::g::Fuse::Scripting::NativeModule_type* FileSystemModule_typeof();
void FileSystemModule__ctor_2_fn(FileSystemModule* __this);
void FileSystemModule__AppendTextToFile_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__AppendTextToFileSync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__Copy_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__CopySync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__CreateDirectory_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__CreateDirectorySync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__Delete_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__DeleteSync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__Exists_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__ExistsSync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__GetArg_fn(uType* __type, uArray* args, int32_t* index, uString* error, uObject** __retval);
void FileSystemModule__GetCacheDirectory_fn(FileSystemModule* __this, uString** __retval);
void FileSystemModule__GetDataDirectory_fn(FileSystemModule* __this, uString** __retval);
void FileSystemModule__GetDirectoryInfo_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__GetDirectoryInfoSync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__GetFileInfo_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__GetFileInfoSync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__GetIosPaths_fn(FileSystemModule* __this, ::g::Uno::Collections::Dictionary** __retval);
void FileSystemModule__GetPathFromArgs_fn(uArray* args, uString** __retval);
void FileSystemModule__ListDirectories_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__ListDirectoriesSync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__ListEntries_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__ListEntriesSync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__ListFiles_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__ListFilesSync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__Move_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__MoveSync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__New2_fn(FileSystemModule** __retval);
void FileSystemModule__ReadBufferFromFile_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__ReadBufferFromFileSync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__ReadTextFromFile_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__ReadTextFromFileSync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__ToScriptingArray_fn(uType* __type, ::g::Fuse::Scripting::Context* context, uArray* sourceArray, ::g::Fuse::Scripting::Array** __retval);
void FileSystemModule__ToScriptingDate_fn(::g::Fuse::Scripting::Context* context, ::g::Uno::Time::ZonedDateTime* time, uObject** __retval);
void FileSystemModule__ToScriptingObject_fn(::g::Fuse::Scripting::Context* context, ::g::Uno::IO::FileSystemInfo* info, ::g::Fuse::Scripting::Object** __retval);
void FileSystemModule__ToScriptingObject1_fn(uType* __type, ::g::Fuse::Scripting::Context* context, ::g::Uno::Collections::Dictionary* dict, ::g::Fuse::Scripting::Object** __retval);
void FileSystemModule__WriteBufferToFile_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__WriteBufferToFileSync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
void FileSystemModule__WriteTextToFile_fn(FileSystemModule* __this, uArray* args, ::g::Uno::Threading::Future1** __retval);
void FileSystemModule__WriteTextToFileSync_fn(FileSystemModule* __this, ::g::Fuse::Scripting::Context* context, uArray* args, uObject** __retval);
struct FileSystemModule : ::g::Fuse::Scripting::NativeModule
{
static uSStrong<FileSystemModule*> _instance_;
static uSStrong<FileSystemModule*>& _instance() { return _instance_; }
uStrong< ::g::Fuse::FileSystem::FileSystemOperations*> _operations;
void ctor_2();
::g::Uno::Threading::Future1* AppendTextToFile(uArray* args);
uObject* AppendTextToFileSync(::g::Fuse::Scripting::Context* context, uArray* args);
::g::Uno::Threading::Future1* Copy(uArray* args);
uObject* CopySync(::g::Fuse::Scripting::Context* context, uArray* args);
::g::Uno::Threading::Future1* CreateDirectory(uArray* args);
uObject* CreateDirectorySync(::g::Fuse::Scripting::Context* context, uArray* args);
::g::Uno::Threading::Future1* Delete(uArray* args);
uObject* DeleteSync(::g::Fuse::Scripting::Context* context, uArray* args);
::g::Uno::Threading::Future1* Exists(uArray* args);
uObject* ExistsSync(::g::Fuse::Scripting::Context* context, uArray* args);
uString* GetCacheDirectory();
uString* GetDataDirectory();
::g::Uno::Threading::Future1* GetDirectoryInfo(uArray* args);
uObject* GetDirectoryInfoSync(::g::Fuse::Scripting::Context* context, uArray* args);
::g::Uno::Threading::Future1* GetFileInfo(uArray* args);
uObject* GetFileInfoSync(::g::Fuse::Scripting::Context* context, uArray* args);
::g::Uno::Collections::Dictionary* GetIosPaths();
::g::Uno::Threading::Future1* ListDirectories(uArray* args);
uObject* ListDirectoriesSync(::g::Fuse::Scripting::Context* context, uArray* args);
::g::Uno::Threading::Future1* ListEntries(uArray* args);
uObject* ListEntriesSync(::g::Fuse::Scripting::Context* context, uArray* args);
::g::Uno::Threading::Future1* ListFiles(uArray* args);
uObject* ListFilesSync(::g::Fuse::Scripting::Context* context, uArray* args);
::g::Uno::Threading::Future1* Move(uArray* args);
uObject* MoveSync(::g::Fuse::Scripting::Context* context, uArray* args);
::g::Uno::Threading::Future1* ReadBufferFromFile(uArray* args);
uObject* ReadBufferFromFileSync(::g::Fuse::Scripting::Context* context, uArray* args);
::g::Uno::Threading::Future1* ReadTextFromFile(uArray* args);
uObject* ReadTextFromFileSync(::g::Fuse::Scripting::Context* context, uArray* args);
::g::Uno::Threading::Future1* WriteBufferToFile(uArray* args);
uObject* WriteBufferToFileSync(::g::Fuse::Scripting::Context* context, uArray* args);
::g::Uno::Threading::Future1* WriteTextToFile(uArray* args);
uObject* WriteTextToFileSync(::g::Fuse::Scripting::Context* context, uArray* args);
static uObject* GetArg(uType* __type, uArray* args, int32_t index, uString* error);
static uString* GetPathFromArgs(uArray* args);
static FileSystemModule* New2();
static ::g::Fuse::Scripting::Array* ToScriptingArray(uType* __type, ::g::Fuse::Scripting::Context* context, uArray* sourceArray);
static uObject* ToScriptingDate(::g::Fuse::Scripting::Context* context, ::g::Uno::Time::ZonedDateTime* time);
static ::g::Fuse::Scripting::Object* ToScriptingObject(::g::Fuse::Scripting::Context* context, ::g::Uno::IO::FileSystemInfo* info);
static ::g::Fuse::Scripting::Object* ToScriptingObject1(uType* __type, ::g::Fuse::Scripting::Context* context, ::g::Uno::Collections::Dictionary* dict);
};
// }
}}} // ::g::Fuse::FileSystem
| [
"cowodbs156@gmail.com"
] | cowodbs156@gmail.com |
2ca3caec54cf18d9d5a257c8301289d679141e7e | dade68692ef52473c3f949ea7dbe201553e407d2 | /Multiplayer/Source/Multiplayer/MultiplayerGameModeBase.cpp | d4050e5fd32981feb7165261d927fa9b2cc51f9d | [] | no_license | CHADALAK1/MultiplayerUE4 | f2685c52666d77f2d97be5304cf016ba31928fca | 0d29b98551f176e226b2085c611a77ef99603fab | refs/heads/master | 2021-01-24T20:14:52.285065 | 2018-10-20T23:52:01 | 2018-10-20T23:52:01 | 123,249,177 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 950 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "MultiplayerGameModeBase.h"
#include "GameFramework/PlayerController.h"
#include "Announcer/MAnnouncer.h"
#include "GameInstance/MGameInstance.h"
#include "Sound/SoundCue.h"
AMultiplayerGameModeBase::AMultiplayerGameModeBase()
{
}
void AMultiplayerGameModeBase::PlayAnnoucerSound(USoundCue *Sound)
{
if (Sound)
{
for (FConstPlayerControllerIterator Iterator = GetWorld()->GetPlayerControllerIterator(); Iterator; ++Iterator)
{
if (!(Iterator->IsValid())) continue;
Iterator->Get()->ClientPlaySound(Sound);
}
}
}
void AMultiplayerGameModeBase::RespawnDeadPlayer()
{
for (FConstPlayerControllerIterator Iterator = GetWorld()->GetPlayerControllerIterator(); Iterator; ++Iterator)
{
if (!(Iterator->IsValid())) continue;
APlayerController *PC = Iterator->Get();
if (PC && PC->GetPawn() == nullptr)
{
RestartPlayer(PC);
}
}
}
| [
"chad_reddick2008@yahoo.com"
] | chad_reddick2008@yahoo.com |
821af05294b4ac379d3c1a140ad74f17701364f4 | ada61d2d0b227a0d428c237ebc6df87137a5f8b3 | /third_party/skia/src/core/SkGeometry.cpp | b4d12dbfa42e902eb18179da19b9c7717d5c28b3 | [
"BSD-3-Clause"
] | permissive | lineCode/libui-1 | 240b22f8ed542e6dc3d623b465d1170b8cb03b31 | 53e01ad28601aa0fb7b050a39185b46de0bd99fa | refs/heads/master | 2021-01-24T16:48:40.299172 | 2015-11-19T01:46:28 | 2015-11-19T01:46:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46,744 | cpp | /*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkGeometry.h"
#include "SkMatrix.h"
/** If defined, this makes eval_quad and eval_cubic do more setup (sometimes
involving integer multiplies by 2 or 3, but fewer calls to SkScalarMul.
May also introduce overflow of fixed when we compute our setup.
*/
// #define DIRECT_EVAL_OF_POLYNOMIALS
////////////////////////////////////////////////////////////////////////
static int is_not_monotonic(SkScalar a, SkScalar b, SkScalar c) {
SkScalar ab = a - b;
SkScalar bc = b - c;
if (ab < 0) {
bc = -bc;
}
return ab == 0 || bc < 0;
}
////////////////////////////////////////////////////////////////////////
static bool is_unit_interval(SkScalar x) {
return x > 0 && x < SK_Scalar1;
}
static int valid_unit_divide(SkScalar numer, SkScalar denom, SkScalar* ratio) {
SkASSERT(ratio);
if (numer < 0) {
numer = -numer;
denom = -denom;
}
if (denom == 0 || numer == 0 || numer >= denom) {
return 0;
}
SkScalar r = SkScalarDiv(numer, denom);
if (SkScalarIsNaN(r)) {
return 0;
}
SkASSERTF(r >= 0 && r < SK_Scalar1, "numer %f, denom %f, r %f", numer, denom, r);
if (r == 0) { // catch underflow if numer <<<< denom
return 0;
}
*ratio = r;
return 1;
}
/** From Numerical Recipes in C.
Q = -1/2 (B + sign(B) sqrt[B*B - 4*A*C])
x1 = Q / A
x2 = C / Q
*/
int SkFindUnitQuadRoots(SkScalar A, SkScalar B, SkScalar C, SkScalar roots[2]) {
SkASSERT(roots);
if (A == 0) {
return valid_unit_divide(-C, B, roots);
}
SkScalar* r = roots;
SkScalar R = B*B - 4*A*C;
if (R < 0 || SkScalarIsNaN(R)) { // complex roots
return 0;
}
R = SkScalarSqrt(R);
SkScalar Q = (B < 0) ? -(B-R)/2 : -(B+R)/2;
r += valid_unit_divide(Q, A, r);
r += valid_unit_divide(C, Q, r);
if (r - roots == 2) {
if (roots[0] > roots[1])
SkTSwap<SkScalar>(roots[0], roots[1]);
else if (roots[0] == roots[1]) // nearly-equal?
r -= 1; // skip the double root
}
return (int)(r - roots);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
static SkScalar eval_quad(const SkScalar src[], SkScalar t) {
SkASSERT(src);
SkASSERT(t >= 0 && t <= SK_Scalar1);
#ifdef DIRECT_EVAL_OF_POLYNOMIALS
SkScalar C = src[0];
SkScalar A = src[4] - 2 * src[2] + C;
SkScalar B = 2 * (src[2] - C);
return SkScalarMulAdd(SkScalarMulAdd(A, t, B), t, C);
#else
SkScalar ab = SkScalarInterp(src[0], src[2], t);
SkScalar bc = SkScalarInterp(src[2], src[4], t);
return SkScalarInterp(ab, bc, t);
#endif
}
static SkScalar eval_quad_derivative(const SkScalar src[], SkScalar t) {
SkScalar A = src[4] - 2 * src[2] + src[0];
SkScalar B = src[2] - src[0];
return 2 * SkScalarMulAdd(A, t, B);
}
static SkScalar eval_quad_derivative_at_half(const SkScalar src[]) {
SkScalar A = src[4] - 2 * src[2] + src[0];
SkScalar B = src[2] - src[0];
return A + 2 * B;
}
void SkEvalQuadAt(const SkPoint src[3], SkScalar t, SkPoint* pt,
SkVector* tangent) {
SkASSERT(src);
SkASSERT(t >= 0 && t <= SK_Scalar1);
if (pt) {
pt->set(eval_quad(&src[0].fX, t), eval_quad(&src[0].fY, t));
}
if (tangent) {
tangent->set(eval_quad_derivative(&src[0].fX, t),
eval_quad_derivative(&src[0].fY, t));
}
}
void SkEvalQuadAtHalf(const SkPoint src[3], SkPoint* pt, SkVector* tangent) {
SkASSERT(src);
if (pt) {
SkScalar x01 = SkScalarAve(src[0].fX, src[1].fX);
SkScalar y01 = SkScalarAve(src[0].fY, src[1].fY);
SkScalar x12 = SkScalarAve(src[1].fX, src[2].fX);
SkScalar y12 = SkScalarAve(src[1].fY, src[2].fY);
pt->set(SkScalarAve(x01, x12), SkScalarAve(y01, y12));
}
if (tangent) {
tangent->set(eval_quad_derivative_at_half(&src[0].fX),
eval_quad_derivative_at_half(&src[0].fY));
}
}
static void interp_quad_coords(const SkScalar* src, SkScalar* dst, SkScalar t) {
SkScalar ab = SkScalarInterp(src[0], src[2], t);
SkScalar bc = SkScalarInterp(src[2], src[4], t);
dst[0] = src[0];
dst[2] = ab;
dst[4] = SkScalarInterp(ab, bc, t);
dst[6] = bc;
dst[8] = src[4];
}
void SkChopQuadAt(const SkPoint src[3], SkPoint dst[5], SkScalar t) {
SkASSERT(t > 0 && t < SK_Scalar1);
interp_quad_coords(&src[0].fX, &dst[0].fX, t);
interp_quad_coords(&src[0].fY, &dst[0].fY, t);
}
void SkChopQuadAtHalf(const SkPoint src[3], SkPoint dst[5]) {
SkScalar x01 = SkScalarAve(src[0].fX, src[1].fX);
SkScalar y01 = SkScalarAve(src[0].fY, src[1].fY);
SkScalar x12 = SkScalarAve(src[1].fX, src[2].fX);
SkScalar y12 = SkScalarAve(src[1].fY, src[2].fY);
dst[0] = src[0];
dst[1].set(x01, y01);
dst[2].set(SkScalarAve(x01, x12), SkScalarAve(y01, y12));
dst[3].set(x12, y12);
dst[4] = src[2];
}
/** Quad'(t) = At + B, where
A = 2(a - 2b + c)
B = 2(b - a)
Solve for t, only if it fits between 0 < t < 1
*/
int SkFindQuadExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar tValue[1]) {
/* At + B == 0
t = -B / A
*/
return valid_unit_divide(a - b, a - b - b + c, tValue);
}
static inline void flatten_double_quad_extrema(SkScalar coords[14]) {
coords[2] = coords[6] = coords[4];
}
/* Returns 0 for 1 quad, and 1 for two quads, either way the answer is
stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
*/
int SkChopQuadAtYExtrema(const SkPoint src[3], SkPoint dst[5]) {
SkASSERT(src);
SkASSERT(dst);
SkScalar a = src[0].fY;
SkScalar b = src[1].fY;
SkScalar c = src[2].fY;
if (is_not_monotonic(a, b, c)) {
SkScalar tValue;
if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
SkChopQuadAt(src, dst, tValue);
flatten_double_quad_extrema(&dst[0].fY);
return 1;
}
// if we get here, we need to force dst to be monotonic, even though
// we couldn't compute a unit_divide value (probably underflow).
b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
}
dst[0].set(src[0].fX, a);
dst[1].set(src[1].fX, b);
dst[2].set(src[2].fX, c);
return 0;
}
/* Returns 0 for 1 quad, and 1 for two quads, either way the answer is
stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
*/
int SkChopQuadAtXExtrema(const SkPoint src[3], SkPoint dst[5]) {
SkASSERT(src);
SkASSERT(dst);
SkScalar a = src[0].fX;
SkScalar b = src[1].fX;
SkScalar c = src[2].fX;
if (is_not_monotonic(a, b, c)) {
SkScalar tValue;
if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
SkChopQuadAt(src, dst, tValue);
flatten_double_quad_extrema(&dst[0].fX);
return 1;
}
// if we get here, we need to force dst to be monotonic, even though
// we couldn't compute a unit_divide value (probably underflow).
b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
}
dst[0].set(a, src[0].fY);
dst[1].set(b, src[1].fY);
dst[2].set(c, src[2].fY);
return 0;
}
// F(t) = a (1 - t) ^ 2 + 2 b t (1 - t) + c t ^ 2
// F'(t) = 2 (b - a) + 2 (a - 2b + c) t
// F''(t) = 2 (a - 2b + c)
//
// A = 2 (b - a)
// B = 2 (a - 2b + c)
//
// Maximum curvature for a quadratic means solving
// Fx' Fx'' + Fy' Fy'' = 0
//
// t = - (Ax Bx + Ay By) / (Bx ^ 2 + By ^ 2)
//
SkScalar SkFindQuadMaxCurvature(const SkPoint src[3]) {
SkScalar Ax = src[1].fX - src[0].fX;
SkScalar Ay = src[1].fY - src[0].fY;
SkScalar Bx = src[0].fX - src[1].fX - src[1].fX + src[2].fX;
SkScalar By = src[0].fY - src[1].fY - src[1].fY + src[2].fY;
SkScalar t = 0; // 0 means don't chop
(void)valid_unit_divide(-(Ax * Bx + Ay * By), Bx * Bx + By * By, &t);
return t;
}
int SkChopQuadAtMaxCurvature(const SkPoint src[3], SkPoint dst[5]) {
SkScalar t = SkFindQuadMaxCurvature(src);
if (t == 0) {
memcpy(dst, src, 3 * sizeof(SkPoint));
return 1;
} else {
SkChopQuadAt(src, dst, t);
return 2;
}
}
#define SK_ScalarTwoThirds (0.666666666f)
void SkConvertQuadToCubic(const SkPoint src[3], SkPoint dst[4]) {
const SkScalar scale = SK_ScalarTwoThirds;
dst[0] = src[0];
dst[1].set(src[0].fX + SkScalarMul(src[1].fX - src[0].fX, scale),
src[0].fY + SkScalarMul(src[1].fY - src[0].fY, scale));
dst[2].set(src[2].fX + SkScalarMul(src[1].fX - src[2].fX, scale),
src[2].fY + SkScalarMul(src[1].fY - src[2].fY, scale));
dst[3] = src[2];
}
//////////////////////////////////////////////////////////////////////////////
///// CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS /////
//////////////////////////////////////////////////////////////////////////////
static void get_cubic_coeff(const SkScalar pt[], SkScalar coeff[4]) {
coeff[0] = pt[6] + 3*(pt[2] - pt[4]) - pt[0];
coeff[1] = 3*(pt[4] - pt[2] - pt[2] + pt[0]);
coeff[2] = 3*(pt[2] - pt[0]);
coeff[3] = pt[0];
}
void SkGetCubicCoeff(const SkPoint pts[4], SkScalar cx[4], SkScalar cy[4]) {
SkASSERT(pts);
if (cx) {
get_cubic_coeff(&pts[0].fX, cx);
}
if (cy) {
get_cubic_coeff(&pts[0].fY, cy);
}
}
static SkScalar eval_cubic(const SkScalar src[], SkScalar t) {
SkASSERT(src);
SkASSERT(t >= 0 && t <= SK_Scalar1);
if (t == 0) {
return src[0];
}
#ifdef DIRECT_EVAL_OF_POLYNOMIALS
SkScalar D = src[0];
SkScalar A = src[6] + 3*(src[2] - src[4]) - D;
SkScalar B = 3*(src[4] - src[2] - src[2] + D);
SkScalar C = 3*(src[2] - D);
return SkScalarMulAdd(SkScalarMulAdd(SkScalarMulAdd(A, t, B), t, C), t, D);
#else
SkScalar ab = SkScalarInterp(src[0], src[2], t);
SkScalar bc = SkScalarInterp(src[2], src[4], t);
SkScalar cd = SkScalarInterp(src[4], src[6], t);
SkScalar abc = SkScalarInterp(ab, bc, t);
SkScalar bcd = SkScalarInterp(bc, cd, t);
return SkScalarInterp(abc, bcd, t);
#endif
}
/** return At^2 + Bt + C
*/
static SkScalar eval_quadratic(SkScalar A, SkScalar B, SkScalar C, SkScalar t) {
SkASSERT(t >= 0 && t <= SK_Scalar1);
return SkScalarMulAdd(SkScalarMulAdd(A, t, B), t, C);
}
static SkScalar eval_cubic_derivative(const SkScalar src[], SkScalar t) {
SkScalar A = src[6] + 3*(src[2] - src[4]) - src[0];
SkScalar B = 2*(src[4] - 2 * src[2] + src[0]);
SkScalar C = src[2] - src[0];
return eval_quadratic(A, B, C, t);
}
static SkScalar eval_cubic_2ndDerivative(const SkScalar src[], SkScalar t) {
SkScalar A = src[6] + 3*(src[2] - src[4]) - src[0];
SkScalar B = src[4] - 2 * src[2] + src[0];
return SkScalarMulAdd(A, t, B);
}
void SkEvalCubicAt(const SkPoint src[4], SkScalar t, SkPoint* loc,
SkVector* tangent, SkVector* curvature) {
SkASSERT(src);
SkASSERT(t >= 0 && t <= SK_Scalar1);
if (loc) {
loc->set(eval_cubic(&src[0].fX, t), eval_cubic(&src[0].fY, t));
}
if (tangent) {
tangent->set(eval_cubic_derivative(&src[0].fX, t),
eval_cubic_derivative(&src[0].fY, t));
}
if (curvature) {
curvature->set(eval_cubic_2ndDerivative(&src[0].fX, t),
eval_cubic_2ndDerivative(&src[0].fY, t));
}
}
/** Cubic'(t) = At^2 + Bt + C, where
A = 3(-a + 3(b - c) + d)
B = 6(a - 2b + c)
C = 3(b - a)
Solve for t, keeping only those that fit betwee 0 < t < 1
*/
int SkFindCubicExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar d,
SkScalar tValues[2]) {
// we divide A,B,C by 3 to simplify
SkScalar A = d - a + 3*(b - c);
SkScalar B = 2*(a - b - b + c);
SkScalar C = b - a;
return SkFindUnitQuadRoots(A, B, C, tValues);
}
static void interp_cubic_coords(const SkScalar* src, SkScalar* dst,
SkScalar t) {
SkScalar ab = SkScalarInterp(src[0], src[2], t);
SkScalar bc = SkScalarInterp(src[2], src[4], t);
SkScalar cd = SkScalarInterp(src[4], src[6], t);
SkScalar abc = SkScalarInterp(ab, bc, t);
SkScalar bcd = SkScalarInterp(bc, cd, t);
SkScalar abcd = SkScalarInterp(abc, bcd, t);
dst[0] = src[0];
dst[2] = ab;
dst[4] = abc;
dst[6] = abcd;
dst[8] = bcd;
dst[10] = cd;
dst[12] = src[6];
}
void SkChopCubicAt(const SkPoint src[4], SkPoint dst[7], SkScalar t) {
SkASSERT(t > 0 && t < SK_Scalar1);
interp_cubic_coords(&src[0].fX, &dst[0].fX, t);
interp_cubic_coords(&src[0].fY, &dst[0].fY, t);
}
/* http://code.google.com/p/skia/issues/detail?id=32
This test code would fail when we didn't check the return result of
valid_unit_divide in SkChopCubicAt(... tValues[], int roots). The reason is
that after the first chop, the parameters to valid_unit_divide are equal
(thanks to finite float precision and rounding in the subtracts). Thus
even though the 2nd tValue looks < 1.0, after we renormalize it, we end
up with 1.0, hence the need to check and just return the last cubic as
a degenerate clump of 4 points in the sampe place.
static void test_cubic() {
SkPoint src[4] = {
{ 556.25000, 523.03003 },
{ 556.23999, 522.96002 },
{ 556.21997, 522.89001 },
{ 556.21997, 522.82001 }
};
SkPoint dst[10];
SkScalar tval[] = { 0.33333334f, 0.99999994f };
SkChopCubicAt(src, dst, tval, 2);
}
*/
void SkChopCubicAt(const SkPoint src[4], SkPoint dst[],
const SkScalar tValues[], int roots) {
#ifdef SK_DEBUG
{
for (int i = 0; i < roots - 1; i++)
{
SkASSERT(is_unit_interval(tValues[i]));
SkASSERT(is_unit_interval(tValues[i+1]));
SkASSERT(tValues[i] < tValues[i+1]);
}
}
#endif
if (dst) {
if (roots == 0) { // nothing to chop
memcpy(dst, src, 4*sizeof(SkPoint));
} else {
SkScalar t = tValues[0];
SkPoint tmp[4];
for (int i = 0; i < roots; i++) {
SkChopCubicAt(src, dst, t);
if (i == roots - 1) {
break;
}
dst += 3;
// have src point to the remaining cubic (after the chop)
memcpy(tmp, dst, 4 * sizeof(SkPoint));
src = tmp;
// watch out in case the renormalized t isn't in range
if (!valid_unit_divide(tValues[i+1] - tValues[i],
SK_Scalar1 - tValues[i], &t)) {
// if we can't, just create a degenerate cubic
dst[4] = dst[5] = dst[6] = src[3];
break;
}
}
}
}
}
void SkChopCubicAtHalf(const SkPoint src[4], SkPoint dst[7]) {
SkScalar x01 = SkScalarAve(src[0].fX, src[1].fX);
SkScalar y01 = SkScalarAve(src[0].fY, src[1].fY);
SkScalar x12 = SkScalarAve(src[1].fX, src[2].fX);
SkScalar y12 = SkScalarAve(src[1].fY, src[2].fY);
SkScalar x23 = SkScalarAve(src[2].fX, src[3].fX);
SkScalar y23 = SkScalarAve(src[2].fY, src[3].fY);
SkScalar x012 = SkScalarAve(x01, x12);
SkScalar y012 = SkScalarAve(y01, y12);
SkScalar x123 = SkScalarAve(x12, x23);
SkScalar y123 = SkScalarAve(y12, y23);
dst[0] = src[0];
dst[1].set(x01, y01);
dst[2].set(x012, y012);
dst[3].set(SkScalarAve(x012, x123), SkScalarAve(y012, y123));
dst[4].set(x123, y123);
dst[5].set(x23, y23);
dst[6] = src[3];
}
static void flatten_double_cubic_extrema(SkScalar coords[14]) {
coords[4] = coords[8] = coords[6];
}
/** Given 4 points on a cubic bezier, chop it into 1, 2, 3 beziers such that
the resulting beziers are monotonic in Y. This is called by the scan
converter. Depending on what is returned, dst[] is treated as follows:
0 dst[0..3] is the original cubic
1 dst[0..3] and dst[3..6] are the two new cubics
2 dst[0..3], dst[3..6], dst[6..9] are the three new cubics
If dst == null, it is ignored and only the count is returned.
*/
int SkChopCubicAtYExtrema(const SkPoint src[4], SkPoint dst[10]) {
SkScalar tValues[2];
int roots = SkFindCubicExtrema(src[0].fY, src[1].fY, src[2].fY,
src[3].fY, tValues);
SkChopCubicAt(src, dst, tValues, roots);
if (dst && roots > 0) {
// we do some cleanup to ensure our Y extrema are flat
flatten_double_cubic_extrema(&dst[0].fY);
if (roots == 2) {
flatten_double_cubic_extrema(&dst[3].fY);
}
}
return roots;
}
int SkChopCubicAtXExtrema(const SkPoint src[4], SkPoint dst[10]) {
SkScalar tValues[2];
int roots = SkFindCubicExtrema(src[0].fX, src[1].fX, src[2].fX,
src[3].fX, tValues);
SkChopCubicAt(src, dst, tValues, roots);
if (dst && roots > 0) {
// we do some cleanup to ensure our Y extrema are flat
flatten_double_cubic_extrema(&dst[0].fX);
if (roots == 2) {
flatten_double_cubic_extrema(&dst[3].fX);
}
}
return roots;
}
/** http://www.faculty.idc.ac.il/arik/quality/appendixA.html
Inflection means that curvature is zero.
Curvature is [F' x F''] / [F'^3]
So we solve F'x X F''y - F'y X F''y == 0
After some canceling of the cubic term, we get
A = b - a
B = c - 2b + a
C = d - 3c + 3b - a
(BxCy - ByCx)t^2 + (AxCy - AyCx)t + AxBy - AyBx == 0
*/
int SkFindCubicInflections(const SkPoint src[4], SkScalar tValues[]) {
SkScalar Ax = src[1].fX - src[0].fX;
SkScalar Ay = src[1].fY - src[0].fY;
SkScalar Bx = src[2].fX - 2 * src[1].fX + src[0].fX;
SkScalar By = src[2].fY - 2 * src[1].fY + src[0].fY;
SkScalar Cx = src[3].fX + 3 * (src[1].fX - src[2].fX) - src[0].fX;
SkScalar Cy = src[3].fY + 3 * (src[1].fY - src[2].fY) - src[0].fY;
return SkFindUnitQuadRoots(Bx*Cy - By*Cx,
Ax*Cy - Ay*Cx,
Ax*By - Ay*Bx,
tValues);
}
int SkChopCubicAtInflections(const SkPoint src[], SkPoint dst[10]) {
SkScalar tValues[2];
int count = SkFindCubicInflections(src, tValues);
if (dst) {
if (count == 0) {
memcpy(dst, src, 4 * sizeof(SkPoint));
} else {
SkChopCubicAt(src, dst, tValues, count);
}
}
return count + 1;
}
// See http://http.developer.nvidia.com/GPUGems3/gpugems3_ch25.html (from the book GPU Gems 3)
// discr(I) = d0^2 * (3*d1^2 - 4*d0*d2)
// Classification:
// discr(I) > 0 Serpentine
// discr(I) = 0 Cusp
// discr(I) < 0 Loop
// d0 = d1 = 0 Quadratic
// d0 = d1 = d2 = 0 Line
// p0 = p1 = p2 = p3 Point
static SkCubicType classify_cubic(const SkPoint p[4], const SkScalar d[3]) {
if (p[0] == p[1] && p[0] == p[2] && p[0] == p[3]) {
return kPoint_SkCubicType;
}
const SkScalar discr = d[0] * d[0] * (3.f * d[1] * d[1] - 4.f * d[0] * d[2]);
if (discr > SK_ScalarNearlyZero) {
return kSerpentine_SkCubicType;
} else if (discr < -SK_ScalarNearlyZero) {
return kLoop_SkCubicType;
} else {
if (0.f == d[0] && 0.f == d[1]) {
return (0.f == d[2] ? kLine_SkCubicType : kQuadratic_SkCubicType);
} else {
return kCusp_SkCubicType;
}
}
}
// Assumes the third component of points is 1.
// Calcs p0 . (p1 x p2)
static SkScalar calc_dot_cross_cubic(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2) {
const SkScalar xComp = p0.fX * (p1.fY - p2.fY);
const SkScalar yComp = p0.fY * (p2.fX - p1.fX);
const SkScalar wComp = p1.fX * p2.fY - p1.fY * p2.fX;
return (xComp + yComp + wComp);
}
// Calc coefficients of I(s,t) where roots of I are inflection points of curve
// I(s,t) = t*(3*d0*s^2 - 3*d1*s*t + d2*t^2)
// d0 = a1 - 2*a2+3*a3
// d1 = -a2 + 3*a3
// d2 = 3*a3
// a1 = p0 . (p3 x p2)
// a2 = p1 . (p0 x p3)
// a3 = p2 . (p1 x p0)
// Places the values of d1, d2, d3 in array d passed in
static void calc_cubic_inflection_func(const SkPoint p[4], SkScalar d[3]) {
SkScalar a1 = calc_dot_cross_cubic(p[0], p[3], p[2]);
SkScalar a2 = calc_dot_cross_cubic(p[1], p[0], p[3]);
SkScalar a3 = calc_dot_cross_cubic(p[2], p[1], p[0]);
// need to scale a's or values in later calculations will grow to high
SkScalar max = SkScalarAbs(a1);
max = SkMaxScalar(max, SkScalarAbs(a2));
max = SkMaxScalar(max, SkScalarAbs(a3));
max = 1.f/max;
a1 = a1 * max;
a2 = a2 * max;
a3 = a3 * max;
d[2] = 3.f * a3;
d[1] = d[2] - a2;
d[0] = d[1] - a2 + a1;
}
SkCubicType SkClassifyCubic(const SkPoint src[4], SkScalar d[3]) {
calc_cubic_inflection_func(src, d);
return classify_cubic(src, d);
}
template <typename T> void bubble_sort(T array[], int count) {
for (int i = count - 1; i > 0; --i)
for (int j = i; j > 0; --j)
if (array[j] < array[j-1])
{
T tmp(array[j]);
array[j] = array[j-1];
array[j-1] = tmp;
}
}
/**
* Given an array and count, remove all pair-wise duplicates from the array,
* keeping the existing sorting, and return the new count
*/
static int collaps_duplicates(SkScalar array[], int count) {
for (int n = count; n > 1; --n) {
if (array[0] == array[1]) {
for (int i = 1; i < n; ++i) {
array[i - 1] = array[i];
}
count -= 1;
} else {
array += 1;
}
}
return count;
}
#ifdef SK_DEBUG
#define TEST_COLLAPS_ENTRY(array) array, SK_ARRAY_COUNT(array)
static void test_collaps_duplicates() {
static bool gOnce;
if (gOnce) { return; }
gOnce = true;
const SkScalar src0[] = { 0 };
const SkScalar src1[] = { 0, 0 };
const SkScalar src2[] = { 0, 1 };
const SkScalar src3[] = { 0, 0, 0 };
const SkScalar src4[] = { 0, 0, 1 };
const SkScalar src5[] = { 0, 1, 1 };
const SkScalar src6[] = { 0, 1, 2 };
const struct {
const SkScalar* fData;
int fCount;
int fCollapsedCount;
} data[] = {
{ TEST_COLLAPS_ENTRY(src0), 1 },
{ TEST_COLLAPS_ENTRY(src1), 1 },
{ TEST_COLLAPS_ENTRY(src2), 2 },
{ TEST_COLLAPS_ENTRY(src3), 1 },
{ TEST_COLLAPS_ENTRY(src4), 2 },
{ TEST_COLLAPS_ENTRY(src5), 2 },
{ TEST_COLLAPS_ENTRY(src6), 3 },
};
for (size_t i = 0; i < SK_ARRAY_COUNT(data); ++i) {
SkScalar dst[3];
memcpy(dst, data[i].fData, data[i].fCount * sizeof(dst[0]));
int count = collaps_duplicates(dst, data[i].fCount);
SkASSERT(data[i].fCollapsedCount == count);
for (int j = 1; j < count; ++j) {
SkASSERT(dst[j-1] < dst[j]);
}
}
}
#endif
static SkScalar SkScalarCubeRoot(SkScalar x) {
return SkScalarPow(x, 0.3333333f);
}
/* Solve coeff(t) == 0, returning the number of roots that
lie withing 0 < t < 1.
coeff[0]t^3 + coeff[1]t^2 + coeff[2]t + coeff[3]
Eliminates repeated roots (so that all tValues are distinct, and are always
in increasing order.
*/
static int solve_cubic_poly(const SkScalar coeff[4], SkScalar tValues[3]) {
if (SkScalarNearlyZero(coeff[0])) { // we're just a quadratic
return SkFindUnitQuadRoots(coeff[1], coeff[2], coeff[3], tValues);
}
SkScalar a, b, c, Q, R;
{
SkASSERT(coeff[0] != 0);
SkScalar inva = SkScalarInvert(coeff[0]);
a = coeff[1] * inva;
b = coeff[2] * inva;
c = coeff[3] * inva;
}
Q = (a*a - b*3) / 9;
R = (2*a*a*a - 9*a*b + 27*c) / 54;
SkScalar Q3 = Q * Q * Q;
SkScalar R2MinusQ3 = R * R - Q3;
SkScalar adiv3 = a / 3;
SkScalar* roots = tValues;
SkScalar r;
if (R2MinusQ3 < 0) { // we have 3 real roots
SkScalar theta = SkScalarACos(R / SkScalarSqrt(Q3));
SkScalar neg2RootQ = -2 * SkScalarSqrt(Q);
r = neg2RootQ * SkScalarCos(theta/3) - adiv3;
if (is_unit_interval(r)) {
*roots++ = r;
}
r = neg2RootQ * SkScalarCos((theta + 2*SK_ScalarPI)/3) - adiv3;
if (is_unit_interval(r)) {
*roots++ = r;
}
r = neg2RootQ * SkScalarCos((theta - 2*SK_ScalarPI)/3) - adiv3;
if (is_unit_interval(r)) {
*roots++ = r;
}
SkDEBUGCODE(test_collaps_duplicates();)
// now sort the roots
int count = (int)(roots - tValues);
SkASSERT((unsigned)count <= 3);
bubble_sort(tValues, count);
count = collaps_duplicates(tValues, count);
roots = tValues + count; // so we compute the proper count below
} else { // we have 1 real root
SkScalar A = SkScalarAbs(R) + SkScalarSqrt(R2MinusQ3);
A = SkScalarCubeRoot(A);
if (R > 0) {
A = -A;
}
if (A != 0) {
A += Q / A;
}
r = A - adiv3;
if (is_unit_interval(r)) {
*roots++ = r;
}
}
return (int)(roots - tValues);
}
/* Looking for F' dot F'' == 0
A = b - a
B = c - 2b + a
C = d - 3c + 3b - a
F' = 3Ct^2 + 6Bt + 3A
F'' = 6Ct + 6B
F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
*/
static void formulate_F1DotF2(const SkScalar src[], SkScalar coeff[4]) {
SkScalar a = src[2] - src[0];
SkScalar b = src[4] - 2 * src[2] + src[0];
SkScalar c = src[6] + 3 * (src[2] - src[4]) - src[0];
coeff[0] = c * c;
coeff[1] = 3 * b * c;
coeff[2] = 2 * b * b + c * a;
coeff[3] = a * b;
}
/* Looking for F' dot F'' == 0
A = b - a
B = c - 2b + a
C = d - 3c + 3b - a
F' = 3Ct^2 + 6Bt + 3A
F'' = 6Ct + 6B
F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
*/
int SkFindCubicMaxCurvature(const SkPoint src[4], SkScalar tValues[3]) {
SkScalar coeffX[4], coeffY[4];
int i;
formulate_F1DotF2(&src[0].fX, coeffX);
formulate_F1DotF2(&src[0].fY, coeffY);
for (i = 0; i < 4; i++) {
coeffX[i] += coeffY[i];
}
SkScalar t[3];
int count = solve_cubic_poly(coeffX, t);
int maxCount = 0;
// now remove extrema where the curvature is zero (mins)
// !!!! need a test for this !!!!
for (i = 0; i < count; i++) {
// if (not_min_curvature())
if (t[i] > 0 && t[i] < SK_Scalar1) {
tValues[maxCount++] = t[i];
}
}
return maxCount;
}
int SkChopCubicAtMaxCurvature(const SkPoint src[4], SkPoint dst[13],
SkScalar tValues[3]) {
SkScalar t_storage[3];
if (tValues == NULL) {
tValues = t_storage;
}
int count = SkFindCubicMaxCurvature(src, tValues);
if (dst) {
if (count == 0) {
memcpy(dst, src, 4 * sizeof(SkPoint));
} else {
SkChopCubicAt(src, dst, tValues, count);
}
}
return count + 1;
}
///////////////////////////////////////////////////////////////////////////////
/* Find t value for quadratic [a, b, c] = d.
Return 0 if there is no solution within [0, 1)
*/
static SkScalar quad_solve(SkScalar a, SkScalar b, SkScalar c, SkScalar d) {
// At^2 + Bt + C = d
SkScalar A = a - 2 * b + c;
SkScalar B = 2 * (b - a);
SkScalar C = a - d;
SkScalar roots[2];
int count = SkFindUnitQuadRoots(A, B, C, roots);
SkASSERT(count <= 1);
return count == 1 ? roots[0] : 0;
}
/* given a quad-curve and a point (x,y), chop the quad at that point and place
the new off-curve point and endpoint into 'dest'.
Should only return false if the computed pos is the start of the curve
(i.e. root == 0)
*/
static bool truncate_last_curve(const SkPoint quad[3], SkScalar x, SkScalar y,
SkPoint* dest) {
const SkScalar* base;
SkScalar value;
if (SkScalarAbs(x) < SkScalarAbs(y)) {
base = &quad[0].fX;
value = x;
} else {
base = &quad[0].fY;
value = y;
}
// note: this returns 0 if it thinks value is out of range, meaning the
// root might return something outside of [0, 1)
SkScalar t = quad_solve(base[0], base[2], base[4], value);
if (t > 0) {
SkPoint tmp[5];
SkChopQuadAt(quad, tmp, t);
dest[0] = tmp[1];
dest[1].set(x, y);
return true;
} else {
/* t == 0 means either the value triggered a root outside of [0, 1)
For our purposes, we can ignore the <= 0 roots, but we want to
catch the >= 1 roots (which given our caller, will basically mean
a root of 1, give-or-take numerical instability). If we are in the
>= 1 case, return the existing offCurve point.
The test below checks to see if we are close to the "end" of the
curve (near base[4]). Rather than specifying a tolerance, I just
check to see if value is on to the right/left of the middle point
(depending on the direction/sign of the end points).
*/
if ((base[0] < base[4] && value > base[2]) ||
(base[0] > base[4] && value < base[2])) // should root have been 1
{
dest[0] = quad[1];
dest[1].set(x, y);
return true;
}
}
return false;
}
static const SkPoint gQuadCirclePts[kSkBuildQuadArcStorage] = {
// The mid point of the quadratic arc approximation is half way between the two
// control points. The float epsilon adjustment moves the on curve point out by
// two bits, distributing the convex test error between the round rect
// approximation and the convex cross product sign equality test.
#define SK_MID_RRECT_OFFSET \
(SK_Scalar1 + SK_ScalarTanPIOver8 + FLT_EPSILON * 4) / 2
{ SK_Scalar1, 0 },
{ SK_Scalar1, SK_ScalarTanPIOver8 },
{ SK_MID_RRECT_OFFSET, SK_MID_RRECT_OFFSET },
{ SK_ScalarTanPIOver8, SK_Scalar1 },
{ 0, SK_Scalar1 },
{ -SK_ScalarTanPIOver8, SK_Scalar1 },
{ -SK_MID_RRECT_OFFSET, SK_MID_RRECT_OFFSET },
{ -SK_Scalar1, SK_ScalarTanPIOver8 },
{ -SK_Scalar1, 0 },
{ -SK_Scalar1, -SK_ScalarTanPIOver8 },
{ -SK_MID_RRECT_OFFSET, -SK_MID_RRECT_OFFSET },
{ -SK_ScalarTanPIOver8, -SK_Scalar1 },
{ 0, -SK_Scalar1 },
{ SK_ScalarTanPIOver8, -SK_Scalar1 },
{ SK_MID_RRECT_OFFSET, -SK_MID_RRECT_OFFSET },
{ SK_Scalar1, -SK_ScalarTanPIOver8 },
{ SK_Scalar1, 0 }
#undef SK_MID_RRECT_OFFSET
};
int SkBuildQuadArc(const SkVector& uStart, const SkVector& uStop,
SkRotationDirection dir, const SkMatrix* userMatrix,
SkPoint quadPoints[]) {
// rotate by x,y so that uStart is (1.0)
SkScalar x = SkPoint::DotProduct(uStart, uStop);
SkScalar y = SkPoint::CrossProduct(uStart, uStop);
SkScalar absX = SkScalarAbs(x);
SkScalar absY = SkScalarAbs(y);
int pointCount;
// check for (effectively) coincident vectors
// this can happen if our angle is nearly 0 or nearly 180 (y == 0)
// ... we use the dot-prod to distinguish between 0 and 180 (x > 0)
if (absY <= SK_ScalarNearlyZero && x > 0 &&
((y >= 0 && kCW_SkRotationDirection == dir) ||
(y <= 0 && kCCW_SkRotationDirection == dir))) {
// just return the start-point
quadPoints[0].set(SK_Scalar1, 0);
pointCount = 1;
} else {
if (dir == kCCW_SkRotationDirection) {
y = -y;
}
// what octant (quadratic curve) is [xy] in?
int oct = 0;
bool sameSign = true;
if (0 == y) {
oct = 4; // 180
SkASSERT(SkScalarAbs(x + SK_Scalar1) <= SK_ScalarNearlyZero);
} else if (0 == x) {
SkASSERT(absY - SK_Scalar1 <= SK_ScalarNearlyZero);
oct = y > 0 ? 2 : 6; // 90 : 270
} else {
if (y < 0) {
oct += 4;
}
if ((x < 0) != (y < 0)) {
oct += 2;
sameSign = false;
}
if ((absX < absY) == sameSign) {
oct += 1;
}
}
int wholeCount = oct << 1;
memcpy(quadPoints, gQuadCirclePts, (wholeCount + 1) * sizeof(SkPoint));
const SkPoint* arc = &gQuadCirclePts[wholeCount];
if (truncate_last_curve(arc, x, y, &quadPoints[wholeCount + 1])) {
wholeCount += 2;
}
pointCount = wholeCount + 1;
}
// now handle counter-clockwise and the initial unitStart rotation
SkMatrix matrix;
matrix.setSinCos(uStart.fY, uStart.fX);
if (dir == kCCW_SkRotationDirection) {
matrix.preScale(SK_Scalar1, -SK_Scalar1);
}
if (userMatrix) {
matrix.postConcat(*userMatrix);
}
matrix.mapPoints(quadPoints, pointCount);
return pointCount;
}
///////////////////////////////////////////////////////////////////////////////
//
// NURB representation for conics. Helpful explanations at:
//
// http://citeseerx.ist.psu.edu/viewdoc/
// download?doi=10.1.1.44.5740&rep=rep1&type=ps
// and
// http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/NURBS/RB-conics.html
//
// F = (A (1 - t)^2 + C t^2 + 2 B (1 - t) t w)
// ------------------------------------------
// ((1 - t)^2 + t^2 + 2 (1 - t) t w)
//
// = {t^2 (P0 + P2 - 2 P1 w), t (-2 P0 + 2 P1 w), P0}
// ------------------------------------------------
// {t^2 (2 - 2 w), t (-2 + 2 w), 1}
//
static SkScalar conic_eval_pos(const SkScalar src[], SkScalar w, SkScalar t) {
SkASSERT(src);
SkASSERT(t >= 0 && t <= SK_Scalar1);
SkScalar src2w = SkScalarMul(src[2], w);
SkScalar C = src[0];
SkScalar A = src[4] - 2 * src2w + C;
SkScalar B = 2 * (src2w - C);
SkScalar numer = SkScalarMulAdd(SkScalarMulAdd(A, t, B), t, C);
B = 2 * (w - SK_Scalar1);
C = SK_Scalar1;
A = -B;
SkScalar denom = SkScalarMulAdd(SkScalarMulAdd(A, t, B), t, C);
return SkScalarDiv(numer, denom);
}
// F' = 2 (C t (1 + t (-1 + w)) - A (-1 + t) (t (-1 + w) - w) + B (1 - 2 t) w)
//
// t^2 : (2 P0 - 2 P2 - 2 P0 w + 2 P2 w)
// t^1 : (-2 P0 + 2 P2 + 4 P0 w - 4 P1 w)
// t^0 : -2 P0 w + 2 P1 w
//
// We disregard magnitude, so we can freely ignore the denominator of F', and
// divide the numerator by 2
//
// coeff[0] for t^2
// coeff[1] for t^1
// coeff[2] for t^0
//
static void conic_deriv_coeff(const SkScalar src[],
SkScalar w,
SkScalar coeff[3]) {
const SkScalar P20 = src[4] - src[0];
const SkScalar P10 = src[2] - src[0];
const SkScalar wP10 = w * P10;
coeff[0] = w * P20 - P20;
coeff[1] = P20 - 2 * wP10;
coeff[2] = wP10;
}
static SkScalar conic_eval_tan(const SkScalar coord[], SkScalar w, SkScalar t) {
SkScalar coeff[3];
conic_deriv_coeff(coord, w, coeff);
return t * (t * coeff[0] + coeff[1]) + coeff[2];
}
static bool conic_find_extrema(const SkScalar src[], SkScalar w, SkScalar* t) {
SkScalar coeff[3];
conic_deriv_coeff(src, w, coeff);
SkScalar tValues[2];
int roots = SkFindUnitQuadRoots(coeff[0], coeff[1], coeff[2], tValues);
SkASSERT(0 == roots || 1 == roots);
if (1 == roots) {
*t = tValues[0];
return true;
}
return false;
}
struct SkP3D {
SkScalar fX, fY, fZ;
void set(SkScalar x, SkScalar y, SkScalar z) {
fX = x; fY = y; fZ = z;
}
void projectDown(SkPoint* dst) const {
dst->set(fX / fZ, fY / fZ);
}
};
// We only interpolate one dimension at a time (the first, at +0, +3, +6).
static void p3d_interp(const SkScalar src[7], SkScalar dst[7], SkScalar t) {
SkScalar ab = SkScalarInterp(src[0], src[3], t);
SkScalar bc = SkScalarInterp(src[3], src[6], t);
dst[0] = ab;
dst[3] = SkScalarInterp(ab, bc, t);
dst[6] = bc;
}
static void ratquad_mapTo3D(const SkPoint src[3], SkScalar w, SkP3D dst[]) {
dst[0].set(src[0].fX * 1, src[0].fY * 1, 1);
dst[1].set(src[1].fX * w, src[1].fY * w, w);
dst[2].set(src[2].fX * 1, src[2].fY * 1, 1);
}
void SkConic::evalAt(SkScalar t, SkPoint* pt, SkVector* tangent) const {
SkASSERT(t >= 0 && t <= SK_Scalar1);
if (pt) {
pt->set(conic_eval_pos(&fPts[0].fX, fW, t),
conic_eval_pos(&fPts[0].fY, fW, t));
}
if (tangent) {
tangent->set(conic_eval_tan(&fPts[0].fX, fW, t),
conic_eval_tan(&fPts[0].fY, fW, t));
}
}
void SkConic::chopAt(SkScalar t, SkConic dst[2]) const {
SkP3D tmp[3], tmp2[3];
ratquad_mapTo3D(fPts, fW, tmp);
p3d_interp(&tmp[0].fX, &tmp2[0].fX, t);
p3d_interp(&tmp[0].fY, &tmp2[0].fY, t);
p3d_interp(&tmp[0].fZ, &tmp2[0].fZ, t);
dst[0].fPts[0] = fPts[0];
tmp2[0].projectDown(&dst[0].fPts[1]);
tmp2[1].projectDown(&dst[0].fPts[2]); dst[1].fPts[0] = dst[0].fPts[2];
tmp2[2].projectDown(&dst[1].fPts[1]);
dst[1].fPts[2] = fPts[2];
// to put in "standard form", where w0 and w2 are both 1, we compute the
// new w1 as sqrt(w1*w1/w0*w2)
// or
// w1 /= sqrt(w0*w2)
//
// However, in our case, we know that for dst[0]:
// w0 == 1, and for dst[1], w2 == 1
//
SkScalar root = SkScalarSqrt(tmp2[1].fZ);
dst[0].fW = tmp2[0].fZ / root;
dst[1].fW = tmp2[2].fZ / root;
}
static SkScalar subdivide_w_value(SkScalar w) {
return SkScalarSqrt(SK_ScalarHalf + w * SK_ScalarHalf);
}
void SkConic::chop(SkConic dst[2]) const {
SkScalar scale = SkScalarInvert(SK_Scalar1 + fW);
SkScalar p1x = fW * fPts[1].fX;
SkScalar p1y = fW * fPts[1].fY;
SkScalar mx = (fPts[0].fX + 2 * p1x + fPts[2].fX) * scale * SK_ScalarHalf;
SkScalar my = (fPts[0].fY + 2 * p1y + fPts[2].fY) * scale * SK_ScalarHalf;
dst[0].fPts[0] = fPts[0];
dst[0].fPts[1].set((fPts[0].fX + p1x) * scale,
(fPts[0].fY + p1y) * scale);
dst[0].fPts[2].set(mx, my);
dst[1].fPts[0].set(mx, my);
dst[1].fPts[1].set((p1x + fPts[2].fX) * scale,
(p1y + fPts[2].fY) * scale);
dst[1].fPts[2] = fPts[2];
dst[0].fW = dst[1].fW = subdivide_w_value(fW);
}
/*
* "High order approximation of conic sections by quadratic splines"
* by Michael Floater, 1993
*/
#define AS_QUAD_ERROR_SETUP \
SkScalar a = fW - 1; \
SkScalar k = a / (4 * (2 + a)); \
SkScalar x = k * (fPts[0].fX - 2 * fPts[1].fX + fPts[2].fX); \
SkScalar y = k * (fPts[0].fY - 2 * fPts[1].fY + fPts[2].fY);
void SkConic::computeAsQuadError(SkVector* err) const {
AS_QUAD_ERROR_SETUP
err->set(x, y);
}
bool SkConic::asQuadTol(SkScalar tol) const {
AS_QUAD_ERROR_SETUP
return (x * x + y * y) <= tol * tol;
}
// Limit the number of suggested quads to approximate a conic
#define kMaxConicToQuadPOW2 5
int SkConic::computeQuadPOW2(SkScalar tol) const {
if (tol < 0 || !SkScalarIsFinite(tol)) {
return 0;
}
AS_QUAD_ERROR_SETUP
SkScalar error = SkScalarSqrt(x * x + y * y);
int pow2;
for (pow2 = 0; pow2 < kMaxConicToQuadPOW2; ++pow2) {
if (error <= tol) {
break;
}
error *= 0.25f;
}
// float version -- using ceil gives the same results as the above.
if (false) {
SkScalar err = SkScalarSqrt(x * x + y * y);
if (err <= tol) {
return 0;
}
SkScalar tol2 = tol * tol;
if (tol2 == 0) {
return kMaxConicToQuadPOW2;
}
SkScalar fpow2 = SkScalarLog2((x * x + y * y) / tol2) * 0.25f;
int altPow2 = SkScalarCeilToInt(fpow2);
if (altPow2 != pow2) {
SkDebugf("pow2 %d altPow2 %d fbits %g err %g tol %g\n", pow2, altPow2, fpow2, err, tol);
}
pow2 = altPow2;
}
return pow2;
}
static SkPoint* subdivide(const SkConic& src, SkPoint pts[], int level) {
SkASSERT(level >= 0);
if (0 == level) {
memcpy(pts, &src.fPts[1], 2 * sizeof(SkPoint));
return pts + 2;
} else {
SkConic dst[2];
src.chop(dst);
--level;
pts = subdivide(dst[0], pts, level);
return subdivide(dst[1], pts, level);
}
}
int SkConic::chopIntoQuadsPOW2(SkPoint pts[], int pow2) const {
SkASSERT(pow2 >= 0);
*pts = fPts[0];
SkDEBUGCODE(SkPoint* endPts =) subdivide(*this, pts + 1, pow2);
SkASSERT(endPts - pts == (2 * (1 << pow2) + 1));
return 1 << pow2;
}
bool SkConic::findXExtrema(SkScalar* t) const {
return conic_find_extrema(&fPts[0].fX, fW, t);
}
bool SkConic::findYExtrema(SkScalar* t) const {
return conic_find_extrema(&fPts[0].fY, fW, t);
}
bool SkConic::chopAtXExtrema(SkConic dst[2]) const {
SkScalar t;
if (this->findXExtrema(&t)) {
this->chopAt(t, dst);
// now clean-up the middle, since we know t was meant to be at
// an X-extrema
SkScalar value = dst[0].fPts[2].fX;
dst[0].fPts[1].fX = value;
dst[1].fPts[0].fX = value;
dst[1].fPts[1].fX = value;
return true;
}
return false;
}
bool SkConic::chopAtYExtrema(SkConic dst[2]) const {
SkScalar t;
if (this->findYExtrema(&t)) {
this->chopAt(t, dst);
// now clean-up the middle, since we know t was meant to be at
// an Y-extrema
SkScalar value = dst[0].fPts[2].fY;
dst[0].fPts[1].fY = value;
dst[1].fPts[0].fY = value;
dst[1].fPts[1].fY = value;
return true;
}
return false;
}
void SkConic::computeTightBounds(SkRect* bounds) const {
SkPoint pts[4];
pts[0] = fPts[0];
pts[1] = fPts[2];
int count = 2;
SkScalar t;
if (this->findXExtrema(&t)) {
this->evalAt(t, &pts[count++]);
}
if (this->findYExtrema(&t)) {
this->evalAt(t, &pts[count++]);
}
bounds->set(pts, count);
}
void SkConic::computeFastBounds(SkRect* bounds) const {
bounds->set(fPts, 3);
}
bool SkConic::findMaxCurvature(SkScalar* t) const {
// TODO: Implement me
return false;
}
SkScalar SkConic::TransformW(const SkPoint pts[], SkScalar w,
const SkMatrix& matrix) {
if (!matrix.hasPerspective()) {
return w;
}
SkP3D src[3], dst[3];
ratquad_mapTo3D(pts, w, src);
matrix.mapHomogeneousPoints(&dst[0].fX, &src[0].fX, 3);
// w' = sqrt(w1*w1/w0*w2)
SkScalar w0 = dst[0].fZ;
SkScalar w1 = dst[1].fZ;
SkScalar w2 = dst[2].fZ;
w = SkScalarSqrt((w1 * w1) / (w0 * w2));
return w;
}
int SkConic::BuildUnitArc(const SkVector& uStart, const SkVector& uStop, SkRotationDirection dir,
const SkMatrix* userMatrix, SkConic dst[kMaxConicsForArc]) {
// rotate by x,y so that uStart is (1.0)
SkScalar x = SkPoint::DotProduct(uStart, uStop);
SkScalar y = SkPoint::CrossProduct(uStart, uStop);
SkScalar absY = SkScalarAbs(y);
// check for (effectively) coincident vectors
// this can happen if our angle is nearly 0 or nearly 180 (y == 0)
// ... we use the dot-prod to distinguish between 0 and 180 (x > 0)
if (absY <= SK_ScalarNearlyZero && x > 0 && ((y >= 0 && kCW_SkRotationDirection == dir) ||
(y <= 0 && kCCW_SkRotationDirection == dir))) {
return 0;
}
if (dir == kCCW_SkRotationDirection) {
y = -y;
}
// We decide to use 1-conic per quadrant of a circle. What quadrant does [xy] lie in?
// 0 == [0 .. 90)
// 1 == [90 ..180)
// 2 == [180..270)
// 3 == [270..360)
//
int quadrant = 0;
if (0 == y) {
quadrant = 2; // 180
SkASSERT(SkScalarAbs(x + SK_Scalar1) <= SK_ScalarNearlyZero);
} else if (0 == x) {
SkASSERT(absY - SK_Scalar1 <= SK_ScalarNearlyZero);
quadrant = y > 0 ? 1 : 3; // 90 : 270
} else {
if (y < 0) {
quadrant += 2;
}
if ((x < 0) != (y < 0)) {
quadrant += 1;
}
}
const SkPoint quadrantPts[] = {
{ 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 }, { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 }
};
const SkScalar quadrantWeight = SK_ScalarRoot2Over2;
int conicCount = quadrant;
for (int i = 0; i < conicCount; ++i) {
dst[i].set(&quadrantPts[i * 2], quadrantWeight);
}
// Now compute any remaing (sub-90-degree) arc for the last conic
const SkPoint finalP = { x, y };
const SkPoint& lastQ = quadrantPts[quadrant * 2]; // will already be a unit-vector
const SkScalar dot = SkVector::DotProduct(lastQ, finalP);
SkASSERT(0 <= dot && dot <= SK_Scalar1 + SK_ScalarNearlyZero);
if (dot < 1 - SK_ScalarNearlyZero) {
SkVector offCurve = { lastQ.x() + x, lastQ.y() + y };
// compute the bisector vector, and then rescale to be the off-curve point.
// we compute its length from cos(theta/2) = length / 1, using half-angle identity we get
// length = sqrt(2 / (1 + cos(theta)). We already have cos() when to computed the dot.
// This is nice, since our computed weight is cos(theta/2) as well!
//
const SkScalar cosThetaOver2 = SkScalarSqrt((1 + dot) / 2);
offCurve.setLength(SkScalarInvert(cosThetaOver2));
dst[conicCount].set(lastQ, offCurve, finalP, cosThetaOver2);
conicCount += 1;
}
// now handle counter-clockwise and the initial unitStart rotation
SkMatrix matrix;
matrix.setSinCos(uStart.fY, uStart.fX);
if (dir == kCCW_SkRotationDirection) {
matrix.preScale(SK_Scalar1, -SK_Scalar1);
}
if (userMatrix) {
matrix.postConcat(*userMatrix);
}
for (int i = 0; i < conicCount; ++i) {
matrix.mapPoints(dst[i].fPts, 3);
}
return conicCount;
}
| [
"merck.hung@intel.com"
] | merck.hung@intel.com |
349a0af5844c153b303fff27cdf027cf14473ae2 | a71efc70ffb0d1884a63e44d84cc232d6a223513 | /include/basecode/core/log/system/default.h | 82ca99d8a4811730190489dc4d4dfac70f19bf8a | [] | no_license | basecode-lang/foundation | 753864a5b232b8ce9356e5f5dee8b98e7b092618 | 0d889ed7b928a21dcb27782cd8befb71496f8373 | refs/heads/develop | 2021-08-01T23:11:00.505299 | 2020-10-26T11:44:59 | 2020-10-26T11:44:59 | 251,269,067 | 4 | 2 | null | 2021-05-14T14:54:56 | 2020-03-30T10:14:01 | C | UTF-8 | C++ | false | false | 940 | h | // ----------------------------------------------------------------------------
// ____ _
// | _\ | |
// | |_)| __ _ ___ ___ ___ ___ __| | ___ TM
// | _< / _` / __|/ _ \/ __/ _ \ / _` |/ _ \
// | |_)| (_| \__ \ __/ (_| (_) | (_| | __/
// |____/\__,_|___/\___|\___\___/ \__,_|\___|
//
// F O U N D A T I O N P R O J E C T
//
// Copyright (C) 2020 Jeff Panici
// All rights reserved.
//
// This software source file is licensed under the terms of MIT license.
// For details, please read the LICENSE file.
//
// ----------------------------------------------------------------------------
#pragma once
#include <basecode/core/log.h>
namespace basecode {
struct default_config_t : logger_config_t {
FILE* file;
const s8* process_arg;
};
namespace log::default_ {
logger_system_t* system();
}
}
| [
"jeff.panici@panici-software.com"
] | jeff.panici@panici-software.com |
8d0aac3496964b7a02a60aa21054442e044e33ae | 06b5659e11702587ce032c8e245571d39c01bd83 | /feature_index.cpp | 2d3c7f616dd38262bc7d8384909686dd90488dcf | [] | no_license | rm-rf-me/CRF_Learn | 9aa27dfac22fe80e1176185f096194b5942610a2 | 4b769a8e99c201a65ff3e9d159c0af0619ac6613 | refs/heads/master | 2022-06-08T11:50:45.061186 | 2020-05-07T18:35:12 | 2020-05-07T18:35:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,804 | cpp | //
// CRF++ -- Yet Another CRF toolkit
//
// $Id: feature_index.cpp 1587 2007-02-12 09:00:36Z taku $;
//
// Copyright(C) 2005-2007 Taku Kudo <taku@chasen.org>
//
#include <iostream>
#include <fstream>
#include <cstring>
#include <set>
#include "common.h"
#include "feature_index.h"
namespace CRFPP {
namespace {
const char *read_ptr(const char **ptr, size_t size) {
const char *r = *ptr;
*ptr += size;
return r;
}
template <class T> static inline void read_static(const char **ptr,
T *value) {
const char *r = read_ptr(ptr, sizeof(T));
memcpy(value, r, sizeof(T));
}
void make_templs(const std::vector<std::string> unigram_templs, // 非常简单的方式拼接两个txt文件
const std::vector<std::string> bigram_templs,
std::string *templs) {
templs->clear();
for (size_t i = 0; i < unigram_templs.size(); ++i) {
templs->append(unigram_templs[i]);
templs->append("\n");
}
for (size_t i = 0; i < bigram_templs.size(); ++i) {
templs->append(bigram_templs[i]);
templs->append("\n");
}
}
} // namespace
char *Allocator::strdup(const char *p) {
const size_t len = std::strlen(p);
char *q = char_freelist_->alloc(len + 1);
std::strcpy(q, p);
return q;
}
Allocator::Allocator(size_t thread_num)
: thread_num_(thread_num),
feature_cache_(new FeatureCache),
char_freelist_(new FreeList<char>(8192)) {
init();
}
Allocator::Allocator()
: thread_num_(1),
feature_cache_(new FeatureCache),
char_freelist_(new FreeList<char>(8192)) {
init();
}
Allocator::~Allocator() {}
Path *Allocator::newPath(size_t thread_id) {
return path_freelist_[thread_id].alloc();
}
Node *Allocator::newNode(size_t thread_id) {
return node_freelist_[thread_id].alloc();
}
void Allocator::clear() {
feature_cache_->clear();
char_freelist_->free();
for (size_t i = 0; i < thread_num_; ++i) {
path_freelist_[i].free();
node_freelist_[i].free();
}
}
void Allocator::clear_freelist(size_t thread_id) {
path_freelist_[thread_id].free();
node_freelist_[thread_id].free();
}
FeatureCache *Allocator::feature_cache() const {
return feature_cache_.get();
}
size_t Allocator::thread_num() const {
return thread_num_;
}
void Allocator::init() {
path_freelist_.reset(new FreeList<Path> [thread_num_]);
node_freelist_.reset(new FreeList<Node> [thread_num_]);
for (size_t i = 0; i < thread_num_; ++i) {
path_freelist_[i].set_size(8192 * 16);
node_freelist_[i].set_size(8192);
}
}
int DecoderFeatureIndex::getID(const char *key) const {
return da_.exactMatchSearch<Darts::DoubleArray::result_type>(key);
}
int EncoderFeatureIndex::getID(const char *key) const {
std::map <std::string, std::pair<int, unsigned int> >::iterator
it = dic_.find(key);
if (it == dic_.end()) {
dic_.insert(std::make_pair
(std::string(key),
std::make_pair(maxid_, static_cast<unsigned int>(1))));
const int n = maxid_;
maxid_ += (key[0] == 'U' ? y_.size() : y_.size() * y_.size());
return n;
} else {
it->second.second++;
return it->second.first;
}
return -1;
}
bool EncoderFeatureIndex::open(const char *template_filename, // 根据模板抽取文件特征
const char *train_filename) {
check_max_xsize_ = true;
return openTemplate(template_filename) && openTagSet(train_filename);
}
bool EncoderFeatureIndex::openTemplate(const char *filename) { // 读取模板文件并获取特征模板
std::ifstream ifs(WPATH(filename));
CHECK_FALSE(ifs) << "open failed: " << filename;
std::string line;
while (std::getline(ifs, line)) {
if (!line[0] || line[0] == '#') {
continue;
}
if (line[0] == 'U') {
unigram_templs_.push_back(line);
} else if (line[0] == 'B') {
bigram_templs_.push_back(line);
} else {
CHECK_FALSE(true) << "unknown type: " << line << " " << filename;
}
}
make_templs(unigram_templs_, bigram_templs_, &templs_);
return true;
}
bool EncoderFeatureIndex::openTagSet(const char *filename) {
std::ifstream ifs(WPATH(filename));
CHECK_FALSE(ifs) << "no such file or directory: " << filename;
scoped_fixed_array<char, 8192> line;
scoped_fixed_array<char *, 1024> column;
size_t max_size = 0;
std::set<std::string> candset;
while (ifs.getline(line.get(), line.size())) {
if (line[0] == '\0' || line[0] == ' ' || line[0] == '\t') {
continue;
}
const size_t size = tokenize2(line.get(), "\t ",
column.get(), column.size());
if (max_size == 0) {
max_size = size;
}
CHECK_FALSE(max_size == size)
<< "inconsistent column size: "
<< max_size << " " << size << " " << filename;
xsize_ = size - 1;
candset.insert(column[max_size-1]);
}
y_.clear();
for (std::set<std::string>::iterator it = candset.begin();
it != candset.end(); ++it) {
y_.push_back(*it);
}
ifs.close();
return true;
}
bool DecoderFeatureIndex::open(const char *model_filename) {
CHECK_FALSE(mmap_.open(model_filename)) << mmap_.what();
return openFromArray(mmap_.begin(), mmap_.file_size());
}
bool DecoderFeatureIndex::openFromArray(const char *ptr, size_t size) {
unsigned int version_ = 0;
const char *end = ptr + size;
read_static<unsigned int>(&ptr, &version_);
CHECK_FALSE(version_ / 100 == version / 100)
<< "model version is different: " << version_
<< " vs " << version;
int type = 0;
read_static<int>(&ptr, &type);
read_static<double>(&ptr, &cost_factor_);
read_static<unsigned int>(&ptr, &maxid_);
read_static<unsigned int>(&ptr, &xsize_);
unsigned int dsize = 0;
read_static<unsigned int>(&ptr, &dsize);
unsigned int y_str_size;
read_static<unsigned int>(&ptr, &y_str_size);
const char *y_str = read_ptr(&ptr, y_str_size);
size_t pos = 0;
while (pos < y_str_size) {
y_.push_back(y_str + pos);
while (y_str[pos++] != '\0') {}
}
unsigned int tmpl_str_size;
read_static<unsigned int>(&ptr, &tmpl_str_size);
const char *tmpl_str = read_ptr(&ptr, tmpl_str_size);
pos = 0;
while (pos < tmpl_str_size) {
const char *v = tmpl_str + pos;
if (v[0] == '\0') {
++pos;
} else if (v[0] == 'U') {
unigram_templs_.push_back(v);
} else if (v[0] == 'B') {
bigram_templs_.push_back(v);
} else {
CHECK_FALSE(true) << "unknown type: " << v;
}
while (tmpl_str[pos++] != '\0') {}
}
make_templs(unigram_templs_, bigram_templs_, &templs_);
da_.set_array(const_cast<char *>(ptr));
ptr += dsize;
alpha_float_ = reinterpret_cast<const float *>(ptr);
ptr += sizeof(alpha_float_[0]) * maxid_;
CHECK_FALSE(ptr == end) << "model file is broken.";
return true;
}
void EncoderFeatureIndex::shrink(size_t freq, Allocator *allocator) { // 根据阈值过滤特征
if (freq <= 1) {
return;
}
std::map<int, int> old2new;
int new_maxid = 0;
for (std::map<std::string, std::pair<int, unsigned int> >::iterator
it = dic_.begin(); it != dic_.end();) {
const std::string &key = it->first;
if (it->second.second >= freq) {
old2new.insert(std::make_pair(it->second.first, new_maxid));
it->second.first = new_maxid;
new_maxid += (key[0] == 'U' ? y_.size() : y_.size() * y_.size());
++it;
} else {
dic_.erase(it++);
}
}
allocator->feature_cache()->shrink(&old2new);
maxid_ = new_maxid;
}
bool EncoderFeatureIndex::convert(const char *text_filename,
const char *binary_filename) {
std::ifstream ifs(WPATH(text_filename));
y_.clear();
dic_.clear();
unigram_templs_.clear();
bigram_templs_.clear();
xsize_ = 0;
maxid_ = 0;
CHECK_FALSE(ifs) << "open failed: " << text_filename;
scoped_fixed_array<char, 8192> line;
char *column[8];
// read header
while (true) {
CHECK_FALSE(ifs.getline(line.get(), line.size()))
<< " format error: " << text_filename;
if (std::strlen(line.get()) == 0) {
break;
}
const size_t size = tokenize(line.get(), "\t ", column, 2);
CHECK_FALSE(size == 2) << "format error: " << text_filename;
if (std::strcmp(column[0], "xsize:") == 0) {
xsize_ = std::atoi(column[1]);
}
if (std::strcmp(column[0], "maxid:") == 0) {
maxid_ = std::atoi(column[1]);
}
}
CHECK_FALSE(maxid_ > 0) << "maxid is not defined: " << text_filename;
CHECK_FALSE(xsize_ > 0) << "xsize is not defined: " << text_filename;
while (true) {
CHECK_FALSE(ifs.getline(line.get(), line.size()))
<< "format error: " << text_filename;
if (std::strlen(line.get()) == 0) {
break;
}
y_.push_back(line.get());
}
while (true) {
CHECK_FALSE(ifs.getline(line.get(), line.size()))
<< "format error: " << text_filename;
if (std::strlen(line.get()) == 0) {
break;
}
if (line[0] == 'U') {
unigram_templs_.push_back(line.get());
} else if (line[0] == 'B') {
bigram_templs_.push_back(line.get());
} else {
CHECK_FALSE(true) << "unknown type: " << line.get()
<< " " << text_filename;
}
}
while (true) {
CHECK_FALSE(ifs.getline(line.get(), line.size()))
<< "format error: " << text_filename;
if (std::strlen(line.get()) == 0) {
break;
}
const size_t size = tokenize(line.get(), "\t ", column, 2);
CHECK_FALSE(size == 2) << "format error: " << text_filename;
dic_.insert(std::make_pair
(std::string(column[1]),
std::make_pair(std::atoi(column[0]),
static_cast<unsigned int>(1))));
}
std::vector<double> alpha;
while (ifs.getline(line.get(), line.size())) {
alpha.push_back(std::atof(line.get()));
}
alpha_ = &alpha[0];
CHECK_FALSE(alpha.size() == maxid_) << " file is broken: " << text_filename;
return save(binary_filename, false);
}
bool EncoderFeatureIndex::save(const char *filename,
bool textmodelfile) {
std::vector<char *> key;
std::vector<int> val;
std::string y_str;
for (size_t i = 0; i < y_.size(); ++i) {
y_str += y_[i];
y_str += '\0';
}
std::string templ_str;
for (size_t i = 0; i < unigram_templs_.size(); ++i) {
templ_str += unigram_templs_[i];
templ_str += '\0';
}
for (size_t i = 0; i < bigram_templs_.size(); ++i) {
templ_str += bigram_templs_[i];
templ_str += '\0';
}
while ((y_str.size() + templ_str.size()) % 4 != 0) {
templ_str += '\0';
}
for (std::map<std::string, std::pair<int, unsigned int> >::iterator
it = dic_.begin();
it != dic_.end(); ++it) {
key.push_back(const_cast<char *>(it->first.c_str()));
val.push_back(it->second.first);
}
Darts::DoubleArray da;
CHECK_FALSE(da.build(key.size(), &key[0], 0, &val[0]) == 0)
<< "cannot build double-array";
std::ofstream bofs;
bofs.open(WPATH(filename), OUTPUT_MODE);
CHECK_FALSE(bofs) << "open failed: " << filename;
unsigned int version_ = version;
bofs.write(reinterpret_cast<char *>(&version_), sizeof(unsigned int));
int type = 0;
bofs.write(reinterpret_cast<char *>(&type), sizeof(type));
bofs.write(reinterpret_cast<char *>(&cost_factor_), sizeof(cost_factor_));
bofs.write(reinterpret_cast<char *>(&maxid_), sizeof(maxid_));
if (max_xsize_ > 0) {
xsize_ = std::min(xsize_, max_xsize_);
}
bofs.write(reinterpret_cast<char *>(&xsize_), sizeof(xsize_));
unsigned int dsize = da.unit_size() * da.size();
bofs.write(reinterpret_cast<char *>(&dsize), sizeof(dsize));
unsigned int size = y_str.size();
bofs.write(reinterpret_cast<char *>(&size), sizeof(size));
bofs.write(const_cast<char *>(y_str.data()), y_str.size());
size = templ_str.size();
bofs.write(reinterpret_cast<char *>(&size), sizeof(size));
bofs.write(const_cast<char *>(templ_str.data()), templ_str.size());
bofs.write(reinterpret_cast<const char *>(da.array()), dsize);
for (size_t i = 0; i < maxid_; ++i) {
float alpha = static_cast<float>(alpha_[i]);
bofs.write(reinterpret_cast<char *>(&alpha), sizeof(alpha));
}
bofs.close();
if (textmodelfile) {
std::string filename2 = filename;
filename2 += ".txt";
std::ofstream tofs(WPATH(filename2.c_str()));
CHECK_FALSE(tofs) << " no such file or directory: " << filename2;
// header
tofs << "version: " << version_ << std::endl;
tofs << "cost-factor: " << cost_factor_ << std::endl;
tofs << "maxid: " << maxid_ << std::endl;
tofs << "xsize: " << xsize_ << std::endl;
tofs << std::endl;
// y
for (size_t i = 0; i < y_.size(); ++i) {
tofs << y_[i] << std::endl;
}
tofs << std::endl;
// template
for (size_t i = 0; i < unigram_templs_.size(); ++i) {
tofs << unigram_templs_[i] << std::endl;
}
for (size_t i = 0; i < bigram_templs_.size(); ++i) {
tofs << bigram_templs_[i] << std::endl;
}
tofs << std::endl;
// dic
for (std::map<std::string, std::pair<int, unsigned int> >::iterator
it = dic_.begin();
it != dic_.end(); ++it) {
tofs << it->second.first << " " << it->first << std::endl;
}
tofs << std::endl;
tofs.setf(std::ios::fixed, std::ios::floatfield);
tofs.precision(16);
for (size_t i = 0; i < maxid_; ++i) {
tofs << alpha_[i] << std::endl;
}
}
return true;
}
const char *FeatureIndex::getTemplate() const { // 获得模板
return templs_.c_str();
}
void FeatureIndex::calcCost(Node *n) const { // 计算当前节点的cost,cost就是权值乘以特征函数,具体见论文
n->cost = 0.0;
#define ADD_COST(T, A)
do { T c = 0;
for (const int *f = n->fvector; *f != -1; ++f) {
c += (A)[*f + n->y]; // 对当前节点命中的每个特征函数对应当前节点标签的特征求和
}
n->cost = cost_factor_ *(T)c;
} while (0) // 这个while写的什么破玩意。。。
if (alpha_float_) {
ADD_COST(float, alpha_float_);
} else {
ADD_COST(double, alpha_);
}
#undef ADD_COST
}
void FeatureIndex::calcCost(Path *p) const { // 同上
p->cost = 0.0;
#define ADD_COST(T, A) \
{ T c = 0.0; \
for (const int *f = p->fvector; *f != -1; ++f) { \
c += (A)[*f + p->lnode->y * y_.size() + p->rnode->y]; \
} \
p->cost =cost_factor_*(T)c; }
if (alpha_float_) {
ADD_COST(float, alpha_float_);
} else {
ADD_COST(double, alpha_);
}
}
#undef ADD_COST
}
| [
"1127429568@qq.com"
] | 1127429568@qq.com |
d1556fce053044361f4da4ef5fb52f4675e6ccaa | 6af66266477d93fb950ef00f015e43442029e750 | /10037-bridge.cpp | 7a5ce1bc40754d96faeb1c906032b381bcfd74d0 | [] | no_license | danys/UVa | d34aa5014e94fe4f228371a736e145b413f4abc6 | 8742624906b0a204cfcd4a071fa4a6e5676c7a92 | refs/heads/master | 2020-05-19T18:53:19.763872 | 2015-10-30T22:16:07 | 2015-10-30T22:16:07 | 19,714,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,778 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> people;
vector<int> solution;
int totaltime;
void solve(int n)
{
if (n<1) return;
else if (n==1)
{
solution.push_back(people[0]);
solution.push_back(-1);
totaltime += people[0];
}
else if (n==2)
{
solution.push_back(min(people[0],people[1]));
solution.push_back(max(people[0],people[1]));
solution.push_back(-1);
totaltime += max(people[0],people[1]);
}
else if (n==3)
{
solution.push_back(people[0]);
solution.push_back(people[2]);
solution.push_back(-1);
solution.push_back(people[0]);
solution.push_back(-1);
solution.push_back(people[0]);
solution.push_back(people[1]);
solution.push_back(-1);
totaltime += people[0]+people[1]+people[2];
}
else
{
int x1,x2,x3,x4;
x1=people[0];
x2=people[1];
x3=people[n-2];
x4=people[n-1];
if (x1+x3<2*x2)
{
solution.push_back(x1);
solution.push_back(x4);
solution.push_back(-1);
solution.push_back(x1);
solution.push_back(-1);
solution.push_back(x1);
solution.push_back(x3);
solution.push_back(-1);
solution.push_back(x1);
solution.push_back(-1);
totaltime += x4+x1+x3+x1;
}
else
{
solution.push_back(x1);
solution.push_back(x2);
solution.push_back(-1);
solution.push_back(x1);
solution.push_back(-1);
solution.push_back(x3);
solution.push_back(x4);
solution.push_back(-1);
solution.push_back(x2);
solution.push_back(-1);
totaltime += x2+x1+x4+x2;
}
people.pop_back();
people.pop_back();
solve(n-2);
}
}
void print()
{
cout << totaltime << endl;
for(vector<int>::iterator i=solution.begin();i!=solution.end(); ++i)
{
if (*i==-1) cout << endl;
else
{
if (*(i+1)==-1) cout << *i;
else cout << *i << " ";
}
}
}
void init()
{
people.clear();
solution.clear();
totaltime = 0;
}
int main()
{
int cases,n,t;
string str;
cin >> cases;
for(int z=1;z<=cases;z++)
{
cin.ignore();
getline(cin,str);
cin >> n;
init();
for(int i=0;i<n;i++)
{
cin >> t;
people.push_back(t);
}
sort(people.begin(),people.end());
solve(n);
print();
if (z!=cases) cout << endl;
}
}
| [
"netfox2006@hotmail.com"
] | netfox2006@hotmail.com |
b36be09c9afa544d702ae93e2aaa5689799d70df | 286d09352bbab8d5c9c0e618e5c34658a477f2e0 | /Programmers/주식가격.cpp | 48e4007c4a490c75ceb4dbf6641ba101ef1baeea | [] | no_license | Othereum/Problem-Solving | 87a0a7eced07fb1fb7ec60613630405d73afdc50 | b7d4a59710fae5a09a5a244360c01e0e9be56c36 | refs/heads/master | 2021-07-16T16:52:26.361754 | 2020-06-14T14:22:42 | 2020-06-14T14:22:42 | 174,680,007 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 372 | cpp | // https://programmers.co.kr/learn/courses/30/lessons/42584
#include <vector>
using namespace std;
vector<int> solution(const vector<int> prices)
{
vector<int> answer(prices.size());
for (size_t i = 0; i < prices.size(); ++i)
{
for (auto j = i + 1; j < prices.size(); ++j)
{
++answer[i];
if (prices[i] > prices[j]) break;
}
}
return answer;
}
| [
"seokjin.dev@gmail.com"
] | seokjin.dev@gmail.com |
cb11f6c94e399fa86a9ef539bbd3eb8bbcba3b50 | d305e9667f18127e4a1d4d65e5370cf60df30102 | /mindspore/ccsrc/runtime/device/ascend/profiling/profiling_engine_impl.cc | 1f35cba0f74bea58d934143e4c12158a1af44f38 | [
"Apache-2.0",
"MIT",
"Libpng",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-only",
"AGPL-3.0-only",
"MPL-2.0-no-copyleft-exception",
"IJG",
"Zlib",
"MPL-1.1",
"BSD-3-Clause",
"BSD-3-Clause-Open-MPI",
"MPL-1.0",
"GPL-2.0-only",
"MPL-2.0",
"BSL-1.0",
"LicenseRef-scancode-unknow... | permissive | imyzx2017/mindspore_pcl | d8e5bd1f80458538d07ef0a8fc447b552bd87420 | f548c9dae106879d1a83377dd06b10d96427fd2d | refs/heads/master | 2023-01-13T22:28:42.064535 | 2020-11-18T11:15:41 | 2020-11-18T11:15:41 | 313,906,414 | 6 | 1 | Apache-2.0 | 2020-11-18T11:25:08 | 2020-11-18T10:57:26 | null | UTF-8 | C++ | false | false | 1,186 | cc | /**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "runtime/device/ascend/profiling/profiling_engine_impl.h"
#include "utils/log_adapter.h"
#include "runtime/device/ascend/profiling/plugin_impl.h"
namespace mindspore {
namespace device {
namespace ascend {
PluginIntf *ProfilingEngineImpl::CreatePlugin() {
MS_LOG(INFO) << "Create Plugin.";
return new (std::nothrow) PluginImpl("Framework");
}
int ProfilingEngineImpl::ReleasePlugin(PluginIntf *plugin) {
if (plugin != nullptr) {
delete plugin;
plugin = nullptr;
}
return 0;
}
} // namespace ascend
} // namespace device
} // namespace mindspore
| [
"513344092@qq.com"
] | 513344092@qq.com |
282685700cde6ee9d9ab137911111bdf7d807ca2 | d2cf3776378fbef224000686dbc354bc98b53a8b | /Marlin_HICTOP/Marlin_HICTOP.ino | cf0c903e614f27684e7a7b1ea0e8717a1b3dad44 | [] | no_license | electronicsuk/HictopI3Newest | 98520701b357e28e0a7212a599b8d9563315f9fa | 20da18197eb585d40d60f39fbfd1c4ddf5238cfb | refs/heads/master | 2020-06-20T04:39:33.097509 | 2016-11-27T20:13:20 | 2016-11-27T20:13:20 | 74,881,120 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,202 | ino | /** Original
Marlin 3D Printer Firmware
Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
Based on Sprinter and grbl.
Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
About Marlin
This firmware is a mashup between Sprinter and grbl.
- https://github.com/kliment/Sprinter
- https://github.com/simen/grbl/tree
It has preliminary support for Matthew Roberts advance algorithm
- http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
*/
/* All the implementation is done in *.cpp files to get better compatibility with avr-gcc without the Arduino IDE */
/* Use this file to help the Arduino IDE find which Arduino libraries are needed and to keep documentation on GCode */
#include "Configuration.h"
#include "pins.h"
#if ENABLED(ULTRA_LCD)
#if ENABLED(LCD_I2C_TYPE_PCF8575)
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#elif ENABLED(LCD_I2C_TYPE_MCP23017) || ENABLED(LCD_I2C_TYPE_MCP23008)
#include <Wire.h>
#include <LiquidTWI2.h>
#elif ENABLED(LCM1602)
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#elif ENABLED(DOGLCD)
#include <U8glib.h> // library for graphics LCD by Oli Kraus (https://github.com/olikraus/U8glib_Arduino)
#else
#include <LiquidCrystal.h> // library for character LCD
#endif
#endif
#if HAS_DIGIPOTSS
#include <SPI.h>
#endif
#if ENABLED(DIGIPOT_I2C)
#include <Wire.h>
#endif
#if ENABLED(HAVE_TMCDRIVER)
#include <SPI.h>
#include <TMC26XStepper.h>
#endif
#if ENABLED(HAVE_L6470DRIVER)
#include <SPI.h>
#include <L6470.h>
#endif
| [
"swchoi.choi@googlemail.com"
] | swchoi.choi@googlemail.com |
08030c0d994c5e5a7b561400d224345399e443fc | 7b2753066917a0dc8b1abb5b49dd64c590307b00 | /Src/CSSParser/Selectors/SelectorGroup.hpp | 7b4b438bc502ce9e07666fcf8793e12409787a97 | [] | no_license | lixiaoyu0123/CSSParser | 68afb3b9722550d50d8ed8af4396f1f5298931d7 | d9f9d682885105b1896ebb178f9d28e6d10dac54 | refs/heads/master | 2020-03-27T17:28:31.067600 | 2018-08-31T06:47:24 | 2018-08-31T06:47:24 | 146,853,766 | 1 | 0 | null | 2018-08-31T06:54:36 | 2018-08-31T06:54:36 | null | UTF-8 | C++ | false | false | 756 | hpp | //
// SelectorGroup.hpp
// DDCSSParser
//
// Created by 1m0nster on 2018/8/7.
// Copyright © 2018 1m0nster. All rights reserved.
//
#ifndef SelectorGroup_hpp
#define SelectorGroup_hpp
#include <stdio.h>
#include <iostream>
#include <list>
#include "Selector.hpp"
namespace future {
class GroupSelector: public Selector {
public:
GroupSelector()
{
m_selectorType = Selector::SelectorGroup;
}
~GroupSelector();
void addSelector(Selector *);
std::list<Selector *>getAllSelectors()
{
return m_selectors;
}
bool isBaseSelector();
int weight();
private:
std::list<Selector *> m_selectors;
};
}
#endif /* SelectorGroup_hpp */
| [
"fuguoqiang@luojilab.com"
] | fuguoqiang@luojilab.com |
28f6a1320ae2f0b70845389dfed81ff20a021ce8 | 5a28eb7e202e21d43a5c268a5c5cb59c6d0ee9e8 | /block.cpp | 9351070f0fcdec6a0620f57eef0f6dafc23214b8 | [] | no_license | jessicawaz/Snake-Game | ab550bd9c225171b22a5135ddfbcc322fd77871e | 0e1e9fbdf40866bdbb2721b80f9124cf06f9a1d0 | refs/heads/master | 2023-01-29T06:33:23.100368 | 2020-12-03T15:54:41 | 2020-12-03T15:54:41 | 318,244,853 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,805 | cpp | /**********************************************************
* file: b.cpp
* by: Jessica Wazbinski
* org: COP 2001, Spring 2020
* for: Implementation file for a point class object by
column and row
**********************************************************/
#include "block.h"
//-------------------------------------------
// Constructors
//-------------------------------------------
/**********************************************************
Default constructor of a point block class object, will
instantiate an empty block
Parameters:
Returns:
Block(-1, -1) ... doesnt really return anything
just a comment for us
***********************************************************/
Block::Block() {
column = -1;
row = -1;
forward = nullptr;
backward = nullptr;
}
/**********************************************************
Instantiate a point block class object at column and row
Parameters:
columnIn - x-coord
rowIn - y-coord
Returns:
Block(columnIn, rowIn)
***********************************************************/
Block::Block(int columnIn, int rowIn) {
column = columnIn;
row = rowIn;
forward = nullptr;
backward = nullptr;
}
/**********************************************************
Copy constructor sets block column and row from another
block
Parameters:
other - pointer to block to copy
Returns:
***********************************************************/
Block::Block(Block* other) {
//copy the column and row values
copy(other);
forward = nullptr;
backward = nullptr;
}
//-------------------------------------------
// Accessors
//-------------------------------------------
/**********************************************************
Returns the current column property value
Parameters:
Returns:
int - column value or -1 if empty
***********************************************************/
int Block::getColumn() {
return column;
}
/**********************************************************
Modify the current column property value
Parameters:
column - column value to set
Returns:
void
***********************************************************/
void Block::setColumn(int columnIn) {
column = columnIn;
}
/**********************************************************
Returns the current row property value
Parameters:
Returns:
int - row value or -1 if empty
***********************************************************/
int Block::getRow() {
return row;
}
/**********************************************************
Modify the current row property value
Parameters:
rowIn - row value to set
Returns:
void
***********************************************************/
void Block::setRow(int rowIn) {
row = rowIn;
}
/**********************************************************
Returns the pointer to the block in front of this one
Parameters:
Returns:
Block* - pointer to block
***********************************************************/
Block* Block::getForward() {
return forward;
}
/**********************************************************
Returns the pointer to the block in front of this one
Parameters :
Returns:
Block * -pointer to block
* **********************************************************/
Block* Block::getBackward() {
return backward;
}
//-------------------------------------------
// Methods
//-------------------------------------------
/**********************************************************
Determine if another block is the same as this one by
column and row
Parameters:
other - block to check for equality
Returns:
bool - true if same column and row
***********************************************************/
bool Block::equals(Block other) {
return column == other.getColumn() && //enter after logical operator breaks up long expression
row == other.getRow();
}
/**********************************************************
Determine if this block is empty
Parameters:
Returns:
bool - true if this block is empty
***********************************************************/
bool Block::isEmpty() {
Block empty = Block(); //creates empty block
return equals(empty); //if block above = empty block
}
/**********************************************************
Copy the values of another block to this one
Parameters:
other - block to copy
Returns:
void
***********************************************************/
void Block::copy(Block* other) {
column = other->getColumn();
row = other->getRow();
return;
}
/**********************************************************
Link another block to the backward pointer of this one
Parameters:
other - block to link
Returns:
void
***********************************************************/
void Block::append(Block* other) {
backward = new Block(other); //made a new block and copied from prev tail
backward->forward = this;
return;
}
| [
"jesswaz24@gmail.com"
] | jesswaz24@gmail.com |
a1912e8d5bbc3e16af48769e7c45cc6a822615e4 | 3bcfc8cf93fb48dc1c4135e2a355eb80e0c83e93 | /launchframe.cpp | 367d8ec9ecda14f55473cf7b562f9622b27835f2 | [
"MIT"
] | permissive | radtek/amp | d65aa2c6e35a193545e60f79acc2a7712353b2d3 | efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763 | refs/heads/master | 2023-01-10T10:23:05.786483 | 2020-11-15T10:13:41 | 2020-11-15T10:13:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,988 | cpp | #include "launchframe.h"
#include "datathread.h"
#include <QMessageBox>
#include <QJsonParseError>
#include "mainwindow.h"
static int setupSteps = 0;
QApplication* gApp = nullptr;
LaunchFrame::LaunchFrame(QWidget *parent) :
QFrame(parent)
{
this->setObjectName("launchWnd");
this->setStyleSheet("LaunchFrame#launchWnd{ border-image: url(:/res/img/grass.jpg);}");
_rediscli = new RedisClient(this);
_rediscli->connectToServer(REDISSERVER, REDISPORT);
_loading = new QLabel(this);
_loading->setText("Loading ...");
}
LaunchFrame::~LaunchFrame()
{
}
void LaunchFrame::showEvent(QShowEvent* e) {
QFrame::showEvent(e);
}
void LaunchFrame::resizeEvent(QResizeEvent* e) {
QFrame::resizeEvent(e);
QRect rect = this->geometry();
_loading->setGeometry(10, 10, rect.width() - 10, 50);
}
void LaunchFrame::switchMainFrame() {
static MainWindow *w = nullptr;
if(nullptr == w) {
w = new MainWindow();
}
w->setMinimumSize(800, 600);
// w->setMaximumSize(1024, 768);
w->showFullScreen();
gApp->connect( gApp, SIGNAL( lastWindowClosed() ), w, SLOT( quit() ) );
}
void LaunchFrame::connected() {
qDebug() << "redis connect to local server OK";
_rediscli->sendCommand(Command::Auth(REDISAUTH));
}
void LaunchFrame::disconnected() {
usleep(2 * 1000 * 1000);
_rediscli->connectToServer(REDISSERVER, REDISPORT); //重连
}
bool LaunchFrame::loadTables() {
QFile tab(QString("%1/tables.conf").arg(WORKDIR));
if( tab.exists() == false) {
qDebug() << "load tables conf failed: file is not exists";
return false;
}
if(!tab.open(QIODevice::ReadWrite))
{
qDebug() << "load tables conf failed: file opened failed";
return false;
}
QString data = tab.readAll();
QJsonParseError json_error;
QJsonDocument jsonDoc(QJsonDocument::fromJson(QByteArray::fromPercentEncoding(data.toLocal8Bit()), &json_error));
if(json_error.error != QJsonParseError::NoError)
{
//QMessageBox::warning(nullptr, "错误", "无法加载口味设置配置文件,配置文件格式不合法");
qDebug() << "load local data failed, json error: " << json_error.errorString();
return false;
} else {
gTables = jsonDoc.toVariant().toList();
this->_rediscli->sendCommand(Command::GET("echo"));
return true;
}
}
bool LaunchFrame::loadFlavors() {
QFile flavors(QString("%1/flavors.conf").arg(WORKDIR));
if( flavors.exists() == false) {
qDebug() << "load flavors conf failed: file is not exists";
return false;
}
if(!flavors.open(QIODevice::ReadWrite))
{
qDebug() << "load flavors conf failed: file opened failed";
return false;
}
QString data = flavors.readAll();
QJsonParseError json_error;
QJsonDocument jsonDoc(QJsonDocument::fromJson(QByteArray::fromPercentEncoding(data.toLocal8Bit()), &json_error));
if(json_error.error != QJsonParseError::NoError)
{
//QMessageBox::warning(nullptr, "错误", "无法加载口味设置配置文件,配置文件格式不合法");
qDebug() << "load local data failed, json error: " << json_error.errorString();
return false;
} else {
gFlavors = jsonDoc.toVariant().toMap();
this->_rediscli->sendCommand(Command::GET("echo"));
return true;
}
}
void LaunchFrame::onReply(const QString& cmd, Reply value) {
//
setupSteps++;
qDebug() << "LaunchFrame::onReply step: " << setupSteps << ", cmd: " << cmd << ", value: " << value.value().toString();
QString key = cmd.toLower().trimmed();
if(key.startsWith("auth")) {
if(value.value().toString().trimmed() != "OK") {
setupSteps --;
this->_loading->setText("AMP: Connect to Server Failed");
return;
}
} else if(key.startsWith(QString("hgetall res:info:%1").arg(gRID))) {
QList<QVariant> item = value.value().toList();
if(item.length() == 0) {
QMessageBox::warning(nullptr, "错误", "当前店家没有设置安装数据");
return;
}
for(int i = 0; i < item.length(); i++) {
if( item[i].toString() == "rid") {
gRestaurant.insert("rid", item[i + 1].toInt());
gRestaurant.insert("id", item[i + 1].toInt());
} else if(item[i].toString() == "account") {
gRestaurant.insert("account", item[i + 1].toString());
} else if(item[i].toString() == "name") {
gRestaurant.insert("name", item[i + 1].toString());
} else if(item[i].toString() == "uuid") {
gRestaurant.insert("uuid", item[i + 1].toString());
} else if(item[i].toString() == "token") {
gRestaurant.insert("token", item[i + 1].toString());
} else if(item[i].toString() == "taxRate") {
gRestaurant.insert("taxRate", item[i + 1].toFloat());
} else if(item[i].toString() == "address") {
gRestaurant.insert("address", item[i + 1].toString());
} else if(item[i].toString() == "phoneNumbers") {
gRestaurant.insert("phoneNumbers", item[i + 1].toString());
} else if(item[i].toString() == "cloudIP") {
gRestaurant.insert("cloudIP", item[i + 1].toString());
}
}
} else if(key.startsWith(QString("hgetall res:printer:config:rid:%1").arg(gRID))) {
_kitchPrinter.clear();
_cashierPrinter = "";
QList<QVariant> item = value.value().toList();
for(int i = 0; i < item.length() - 1; i++) {
if( item[i + 1].toString() == "cashier") {
_cashierPrinter = item[i].toString();
} else if( item[i + 1].toString().startsWith("kitchen-")) {
_kitchPrinter.push_back( item[i].toString());
}
}
if("" == _cashierPrinter) {
QMessageBox::warning(nullptr, "错误", "前台打印机设置无效");
}
} else if(key.startsWith(QString("hget res:conf:%1 flavors").arg(gRID))) {
QString flavors = value.value().toString();
if("" == flavors) {
setupSteps--;
}
else {
QJsonParseError json_error;
QJsonDocument jsonDoc(QJsonDocument::fromJson(QByteArray::fromPercentEncoding(flavors.toLocal8Bit()), &json_error));
if(json_error.error != QJsonParseError::NoError)
{
//QMessageBox::warning(nullptr, "错误", "无法加载口味设置配置文件,配置文件格式不合法");
qDebug() << "json error: " << json_error.errorString();
gFlavors = QVariantMap();
} else {
gFlavors = jsonDoc.toVariant().toMap();
}
}
} else if(key.startsWith(QString("hget res:conf:%1 tables").arg(gRID))) {
QString tables = value.value().toString();
if("" == tables) {
setupSteps--;
}
else {
QJsonParseError json_error;
QJsonDocument jsonDoc(QJsonDocument::fromJson(QByteArray::fromPercentEncoding(tables.toLocal8Bit()), &json_error));
if(json_error.error != QJsonParseError::NoError)
{
//QMessageBox::warning(nullptr, "错误", "无法加载桌台设置配置文件,配置文件格式不合法");
qDebug() << "json error: " << json_error.errorString();
gTables = QList<QVariant>();
setupSteps--;
} else {
gTables = jsonDoc.toVariant().toList();
}
}
}
usleep(200 * 1000);
switch(setupSteps) {
case 1:
this->_loading->setText("AMP: Connect to Server OK, Waiting for loding shop's information...");
_rediscli->sendCommand(Command::HGETALL("res:info:" + QString::number(gRID) ));
break;
case 2:
this->_loading->setText("AMP: loading shop's info OK, Waiting for loding shop's printers...");
_rediscli->sendCommand(Command::HGETALL("printers:config:" + QString::number(gRID)));
break;
case 3:
if( false == this->loadTables()) {
this->_loading->setText("AMP: Connect to Server OK, Waiting for loding shop's tables info ...");
_rediscli->sendCommand(Command::HGET("res:conf:" + QString::number(gRID), "tables"));
}
break;
case 4:
if(false == this->loadFlavors()) {
this->_loading->setText("AMP: Connect to Server OK, Waiting for loding shop's flavors info ...");
_rediscli->sendCommand(Command::HGET("res:conf:" + QString::number(gRID), "flavors"));
break;
}
break;
case 5:
{
this->hide();
this->switchMainFrame();
break;
}
}
this->_loading->update();
}
| [
"noreply@github.com"
] | noreply@github.com |
57ff131783cc5c6b27ec27fc8d5e4cc2008fb499 | fcb7ae81b94e4ca1622a50bac42c1f4123ba7eca | /Lemon01/SourceCode/AutoMachine/NoticeDialog.h | b2700722f38909b57b11ecbf9dc7aafb6d1eb992 | [] | no_license | BigMouseFive/lemon01 | 4dd126cd8ef0a65c66f5599526d6f3a47177da3f | 3ada0af2db7bd43379f055f2cd2f9ec91f4af8e4 | refs/heads/master | 2022-07-14T00:34:44.184880 | 2022-07-03T10:55:29 | 2022-07-03T10:55:29 | 144,717,391 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 317 | h | #ifndef NOTICEDIALOG_H
#define NOTICEDIALOG_H
#include <QDialog>
namespace Ui {
class NoticeDialog;
}
class NoticeDialog : public QDialog
{
Q_OBJECT
public:
explicit NoticeDialog(std::string shop, QWidget *parent = 0);
~NoticeDialog();
private:
Ui::NoticeDialog *ui;
};
#endif // NOTICEDIALOG_H
| [
"790545771@qq.com"
] | 790545771@qq.com |
0fdd28a62684be0cba081049da3f582a7c7ec665 | 377b1a9f30df8966e8b0f86500848465eb39d7f2 | /src/ecs/Entity.h | 9c757ae8438b6978b3d11df8c83d9eb2577a6139 | [] | no_license | mdzidko/Simple2DEngine | 08194eb35227687cc474a97be188ebe81117779e | 6ffad5df3498b3d1e1573ba1d844959be18096ec | refs/heads/master | 2021-04-06T00:37:17.662702 | 2018-08-13T20:15:26 | 2018-08-13T20:15:26 | 125,253,605 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,373 | h | #pragma once
#include <vector>
#include <array>
#include <memory>
#include <bitset>
#include <assert.h>
#include "UniqueId.h"
#include "Component.h"
class Component;
class Entity
{
public:
bool IsAlive();
void Destroy();
std::bitset<MAX_COMPONENTS> GetMask() const;
template <typename T> bool HasComponent() const
{
return componentsMask[UniqueId::GetUId<T>()];
};
template <typename T> T& GetComponent()
{
assert(HasComponent<T>());
auto ptr = componentsArray[UniqueId::GetUId<T>()];
return *static_cast<T*>(ptr);
}
template<typename T, typename... TArgs> T& AddComponent(TArgs&&... args)
{
//assert(!HasComponent<T>());
T* c(new T(std::forward<TArgs>(args)...));
c->SetParent(this);
std::unique_ptr<T> uPtr{ c };
components.push_back(std::move(uPtr));
componentsArray[UniqueId::GetUId<T>()] = c;
componentsMask[UniqueId::GetUId<T>()] = true;
return *c;
}
template<typename T> void RemoveComponent()
{
//assert(HasComponent<T>());
delete(componentsArray[UniqueId::GetUId<T>()]);
componentsArray[UniqueId::GetUId<T>()] = nullptr;
componentsMask[UniqueId::GetUId<T>()] = false;
}
private:
bool alive{ true };
std::bitset<MAX_COMPONENTS> componentsMask;
std::vector<std::unique_ptr<Component>> components;
std::array<Component*, MAX_COMPONENTS> componentsArray;
};
using EntityPtr = std::unique_ptr<Entity>;
| [
"mdzidko@gmail.com"
] | mdzidko@gmail.com |
660c222d8c7641549ee4e0f3024d6f9f38a3c702 | 3437a528dd29e15804753a20b8022a5d7b7b3424 | /geom/test_matrix.cc | 2025e3db89b023aac876a48f810ff86e538183a9 | [
"Apache-2.0"
] | permissive | tintor/sima | 550dcfbcd9ab589773218391e3adc0220c02957f | 7bc21cf1383ee81b7082158ce690befe025f0a4e | refs/heads/master | 2021-07-08T14:39:34.372646 | 2020-06-28T05:53:22 | 2020-06-28T05:53:22 | 132,295,467 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,535 | cc | #include <core/exception.h>
#include <core/range.h>
#include <geom/matrix.h>
#include <catch.hpp>
TEST_CASE("inv(double22)", "[matrix]") {
std::default_random_engine rnd;
rnd.seed(0);
for (auto i : range(100)) {
double22 m;
m.a = uniform2(rnd, 0, 1);
m.b = uniform2(rnd, 0, 1);
double22 n = inv(m);
double22 e = m * n;
REQUIRE_NEAR(e.a, d2(1, 0), 5e-14);
#ifndef __linux__
REQUIRE_NEAR(e.b, d2(0, 1), 5e-14); // TODO Crashing on Linux!
#endif
}
}
TEST_CASE("inv(double33)", "[matrix]") {
std::default_random_engine rnd;
rnd.seed(0);
for (auto i : range(100)) {
double33 m;
m.a = uniform3(rnd, 0, 1);
m.b = uniform3(rnd, 0, 1);
m.c = uniform3(rnd, 0, 1);
double33 n = inv(m);
double33 e = m * n;
REQUIRE_NEAR(e.a, d3(1, 0, 0), 1e-13);
REQUIRE_NEAR(e.b, d3(0, 1, 0), 1e-13);
REQUIRE_NEAR(e.c, d3(0, 0, 1), 1e-13);
}
}
TEST_CASE("inv(double44)", "[matrix]") {
std::default_random_engine rnd;
rnd.seed(0);
for (auto i : range(100)) {
double44 m;
m.a = uniform4(rnd, 0, 1);
m.b = uniform4(rnd, 0, 1);
m.c = uniform4(rnd, 0, 1);
m.d = uniform4(rnd, 0, 1);
double44 n = inv(m);
double44 e = m * n;
REQUIRE_NEAR(e.a, d4(1, 0, 0, 0), 3e-13);
REQUIRE_NEAR(e.b, d4(0, 1, 0, 0), 3e-13);
REQUIRE_NEAR(e.c, d4(0, 0, 1, 0), 3e-13);
REQUIRE_NEAR(e.d, d4(0, 0, 0, 1), 3e-13);
}
}
| [
"marko@tintor.net"
] | marko@tintor.net |
d2f04588618f74635050d2c5d6f897382d91309b | 0b6617ba233ad141411cbf55531b036f765ede31 | /ImageIdentification/build/include/QCAR/WordList.h | 44f8d1ea944011ac13d6e437ad82f1d2cc596e21 | [] | no_license | nofailyoung/ImageIdentification | a33d77a9163d2cdde1bdff54397e285e08c8c7f4 | 68ad65fc9d21dd678ee81cea29610edff967b3c4 | refs/heads/master | 2021-01-18T16:40:26.995496 | 2015-03-23T03:34:54 | 2015-03-23T03:34:54 | 62,685,794 | 1 | 0 | null | 2016-07-06T02:46:45 | 2016-07-06T02:46:45 | null | UTF-8 | C++ | false | false | 7,354 | h | /*===============================================================================
Copyright (c) 2013-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
Vuforia is a trademark of QUALCOMM Incorporated, registered in the United States
and other countries. Trademarks of QUALCOMM Incorporated are used with permission.
@file
WordList.h
@brief
Header file for WordList class.
===============================================================================*/
#ifndef _QCAR_WORD_LIST_H_
#define _QCAR_WORD_LIST_H_
#include <System.h>
#include <NonCopyable.h>
#include <QCAR.h>
namespace QCAR
{
/// A list of words that the TextTracker can detect and track
/**
* The WordList represents the set of detectable Words. This list is
* loaded from a binary data file using loadWordList.
* By default a WordList for the English language is provided with the SDK.
* The application may choose to add a small set of additional custom words to
* the WordList using the APIs below.
* The filter list allows an application to specify a subset of Words
* from the WordList that will be detected and tracked.
* Due to the large number of words in the WordList it is not possible to
* query the contents of the WordList at run-time.
* Note that the TextTracker needs to be stopped prior to making modifications
* to the WordList.
*/
class QCAR_API WordList : public NonCopyable
{
public:
/// Deprecated enum. Use QCAR::STORAGE_TYPE instead.
/// Types of storage locations
enum STORAGE_TYPE {
STORAGE_APP, ///< Storage private to the application
STORAGE_APPRESOURCE, ///< Storage for assets bundled with the
///< application
STORAGE_ABSOLUTE ///< Helper type for specifying an absolute path
};
/// Types of filter modes
enum FILTER_MODE {
FILTER_MODE_NONE, ///< Word filtering is disabled
FILTER_MODE_BLACK_LIST, ///< Prevent specific words from being detected
FILTER_MODE_WHITE_LIST ///< Enable selected words only to be detected
};
/// Loads the word list from a binary file at the specified path
/// and storage location.
/**
* Loads the word list from the given input file.
* Returns false if the path is NULL.
*/
virtual bool loadWordList(const char* path, QCAR::STORAGE_TYPE storageType) = 0;
/// Loads the word list from a binary file at the specified path
/// and storage location.
/**
* Loads the word list from the given input file.
* Returns false if the path is NULL.
*
* This version is now deprecated, please use QCAR::STORAGE_TYPE based
* method instead.
*/
virtual bool loadWordList(const char* path, STORAGE_TYPE storageType) = 0;
/// Loads a set of custom words from a plain text file
/**
* The word list is extended with the custom words in the plain text file.
* Each word must be between 2-45 characters in length. Returns the
* number of loaded custom words. The text file shall be encoded in UTF-8.
* If path is NULL the return value is -1.
*/
virtual int addWordsFromFile(const char* path, QCAR::STORAGE_TYPE storageType) = 0;
/// Loads a set of custom words from a plain text file
/**
* The word list is extended with the custom words in the plain text file.
* Each word must be between 2-45 characters in length. Returns the
* number of loaded custom words. The text file shall be encoded in UTF-8.
* If path is NULL the return value is -1.
*
* This version is now deprecated, please use QCAR::STORAGE_TYPE based
* method instead.
*/
virtual int addWordsFromFile(const char* path, STORAGE_TYPE storageType) = 0;
/// Add a single custom word to the word list (Unicode)
/**
* Use containsWord to check if the word is already in the word list prior
* calling this.
* Returns false if word is NULL;
*/
virtual bool addWordU(const UInt16* word) = 0;
/// Remove a custom word from the word list (Unicode)
virtual bool removeWordU(const UInt16* word) = 0;
/// Returns true if the given word is present in the WordList (Unicode)
/**
* This function can be used to check if a word already exists in the
* WordList prior to adding it as a custom word.
* Returns false if word is NULL;
*/
virtual bool containsWordU(const UInt16* word) = 0;
/// Clears the word list as well as the filter list.
/**
* Call this to reset the word list and release all acquired system
* resources.
* Return false if word is NULL;
*/
virtual bool unloadAllLists() = 0;
/// Sets the mode for the filter list
/**
* The filter list allows an application to specify a subset of Words
* from the word list that will be detected and tracked. It can do this
* in two modes of operation. In black list mode, any word in the filter
* list will be prevented from being detected. In the white list mode,
* only words in the the filter list can be detected.
* By default the filter mode is FILTER_MODE_NONE where no words are
* filtered.
*/
virtual bool setFilterMode(FILTER_MODE mode) = 0;
/// Returns the filter mode.
virtual FILTER_MODE getFilterMode() const = 0;
/// Add a single word to the filter list (Unicode)
/**
* Adds a word to the filter list.
* Returns true if successful, false if unsuccessful or if word
* is NULL.
*/
virtual bool addWordToFilterListU(const UInt16* word) = 0;
/// Remove a word from the filter list (Unicode)
/**
* Remove a word from the filter list
* Returns true if successful, false if unsuccessful or if word
* is NULL.
*/
virtual bool removeWordFromFilterListU(const UInt16* word) = 0;
/// Clear the filter list.
virtual bool clearFilterList() = 0;
/// Loads the filter list from a plain text file.
/**
* The text file shall be encoded in UTF-8.
* Returns false if the filter list cannot be loaded. Note
* some words may have been added to the filter list so it
* may be necessary to call getFilterListWordCount to find
* out what, if any, words have been loaded by this routine
* if it fails.
*
* This version is now deprecated, please use QCAR::STORAGE_TYPE based
* method instead.
*/
virtual bool loadFilterList(const char* path, STORAGE_TYPE storageType) = 0;
/// Loads the filter list from a plain text file.
/**
* The text file shall be encoded in UTF-8.
* Returns false if the filter list cannot be loaded. Note
* some words may have been added to the filter list so it
* may be necessary to call getFilterListWordCount to find
* out what, if any, words have been loaded by this routine
* if it fails.
*/
virtual bool loadFilterList(const char* path, QCAR::STORAGE_TYPE storageType) = 0;
/// Query the number of words in the filter list.
virtual int getFilterListWordCount() = 0;
/// Return the ith element in the filter list (Unicode)
virtual const UInt16* getFilterListWordU(int i) = 0;
};
} // namespace QCAR
#endif /* _QCAR_WORD_LIST_H_ */
| [
"zjjmusic@163.com"
] | zjjmusic@163.com |
f2daf1bc795d6cb06f660d0569bc549b3bae4782 | ef91391eacc931fbd6a392d4577fc2404c631b2d | /Algorithm & Design/Modulus use.cpp | 4c109118a7a0575bf10ebdbcc32768595c429e95 | [] | no_license | LWilliams-law67/Academic-programming | 8ef05f8da3ef193dbe1e6c3c841a4e98effff3d5 | 7ffb313b90ceb5db53e8c98750f3e0fe3fe9bbf5 | refs/heads/master | 2022-04-02T03:06:48.535551 | 2020-01-07T23:38:15 | 2020-01-07T23:38:15 | 191,382,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 435 | cpp | #include <iostream>
using namespace std;
int main(){
enum days {SUN=0,MON,TUE,WED,THU,FRI,SAT};
string daysofWeek[] = {"Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday"};
days today = MON;
int daysAhead = 9;
int futureDay = today + (daysAhead % 7);
cout << "If today is " << daysofWeek[today] << ", it will be a "
<< daysofWeek[futureDay] << " " << daysAhead
<< " days from today." << endl;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
164ad29054d4161026d19bdc5b94be54101d1478 | 4cb5d6ad82060b0ca99d6cde4834efd5317644b6 | /001 TwoSum/main.cpp | 26dd89585ce17cae0df993c1e7c452f46c40b3d0 | [] | no_license | sup6yj3a8/Leetcode | eb20db85164a118aa95f6e4cd16cabfb6a7abeb7 | 610f6b520cc8d2480b97fe7cc83b6cec445898d3 | refs/heads/main | 2023-09-01T12:13:30.673603 | 2021-09-23T05:33:16 | 2021-09-23T05:33:16 | 381,276,589 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,034 | cpp | //
// main.cpp
// 001 TwoSum
//
// Created by Aaron on 2021/6/28.
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target) {
// Copy
vector<int*> numsP;
for (int i=0; i<nums.size(); ++i){numsP.push_back(&nums[i]);}
// Sort
sort(numsP.begin(), numsP.end(), [](int *a, int *b){return *a<*b;});
// Sum
int *n1 = nullptr;
int *n2 = nullptr;
int remain;
for (int i=0; i<numsP.size(); ++i){
n1 = numsP[i];
remain = target - *n1; // Reset remain
for (int j=i+1; j<numsP.size(); ++j){
if (remain == *numsP[j]){
n2 = numsP[j];
return vector<int> {static_cast<int>(n1 - &nums[0]), static_cast<int>(n2 - &nums[0])};
}
}
}
return vector<int> ();
}
int main() {
vector<int> a {2,7,11,15};
int t = 9;
vector<int> b = twoSum(a, t);
for (auto i : b) {
cout << i << " ";
}
return 0;
}
| [
"sup6yj3a8@yahoo.com.tw"
] | sup6yj3a8@yahoo.com.tw |
45b620deded2453c123a00250615fac75e32716d | d2f67d6c5933f96b816a3195401aabd56a4f7f05 | /Day_02/ex00/Fixed.cpp | 73c1e945290571279e1e03366520be1feb5ae6e5 | [] | no_license | florianne1212/CPP_piscine_42 | 2ce473fdd4cdac4ee100159b80a28ac91426843f | c151616103e606ab05f2f6ac66d5a93b2900591b | refs/heads/master | 2023-03-25T03:43:53.828656 | 2021-03-24T11:15:04 | 2021-03-24T11:15:04 | 316,215,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | cpp | #include "Fixed.hpp"
Fixed::Fixed(void) : _fixed_point(0)
{
std::cout << "Default constructor called" << std::endl;
return;
}
Fixed::Fixed(Fixed const & copy)
{
std::cout << "Copy constructor called" << std::endl;
*this = copy;
return;
}
Fixed::~Fixed(void)
{
std::cout << "Destructor called" << std::endl;
return;
}
int Fixed::getRawBits(void) const
{
std::cout << "getRawBits member function called" << std::endl;
return this->_fixed_point;
}
void Fixed::setRawBits(int const raw)
{
this->_fixed_point = raw;
}
Fixed & Fixed::operator=( Fixed const & ope)
{
std::cout << "Assignation operator called" << std::endl;
if (this != &ope)
this->_fixed_point = ope.getRawBits();
return (*this);
} | [
"fcoudert@student.fr"
] | fcoudert@student.fr |
99fcd12bfc80da467f92c0e5fb1a9200985215cf | 1f1bb45f59a1437d9ce76f1365f2fa0f2d40d5a5 | /active_planner/src/frontier_evaluator.cpp | 5c634baaea198f5f1e8edb9f3d2a306083257ea2 | [] | no_license | sujalharkut/inter_iit_dgre_voad | ddb1b0520ab0936e793cc3e3716df5f800b143fb | 2c0c47fe6f4ae9586ccf909eb92a16d2337ff2b6 | refs/heads/main | 2023-04-02T03:17:56.209041 | 2021-03-31T12:32:41 | 2021-03-31T12:32:41 | 435,244,637 | 0 | 1 | null | 2021-12-05T18:19:46 | 2021-12-05T18:19:46 | null | UTF-8 | C++ | false | false | 9,911 | cpp | #include <active_planner/frontier_evaluator.hpp>
namespace local_planner {
FrontierEvaluator::FrontierEvaluator(ros::NodeHandle& nh, ros::NodeHandle& nh_private)
: esdf_server_(nh, nh_private) {
// Load Parameters
nh_private.getParam("accurate_frontiers", accurate_frontiers_);
nh_private.getParam("checking_distance", checking_dist_);
nh_private.getParam("visualize_frontier", visualize_);
nh_private.getParam("frame_id", frame_id_);
nh_private.getParam("occupancy_distance", occupancy_distance_);
nh_private.getParam("slice_level", slice_level_);
nh_private.getParam("upper_range", upper_range_);
nh_private.getParam("lower_range", lower_range_);
nh_private.getParam("min_frontier_size", min_frontier_size_);
nh_private.getParam("robot_radius", robot_radius_);
esdf_server_.setTraversabilityRadius(robot_radius_);
voxel_size_ = esdf_server_.getTsdfMapPtr()->voxel_size();
block_size_ = esdf_server_.getTsdfMapPtr()->block_size();
// Precompute relative vectors for calculating neighbours
auto vs = voxel_size_ * checking_dist_;
if (!accurate_frontiers_) { // Consider only 6 neighbours along the 3 axes
neighbor_voxels_.push_back(Eigen::Vector3d(vs, 0, 0));
neighbor_voxels_.push_back(Eigen::Vector3d(-vs, 0, 0));
neighbor_voxels_.push_back(Eigen::Vector3d(0, vs, 0));
neighbor_voxels_.push_back(Eigen::Vector3d(0, -vs, 0));
neighbor_voxels_.push_back(Eigen::Vector3d(0, 0, vs));
neighbor_voxels_.push_back(Eigen::Vector3d(0, 0, -vs));
} else {// Consider all 27 neighbours in 3D space
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
for (int k = -1; k <= 1; k++) {
if ((abs(i) + abs(j) + abs(k)) == 0) {
continue;
}
neighbor_voxels_.push_back(Eigen::Vector3d(i * vs, j * vs, k * vs));
}
}
}
}
// Relative vectors for 4 neighbours in the plane
for (int i = -2; i <= 2; i++) {
for (int j = -2; j <= 2; j++) {
if ((abs(i) + abs(j)) == 0) {
continue;
}
planar_neighbor_voxels_.push_back(Eigen::Vector3d(i * vs, j * vs, 0));
}
}
// Register publishers for visualization
if (visualize_) {
visualizer_.init(nh, nh_private);
visualizer_.createPublisher("free_voxels");
visualizer_.createPublisher("unknown_voxels");
visualizer_.createPublisher("occupied_voxels");
visualizer_.createPublisher("frontiers");
visualizer_.createPublisher("frontier_centers");
}
}
// Find all frontiers
void FrontierEvaluator::findFrontiers() {
frontiers_.clear();
hash_map_.clear();
size_t vps = esdf_server_.getTsdfMapPtr()->getTsdfLayerPtr()->voxels_per_side();
size_t num_voxels_per_block = vps * vps * vps;
voxblox::BlockIndexList blocks;
esdf_server_.getTsdfMapPtr()->getTsdfLayerPtr()->getAllAllocatedBlocks(&blocks);
// Iterate over TSDF map to get frontier voxels
for (const auto& index : blocks) {
const voxblox::Block<voxblox::TsdfVoxel>& block = esdf_server_.getTsdfMapPtr()->getTsdfLayerPtr()->getBlockByIndex(index);
for (size_t linear_index = 0; linear_index < num_voxels_per_block; ++linear_index) {
Eigen::Vector3d coord = block.computeCoordinatesFromLinearIndex(linear_index).cast<double>();
if (isFrontierVoxel(coord)) {
hash_map_[getHash(coord)] = coord;
}
}
}
// Clustering frontier points
while (!hash_map_.empty()) {
Frontier frontier;
findNeighbours(hash_map_.begin()->first, frontier);
if (frontier.points.size() < min_frontier_size_) {
continue;
}
frontiers_.push_back(frontier);
}
// Visualization functions
if (visualize_) {
visualizeFrontierPoints();
visualizeFrontierCenters();
visualizeVoxelStates();
}
}
// Retrieve frontier centers
std::vector<FrontierEvaluator::FrontierCenter> FrontierEvaluator::getFrontiers() {
std::vector<FrontierEvaluator::FrontierCenter> centers;
for (auto f : frontiers_) {
FrontierEvaluator::FrontierCenter center(f);
centers.push_back(center);
}
return centers;
}
// Recursively find frontier neighbours to create frontier clusters
void FrontierEvaluator::findNeighbours(const std::string& key, Frontier& frontier) {
auto point = hash_map_.at(key);
hash_map_.erase(key);
frontier.center = (frontier.center * frontier.points.size() + point) / (frontier.points.size() + 1);
frontier.points.push_back(point);
for (auto& next_point : planar_neighbor_voxels_) {
auto neighbour_hash = getHash(point + next_point);
if (hash_map_.find(neighbour_hash) != hash_map_.end()) {
findNeighbours(neighbour_hash, frontier);
}
}
}
// Check if current voxel is a frontier
bool FrontierEvaluator::isFrontierVoxel(const Eigen::Vector3d& voxel) {
if (getVoxelState(voxel) != VoxelState::FREE) {
return false;
}
if (!inHeightRange(voxel(2, 0))) {
return false;
}
VoxelState voxel_state;
int num_unknown = 0;
for (auto& neighbour : neighbor_voxels_) {
voxel_state = getVoxelState(voxel + neighbour);
if (voxel_state == VoxelState::UNKNOWN) {
num_unknown++;
}
}
return (num_unknown > 1); // Frontier - free point with more than one unknown neighbour
}
// Check if current voxel is occupied, free or unknown
VoxelState FrontierEvaluator::getVoxelState(const Eigen::Vector3d& point) {
double distance = 0.0, weight = 0.0;
if (getVoxelDistance(point, distance) && getVoxelWeight(point, weight)) {
if (std::abs(distance) < voxel_size_ * occupancy_distance_ && weight > 1e-3) {
return VoxelState::OCCUPIED;
} else if (distance >= voxel_size_) {
return VoxelState::FREE;
} else {
return VoxelState::UNKNOWN;
}
} else {
return VoxelState::OCCUPIED;
}
}
// TSDF Helper function
bool FrontierEvaluator::getVoxelDistance(const Eigen::Vector3d& point, double& distance) {
voxblox::Point voxblox_point(point.x(), point.y(), point.z());
voxblox::Block<voxblox::TsdfVoxel>::Ptr block_ptr = esdf_server_.getTsdfMapPtr()->getTsdfLayerPtr()->getBlockPtrByCoordinates(voxblox_point);
if (block_ptr) {
voxblox::TsdfVoxel* tsdf_voxel_ptr = block_ptr->getVoxelPtrByCoordinates(voxblox_point);
if (tsdf_voxel_ptr) {
distance = tsdf_voxel_ptr->distance;
return true;
}
}
return false;
}
// TSDF helper function
bool FrontierEvaluator::getVoxelWeight(const Eigen::Vector3d& point, double& weight) {
voxblox::Point voxblox_point(point.x(), point.y(), point.z());
voxblox::Block<voxblox::TsdfVoxel>::Ptr block_ptr = esdf_server_.getTsdfMapPtr()->getTsdfLayerPtr()->getBlockPtrByCoordinates(voxblox_point);
if (block_ptr) {
voxblox::TsdfVoxel* tsdf_voxel_ptr = block_ptr->getVoxelPtrByCoordinates(voxblox_point);
if (tsdf_voxel_ptr) {
weight = tsdf_voxel_ptr->weight;
return true;
}
}
return false;
}
// Visualize free, occupied and unknown voxels
void FrontierEvaluator::visualizeVoxelStates() {
if (!visualize_) {
return;
}
size_t vps = esdf_server_.getTsdfMapPtr()->getTsdfLayerPtr()->voxels_per_side();
size_t num_voxels_per_block = vps * vps * vps;
std::vector<Eigen::Vector3d> free_voxels, occupied_voxels, unknown_voxels;
voxblox::BlockIndexList blocks;
double weight = 0.0;
esdf_server_.getTsdfMapPtr()->getTsdfLayerPtr()->getAllAllocatedBlocks(&blocks);
for (const auto& index : blocks) {
const voxblox::Block<voxblox::TsdfVoxel>& block = esdf_server_.getTsdfMapPtr()->getTsdfLayerPtr()->getBlockByIndex(index);
for (size_t linear_index = 0; linear_index < num_voxels_per_block; ++linear_index) {
Eigen::Vector3d coord = block.computeCoordinatesFromLinearIndex(linear_index).cast<double>();
if (getVoxelWeight(coord, weight) && weight > 1e-3) {
switch (getVoxelState(coord)) {
case VoxelState::OCCUPIED:
occupied_voxels.push_back(coord);
break;
case VoxelState::FREE:
free_voxels.push_back(coord);
break;
case VoxelState::UNKNOWN:
unknown_voxels.push_back(coord);
break;
}
}
}
}
visualizer_.visualizePoints("free_voxels", free_voxels, frame_id_, Visualizer::ColorType::BLUE);
visualizer_.visualizePoints("unknown_voxels", unknown_voxels, frame_id_, Visualizer::ColorType::TEAL);
visualizer_.visualizePoints("occupied_voxels", occupied_voxels, frame_id_, Visualizer::ColorType::PURPLE);
}
// Visualize frontiers
void FrontierEvaluator::visualizeFrontierPoints() {
if (!visualize_) {
return;
}
std::vector<Eigen::Vector3d> points;
for (auto& frontier : frontiers_) {
for (auto& point : frontier.points) {
points.push_back(point);
}
}
visualizer_.visualizePoints("frontiers", points, frame_id_, Visualizer::ColorType::WHITE, 0.5);
}
void FrontierEvaluator::visualizeFrontierCenters() {
if (!visualize_) {
return;
}
std::vector<Eigen::Vector3d> centers;
for (auto& frontier : frontiers_) {
centers.push_back(frontier.center);
}
visualizer_.visualizePoints("frontier_centers", centers, frame_id_, Visualizer::ColorType::RED, 2.0);
}
} // namespace local_planner | [
"ashwins@iitk.ac.in"
] | ashwins@iitk.ac.in |
0947c91e5b0341bcd1148b18ff845aee0e0819aa | 8d1725e2bedd244d7bc865df75317a85d2468e93 | /qt_3d_core/c_lib/src/qt_3d_core_c_QComponent.cpp | dbd65df3d380bb6e20f1d577c3605caf3cb75da9 | [] | no_license | aristotle9/qt_generator-output | 04100597f923b117314afcc80f0ea85417d342be | be98dd92de8d2e2c43cf8e9e20ebd1316fd4b101 | refs/heads/master | 2021-07-23T12:20:15.277052 | 2017-10-24T08:20:03 | 2017-10-24T08:20:03 | 108,097,475 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,464 | cpp | #include "qt_3d_core_c_QComponent.h"
Qt3DCore::QComponent* qt_3d_core_c_QComponent_G_dynamic_cast_Qt3DCore_QComponent_ptr(Qt3DCore::QNode* ptr) {
return dynamic_cast<Qt3DCore::QComponent*>(ptr);
}
QObject* qt_3d_core_c_QComponent_G_static_cast_QObject_ptr(Qt3DCore::QComponent* ptr) {
return static_cast<QObject*>(ptr);
}
Qt3DCore::QComponent* qt_3d_core_c_QComponent_G_static_cast_Qt3DCore_QComponent_ptr_QObject(QObject* ptr) {
return static_cast<Qt3DCore::QComponent*>(ptr);
}
Qt3DCore::QComponent* qt_3d_core_c_QComponent_G_static_cast_Qt3DCore_QComponent_ptr_Qt3DCore_QNode(Qt3DCore::QNode* ptr) {
return static_cast<Qt3DCore::QComponent*>(ptr);
}
Qt3DCore::QNode* qt_3d_core_c_QComponent_G_static_cast_Qt3DCore_QNode_ptr(Qt3DCore::QComponent* ptr) {
return static_cast<Qt3DCore::QNode*>(ptr);
}
void qt_3d_core_c_Qt3DCore_QComponent_delete(Qt3DCore::QComponent* this_ptr) {
delete this_ptr;
}
void qt_3d_core_c_Qt3DCore_QComponent_entities_to_output(const Qt3DCore::QComponent* this_ptr, QVector< Qt3DCore::QEntity* >* output) {
new(output) QVector< Qt3DCore::QEntity* >(this_ptr->entities());
}
bool qt_3d_core_c_Qt3DCore_QComponent_isShareable(const Qt3DCore::QComponent* this_ptr) {
return this_ptr->isShareable();
}
const QMetaObject* qt_3d_core_c_Qt3DCore_QComponent_metaObject(const Qt3DCore::QComponent* this_ptr) {
return this_ptr->metaObject();
}
Qt3DCore::QComponent* qt_3d_core_c_Qt3DCore_QComponent_new_no_args() {
return new Qt3DCore::QComponent();
}
Qt3DCore::QComponent* qt_3d_core_c_Qt3DCore_QComponent_new_parent(Qt3DCore::QNode* parent) {
return new Qt3DCore::QComponent(parent);
}
int qt_3d_core_c_Qt3DCore_QComponent_qt_metacall(Qt3DCore::QComponent* this_ptr, const QMetaObject::Call* arg1, int arg2, void** arg3) {
return this_ptr->qt_metacall(*arg1, arg2, arg3);
}
void* qt_3d_core_c_Qt3DCore_QComponent_qt_metacast(Qt3DCore::QComponent* this_ptr, const char* arg1) {
return this_ptr->qt_metacast(arg1);
}
void qt_3d_core_c_Qt3DCore_QComponent_setShareable(Qt3DCore::QComponent* this_ptr, bool isShareable) {
this_ptr->setShareable(isShareable);
}
void qt_3d_core_c_Qt3DCore_QComponent_trUtf8_to_output(const char* s, const char* c, int n, QString* output) {
new(output) QString(Qt3DCore::QComponent::trUtf8(s, c, n));
}
void qt_3d_core_c_Qt3DCore_QComponent_tr_to_output(const char* s, const char* c, int n, QString* output) {
new(output) QString(Qt3DCore::QComponent::tr(s, c, n));
}
| [
"lanfan.1987@gmail.com"
] | lanfan.1987@gmail.com |
7a3b794b645cc553af2251311735fca9014ecbbb | a8a333173d00b0e481b08d94f222c2c73a77a0ba | /protocol/BRSRtmpMsgArray.cpp | be302ac7e71c8ff185f21b9a0cc2010b80073e08 | [] | no_license | taoboy/share_rtmp_server | 0d8f874a4d32148ff5bf6e4f925c66a27d06b761 | b4b7d2d53e6cfce2491b4db0567308a2933e8de8 | refs/heads/master | 2021-01-20T02:42:37.950018 | 2016-12-30T06:30:45 | 2016-12-30T06:30:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | cpp | #include <BRSRtmpMsgArray.h>
namespace BRS
{
BrsMessageArray::BrsMessageArray(int argMax)
{
assert(argMax > 0 );
msgs = new BrsSharedPtrMessage*[argMax];
max = argMax;
zero(argMax);
}
BrsMessageArray::~BrsMessageArray()
{
SafeDeleteArray(msgs);
}
void BrsMessageArray::free(int count)
{
for(int i=0;i<count;i++)
{
BrsSharedPtrMessage *msg = msgs[i];
SafeDelete(msg);
msgs[i] = NULL;
}
}
void BrsMessageArray::zero(int count)
{
for(int i =0;i<count;i++)
{
msgs[i] = NULL;
}
}
}
| [
"bravehan@bravehan-G41MT-S2"
] | bravehan@bravehan-G41MT-S2 |
441998a996ab6e1a362d14cc50ce1093290f707d | bcfd3336ae1dcac5e6f3b9e2154caad199043b27 | /src/util/Fs.h | f257798a0d5cab79961ca902a6328468a7e2a5f3 | [
"MIT",
"BSD-3-Clause",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | acgchain/acg-core | 58ba9d4e0dd147c45a51b33017d75402cdce9531 | 098676521a3211ab702d5f473510dc07e60467e2 | refs/heads/master | 2020-07-26T11:57:58.634134 | 2019-10-08T03:39:28 | 2019-10-08T03:39:28 | 208,636,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,439 | h | #pragma once
// Copyright 2015 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include <functional>
#include <string>
#include <vector>
namespace acg
{
namespace fs
{
////
// Utility for manipulating process ids
////
long getCurrentPid();
bool processExists(long pid);
////
// Utility functions for operating on the filesystem.
////
// raises an exception if a lock file cannot be created
void lockFile(std::string const& path);
// unlocks a file locked with `lockFile`
void unlockFile(std::string const& path);
// Whether a path exists
bool exists(std::string const& path);
// Delete a path and everything inside it (if a dir)
void deltree(std::string const& path);
// Make a single dir; not mkdir -p, i.e. non-recursive
bool mkdir(std::string const& path);
// Make a dir path like mkdir -p, i.e. recursive, uses '/' as dir separator
bool mkpath(std::string const& path);
// Get list of all files with names matching predicate
// Returned names are relative to path
std::vector<std::string>
findfiles(std::string const& path,
std::function<bool(std::string const& name)> predicate);
class PathSplitter
{
public:
explicit PathSplitter(std::string path);
std::string next();
bool hasNext() const;
private:
std::string mPath;
std::string::size_type mPos;
};
////
// Utility functions for constructing path names
////
// Format a 32bit number as an 8-char hex string
std::string hexStr(uint32_t checkpointNum);
// Map any >6 hex char string "ABCDEF..." to the path "AB/CD/EF"
std::string hexDir(std::string const& hexStr);
// Construct the string <type>-<hexstr>.<suffix>
std::string baseName(std::string const& type, std::string const& hexStr,
std::string const& suffix);
// Construct the string <type>/hexdir(hexStr)
std::string remoteDir(std::string const& type, std::string const& hexStr);
// Construct the string <type>/hexdir(hexStr)/<type>-<hexstr>.<suffix>
std::string remoteName(std::string const& type, std::string const& hexStr,
std::string const& suffix);
void checkGzipSuffix(std::string const& filename);
void checkNoGzipSuffix(std::string const& filename);
// returns the maximum number of connections that can be done at the same time
int getMaxConnections();
}
}
| [
"ubuntu@ip-172-31-20-103.ap-southeast-1.compute.internal"
] | ubuntu@ip-172-31-20-103.ap-southeast-1.compute.internal |
f2a0f9479b3eba0455e813622d8fff57aa309a83 | 309e2962d86c151e2e5d101ab76730c6c98c89c0 | /loopingBasics/main.cpp | f56d5c183b81ecc3091b114005770dbebbd2d10b | [] | no_license | KylepFedalen/CPP2019 | d49188ab89e25aa334ab181ba994eefe57a307b0 | e27d053328cd0d119bcec6baa2c86bd5eb86188e | refs/heads/master | 2021-04-14T06:16:51.730305 | 2020-03-22T15:27:19 | 2020-03-22T15:27:19 | 249,212,334 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | cpp | #include <iostream>
using namespace std;
int loopvar = 0;
int main() {
cout << "start program" << endl;
while(loopvar < 10){
if(loopvar == 5){
break;
}
cout << "looping..." << endl;
loopvar++;
}
cout << "Break! loop broken" << endl;
cout << "Continuing... program" << endl;
cout << "end program" << endl;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
2c813cea91308d67d001f5ed0f04267e88ca5278 | f562721faac05a4becfd52a6b3b2877b48434b04 | /src/task3.cpp | 8f089c4ff1af32891a6ccc060a2c88359c71b9bc | [] | no_license | ovorlova/tp-lab-9 | 0bd4cdc0bc6de7075ad3a743a69a13b3a0201ce7 | 39d339f40943f4faf1a50e8511ebfb64cb071d89 | refs/heads/master | 2022-09-18T12:59:32.028824 | 2020-06-03T09:57:06 | 2020-06-03T09:57:06 | 264,277,088 | 0 | 0 | null | 2020-05-15T19:08:38 | 2020-05-15T19:08:37 | null | UTF-8 | C++ | false | false | 2,456 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <thread>
#include <mutex>
#include <queue>
#include <time.h>
#include <chrono>
#include <list>
struct Customer {
Customer(std::vector<int> purchases) {
this->purchases = purchases;
}
std::vector<int> purchases;
};
class Shop {
public:
Shop(int max_products, int max_customers, int max_price, int queue_len) :
max_products(max_products), max_customers(max_customers), max_price(max_price), queue_len(queue_len) {}
Customer create_customer() {
int products = rand() % max_products + 1;
std::vector<int> purchases(products);
for (int j = 0; j < products; ++j) {
purchases[j] = rand() % max_price + 1;
}
return Customer(purchases);
}
void serve(Customer customer, int num) {
for (std::size_t i = 0; i < customer.purchases.size(); i++) {
int time = rand() % 1000;
std::this_thread::sleep_for(std::chrono::milliseconds(time));
std::unique_lock<std::mutex> lk(mx);
std::cout << "Cash desk id " << std::this_thread::get_id() << ", customer " << num << " with purchase " << i + 1 << '\n';
lk.unlock();
}
}
void run_cash_desk(std::queue <Customer> * customers) {
int count_customers = 1;
while (!customers->empty()) {
auto customer = customers->front();
customers->pop();
serve(customer, count_customers);
count_customers++;
}
delete customers;
}
void serve_all() {
for (int i = 0; i < max_customers; ++i) {
bool find_queue = false;
auto it = queues.begin();
while (it != queues.end()) {
int time = rand() % 500;
std::this_thread::sleep_for(std::chrono::milliseconds(time));
if ((*it) == nullptr) {
auto new_it = it;
new_it++;
queues.erase(it);
it = new_it;
continue;
}
if ((*it)->size() < queue_len) {
(*it)->push(create_customer());
find_queue = true;
break;
}
++it;
}
if (!find_queue) {
auto it_q = new std::queue<Customer>;
it_q->push(create_customer());
queues.push_back(it_q);
threads.push_back(new std::thread(&Shop::run_cash_desk, this, it_q));
}
}
}
void run() {
serve_all();
for (auto cur_queue : threads) {
cur_queue->join();
}
}
private:
std::vector<std::thread*> threads;
std::list<std::queue<Customer>*> queues;
int max_products;
int max_customers;
int max_price;
int queue_len;
std::mutex mx;
};
int main() {
srand(time(nullptr));
Shop shop(10, 50, 20, 5);
shop.run();
return 0;
} | [
"olia_orlova2000@mail.ru"
] | olia_orlova2000@mail.ru |
337dd94b3fbad02236bd881787f10fec80218b14 | 5ec06dab1409d790496ce082dacb321392b32fe9 | /clients/cpp-restbed-server/generated/model/ApacheSlingHealthCheckResultHTMLSerializerInfo.cpp | 042c607c75d660f4a2f082ea5601f831c0bc280d | [
"Apache-2.0"
] | permissive | shinesolutions/swagger-aem-osgi | e9d2385f44bee70e5bbdc0d577e99a9f2525266f | c2f6e076971d2592c1cbd3f70695c679e807396b | refs/heads/master | 2022-10-29T13:07:40.422092 | 2021-04-09T07:46:03 | 2021-04-09T07:46:03 | 190,217,155 | 3 | 3 | Apache-2.0 | 2022-10-05T03:26:20 | 2019-06-04T14:23:28 | null | UTF-8 | C++ | false | false | 2,558 | cpp | /**
* Adobe Experience Manager OSGI config (AEM) API
* Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API
*
* OpenAPI spec version: 1.0.0-pre.0
* Contact: opensource@shinesolutions.com
*
* NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "ApacheSlingHealthCheckResultHTMLSerializerInfo.h"
#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;
namespace org {
namespace openapitools {
namespace server {
namespace model {
ApacheSlingHealthCheckResultHTMLSerializerInfo::ApacheSlingHealthCheckResultHTMLSerializerInfo()
{
m_Pid = "";
m_Title = "";
m_Description = "";
}
ApacheSlingHealthCheckResultHTMLSerializerInfo::~ApacheSlingHealthCheckResultHTMLSerializerInfo()
{
}
std::string ApacheSlingHealthCheckResultHTMLSerializerInfo::toJsonString()
{
std::stringstream ss;
ptree pt;
pt.put("Pid", m_Pid);
pt.put("Title", m_Title);
pt.put("Description", m_Description);
write_json(ss, pt, false);
return ss.str();
}
void ApacheSlingHealthCheckResultHTMLSerializerInfo::fromJsonString(std::string const& jsonString)
{
std::stringstream ss(jsonString);
ptree pt;
read_json(ss,pt);
m_Pid = pt.get("Pid", "");
m_Title = pt.get("Title", "");
m_Description = pt.get("Description", "");
}
std::string ApacheSlingHealthCheckResultHTMLSerializerInfo::getPid() const
{
return m_Pid;
}
void ApacheSlingHealthCheckResultHTMLSerializerInfo::setPid(std::string value)
{
m_Pid = value;
}
std::string ApacheSlingHealthCheckResultHTMLSerializerInfo::getTitle() const
{
return m_Title;
}
void ApacheSlingHealthCheckResultHTMLSerializerInfo::setTitle(std::string value)
{
m_Title = value;
}
std::string ApacheSlingHealthCheckResultHTMLSerializerInfo::getDescription() const
{
return m_Description;
}
void ApacheSlingHealthCheckResultHTMLSerializerInfo::setDescription(std::string value)
{
m_Description = value;
}
std::shared_ptr<ApacheSlingHealthCheckResultHTMLSerializerProperties> ApacheSlingHealthCheckResultHTMLSerializerInfo::getProperties() const
{
return m_Properties;
}
void ApacheSlingHealthCheckResultHTMLSerializerInfo::setProperties(std::shared_ptr<ApacheSlingHealthCheckResultHTMLSerializerProperties> value)
{
m_Properties = value;
}
}
}
}
}
| [
"cliffano@gmail.com"
] | cliffano@gmail.com |
6046899b3352f7ee9c772e546358dec42e8b7a76 | b9cc7dfec430fab63c89ff40d431ca7a9de7dd12 | /goblim/MyProject/Materials/TPMaterial/TPMaterial.h | bfb88ebb5d7db973afd149c099c38840277e0474 | [] | no_license | Oneloves/shaders | 268296b2e4ac20740014e55d24f925957e041cb3 | a6afbd93040dfdc9a285c87ea7924900a26637d9 | refs/heads/master | 2020-03-30T06:57:52.049938 | 2018-09-29T21:21:44 | 2018-09-29T21:21:44 | 150,903,501 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | h | #ifndef _TPMATERIAL_H
#define _TPMATERIAL_H
#include "Engine/OpenGL/MaterialGL.h"
#include "Engine/OpenGL/Lighting/LightingModelGL.h"
#include <memory.h>
class TPMaterial : public MaterialGL
{
public:
TPMaterial(std::string name);
~TPMaterial();
void setColor(glm::vec4 &c);
virtual void render(Node *o);
virtual void update(Node* o,const int elapsedTime);
GPUmat4* modelViewProj;
GPUfloat* time;
GPUvec3* lightPos;
};
#endif | [
"jeanf"
] | jeanf |
f84d4427f80593a9d0c7151d1e9fde63cdf921b8 | ff2380d39cbf4d08295e8e91a06594edd32113e1 | /ProgrammingCoursework/ProgrammingCoursework/main.cpp | e9e0331f8a56531fa25dbac6d65ae9ef4d58b6a7 | [] | no_license | bstewart2/GP1--Submission | 72c6e79e6151407c23cf5a544a5a24aeef4f830a | 2fb28cfef13e6eca48b08b96576c7dfb94aaee1e | refs/heads/master | 2021-01-10T12:53:39.253072 | 2015-12-15T19:01:54 | 2015-12-15T19:01:54 | 48,061,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,092 | cpp | #define WIN32_LEAN_AND_MEAN
#define WIN32_EXTRA_LEAN
#define GLX_GLXEXT_LEGACY //Must be declared so that our local glxext.h is picked up, rather than the system one
#include <windows.h>
#include "windowOGL.h"
#include "GameConstants.h"
#include "cWNDManager.h"
#include "cInputMgr.h"
#include "cSoundMgr.h"
#include "cFontMgr.h"
#include "cSprite.h"
#include "asteroidsGame.h"
#include "cButton.h"
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR cmdLine,
int cmdShow)
{
//Set our window settings
const int windowWidth = 1024;
const int windowHeight = 768;
const int windowBPP = 16;
//This is our window
static cWNDManager* pgmWNDMgr = cWNDManager::getInstance();
// This is the input manager
static cInputMgr* theInputMgr = cInputMgr::getInstance();
// This is the sound manager
static cSoundMgr* theSoundMgr = cSoundMgr::getInstance();
// This is the Font manager
static cFontMgr* theFontMgr = cFontMgr::getInstance();
//The example OpenGL code
windowOGL theOGLWnd;
//Attach our the OpenGL window
pgmWNDMgr->attachOGLWnd(&theOGLWnd);
// Attach the keyboard manager
pgmWNDMgr->attachInputMgr(theInputMgr);
//Attempt to create the window
if (!pgmWNDMgr->createWND(windowWidth, windowHeight, windowBPP))
{
//If it fails
MessageBox(NULL, "Unable to create the OpenGL Window", "An error occurred", MB_ICONERROR | MB_OK);
pgmWNDMgr->destroyWND(); //Reset the display and exit
return 1;
}
if (!theOGLWnd.initOGL(windowWidth, windowHeight)) //Initialize our example
{
MessageBox(NULL, "Could not initialize the application", "An error occurred", MB_ICONERROR | MB_OK);
pgmWNDMgr->destroyWND(); //Reset the display and exit
return 1;
}
//Clear key buffers
theInputMgr->clearBuffers(theInputMgr->KEYS_DOWN_BUFFER | theInputMgr->KEYS_PRESSED_BUFFER);
/* initialize random seed: */
srand((unsigned int)time(NULL));
// Create vector array of textures
LPCSTR texturesToUse[] = { "Images\\enemyTank.png", "Images\\enemyTank.png", "Images\\enemyTank.png", "Images\\enemyTank.png", "Images\\shot.png" };
for (int tCount = 0; tCount < 5; tCount++)
{
theGameTextures.push_back(new cTexture());
theGameTextures[tCount]->createTexture(texturesToUse[tCount]);
}
// load game sounds
// Load Sound
LPCSTR gameSounds[4] = { "Audio/backgroundmusic.wav", "Audio/shot.wav", "Audio/tankmovement.wav", "Audio /explosion.mp4"};
theSoundMgr->add("Theme", gameSounds[0]);
theSoundMgr->add("Shot", gameSounds[1]);
theSoundMgr->add("Tank", gameSounds[2]);
theSoundMgr->add("Explosion", gameSounds[3]);
// load game fontss
// Load Fonts
LPCSTR gameFonts[1] = { "Fonts/Army.ttf" };
theFontMgr->addFont("Menu", gameFonts[0], 60);
theFontMgr->addFont("Instructions", gameFonts[0], 18);
theFontMgr->addFont("Game", gameFonts[0], 25);
// Spawn enemies and determine positions
for (int astro = 0; astro < 5; astro++)
{
theAsteroids.push_back(new cAsteroid);
theAsteroids[astro]->setSpritePos(glm::vec2(0 + (rand() % 1000), 0 - (rand() % 75)));
theAsteroids[astro]->setSpriteTranslation(glm::vec2((rand() % 4 + 1), (rand() % 4 + 1)));
theAsteroids[astro]->setSpriteRotation(180.f);
int randAsteroid = rand() % 4;
theAsteroids[astro]->setTexture(theGameTextures[randAsteroid]->getTexture());
theAsteroids[astro]->setTextureDimensions(theGameTextures[randAsteroid]->getTWidth(), theGameTextures[randAsteroid]->getTHeight());
theAsteroids[astro]->setSpriteCentre();
theAsteroids[astro]->setAsteroidVelocity(glm::vec2(glm::vec2(0.0f, 0.0f)));
theAsteroids[astro]->setActive(true);
theAsteroids[astro]->setMdlRadius();
}
// Makes half the enemies spawn at the bottom of the screen
for (int astro = 5; astro < 10; astro++)
{
theAsteroids.push_back(new cAsteroid);
theAsteroids[astro]->setSpritePos(glm::vec2(0 +(rand() % 1000), windowHeight + (rand() % 75)));
theAsteroids[astro]->setSpriteTranslation(glm::vec2((rand() % 4 + 1), (rand() % 4 + 1)));
int randAsteroid = rand() % 4;
theAsteroids[astro]->setTexture(theGameTextures[randAsteroid]->getTexture());
theAsteroids[astro]->setTextureDimensions(theGameTextures[randAsteroid]->getTWidth(), theGameTextures[randAsteroid]->getTHeight());
theAsteroids[astro]->setSpriteCentre();
theAsteroids[astro]->setAsteroidVelocity(glm::vec2(glm::vec2(0.0f, 0.0f)));
theAsteroids[astro]->setActive(true);
theAsteroids[astro]->setMdlRadius();
}
// Background texture array
vector<cTexture*> textureBkgList;
LPCSTR bkgTexturesToUse[] = { "Images\\background.png", "Images\\menubackground.png" };
for (int tCount = 0; tCount < 2; tCount++)
{
textureBkgList.push_back(new cTexture());
textureBkgList[tCount]->createTexture(bkgTexturesToUse[tCount]);
}
//Button Texture array
vector<cTexture*> btnTextureList;
LPCSTR btnTexturesToUse[] = { "Images/Buttons/exitBtn.png", "Images/Buttons/playBtn.png", };
for (int tCount = 0; tCount < 2; tCount++)
{
btnTextureList.push_back(new cTexture());
btnTextureList[tCount]->createTexture(btnTexturesToUse[tCount]);
}
// Set sprites for background, buttons and player
cBkGround spriteBkgd;
spriteBkgd.setSpritePos(glm::vec2(0.0f, 0.0f));
spriteBkgd.setTexture(textureBkgList[0]->getTexture());
spriteBkgd.setTextureDimensions(textureBkgList[0]->getTWidth(), textureBkgList[0]->getTHeight());
cBkGround spriteStartBkgd;
spriteStartBkgd.setSpritePos(glm::vec2(0.0f, 0.0f));
spriteStartBkgd.setTexture(textureBkgList[1]->getTexture());
spriteStartBkgd.setTextureDimensions(textureBkgList[1]->getTWidth(), textureBkgList[1]->getTHeight());
cBkGround spriteEndBkgd;
spriteEndBkgd.setSpritePos(glm::vec2(0.0f, 0.0f));
spriteEndBkgd.setTexture(textureBkgList[1]->getTexture());
spriteEndBkgd.setTextureDimensions(textureBkgList[1]->getTWidth(), textureBkgList[1]->getTHeight());
cButton exitButton;
exitButton.attachInputMgr(theInputMgr);
exitButton.setTexture(btnTextureList[0]->getTexture());
exitButton.setTextureDimensions(btnTextureList[0]->getTWidth(), btnTextureList[0]->getTHeight());
cButton playButton;
playButton.attachInputMgr(theInputMgr);
playButton.setTexture(btnTextureList[1]->getTexture());
playButton.setTextureDimensions(btnTextureList[1]->getTWidth(), btnTextureList[1]->getTHeight());
cTexture rocketTxt;
rocketTxt.createTexture("Images\\playerTank.png");
cRocket rocketSprite;
rocketSprite.attachInputMgr(theInputMgr); // Attach the input manager to the sprite
rocketSprite.setSpritePos(glm::vec2(512.0f, 380.0f));
rocketSprite.setTexture(rocketTxt.getTexture());
rocketSprite.setTextureDimensions(rocketTxt.getTWidth(), rocketTxt.getTHeight());
rocketSprite.setSpriteCentre();
rocketSprite.setRocketVelocity(glm::vec2(0.0f, 0.0f));
// Text for game including control instructions
string outputMsg;
string strMsg[] = { "Left and right arrows to move. Up and down to change shooting direction. ", "Tank Battle", "Game over", "E to stop moving, space to Shoot."};
// Attach sound manager to rocket sprite
rocketSprite.attachSoundMgr(theSoundMgr);
gameState theGameState = MENU;
btnTypes theBtnType = EXIT;
// Count enemies destroyed by player
int enemyDestroyed = 0;
//This is the mainloop, we render frames until isRunning returns false
while (pgmWNDMgr->isWNDRunning())
{
pgmWNDMgr->processWNDEvents(); //Process any window events
//We get the time that passed since the last frame
float elapsedTime = pgmWNDMgr->getElapsedSeconds();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// play theme music
theSoundMgr->getSnd("Theme")->playAudio(AL_TRUE);
vector<cAsteroid*>::iterator asteroidIterator = theAsteroids.begin();
// Converts enemy destroyed to the players's score to be displayed
std::string score = std::to_string(enemyDestroyed);
switch (theGameState)
{
case MENU:
// render main menu background and buttons
spriteStartBkgd.render();
playButton.setSpritePos(glm::vec2(450.0f, 300.0f));
exitButton.setSpritePos(glm::vec2(450.0f, 375.0f));
playButton.render();
exitButton.render();
theGameState = playButton.update(theGameState, PLAYING);
exitButton.update();
// Display game name and instructions
outputMsg = strMsg[1];
theFontMgr->getFont("Menu")->printText(outputMsg.c_str(), FTPoint(320.0f, 120, 0.0f));
outputMsg = strMsg[0];
theFontMgr->getFont("Instructions")->printText(outputMsg.c_str(), FTPoint(160.0f, 220, 0.0f));
outputMsg = strMsg[3];
theFontMgr->getFont("Instructions")->printText(outputMsg.c_str(), FTPoint(360.0f, 250, 0.0f));
if (exitButton.getClicked())
{
SendMessage(pgmWNDMgr->getWNDHandle(), WM_CLOSE, NULL, NULL);
}
break;
case PLAYING:
// render background and player
spriteBkgd.render();
rocketSprite.render();
rocketSprite.update(elapsedTime);
// render button and reset clicked to false
while (asteroidIterator != theAsteroids.end())
{
if ((*asteroidIterator)->isActive() == false)
{
asteroidIterator = theAsteroids.erase(asteroidIterator);
enemyDestroyed ++;
}
else
{
(*asteroidIterator)->update(elapsedTime);
(*asteroidIterator)->render();
++asteroidIterator;
}
}
// End game if player destroys all enemies
if (enemyDestroyed > 9)
{
theGameState = END;
}
// Game ends if player his hit by enemy tank
for (vector<cAsteroid*>::iterator asteroidIterator = theAsteroids.begin(); asteroidIterator != theAsteroids.end(); ++asteroidIterator)
{
if ((*asteroidIterator)->collidedWith((*asteroidIterator)->getBoundingRect(), rocketSprite.getBoundingRect()))
{
theGameState = END;
}
}
outputMsg = strMsg[1];
theFontMgr->getFont("Game")->printText(outputMsg.c_str(), FTPoint(10, 25, 0.0f));
outputMsg = "Score: " + score;
theFontMgr->getFont("Game")->printText(outputMsg.c_str(), FTPoint(10.0f, 45.0f, 0.0f)); // Display score
break;
case END:
// Render background and buttons for end screen
spriteEndBkgd.render();
playButton.setClicked(false);
exitButton.setClicked(false);
playButton.setSpritePos(glm::vec2(450.0f, 300.0f));
exitButton.setSpritePos(glm::vec2(450.0f, 375.0f));
playButton.render();
exitButton.render();
theGameState = playButton.update(theGameState, PLAYING);
exitButton.update();
// Display game over text and score
outputMsg = strMsg[2];
theFontMgr->getFont("Menu")->printText(outputMsg.c_str(), FTPoint(350.0f, 170, 0.0f));
outputMsg = "Score: " + score;
theFontMgr->getFont("Menu")->printText(outputMsg.c_str(), FTPoint(373.0f, 250, 0.0f));
if (exitButton.getClicked())
{
SendMessage(pgmWNDMgr->getWNDHandle(), WM_CLOSE, NULL, NULL);
}
break;
}
pgmWNDMgr->swapBuffers();
theInputMgr->clearBuffers(theInputMgr->KEYS_DOWN_BUFFER | theInputMgr->KEYS_PRESSED_BUFFER);
}
theOGLWnd.shutdown(); //Free any resources
pgmWNDMgr->destroyWND(); //Destroy the program window
return 0; //Return success
}
| [
"BSTEWA201@caledonian.ac.uk"
] | BSTEWA201@caledonian.ac.uk |
2f76b8da292d6cff2d909cf7f1de73d3902586ef | d017b807b3753800feef6b8077d084b460027e46 | /cpp/Useful/HueWheelSequence.h | e68122be5713b28112ec60f36947cc2d12558df3 | [] | no_license | awturner/awturner-phd | de64cc0c23e1195df59ea9ac6ebfa8e24ee55f88 | d8280b5602476565d97586854566c93fefe1d431 | refs/heads/master | 2016-09-06T04:47:14.802338 | 2011-06-02T22:33:27 | 2011-06-02T22:33:27 | 32,140,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,125 | h | /*
* ################################################################################
* ### MIT License
* ################################################################################
*
* Copyright (c) 2006-2011 Andy Turner
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef __HUEWHEELSEQUENCE_H__
#define __HUEWHEELSEQUENCE_H__
#include "ColourSequence.h"
#include "ColourConversions.h"
namespace AWT
{
class HueWheelSequence : public ColourSequence
{
public:
typedef ManagedAutoPointer<HueWheelSequence> P;
protected:
HueWheelSequence(const unsigned int ncolours, const double saturation = 1, const double value = 1, const double alpha = 1);
virtual ~HueWheelSequence();
public:
static HueWheelSequence::P getInstance(const unsigned int ncolours, const double saturation = 1, const double value = 1, const double alpha = 1);
virtual std::string getClassName() const;
virtual void nextColour(float* colour);
virtual void nextColour(double* colour);
protected:
struct D;
D* m_D;
};
}
#endif // __HUEWHEELSEQUENCE_H__ | [
"andy.w.turner@gmail.com@8ccf9804-531a-5bdb-f4a8-09d094668cd7"
] | andy.w.turner@gmail.com@8ccf9804-531a-5bdb-f4a8-09d094668cd7 |
650484460ef9e3c99edcff7822cefe06b8d4a955 | 2cd9494421facc54e0015907ee1e545119c7474d | /Array/easy/697_Degree of an Array.cpp | 561ab525bf58e1b3648d92588fed077e981e3883 | [] | no_license | yinzm/LeetCodeSolution | 9d31b297e9e0a34a4792f5a1c5d3e51b4b9c41a6 | d28dc2472a8cbe395476a9d9f870c954d8ba3d88 | refs/heads/master | 2021-04-16T19:15:00.931019 | 2018-08-23T16:04:23 | 2018-08-23T16:04:23 | 126,659,599 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,977 | cpp | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findShortestSubArray(vector<int>& nums) {
int len = nums.size();
int bucket[50010];
memset(bucket, 0, sizeof(bucket));
int degree = 0;
for (int i = 0; i < len; ++i) {
bucket[nums[i]]++;
degree = max(degree, bucket[nums[i]]);
}
int p1 = 0, p2 = 0;
int min_dist = len;
memset(bucket, 0, sizeof(bucket));
bucket[nums[p2]] = 1;
while (p2 < len) {
if (bucket[nums[p2]] == degree) {
min_dist = min(min_dist, p2-p1+1);
bucket[nums[p1]]--;
p1++;
} else {
p2++;
if (p2 >= len) {
break;
}
bucket[nums[p2]]++;
}
}
return min_dist;
}
// 更加好理解的解法
int findShortestSubArray2(vector<int>& nums) {
int len = nums.size();
int bucket[50010];
int left[50010];
int right[50010];
int degree = 0, min_dist = len;
memset(bucket, 0, sizeof(bucket));
memset(left, -1, sizeof(left));
memset(right, -1, sizeof(right));
for (int i = 0; i < len; ++i) {
bucket[nums[i]]++;
degree = max(degree, bucket[nums[i]]);
if (left[nums[i]] == -1) {
left[nums[i]] = i;
}
right[nums[i]] = i;
}
for (int i = 0; i < len; ++i) {
if (bucket[nums[i]] == degree) {
min_dist = min(min_dist, right[nums[i]] - left[nums[i]] + 1);
}
}
return min_dist;
}
};
int main() {
int n;
cin >> n;
vector<int> nums(n, 0);
for (int i = 0; i < n; ++i) {
cin >> nums[i];
}
Solution s;
cout << s.findShortestSubArray(nums) << endl;
return 0;
}
/*
5
1 2 2 3 1
7
1 2 2 3 1 4 2
*/
| [
"yinzongming@gmail.com"
] | yinzongming@gmail.com |
6a613bba4849a184f1c31024d976c7ec5c385ff4 | 97ce80e44d5558cad2ca42758e2d6fb1805815ce | /Source/Scripting/bsfScript/Wrappers/BsScriptOrder.cpp | bcfb127f1e5f8612e2985e6c8b2a572b3f55f0d5 | [
"MIT"
] | permissive | cwmagnus/bsf | ff83ca34e585b32d909b3df196b8cf31ddd625c3 | 36de1caf1f7532d497b040d302823e98e7b966a8 | refs/heads/master | 2020-12-08T00:53:11.021847 | 2020-03-23T22:05:24 | 2020-03-23T22:05:24 | 232,839,774 | 3 | 0 | MIT | 2020-01-09T15:26:22 | 2020-01-09T15:26:21 | null | UTF-8 | C++ | false | false | 530 | cpp | //********************************* bs::framework - Copyright 2018-2019 Marko Pintera ************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#include "Wrappers/BsScriptOrder.h"
namespace bs
{
MonoField* ScriptOrder::indexField = nullptr;
ScriptOrder::ScriptOrder(MonoObject* instance) : ScriptObject(instance)
{ }
void ScriptOrder::initRuntimeData()
{
indexField = metaData.scriptClass->getField("index");
}
}
| [
"bearishsun@gmail.com"
] | bearishsun@gmail.com |
5e7c25a13b47e3a089a641d0014821ed630fd6be | c192aa775f6e66159d6f93431fc5df77175dfea6 | /template_class.cpp | 9ec73a267497da730502b878d75c0dbed7049acc | [] | no_license | KhyatiSaini/Some-basic-Tricks-of-cp | 7a3ddce17975bee4b03a52dac26b53a9ce64ba10 | d8f1723e5d5e1dcc03e500ef94d1ea74478078b4 | refs/heads/master | 2020-08-14T03:20:03.700410 | 2019-10-14T16:35:20 | 2019-10-14T16:35:20 | 215,088,189 | 2 | 2 | null | 2020-05-26T19:36:46 | 2019-10-14T16:07:24 | C++ | UTF-8 | C++ | false | false | 957 | cpp | #include <iostream>
using namespace std;
template<class T>
class List
{
T data;
List *next;
public:
List()
{
next=NULL;
}
void enter()
{
List<T>*start=this;
List<T>*node=new List<T>;
T d;
cout<<"\n enter the data: ";
cin>>d;
node->data=d;
node->next=NULL;
while(start->next!=NULL)
start=start->next;
start->next=node;
}
void display()
{
List<T>*start=this->next;
while(start!=NULL)
{
cout<<"\t"<<start->data;
start=start->next;
}
}
};
int main()
{
cout << "Hello world!" << endl;
List<int>l1;
int s,i;
cout<<"\n enter size of list";
cin>>s;
for(i=0;i<s;i++)
l1.enter();
l1.display();
List<float>l2;
cout<<"\n enter size of list";
cin>>s;
for(i=0;i<s;i++)
l2.enter();
l2.display();
return 0;
}
| [
"apurva925dubey@gmail.com"
] | apurva925dubey@gmail.com |
9a03ac0d0c83d9e3bee8e902e1b1e860475d6d46 | d9a7afdf160f15a2a8bc5f07e07a0422c5d8da8b | /3-work/qt/qt-HMIClient/MESApp/src/Action/networkinfo/netconfig.h | 6d9cbdddd6aaf98b2767aef17d74590d3247a966 | [] | no_license | programcj/programming_path | 964cd53fdef74041241ebe392eeb0c4566eb1d89 | 04a410492a9ee7173612122e367ac1c5b101d7ce | refs/heads/master | 2021-12-15T10:43:33.066541 | 2021-12-11T10:20:01 | 2021-12-11T10:20:01 | 184,296,551 | 1 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 849 | h | #ifndef NETCONFIG_H
#define NETCONFIG_H
#include <QtGui/QDialog>
#include "ui_netconfig.h"
#include <QProcess>
#include "interface.h"
#include "qipaddressedit.h"
#include "qipaddressedititem.h"
class netconfig : public QDialog
{
Q_OBJECT
public:
netconfig(QWidget *parent = 0);
~netconfig();
QList<Interface*> ints;
QProcess *proc;
bool flag;
public slots:
void on_sel_changed(const QString &text);
// void on_toggled(bool b);
void on_bt_ok_clicked();
void refreshInterfaces();
void readConfigs();
void writeConfigs();
void state(bool dhcp);
void proc_finished(int code);
// void on_pbtest_clicked();
protected:
void closeEvent(QCloseEvent * evt);
void moveEvent(QMoveEvent *);
void resizeEvent(QResizeEvent *);
private:
Ui::netconfigClass ui;
};
#endif // NETCONFIG_H
| [
"aa"
] | aa |
1e02b50886143ad8bceeea27840dbe17c51e2c14 | ceae2b140670c0292b471d3c028b69e34b05f1c2 | /coverage/home/arjun/llvm-project/llvm/lib/Support/Program.cpp.html | 29a50d9ebda5642f241c8aefd2f1990c7e8a4dce | [] | no_license | Superty/gbr-coverage | 3dde3370f7d66e364f404fc62932c0d3a63298a6 | 7ee34f25b178aebbb107ab89bce58ddc2559de0b | refs/heads/master | 2022-11-10T07:11:04.341685 | 2020-06-26T00:15:17 | 2020-06-26T00:15:22 | 271,607,293 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,569 | html | <!doctype html><html><head><meta name='viewport' content='width=device-width,initial-scale=1'><meta charset='UTF-8'><link rel='stylesheet' type='text/css' href='../../../../../../../style.css'></head><body><h2>Coverage Report</h2><h4>Created: 2020-06-26 05:44</h4><div class='centered'><table><div class='source-name-title'><pre>/home/arjun/llvm-project/llvm/lib/Support/Program.cpp</pre></div><tr><td><pre>Line</pre></td><td><pre>Count</pre></td><td><pre>Source (<a href='#L34'>jump to first uncovered line</a>)</pre></td></tr><tr><td class='line-number'><a name='L1' href='#L1'><pre>1</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>//===-- Program.cpp - Implement OS Program Concept --------------*- C++ -*-===//</pre></td></tr><tr><td class='line-number'><a name='L2' href='#L2'><pre>2</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>//</pre></td></tr><tr><td class='line-number'><a name='L3' href='#L3'><pre>3</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.</pre></td></tr><tr><td class='line-number'><a name='L4' href='#L4'><pre>4</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>// See https://llvm.org/LICENSE.txt for license information.</pre></td></tr><tr><td class='line-number'><a name='L5' href='#L5'><pre>5</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception</pre></td></tr><tr><td class='line-number'><a name='L6' href='#L6'><pre>6</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>//</pre></td></tr><tr><td class='line-number'><a name='L7' href='#L7'><pre>7</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>//===----------------------------------------------------------------------===//</pre></td></tr><tr><td class='line-number'><a name='L8' href='#L8'><pre>8</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>//</pre></td></tr><tr><td class='line-number'><a name='L9' href='#L9'><pre>9</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>// This file implements the operating system Program concept.</pre></td></tr><tr><td class='line-number'><a name='L10' href='#L10'><pre>10</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>//</pre></td></tr><tr><td class='line-number'><a name='L11' href='#L11'><pre>11</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>//===----------------------------------------------------------------------===//</pre></td></tr><tr><td class='line-number'><a name='L12' href='#L12'><pre>12</pre></a></td><td class='uncovered-line'></td><td class='code'><pre></pre></td></tr><tr><td class='line-number'><a name='L13' href='#L13'><pre>13</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>#include "llvm/Support/Program.h"</pre></td></tr><tr><td class='line-number'><a name='L14' href='#L14'><pre>14</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>#include "llvm/ADT/StringRef.h"</pre></td></tr><tr><td class='line-number'><a name='L15' href='#L15'><pre>15</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>#include "llvm/Config/llvm-config.h"</pre></td></tr><tr><td class='line-number'><a name='L16' href='#L16'><pre>16</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>#include <system_error></pre></td></tr><tr><td class='line-number'><a name='L17' href='#L17'><pre>17</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>using namespace llvm;</pre></td></tr><tr><td class='line-number'><a name='L18' href='#L18'><pre>18</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>using namespace sys;</pre></td></tr><tr><td class='line-number'><a name='L19' href='#L19'><pre>19</pre></a></td><td class='uncovered-line'></td><td class='code'><pre></pre></td></tr><tr><td class='line-number'><a name='L20' href='#L20'><pre>20</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>//===----------------------------------------------------------------------===//</pre></td></tr><tr><td class='line-number'><a name='L21' href='#L21'><pre>21</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>//=== WARNING: Implementation here must contain only TRULY operating system</pre></td></tr><tr><td class='line-number'><a name='L22' href='#L22'><pre>22</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>//=== independent code.</pre></td></tr><tr><td class='line-number'><a name='L23' href='#L23'><pre>23</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>//===----------------------------------------------------------------------===//</pre></td></tr><tr><td class='line-number'><a name='L24' href='#L24'><pre>24</pre></a></td><td class='uncovered-line'></td><td class='code'><pre></pre></td></tr><tr><td class='line-number'><a name='L25' href='#L25'><pre>25</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>static bool Execute(ProcessInfo &PI, StringRef Program,</pre></td></tr><tr><td class='line-number'><a name='L26' href='#L26'><pre>26</pre></a></td><td class='uncovered-line'></td><td class='code'><pre> ArrayRef<StringRef> Args, Optional<ArrayRef<StringRef>> Env,</pre></td></tr><tr><td class='line-number'><a name='L27' href='#L27'><pre>27</pre></a></td><td class='uncovered-line'></td><td class='code'><pre> ArrayRef<Optional<StringRef>> Redirects,</pre></td></tr><tr><td class='line-number'><a name='L28' href='#L28'><pre>28</pre></a></td><td class='uncovered-line'></td><td class='code'><pre> unsigned MemoryLimit, std::string *ErrMsg);</pre></td></tr><tr><td class='line-number'><a name='L29' href='#L29'><pre>29</pre></a></td><td class='uncovered-line'></td><td class='code'><pre></pre></td></tr><tr><td class='line-number'><a name='L30' href='#L30'><pre>30</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>int sys::ExecuteAndWait(StringRef Program, ArrayRef<StringRef> Args,</pre></td></tr><tr><td class='line-number'><a name='L31' href='#L31'><pre>31</pre></a></td><td class='uncovered-line'></td><td class='code'><pre> Optional<ArrayRef<StringRef>> Env,</pre></td></tr><tr><td class='line-number'><a name='L32' href='#L32'><pre>32</pre></a></td><td class='uncovered-line'></td><td class='code'><pre> ArrayRef<Optional<StringRef>> Redirects,</pre></td></tr><tr><td class='line-number'><a name='L33' href='#L33'><pre>33</pre></a></td><td class='uncovered-line'></td><td class='code'><pre> unsigned SecondsToWait, unsigned MemoryLimit,</pre></td></tr><tr><td class='line-number'><a name='L34' href='#L34'><pre>34</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre> std::string *ErrMsg, bool *ExecutionFailed) <span class='red'>{</span></pre></td></tr><tr><td class='line-number'><a name='L35' href='#L35'><pre>35</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> assert(Redirects.empty() || Redirects.size() == 3);</span></pre></td></tr><tr><td class='line-number'><a name='L36' href='#L36'><pre>36</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> ProcessInfo PI;</span></pre></td></tr><tr><td class='line-number'><a name='L37' href='#L37'><pre>37</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> if (</span><span class='red'>Execute(PI, Program, Args, Env, Redirects, MemoryLimit, ErrMsg)</span><span class='red'>) </span><span class='red'>{</span></pre></td></tr><tr><td class='line-number'><a name='L38' href='#L38'><pre>38</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> if (</span><span class='red'>ExecutionFailed</span><span class='red'>)</span></pre></td></tr><tr><td class='line-number'><a name='L39' href='#L39'><pre>39</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> </span><span class='red'>*ExecutionFailed = false</span><span class='red'>;</span></pre></td></tr><tr><td class='line-number'><a name='L40' href='#L40'><pre>40</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> ProcessInfo Result = Wait(</span></pre></td></tr><tr><td class='line-number'><a name='L41' href='#L41'><pre>41</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> PI, SecondsToWait, /*WaitUntilTerminates=*/SecondsToWait == 0, ErrMsg);</span></pre></td></tr><tr><td class='line-number'><a name='L42' href='#L42'><pre>42</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> return Result.ReturnCode;</span></pre></td></tr><tr><td class='line-number'><a name='L43' href='#L43'><pre>43</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> }</span></pre></td></tr><tr><td class='line-number'><a name='L44' href='#L44'><pre>44</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'></span></pre></td></tr><tr><td class='line-number'><a name='L45' href='#L45'><pre>45</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> </span><span class='red'>if (</span><span class='red'>ExecutionFailed</span><span class='red'>)</span></pre></td></tr><tr><td class='line-number'><a name='L46' href='#L46'><pre>46</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> </span><span class='red'>*ExecutionFailed = true</span><span class='red'>;</span></pre></td></tr><tr><td class='line-number'><a name='L47' href='#L47'><pre>47</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'></span></pre></td></tr><tr><td class='line-number'><a name='L48' href='#L48'><pre>48</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> return -1;</span></pre></td></tr><tr><td class='line-number'><a name='L49' href='#L49'><pre>49</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'>}</span></pre></td></tr><tr><td class='line-number'><a name='L50' href='#L50'><pre>50</pre></a></td><td class='uncovered-line'></td><td class='code'><pre></pre></td></tr><tr><td class='line-number'><a name='L51' href='#L51'><pre>51</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>ProcessInfo sys::ExecuteNoWait(StringRef Program, ArrayRef<StringRef> Args,</pre></td></tr><tr><td class='line-number'><a name='L52' href='#L52'><pre>52</pre></a></td><td class='uncovered-line'></td><td class='code'><pre> Optional<ArrayRef<StringRef>> Env,</pre></td></tr><tr><td class='line-number'><a name='L53' href='#L53'><pre>53</pre></a></td><td class='uncovered-line'></td><td class='code'><pre> ArrayRef<Optional<StringRef>> Redirects,</pre></td></tr><tr><td class='line-number'><a name='L54' href='#L54'><pre>54</pre></a></td><td class='uncovered-line'></td><td class='code'><pre> unsigned MemoryLimit, std::string *ErrMsg,</pre></td></tr><tr><td class='line-number'><a name='L55' href='#L55'><pre>55</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre> bool *ExecutionFailed) <span class='red'>{</span></pre></td></tr><tr><td class='line-number'><a name='L56' href='#L56'><pre>56</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> assert(Redirects.empty() || Redirects.size() == 3);</span></pre></td></tr><tr><td class='line-number'><a name='L57' href='#L57'><pre>57</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> ProcessInfo PI;</span></pre></td></tr><tr><td class='line-number'><a name='L58' href='#L58'><pre>58</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> if (</span><span class='red'>ExecutionFailed</span><span class='red'>)</span></pre></td></tr><tr><td class='line-number'><a name='L59' href='#L59'><pre>59</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> </span><span class='red'>*ExecutionFailed = false</span><span class='red'>;</span></pre></td></tr><tr><td class='line-number'><a name='L60' href='#L60'><pre>60</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> if (</span><span class='red'>!Execute(PI, Program, Args, Env, Redirects, MemoryLimit, ErrMsg)</span><span class='red'>)</span></pre></td></tr><tr><td class='line-number'><a name='L61' href='#L61'><pre>61</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> </span><span class='red'>if (</span><span class='red'>ExecutionFailed</span><span class='red'>)</span></pre></td></tr><tr><td class='line-number'><a name='L62' href='#L62'><pre>62</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> </span><span class='red'>*ExecutionFailed = true</span><span class='red'>;</span></pre></td></tr><tr><td class='line-number'><a name='L63' href='#L63'><pre>63</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'></span></pre></td></tr><tr><td class='line-number'><a name='L64' href='#L64'><pre>64</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> return PI;</span></pre></td></tr><tr><td class='line-number'><a name='L65' href='#L65'><pre>65</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'>}</span></pre></td></tr><tr><td class='line-number'><a name='L66' href='#L66'><pre>66</pre></a></td><td class='uncovered-line'></td><td class='code'><pre></pre></td></tr><tr><td class='line-number'><a name='L67' href='#L67'><pre>67</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>bool sys::commandLineFitsWithinSystemLimits(StringRef Program,</pre></td></tr><tr><td class='line-number'><a name='L68' href='#L68'><pre>68</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre> ArrayRef<const char *> Args) <span class='red'>{</span></pre></td></tr><tr><td class='line-number'><a name='L69' href='#L69'><pre>69</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> SmallVector<StringRef, 8> StringRefArgs;</span></pre></td></tr><tr><td class='line-number'><a name='L70' href='#L70'><pre>70</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> StringRefArgs.reserve(Args.size());</span></pre></td></tr><tr><td class='line-number'><a name='L71' href='#L71'><pre>71</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> for (const char *A : Args)</span><span class='red'></span></pre></td></tr><tr><td class='line-number'><a name='L72' href='#L72'><pre>72</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre> <span class='red'>StringRefArgs.emplace_back(A)</span><span class='red'>;</span></pre></td></tr><tr><td class='line-number'><a name='L73' href='#L73'><pre>73</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'> return commandLineFitsWithinSystemLimits(Program, StringRefArgs);</span></pre></td></tr><tr><td class='line-number'><a name='L74' href='#L74'><pre>74</pre></a></td><td class='uncovered-line'><pre>0</pre></td><td class='code'><pre><span class='red'>}</span></pre></td></tr><tr><td class='line-number'><a name='L75' href='#L75'><pre>75</pre></a></td><td class='uncovered-line'></td><td class='code'><pre></pre></td></tr><tr><td class='line-number'><a name='L76' href='#L76'><pre>76</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>// Include the platform-specific parts of this class.</pre></td></tr><tr><td class='line-number'><a name='L77' href='#L77'><pre>77</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>#ifdef LLVM_ON_UNIX</pre></td></tr><tr><td class='line-number'><a name='L78' href='#L78'><pre>78</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>#include "Unix/Program.inc"</pre></td></tr><tr><td class='line-number'><a name='L79' href='#L79'><pre>79</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>#endif</pre></td></tr><tr><td class='line-number'><a name='L80' href='#L80'><pre>80</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>#ifdef _WIN32</pre></td></tr><tr><td class='line-number'><a name='L81' href='#L81'><pre>81</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>#include "Windows/Program.inc"</pre></td></tr><tr><td class='line-number'><a name='L82' href='#L82'><pre>82</pre></a></td><td class='uncovered-line'></td><td class='code'><pre>#endif</pre></td></tr></table></div></body></html> | [
"arjunpitchanathan@gmail.com"
] | arjunpitchanathan@gmail.com |
634e8e41fe539b87fa5ea12e1f8cae80f52489f8 | 79ec9ec8c89b77b1eb0258ceb811d85314f66402 | /src/initializer/parser_layer.cc | 0321a5e8b84cb2e8b168f533bce9fb9bf8069fb2 | [
"BSD-2-Clause"
] | permissive | leegda/blitz | f7d18fc2470e179b1ee2ee339bd3c474e4dbfb12 | ea9a06dc78ef15d772e36d5d47ffac8d3f46034d | refs/heads/master | 2022-11-21T08:34:03.339348 | 2017-06-30T06:31:51 | 2017-06-30T06:31:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,114 | cc | #include "initializer/parser.h"
#include "blitz.h"
#include "layers/affine.h"
#include "layers/conv.h"
#include "layers/pooling.h"
#include "layers/dropout.h"
#include "layers/param_layer.h"
#include "utils/blitz_algorithm_function.h"
namespace blitz {
template<template <typename> class TensorType, typename DType>
shared_ptr<Layer<TensorType, DType> > Parser::SetLayer(const YAML::Node& node) const {
if (!node["name"])
LOG(FATAL) << "'name' parameter missing";
if (!node["type"])
LOG(FATAL) << "'type' parameter missing";
shared_ptr<Layer<TensorType, DType> > layer;
string type = node["type"].as<string>();
string name = node["name"].as<string>();
if (type == "Affine" || type == "Conv") {
shared_ptr<ParamLayer<TensorType, DType> > param_layer;
if (type == "Affine") {
if (!node["nout"])
LOG(FATAL) << "'nout' parameter missing";
if (!node["filler"])
LOG(FATAL) << "'filler' parameter missing";
if (!node["optimizer"])
LOG(FATAL) << "'optimizer' parameter missing";
int nout = node["nout"].as<int>();
string filler_name = node["filler"].as<string>();
string optimizer_name = node["optimizer"].as<string>();
BLITZ_ALGORITHM algorithm = node["kernel"] ?
BlitzParseAlgorithm(node["kernel"].as<string>()) : BLITZ_BLAS_GEMM;
shared_ptr<Activation<TensorType, DType> > activation;
if (node["activation"])
activation = SetActivation<TensorType, DType>(node["activation"]);
param_layer = static_pointer_cast<ParamLayer<TensorType, DType> >(
make_shared<Affine<TensorType, DType> >(name, filler_name,
optimizer_name, activation, nout, algorithm));
} else if (type == "Conv") {
int stride = 1;
int padding = 0;
if (node["stride"]) {
stride = node["stride"].as<int>();
}
if (node["padding"]) {
padding = node["padding"].as<int>();
}
if (!node["fshape"])
LOG(FATAL) << "'fshape' parameter missing";
if (!node["filler"])
LOG(FATAL) << "'filler' parameter missing";
if (!node["optimizer"])
LOG(FATAL) << "'optimizer' parameter missing";
Shape shape(node["fshape"].as<vector<size_t> >());
string filler_name = node["filler"].as<string>();
string optimizer_name = node["optimizer"].as<string>();
BLITZ_ALGORITHM algorithm = node["kernel"] ?
BlitzParseAlgorithm(node["kernel"].as<string>()) : BLITZ_CONVOLUTION_BLAS_GEMM;
shared_ptr<Activation<TensorType, DType> > activation;
if (node["activation"])
activation = SetActivation<TensorType, DType>(node["activation"]);
param_layer = shared_ptr<ParamLayer<TensorType, DType> >(
static_pointer_cast<ParamLayer<TensorType, DType> >(
new Conv<TensorType, DType>(name, filler_name,
optimizer_name, activation, shape, stride, stride, padding,
padding, algorithm)));
}
if (node["bias"]) {
typedef typename ParamLayer<TensorType, DType>::Bias Bias;
const YAML::Node bias_node = node["bias"];
if (!bias_node["name"])
LOG(FATAL) << "'name' parameter missing";
if (!bias_node["filler"])
LOG(FATAL) << "'filler' parameter missing";
if (!bias_node["optimizer"])
LOG(FATAL) << "'optimizer' parameter missing";
string bias_name = bias_node["name"].as<string>();
string bias_filler_name = bias_node["filler"].as<string>();
string bias_optimizer_name = bias_node["optimizer"].as<string>();
shared_ptr<Bias> bias = make_shared<Bias>(bias_name,
bias_filler_name, bias_optimizer_name);
param_layer->set_bias(bias);
}
if (node["batch_norm"]) {
typedef typename ParamLayer<TensorType, DType>::BatchNorm BatchNorm;
const YAML::Node batch_norm_node = node["batch_norm"];
if (!batch_norm_node["name"])
LOG(FATAL) << "'name' parameter missing";
if (!batch_norm_node["gamma_filler"])
LOG(FATAL) << "'beta_filler' parameter missing";
if (!batch_norm_node["gamma_optimizer"])
LOG(FATAL) << "'beta_optimizer' parameter missing";
if (!batch_norm_node["beta_filler"])
LOG(FATAL) << "'beta_filler' parameter missing";
if (!batch_norm_node["beta_optimizer"])
LOG(FATAL) << "'beta_optimizer' parameter missing";
string batch_norm_name = batch_norm_node["name"].as<string>();
string beta_filler_name = batch_norm_node["beta_filler"].
as<string>();
string beta_optimizer_name = batch_norm_node["beta_optimizer"].
as<string>();
string gamma_filler_name = batch_norm_node["gamma_filler"].
as<string>();
string gamma_optimizer_name = batch_norm_node["gamma_optimizer"].
as<string>();
shared_ptr<BatchNorm> batch_norm = make_shared<BatchNorm>(
batch_norm_name, gamma_filler_name, gamma_optimizer_name,
beta_filler_name, beta_optimizer_name);
param_layer->set_batch_norm(batch_norm);
}
layer = static_pointer_cast<Layer<TensorType, DType> >(param_layer);
} else if (type == "Pooling") {
if (!node["fshape"])
LOG(FATAL) << "'fshape' parameter missing";
if (!node["stride"])
LOG(FATAL) << "'stride' parameter missing";
if (!node["op"])
LOG(FATAL) << "'op' parameter missing";
int shape = node["fshape"].as<int>();
int stride = node["stride"].as<int>();
string op = node["op"].as<string>();
layer = static_pointer_cast<Layer<TensorType, DType> >(
make_shared<Pooling<TensorType, DType> >(name,
shape, stride, op));
} else if (type == "Dropout") {
if (!node["keep"])
LOG(FATAL) << "'keep' parameter missing";
DType keep = node["keep"].as<DType>();
layer = static_pointer_cast<Layer<TensorType, DType> >(
make_shared<Dropout<TensorType, DType> >(name,
keep));
} else {
LOG(FATAL) << "Unkown layer type: " << type;
}
return layer;
}
INSTANTIATE_SETTER_CPU(Layer);
#ifdef BLITZ_USE_GPU
INSTANTIATE_SETTER_GPU(Layer);
#endif
} // namespace blitz
| [
"robinho364@gmail.com"
] | robinho364@gmail.com |
ae42fa2f99f08246e0f0339c56eff8d3206247de | d790ee748ede440d0a999072c17166299777ed9d | /devel/include/mavros/WaypointPushResponse.h | f242f61a5917319dea482c0a21744159b935b599 | [] | no_license | mit-uav/pixhawk | 01fc7059a03ae2dc07d2a56c7503a156869d3a1d | f80fb9df6a85b622feaea7d4ef0a77d8e6561ab0 | refs/heads/master | 2016-08-04T16:35:15.408735 | 2015-09-18T21:02:57 | 2015-09-18T21:02:57 | 42,746,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,209 | h | /* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 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.
*
* Auto-generated by genmsg_cpp from file /home/sam/Desktop/pixhawk/src/mavros-mod/mavros/srv/WaypointPush.srv
*
*/
#ifndef MAVROS_MESSAGE_WAYPOINTPUSHRESPONSE_H
#define MAVROS_MESSAGE_WAYPOINTPUSHRESPONSE_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace mavros
{
template <class ContainerAllocator>
struct WaypointPushResponse_
{
typedef WaypointPushResponse_<ContainerAllocator> Type;
WaypointPushResponse_()
: success(false)
, wp_transfered(0) {
}
WaypointPushResponse_(const ContainerAllocator& _alloc)
: success(false)
, wp_transfered(0) {
}
typedef uint8_t _success_type;
_success_type success;
typedef uint32_t _wp_transfered_type;
_wp_transfered_type wp_transfered;
typedef boost::shared_ptr< ::mavros::WaypointPushResponse_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::mavros::WaypointPushResponse_<ContainerAllocator> const> ConstPtr;
}; // struct WaypointPushResponse_
typedef ::mavros::WaypointPushResponse_<std::allocator<void> > WaypointPushResponse;
typedef boost::shared_ptr< ::mavros::WaypointPushResponse > WaypointPushResponsePtr;
typedef boost::shared_ptr< ::mavros::WaypointPushResponse const> WaypointPushResponseConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::mavros::WaypointPushResponse_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::mavros::WaypointPushResponse_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace mavros
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'mavros': ['/home/sam/Desktop/pixhawk/src/mavros-mod/mavros/msg'], 'geometry_msgs': ['/opt/ros/indigo/share/geometry_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/indigo/share/sensor_msgs/cmake/../msg'], 'diagnostic_msgs': ['/opt/ros/indigo/share/diagnostic_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::mavros::WaypointPushResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::mavros::WaypointPushResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::mavros::WaypointPushResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::mavros::WaypointPushResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::mavros::WaypointPushResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::mavros::WaypointPushResponse_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::mavros::WaypointPushResponse_<ContainerAllocator> >
{
static const char* value()
{
return "90e0074a42480231d34eed864d14365e";
}
static const char* value(const ::mavros::WaypointPushResponse_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x90e0074a42480231ULL;
static const uint64_t static_value2 = 0xd34eed864d14365eULL;
};
template<class ContainerAllocator>
struct DataType< ::mavros::WaypointPushResponse_<ContainerAllocator> >
{
static const char* value()
{
return "mavros/WaypointPushResponse";
}
static const char* value(const ::mavros::WaypointPushResponse_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::mavros::WaypointPushResponse_<ContainerAllocator> >
{
static const char* value()
{
return "bool success\n\
uint32 wp_transfered\n\
\n\
";
}
static const char* value(const ::mavros::WaypointPushResponse_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::mavros::WaypointPushResponse_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.success);
stream.next(m.wp_transfered);
}
ROS_DECLARE_ALLINONE_SERIALIZER;
}; // struct WaypointPushResponse_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::mavros::WaypointPushResponse_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::mavros::WaypointPushResponse_<ContainerAllocator>& v)
{
s << indent << "success: ";
Printer<uint8_t>::stream(s, indent + " ", v.success);
s << indent << "wp_transfered: ";
Printer<uint32_t>::stream(s, indent + " ", v.wp_transfered);
}
};
} // namespace message_operations
} // namespace ros
#endif // MAVROS_MESSAGE_WAYPOINTPUSHRESPONSE_H
| [
"sudotong@gmail.com"
] | sudotong@gmail.com |
ca920e4ade43b78dc64d7a5406d5b6fd0a7e7a5b | c76f0563a583e7a186baafb4ef46630487e18d05 | /01. Programming Fundamentals/while loop.cpp | 7bd74f2b5514fb798c4626728c4b749927bdfe62 | [] | no_license | ParvezAhmed111/Data-Structure-and-Algorithms-with-cpp | e7772c2571b5d937e5957769de9c88c236175051 | ee6ad8f3259e8a3b2b1a5f270fee955da9222a72 | refs/heads/main | 2023-08-13T14:20:24.603031 | 2021-09-29T18:21:21 | 2021-09-29T18:21:21 | 411,760,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 133 | cpp | #include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
while(n>0){
cout<<n<<endl;
cin>>n;
}
return 0;
}
| [
"parvezahmed.0947@gmail.com"
] | parvezahmed.0947@gmail.com |
2d024165074c9b11e14b7a75b3549d7572b0b83a | a234f3a0a996e922e8bd3da10116777dc1c34866 | /lrm_drivers/src/vcmdas1_driver.cpp | b2df27b09c1bff595982f60dc4e1380067999eaf | [] | no_license | Aand1/lrm_carina | d3cccbc5f78c37643ccd6e232f5e147d797ccffe | 76de955e3f2349f24436196c8a82d38340028225 | refs/heads/master | 2021-01-20T14:28:51.725555 | 2014-06-17T02:34:05 | 2014-06-17T02:34:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,732 | cpp | /*
* Vcmdas1.cpp
*
* Created on: Feb 10, 2013
* Author: mac
*/
#include "lrm_drivers/vcmdas1_driver.h"
Vcmdas1::Vcmdas1() {
fd = NULL;
this->base_addr = 0;
this->ain_range = 0;
this->ain_offset = 0;
this->ain_gain = 0;
this->aout_range[0] = 0;
this->aout_range[1] = 0;
this->aout_offset[0] = 0;
this->aout_offset[1] = 0;
this->aout_gain[0] = 0;
this->aout_gain[1] = 0;
this->out_val = 0;
}
Vcmdas1::Vcmdas1(const string& charDevicePath, unsigned int base_addr,
unsigned int ain_range, unsigned int aout_0_range,
unsigned int aout_1_range) throw () {
fd = open(charDevicePath.c_str(), O_RDWR);
if (fd == -1) {
throw std::bad_alloc();
return;
}
this->base_addr = base_addr;
this->ain_range = ain_range;
this->ain_offset = 0;
this->ain_gain = 0;
this->aout_range[0] = aout_0_range;
this->aout_range[1] = aout_1_range;
this->aout_offset[0] = 0;
this->aout_offset[1] = 0;
this->aout_gain[0] = 0;
this->aout_gain[1] = 0;
this->out_val = 0;
this->resetCard();
}
void Vcmdas1::resetCard() throw () {
unsigned int data;
/*---------------------------
* reset control register to
* power-on value
*---------------------------*/
this->set_b(this->base_addr + CONTROL, 0);
/*---------------------------
* reset analog input
*---------------------------*/
this->set_b(this->base_addr, 0);
data = this->analogIn(0);
/*---------------------------
* reset all analog output
* channels to 0.000 volts
*---------------------------*/
this->analogOut(0, 0);
this->analogOut(1, 0);
/*--------------------------------
* reset parallel port
*--------------------------------*/
OUT_SAVEW(DIGLO, 0);
/*--------------------------------
* Enable writes to the EEPROM
*--------------------------------*/
this->enableWriteEEPROM();
}
unsigned int Vcmdas1::analogIn(unsigned int channel) throw () {
unsigned int done;
unsigned int timedout;
int data;
/*---------------------------
* select channel and start the conversion
*---------------------------*/
this->set_w(this->base_addr + SELECT, channel);
this->set_b(this->base_addr + CONVERT, 01);
/*---------------------------
* wait for conversion with a timeout loop
*
* Worst case, with Settling Time set at 10, a conversion
* should be complete in 10+10=20 microseconds, we should
* be safe allowing 200 microseconds.
*
* Assuming each iteration of this polling
* loop takes at least 20 clocks, and a
* maximum clock rate of 100 Mhz, each iteration
* takes at least .2 microseconds. We need to
* allow at least 103 microseconds, so we will
* allow 1000 iterations, giving:
* 1000 * .2 = 200 microseconds.
* This should be plenty, even an a speedy machine.
* On the other hand, if it's a lowly 8088
* running at 5 Mhz, and taking more like 80 clocks,
* the timeout will occur in:
* 1000 * 80 * .2 = 1600 microseconds.
*---------------------------*/
done = SSL_IN(base_addr + STATUS) & DONE_BIT;
for (timedout = 8000; !done && timedout; timedout--) {
done = SSL_IN(base_addr + STATUS) & DONE_BIT;
}
/*---------------------------
* return 16-bit data
*---------------------------*/
if (!done) {
throw std::exception();
return 0;
} else {
data = SSL_INW(base_addr + ADCLO);
}
return (data);
}
void Vcmdas1::analogOut(unsigned int channel, int code) throw () {
register unsigned int port;
int i;
/*-------------------------
* calculate the port
* address
*-------------------------*/
port = this->base_addr + SERCS;
/* Enable the chip select for the D/A */
this->set_b(port, VCMDAS1_CSDA);
port = this->base_addr + SERDATA;
/*-----------------------------------------------
* Shift vaule: 16 bits
D15 D14 D13 D12 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0
--- --- --- --- --- --- -- -- -- -- -- -- -- -- -- --
1 B A NC D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0
*-----------------------------------------------*/
// First bit always one
this->set_b(port, 0x01);
if (channel == 0)
channel = 2;
// Output channel B select
this->set_b(port, channel);
// Output channel A select
this->set_b(port, (channel >> 1));
// Output NC
this->set_b(port, 0x00);
for (i = 0; i < 12; i++) {
this->set_b(port, ((code & 0x0800) >> 11));
code = (code << 1);
}
port = this->base_addr + SERCS;
// Disable all serial chip selects
this->set_b(port, 0x00);
// Do a read input, just for a time delay
get_b(port);
// Set D/A load to low
this->set_b(port, VCMDAS1_CSDL);
// Do a read input, just for a time delay
get_b(port);
// Disable all serial chip selects
this->set_b(port, 0x00);
}
void Vcmdas1::enableWriteEEPROM() throw () {
register unsigned int port;
int i;
/* calculate the port address */
port = this->base_addr + SERCS;
/* Enable the chip select for the EEPROM */
this->set_b(port, VCMDAS1_CSEE);
port = this->base_addr + SERDATA;
/*-----------------------------------------------
* Shift vaule: 9 bits
SB OP OP A5 A4 A3 A2 A1 A0
-- -- -- -- -- -- -- -- --
1 0 0 1 1 X X X X
*-----------------------------------------------*/
/* Output start bit of 1 */
this->set_b(port, 1);
/* Output Opcode for EEPROM write enable */
this->set_b(port, 0);
this->set_b(port, 0);
/* Output string of 1s */
for (i = 0; i < 6; i++) {
this->set_b(port, 1);
}
port = this->base_addr + SERCS;
/* Disable all serial chip selects */
this->set_b(port, 0x00);
}
unsigned int Vcmdas1::readEEPROM(unsigned int address) throw () {
register unsigned int port, a;
int i;
unsigned int data;
a = address;
/* calculate the port address */
port = this->base_addr + SERCS;
/* Enable the chip select for the EEPROM */
this->set_b(port, VCMDAS1_CSEE);
port = this->base_addr + SERDATA;
/*-----------------------------------------------
* Shift vaule: 9 bits
SB OP OP A5 A4 A3 A2 A1 A0
-- -- -- -- -- -- -- -- --
1 1 0 X X X X X X
*-----------------------------------------------*/
/* Output start bit of 1 */
this->set_b(port, 1);
/* Output Opcode for EEPROM read */
this->set_b(port, 1);
this->set_b(port, 0);
/* Output address to read from */
for (i = 0; i < 6; i++) {
this->set_b(port, ((a & 0x0020) >> 5));
a = (a << 1);
}
/* First data read is always 0 */
/* Should a check could be done here to see if it is zero? */
data = 0;
for (i = 0; i < 16; i++) {
data = (data << 1); // Make space for the next data bit
this->set_b(port, 0); // Dummy output to clock data
data = (data | (0x01 & this->get_b(port)));
}
port = this->base_addr + SERCS;
/* Disable all serial chip selects */
this->set_b(port, 0x00);
return data;
}
void Vcmdas1::writeEEPROM(unsigned int address, unsigned int data) throw () {
unsigned int eecs_port, eedata_port, d, a;
unsigned int i, done, timedout;
d = data;
a = address;
/* Port address for the EEPROM chip select */
eecs_port = base_addr + SERCS;
/* Port address for the EEPROM serial data */
eedata_port = base_addr + SERDATA;
/* Raise the EEPROM chip select */
this->set_b(eecs_port, VCMDAS1_CSEE);
/*---------------------------------------------------------------------------------
* Shift value: 25 bits
SB OP OP A5 A4 A3 A2 A1 A0 D15 D14 D13 D12 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0
1 0 1
*---------------------------------------------------------------------------------*/
/* Output SB (Start Bit) */
this->set_b(eedata_port, 1);
/* Output OP OP (EEPROM WRITE) */
this->set_b(eedata_port, 0);
this->set_b(eedata_port, 1);
/* Output A5-A0 */
for (i = 0; i < 6; i++) {
this->set_b(eedata_port, ((a & 0x0020) >> 5));
a = (a << 1);
}
/* Output D15-D0 */
for (i = 0; i < 16; i++) {
this->set_b(eedata_port, ((d & 0x8000) >> 15));
d = (d << 1);
}
/* Drop the EEPROM chip select briefly to reveal BUSY-READY status */this->set_b(
eecs_port, 0x00);
this->set_b(eecs_port, VCMDAS1_CSEE);
/* Enter busy loop with timeout escape */
done = this->get_b(eedata_port);
done &= 0x01;
for (timedout = 30000; !done && timedout; timedout--) {
done = this->get_b(eedata_port);
done &= 0x01;
}
/* ---------------------------------------------------------------
* Execution reaches this point when the write operation completes
* or timeout happens, whichever occurs first.
*----------------------------------------------------------------*/
/* Drop the EEPROM chip select */
this->set_b(eecs_port, 0x00);
/* Return the appropriate error code */
if (!done) {
throw std::exception();
}
}
void Vcmdas1::analogOutMiliVolt(unsigned int channel,
int voltage) throw () {
int outputval;
int offset = aout_offset[channel];
int voltRange, rawRange;
rawRange = voltage > 0 ? 2047 - offset : 2048 + offset;
/*---------------------------
* convert to output value
* with rounding
*---------------------------*/
switch (aout_range[channel]) {
/*--------------------------------
* +/- 10 Volt Output Range:
* Divide +/-10000 into
* +/-2048
*--------------------------------*/
case VCMDAS1_PM10:
voltRange = 10000;
break;
/*--------------------------------
* +/- 5 Volt Output
* Divide +/-5000 into
* +/-2048
*--------------------------------*/
case VCMDAS1_PM5:
voltRange = 5000;
break;
}
outputval = (int) (((((long) voltage) * rawRange) + voltRange / 2) / voltRange);
/*---------------------------
* handle overflow
*---------------------------*/
if (outputval > 2047)
outputval = 2047;
if (outputval < -2048)
outputval = -2048;
/*---------------------------
* write the data and return
* the error code
*---------------------------*/
analogOut(channel, outputval);
}
unsigned int Vcmdas1::digitalIN(unsigned int modno) throw () {
return ((get_w(base_addr + DIGLO) >> (15 - modno)) & 1);
}
void Vcmdas1::digitalOut(unsigned int modno, unsigned int val) throw () {
unsigned int mask = 0x8000;
unsigned int data = out_val;
mask >>= modno;
if (val)
data |= mask;
else
data &= (~mask);
OUT_SAVEW(DIGLO, data);
}
void Vcmdas1::ajustDigitalPot(unsigned int channel, unsigned int code) throw () {
register unsigned int port;
unsigned int i, c = code;
// calculate the port address
port = this->base_addr + SERCS;
/* Enable the chip select for the DPot */
this->set_b(port, VCMDAS1_CSDP);
port = this->base_addr + SERDATA;
/*-----------------------------------------------
* Shift vaule: 10 bits
D9 D8 D7 D6 D5 D4 D3 D2 D1 D0
-- -- -- -- -- -- -- -- -- --
A1 A0 D7 D6 D5 D4 D3 D2 D1 D0
*-----------------------------------------------*/
// Output address 1
this->set_b(port, (channel >> 1));
// Output address 0
this->set_b(port, (channel & 0x01));
for (i = 0; i < 8; i++) {
this->set_b(port, ((c & 0x0080) >> 7));
c = (c << 1);
}
port = this->base_addr + SERCS;
// Disable all serial chip selects.
// Output 20000 times. This delay is to allow the dpot to settle.
for (i = 0; i < 20000; i++) {
this->set_b(port, 0x00);
}
}
long Vcmdas1::analogInMicroVolt(unsigned int channel) throw () {
float microvolts = 0;
int data;
/*---------------------------
* read the channel
*---------------------------*/
data = analogIn(channel);
/*---------------------------
* convert to microvolts
* with rounding
*---------------------------*/
switch (ain_range) {
case VCMDAS1_PM10:
/*---------------------------
* +/-10V Input Range:
* Multiply +/-32768 into
* +/-10,000,000
*---------------------------*/
microvolts = ((((float) data) * 10000000L) + 16384L) / 32768L;
break;
case VCMDAS1_PM5:
/*---------------------------
* +/-5V Input Range:
* Multiply +/-32768 into
* +/-5,000,000
*---------------------------*/
microvolts = ((((float) data) * 5000000L) + 16384L) / 32768L;
break;
}
return (long) microvolts;
}
void Vcmdas1::set_b(unsigned int port, unsigned int value) throw () {
StructData pack;
pack.address = port;
pack.data = value;
if (ioctl(fd, SET_B, &pack) != 0) {
throw std::exception();
return;
}
}
void Vcmdas1::set_w(unsigned int port, unsigned int value) throw () {
StructData pack;
pack.address = port;
pack.data = value;
if (ioctl(fd, SET_W, &pack) != 0) {
throw std::exception();
return;
}
}
unsigned int Vcmdas1::get_b(unsigned int port) throw () {
StructData pack;
pack.address = port;
if (ioctl(fd, GET_B, &pack) != 0) {
throw std::exception();
return 0;
}
return pack.data;
}
unsigned int Vcmdas1::get_w(unsigned int port) throw () {
StructData pack;
pack.address = port;
if (ioctl(fd, GET_W, &pack) != 0) {
throw std::exception();
return 0;
}
return pack.data;
}
Vcmdas1::~Vcmdas1() {
this->resetCard();
close(fd);
}
| [
"rlklaser@icmc.usp.br"
] | rlklaser@icmc.usp.br |
c0d4240a04d4b6ce97a4362f785a0d2d27da4d9d | 0caca2bf0ec6c1b680d0bd50dd0855ffb78113fb | /src/game/server/gamecontroller.cpp | 12db689744f6de1c0e37d4faa52ce764f18d0b8f | [
"LicenseRef-scancode-other-permissive",
"Zlib"
] | permissive | sanyaade-gamedev/zteeworlds | e029afd193476c25cb24090a31570c175f1668ba | 73ad5e6d34d5639c67c93298f21dcd523b06bf73 | refs/heads/master | 2021-01-18T17:48:47.321015 | 2010-05-10T15:43:49 | 2010-05-10T15:43:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,158 | cpp | /* copyright (c) 2007 magnus auvinen, see licence.txt for more info */
#include <string.h>
#include <engine/e_config.h>
#include <engine/e_server_interface.h>
#include <game/mapitems.hpp>
#include <game/generated/g_protocol.hpp>
#include "entities/pickup.hpp"
#include "gamecontroller.hpp"
#include "gamecontext.hpp"
GAMECONTROLLER::GAMECONTROLLER()
{
gametype = "unknown";
//
do_warmup(config.sv_warmup);
game_over_tick = -1;
sudden_death = 0;
round_start_tick = server_tick();
round_count = 0;
game_flags = 0;
teamscore[0] = 0;
teamscore[1] = 0;
map_wish[0] = 0;
unbalanced_tick = -1;
force_balanced = false;
num_spawn_points[0] = 0;
num_spawn_points[1] = 0;
num_spawn_points[2] = 0;
}
GAMECONTROLLER::~GAMECONTROLLER()
{
}
float GAMECONTROLLER::evaluate_spawn_pos(SPAWNEVAL *eval, vec2 pos)
{
float score = 0.0f;
CHARACTER *c = (CHARACTER *)game.world.find_first(NETOBJTYPE_CHARACTER);
for(; c; c = (CHARACTER *)c->typenext())
{
// team mates are not as dangerous as enemies
float scoremod = 1.0f;
if(eval->friendly_team != -1 && c->team == eval->friendly_team)
scoremod = 0.5f;
float d = distance(pos, c->pos);
if(d == 0)
score += 1000000000.0f;
else
score += 1.0f/d;
}
return score;
}
void GAMECONTROLLER::evaluate_spawn_type(SPAWNEVAL *eval, int t)
{
// get spawn point
for(int i = 0; i < num_spawn_points[t]; i++)
{
vec2 p = spawn_points[t][i];
float s = evaluate_spawn_pos(eval, p);
if(!eval->got || eval->score > s)
{
eval->got = true;
eval->score = s;
eval->pos = p;
}
}
}
bool GAMECONTROLLER::can_spawn(PLAYER *player, vec2 *out_pos)
{
SPAWNEVAL eval;
// spectators can't spawn
if(player->team == -1)
return false;
if(is_teamplay())
{
eval.friendly_team = player->team;
// try first try own team spawn, then normal spawn and then enemy
evaluate_spawn_type(&eval, 1+(player->team&1));
if(!eval.got)
{
evaluate_spawn_type(&eval, 0);
if(!eval.got)
evaluate_spawn_type(&eval, 1+((player->team+1)&1));
}
}
else
{
evaluate_spawn_type(&eval, 0);
evaluate_spawn_type(&eval, 1);
evaluate_spawn_type(&eval, 2);
}
*out_pos = eval.pos;
return eval.got;
}
bool GAMECONTROLLER::on_entity(int index, vec2 pos)
{
int type = -1;
int subtype = 0;
if(index == ENTITY_SPAWN)
spawn_points[0][num_spawn_points[0]++] = pos;
else if(index == ENTITY_SPAWN_RED)
spawn_points[1][num_spawn_points[1]++] = pos;
else if(index == ENTITY_SPAWN_BLUE)
spawn_points[2][num_spawn_points[2]++] = pos;
else if(index == ENTITY_ARMOR_1)
type = POWERUP_ARMOR;
else if(index == ENTITY_HEALTH_1)
type = POWERUP_HEALTH;
else if(index == ENTITY_WEAPON_SHOTGUN)
{
type = POWERUP_WEAPON;
subtype = WEAPON_SHOTGUN;
}
else if(index == ENTITY_WEAPON_GRENADE)
{
type = POWERUP_WEAPON;
subtype = WEAPON_GRENADE;
}
else if(index == ENTITY_WEAPON_RIFLE)
{
type = POWERUP_WEAPON;
subtype = WEAPON_RIFLE;
}
else if(index == ENTITY_POWERUP_NINJA && config.sv_powerups)
{
type = POWERUP_NINJA;
subtype = WEAPON_NINJA;
}
if(type != -1)
{
PICKUP *pickup = new PICKUP(type, subtype);
pickup->pos = pos;
return true;
}
return false;
}
void GAMECONTROLLER::endround()
{
if(warmup) // game can't end when we are running warmup
return;
game.world.paused = true;
game_over_tick = server_tick();
sudden_death = 0;
}
void GAMECONTROLLER::resetgame()
{
game.world.reset_requested = true;
}
const char *GAMECONTROLLER::get_team_name(int team)
{
if(is_teamplay())
{
if(team == 0)
return _t("red team");
else if(team == 1)
return _t("blue team");
}
else
{
if(team == 0)
return _t("game");
}
return _t("spectators");
}
static bool is_separator(char c) { return c == ';' || c == ' ' || c == ',' || c == '\t'; }
void GAMECONTROLLER::startround()
{
resetgame();
round_start_tick = server_tick();
sudden_death = 0;
game_over_tick = -1;
game.world.paused = false;
teamscore[0] = 0;
teamscore[1] = 0;
unbalanced_tick = -1;
force_balanced = false;
dbg_msg("game",_t("start round type='%s' teamplay='%d'"), gametype, game_flags&GAMEFLAG_TEAMS);
}
void GAMECONTROLLER::change_map(const char *to_map)
{
str_copy(map_wish, to_map, sizeof(map_wish));
endround();
}
void GAMECONTROLLER::cyclemap()
{
if(map_wish[0] != 0)
{
dbg_msg("game", _t("rotating map to %s"), map_wish);
str_copy(config.sv_map, map_wish, sizeof(config.sv_map));
map_wish[0] = 0;
round_count = 0;
return;
}
if(!strlen(config.sv_maprotation))
return;
if(round_count < config.sv_rounds_per_map-1)
return;
// handle maprotation
const char *map_rotation = config.sv_maprotation;
const char *current_map = config.sv_map;
int current_map_len = strlen(current_map);
const char *next_map = map_rotation;
while(*next_map)
{
int wordlen = 0;
while(next_map[wordlen] && !is_separator(next_map[wordlen]))
wordlen++;
if(wordlen == current_map_len && strncmp(next_map, current_map, current_map_len) == 0)
{
// map found
next_map += current_map_len;
while(*next_map && is_separator(*next_map))
next_map++;
break;
}
next_map++;
}
// restart rotation
if(next_map[0] == 0)
next_map = map_rotation;
// cut out the next map
char buf[512];
for(int i = 0; i < 512; i++)
{
buf[i] = next_map[i];
if(is_separator(next_map[i]) || next_map[i] == 0)
{
buf[i] = 0;
break;
}
}
// skip spaces
int i = 0;
while(is_separator(buf[i]))
i++;
round_count = 0;
dbg_msg("game", _t("rotating map to %s"), &buf[i]);
str_copy(config.sv_map, &buf[i], sizeof(config.sv_map));
}
void GAMECONTROLLER::post_reset()
{
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(game.players[i])
{
game.players[i]->respawn();
game.players[i]->score = 0;
}
}
}
void GAMECONTROLLER::on_player_info_change(class PLAYER *p)
{
const int team_colors[2] = {65387, 10223467};
if(is_teamplay())
{
if(p->team >= 0 || p->team <= 1)
{
p->use_custom_color = 1;
p->color_body = team_colors[p->team];
p->color_feet = team_colors[p->team];
}
}
}
int GAMECONTROLLER::on_character_death(class CHARACTER *victim, class PLAYER *killer, int weapon)
{
// do scoreing
if(!killer)
return 0;
if(killer == victim->player)
victim->player->score--; // suicide
else
{
if(is_teamplay() && victim->team == killer->team)
killer->score--; // teamkill
else
killer->score++; // normal kill
}
return 0;
}
void GAMECONTROLLER::on_character_spawn(class CHARACTER *chr)
{
// default health
chr->health = 10;
// give default weapons
chr->weapons[WEAPON_HAMMER].got = 1;
chr->weapons[WEAPON_HAMMER].ammo = -1;
chr->weapons[WEAPON_GUN].got = 1;
chr->weapons[WEAPON_GUN].ammo = 10;
}
void GAMECONTROLLER::do_warmup(int seconds)
{
warmup = seconds*server_tickspeed();
}
bool GAMECONTROLLER::is_friendly_fire(int cid1, int cid2)
{
if(cid1 == cid2)
return false;
if(is_teamplay())
{
if(!game.players[cid1] || !game.players[cid2])
return false;
if(game.players[cid1]->team == game.players[cid2]->team)
return true;
}
return false;
}
bool GAMECONTROLLER::is_force_balanced()
{
if(force_balanced)
{
force_balanced = false;
return true;
}
else
return false;
}
void GAMECONTROLLER::tick()
{
// do warmup
if(warmup)
{
warmup--;
if(!warmup)
startround();
}
if(game_over_tick != -1)
{
// game over.. wait for restart
if(server_tick() > game_over_tick+server_tickspeed()*10)
{
cyclemap();
startround();
round_count++;
}
}
// do team-balancing
if (is_teamplay() && unbalanced_tick != -1 && server_tick() > unbalanced_tick+config.sv_teambalance_time*server_tickspeed()*60)
{
dbg_msg("game", _t("Balancing teams"));
int t[2] = {0,0};
int tscore[2] = {0,0};
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(game.players[i] && game.players[i]->team != -1)
{
t[game.players[i]->team]++;
tscore[game.players[i]->team]+=game.players[i]->score;
}
}
// are teams unbalanced?
if(abs(t[0]-t[1]) >= 2)
{
int m = (t[0] > t[1]) ? 0 : 1;
int num_balance = abs(t[0]-t[1]) / 2;
do
{
PLAYER *p = 0;
int pd = tscore[m];
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(!game.players[i])
continue;
// remember the player who would cause lowest score-difference
if(game.players[i]->team == m && (!p || abs((tscore[m^1]+game.players[i]->score) - (tscore[m]-game.players[i]->score)) < pd))
{
p = game.players[i];
pd = abs((tscore[m^1]+p->score) - (tscore[m]-p->score));
}
}
// move the player to other team without losing his score
// TODO: change in player::set_team needed: player won't lose score on team-change
int score_before = p->score;
p->set_team(m^1);
p->score = score_before;
p->respawn();
p->force_balanced = true;
} while (--num_balance);
force_balanced = true;
}
unbalanced_tick = -1;
}
// update browse info
int prog = -1;
if(config.sv_timelimit > 0)
prog = max(prog, (server_tick()-round_start_tick) * 100 / (config.sv_timelimit*server_tickspeed()*60));
if(config.sv_scorelimit)
{
if(is_teamplay())
{
prog = max(prog, (teamscore[0]*100)/config.sv_scorelimit);
prog = max(prog, (teamscore[1]*100)/config.sv_scorelimit);
}
else
{
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(game.players[i])
prog = max(prog, (game.players[i]->score*100)/config.sv_scorelimit);
}
}
}
if(warmup)
prog = -1;
server_setbrowseinfo(gametype, prog);
}
bool GAMECONTROLLER::is_teamplay() const
{
return game_flags&GAMEFLAG_TEAMS;
}
void GAMECONTROLLER::snap(int snapping_client)
{
NETOBJ_GAME *gameobj = (NETOBJ_GAME *)snap_new_item(NETOBJTYPE_GAME, 0, sizeof(NETOBJ_GAME));
gameobj->paused = game.world.paused;
gameobj->game_over = game_over_tick==-1?0:1;
gameobj->sudden_death = sudden_death;
gameobj->score_limit = config.sv_scorelimit;
gameobj->time_limit = config.sv_timelimit;
gameobj->round_start_tick = round_start_tick;
gameobj->flags = game_flags;
gameobj->warmup = warmup;
gameobj->round_num = (strlen(config.sv_maprotation) && config.sv_rounds_per_map) ? config.sv_rounds_per_map : 0;
gameobj->round_current = round_count+1;
if(snapping_client == -1)
{
// we are recording a demo, just set the scores
gameobj->teamscore_red = teamscore[0];
gameobj->teamscore_blue = teamscore[1];
}
else
{
// TODO: this little hack should be removed
gameobj->teamscore_red = is_teamplay() ? teamscore[0] : game.players[snapping_client]->score;
gameobj->teamscore_blue = teamscore[1];
}
}
int GAMECONTROLLER::get_auto_team(int notthisid)
{
// this will force the auto balancer to work overtime aswell
if(config.dbg_stress)
return 0;
int numplayers[2] = {0,0};
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(game.players[i] && i != notthisid)
{
if(game.players[i]->team == 0 || game.players[i]->team == 1)
numplayers[game.players[i]->team]++;
}
}
int team = 0;
if(is_teamplay())
team = numplayers[0] > numplayers[1] ? 1 : 0;
if(can_join_team(team, notthisid))
return team;
return -1;
}
bool GAMECONTROLLER::can_join_team(int team, int notthisid)
{
(void)team;
int numplayers[2] = {0,0};
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(game.players[i] && i != notthisid)
{
if(game.players[i]->team >= 0 || game.players[i]->team == 1)
numplayers[game.players[i]->team]++;
}
}
return (numplayers[0] + numplayers[1]) < config.sv_max_clients-config.sv_spectator_slots;
}
bool GAMECONTROLLER::check_team_balance()
{
if(!is_teamplay() || !config.sv_teambalance_time)
return true;
int t[2] = {0, 0};
for(int i = 0; i < MAX_CLIENTS; i++)
{
PLAYER *p = game.players[i];
if(p && p->team != -1)
t[p->team]++;
}
if(abs(t[0]-t[1]) >= 2)
{
dbg_msg("game", _t("Team is NOT balanced (red=%d blue=%d)"), t[0], t[1]);
if (game.controller->unbalanced_tick == -1)
game.controller->unbalanced_tick = server_tick();
return false;
}
else
{
dbg_msg("game", _t("Team is balanced (red=%d blue=%d)"), t[0], t[1]);
game.controller->unbalanced_tick = -1;
return true;
}
}
bool GAMECONTROLLER::can_change_team(PLAYER *pplayer, int jointeam)
{
int t[2] = {0, 0};
if (!is_teamplay() || jointeam == -1 || !config.sv_teambalance_time)
return true;
for(int i = 0; i < MAX_CLIENTS; i++)
{
PLAYER *p = game.players[i];
if(p && p->team != -1)
t[p->team]++;
}
// simulate what would happen if changed team
t[jointeam]++;
if (pplayer->team != -1)
t[jointeam^1]--;
// there is a player-difference of at least 2
if(abs(t[0]-t[1]) >= 2)
{
// player wants to join team with less players
if ((t[0] < t[1] && jointeam == 0) || (t[0] > t[1] && jointeam == 1))
return true;
else
return false;
}
else
return true;
}
void GAMECONTROLLER::do_player_score_wincheck()
{
if(game_over_tick == -1 && !warmup)
{
// gather some stats
int topscore = 0;
int topscore_count = 0;
for(int i = 0; i < MAX_CLIENTS; i++)
{
if(game.players[i])
{
if(game.players[i]->score > topscore)
{
topscore = game.players[i]->score;
topscore_count = 1;
}
else if(game.players[i]->score == topscore)
topscore_count++;
}
}
// check score win condition
if((config.sv_scorelimit > 0 && topscore >= config.sv_scorelimit) ||
(config.sv_timelimit > 0 && (server_tick()-round_start_tick) >= config.sv_timelimit*server_tickspeed()*60))
{
if(topscore_count == 1)
endround();
else
sudden_death = 1;
}
}
}
void GAMECONTROLLER::do_team_score_wincheck()
{
if(game_over_tick == -1 && !warmup)
{
// check score win condition
if((config.sv_scorelimit > 0 && (teamscore[0] >= config.sv_scorelimit || teamscore[1] >= config.sv_scorelimit)) ||
(config.sv_timelimit > 0 && (server_tick()-round_start_tick) >= config.sv_timelimit*server_tickspeed()*60))
{
if(teamscore[0] != teamscore[1])
endround();
else
sudden_death = 1;
}
}
}
int GAMECONTROLLER::clampteam(int team)
{
if(team < 0) // spectator
return -1;
if(is_teamplay())
return team&1;
return 0;
}
GAMECONTROLLER *gamecontroller = 0;
| [
"Lite@17bf8faa-f2ac-4608-91d1-a55e81355a97"
] | Lite@17bf8faa-f2ac-4608-91d1-a55e81355a97 |
494f1e05261a7b639b36dccd0c3ad63e606f0e19 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5695413893988352_0/C++/Futurizing/B.cpp | aec9331a353d3c8406369f25febb48de52defb0a | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,880 | cpp | #include <cstdio>
#include <cstring>
using namespace std;
char stra[20];
char strb[20];
int len;
int ansA;
int ansB;
int ansDiff;
void calcDiff() {
int numA = 0;
int numB = 0;
int i;
for (i = 0; i < len; i++) {
numA = (numA * 10) + (stra[i] - '0');
numB = (numB * 10) + (strb[i] - '0');
}
int diff = numA - numB;
if (diff < 0) diff = -diff;
if (
ansDiff == -1 ||
diff < ansDiff ||
(diff == ansDiff && numB < ansB) ||
(diff == ansDiff && numB == ansB & numA < ansA)
) {
ansDiff = diff;
ansA = numA;
ansB = numB;
}
}
/*
comp = 0 : equal
comp = -1 : a < b
comp = 1 : a > b
*/
void calc(int pos, int comp) {
if (pos == len) {
calcDiff();
} else {
char oldA = stra[pos];
char oldB = strb[pos];
if (comp == 0) {
if (stra[pos] == '?' && strb[pos] == '?') {
stra[pos] = '0'; strb[pos] = '0';
calc(pos + 1, 0);
stra[pos] = '0'; strb[pos] = '1';
calc(pos + 1, -1);
stra[pos] = '1'; strb[pos] = '0';
calc(pos + 1, 1);
stra[pos] = oldA;
strb[pos] = oldB;
} else if (stra[pos] == '?') {
char base = strb[pos];
stra[pos] = base;
calc(pos + 1, 0);
if (base != '0') {
stra[pos] = base - 1;
calc(pos + 1, -1);
}
if (base != '9') {
stra[pos] = base + 1;
calc(pos + 1, 1);
}
stra[pos] = oldA;
strb[pos] = oldB;
} else if (strb[pos] == '?') {
char base = stra[pos];
strb[pos] = base;
calc(pos + 1, 0);
if (base != '0') {
strb[pos] = base - 1;
calc(pos + 1, 1);
}
if (base != '9') {
strb[pos] = base + 1;
calc(pos + 1, -1);
}
stra[pos] = oldA;
strb[pos] = oldB;
} else {
if (oldA < oldB) {
calc(pos + 1, -1);
} else if (oldA > oldB) {
calc(pos + 1, 1);
} else {
calc(pos + 1, -0);
}
}
} else if (comp == -1) {
if (stra[pos] == '?') stra[pos] = '9';
if (strb[pos] == '?') strb[pos] = '0';
calc(pos + 1, comp);
stra[pos] = oldA;
strb[pos] = oldB;
} else if (comp == 1) {
if (stra[pos] == '?') stra[pos] = '0';
if (strb[pos] == '?') strb[pos] = '9';
calc(pos + 1, comp);
stra[pos] = oldA;
strb[pos] = oldB;
} else {
printf("THROW: WTF\n");
}
}
}
void testcase() {
int i;
scanf("%s %s", stra, strb);
len = strlen(stra);
ansDiff = -1;
calc(0, 0);
char ansAStr[20];
char ansBStr[20];
for (i = 0; i < len; i++) {
ansAStr[len - i - 1] = ansA % 10 + '0';
ansA /= 10;
ansBStr[len - i - 1] = ansB % 10 + '0';
ansB /= 10;
}
ansAStr[len] = ansBStr[len] = '\0';
printf("%s %s\n", ansAStr, ansBStr);
}
int main() {
int t, tc;
scanf("%d", &tc);
for (t = 1; t <= tc; t++) {
printf("Case #%d: ", t);
testcase();
}
return 0;
}
| [
"alexandra1.back@gmail.com"
] | alexandra1.back@gmail.com |
2ed4b8521993a12c012d48d232fa81e45021bd17 | d29c7e070ab7353eed35b712ee363ed962b9b1fc | /Source/CanonicalCode.cpp | 1733a495348406533c3180d60de78506bd6753e3 | [
"MIT"
] | permissive | Andres6936/Huffman.Coding | ca8aea2975376e60868f2129c3b8a90dae875c38 | 2fe1ab1dbdf06b489dfd380cf2415054a8456cb5 | refs/heads/master | 2022-11-09T00:10:16.268592 | 2020-06-26T21:48:57 | 2020-06-26T21:48:57 | 275,159,894 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,109 | cpp | /*
* Reference Huffman coding
* Copyright (c) Project Nayuki
*
* https://www.nayuki.io/page/reference-huffman-coding
* https://github.com/nayuki/Reference-Huffman-coding
*/
#include <algorithm>
#include <cstddef>
#include <stdexcept>
#include <utility>
#include "Huffman/Coding/CanonicalCode.hpp"
using std::uint32_t;
using std::vector;
CanonicalCode::CanonicalCode(const vector<uint32_t>& codeLens)
{
// Check basic validity
if (codeLens.size() < 2)
throw std::invalid_argument("At least 2 symbols needed");
if (codeLens.size() > UINT32_MAX)
throw std::length_error("Too many symbols");
// Copy once and check for tree validity
codeLengths = codeLens;
std::sort(codeLengths.begin(), codeLengths.end(), std::greater<uint32_t>());
uint32_t currentLevel = codeLengths.front();
uint32_t numNodesAtLevel = 0;
for (uint32_t cl : codeLengths)
{
if (cl == 0)
break;
while (cl < currentLevel)
{
if (numNodesAtLevel % 2 != 0)
throw std::invalid_argument("Under-full Huffman code tree");
numNodesAtLevel /= 2;
currentLevel--;
}
numNodesAtLevel++;
}
while (currentLevel > 0)
{
if (numNodesAtLevel % 2 != 0)
throw std::invalid_argument("Under-full Huffman code tree");
numNodesAtLevel /= 2;
currentLevel--;
}
if (numNodesAtLevel < 1)
throw std::invalid_argument("Under-full Huffman code tree");
if (numNodesAtLevel > 1)
throw std::invalid_argument("Over-full Huffman code tree");
// Copy again
codeLengths = codeLens;
}
CanonicalCode::CanonicalCode(const CodeTree& tree, uint32_t symbolLimit)
{
if (symbolLimit < 2)
throw std::invalid_argument("At least 2 symbols needed");
codeLengths = vector<uint32_t>(symbolLimit, 0);
buildCodeLengths(&tree.root, 0);
}
void CanonicalCode::buildCodeLengths(const Node* node, uint32_t depth)
{
if (dynamic_cast<const InternalNode*>(node) != nullptr)
{
const InternalNode* internalNode = dynamic_cast<const InternalNode*>(node);
buildCodeLengths(internalNode->leftChild.get(), depth + 1);
buildCodeLengths(internalNode->rightChild.get(), depth + 1);
}
else if (dynamic_cast<const Leaf*>(node) != nullptr)
{
uint32_t symbol = dynamic_cast<const Leaf*>(node)->symbol;
if (symbol >= codeLengths.size())
throw std::invalid_argument("Symbol exceeds symbol limit");
// Note: CodeTree already has a checked constraint that disallows a symbol in multiple leaves
if (codeLengths.at(symbol) != 0)
throw std::logic_error("Assertion error: Symbol has more than one code");
codeLengths.at(symbol) = depth;
}
else
{
throw std::logic_error("Assertion error: Illegal node type");
}
}
uint32_t CanonicalCode::getSymbolLimit() const
{
return static_cast<uint32_t>(codeLengths.size());
}
uint32_t CanonicalCode::getCodeLength(uint32_t symbol) const
{
if (symbol >= codeLengths.size())
throw std::domain_error("Symbol out of range");
return codeLengths.at(symbol);
}
CodeTree CanonicalCode::toCodeTree() const
{
vector<std::unique_ptr<Node> > nodes;
for (uint32_t i = *std::max_element(codeLengths.cbegin(), codeLengths.cend());; i--)
{ // Descend through code lengths
if (nodes.size() % 2 != 0)
throw std::logic_error("Assertion error: Violation of canonical code invariants");
vector<std::unique_ptr<Node> > newNodes;
// Add leaves for symbols with positive code length i
if (i > 0)
{
uint32_t j = 0;
for (uint32_t cl : codeLengths)
{
if (cl == i)
newNodes.push_back(std::unique_ptr<Node>(new Leaf(j)));
j++;
}
}
// Merge pairs of nodes from the previous deeper layer
for (std::size_t j = 0; j < nodes.size(); j += 2)
{
newNodes.push_back(std::unique_ptr<Node>(new InternalNode(
std::move(nodes.at(j)), std::move(nodes.at(j + 1)))));
}
nodes = std::move(newNodes);
if (i == 0)
break;
}
if (nodes.size() != 1)
throw std::logic_error("Assertion error: Violation of canonical code invariants");
Node* temp = nodes.front().release();
InternalNode* root = dynamic_cast<InternalNode*>(temp);
CodeTree result(std::move(*root), static_cast<uint32_t>(codeLengths.size()));
delete root;
return result;
}
| [
"andres6936@live.com"
] | andres6936@live.com |
e88870f6a86de1bdca226f3484576873afc67139 | bfa7e61cc3e4dbc353e4d0b972442c91bb5ed053 | /src/net.cpp | e06599e280cb86eba1d77d832a73453522c52220 | [
"MIT"
] | permissive | paulorig/pyrocoin | cf546bee91736a3eb12b4a6a897cf7d13cfb125f | 08d9333e2c2316c858d2fda5414c5f701ba776f4 | refs/heads/master | 2021-01-25T14:09:39.306081 | 2018-03-03T04:04:16 | 2018-03-03T04:04:16 | 123,656,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 62,267 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "strlcpy.h"
#include "addrman.h"
#include "ui_interface.h"
#ifdef WIN32
#include <string.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniwget.h>
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 16;
void ThreadMessageHandler2(void* parg);
void ThreadSocketHandler2(void* parg);
void ThreadOpenConnections2(void* parg);
void ThreadOpenAddedConnections2(void* parg);
#ifdef USE_UPNP
void ThreadMapPort2(void* parg);
#endif
void ThreadDNSAddressSeed2(void* parg);
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
struct LocalServiceInfo {
int nScore;
int nPort;
};
//
// Global state variables
//
bool fDiscover = true;
bool fUseUPnP = false;
uint64_t nLocalServices = NODE_NETWORK;
static CCriticalSection cs_mapLocalHost;
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
CAddress addrSeenByPeer(CService("0.0.0.0", 0), nLocalServices);
uint64_t nLocalHostNonce = 0;
boost::array<int, THREAD_MAX> vnThreadsRunning;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64_t, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
map<CInv, int64_t> mapAlreadyAskedFor;
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
static CSemaphore *semOutbound = NULL;
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", GetDefaultPort()));
}
void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
{
// Filter out duplicate requests
if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
return;
pindexLastGetBlocksBegin = pindexBegin;
hashLastGetBlocksEnd = hashEnd;
PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
{
if (fNoListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
{
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
{
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
{
CAddress ret(CService("0.0.0.0",0),0);
CService addr;
if (GetLocal(addr, paddrPeer))
{
ret = CAddress(addr);
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
}
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
while (true)
{
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0)
{
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
}
else if (nBytes <= 0)
{
if (fShutdown)
return false;
if (nBytes < 0)
{
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
{
MilliSleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0)
{
// socket closed
printf("socket closed\n");
return false;
}
else
{
// socket error
int nErr = WSAGetLastError();
printf("recv failed: %d\n", nErr);
return false;
}
}
}
}
// used when scores of local addresses may have changed
// pushes better local address to peers
void static AdvertizeLocal()
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->fSuccessfullyConnected)
{
CAddress addrLocal = GetLocalAddress(&pnode->addr);
if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
{
pnode->PushAddress(addrLocal);
pnode->addrLocal = addrLocal;
}
}
}
}
void SetReachable(enum Network net, bool fFlag)
{
LOCK(cs_mapLocalHost);
vfReachable[net] = fFlag;
if (net == NET_IPV6 && fFlag)
vfReachable[NET_IPV4] = true;
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo &info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0);
info.nPort = addr.GetPort();
}
SetReachable(addr.GetNetwork());
}
AdvertizeLocal();
return true;
}
bool AddLocal(const CNetAddr &addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr &addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
AdvertizeLocal();
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
LOCK(cs_mapLocalHost);
enum Network net = addr.GetNetwork();
return vfReachable[net] && !vfLimited[net];
}
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
string strLine;
while (RecvLine(hSocket, strLine))
{
if (strLine.empty()) // HTTP response is separated from headers by blank line
{
while (true)
{
if (!RecvLine(hSocket, strLine))
{
closesocket(hSocket);
return false;
}
if (pszKeyword == NULL)
break;
if (strLine.find(pszKeyword) != string::npos)
{
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
break;
}
}
closesocket(hSocket);
if (strLine.find("<") != string::npos)
strLine = strLine.substr(0, strLine.find("<"));
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
strLine.resize(strLine.size()-1);
CService addr(strLine,0,true);
printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
if (!addr.IsValid() || !addr.IsRoutable())
return false;
ipRet.SetIP(addr);
return true;
}
}
closesocket(hSocket);
return error("GetMyExternalIP() : connection closed");
}
// We now get our external IP from the IRC server first and only use this as a backup
bool GetMyExternalIP(CNetAddr& ipRet)
{
CService addrConnect;
const char* pszGet;
const char* pszKeyword;
for (int nLookup = 0; nLookup <= 1; nLookup++)
for (int nHost = 1; nHost <= 2; nHost++)
{
// We should be phasing out our use of sites like these. If we need
// replacements, we should ask for volunteers to put this simple
// php file on their web server that prints the client IP:
// <?php echo $_SERVER["REMOTE_ADDR"]; ?>
if (nHost == 1)
{
addrConnect = CService("216.146.43.70",80); // checkip.dyndns.org
if (nLookup == 1)
{
CService addrIP("checkip.dyndns.org", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET / HTTP/1.1\r\n"
"Host: checkip.dyndns.org\r\n"
"User-Agent: PyroCoin\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = "Address:";
}
else if (nHost == 2)
{
addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
if (nLookup == 1)
{
CService addrIP("www.showmyip.com", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET /simple/ HTTP/1.1\r\n"
"Host: www.showmyip.com\r\n"
"User-Agent: PyroCoin\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = NULL; // Returns just IP address
}
if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
return true;
}
return false;
}
void ThreadGetMyExternalIP(void* parg)
{
// Make this thread recognisable as the external IP detection thread
RenameThread("pyrocoin-ext-ip");
CNetAddr addrLocalHost;
if (GetMyExternalIP(addrLocalHost))
{
printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
AddLocal(addrLocalHost, LOCAL_HTTP);
}
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
CNode* FindNode(const CNetAddr& ip)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
}
return NULL;
}
CNode* FindNode(std::string addrName)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CService)pnode->addr == addr)
return (pnode);
}
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
{
if (pszDest == NULL) {
if (IsLocal(addrConnect))
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
pnode->AddRef();
return pnode;
}
}
/// debug print
printf("trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString().c_str(),
pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
// Connect
SOCKET hSocket;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
{
addrman.Attempt(addrConnect);
/// debug print
printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
// Set to non-blocking
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
#else
if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
#endif
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
return pnode;
}
else
{
return NULL;
}
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET)
{
printf("disconnecting node %s\n", addrName.c_str());
closesocket(hSocket);
hSocket = INVALID_SOCKET;
// in case this fails, we'll empty the recv buffer when the CNode is deleted
TRY_LOCK(cs_vRecvMsg, lockRecv);
if (lockRecv)
vRecvMsg.clear();
}
}
void CNode::PushVersion()
{
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
}
std::map<CNetAddr, int64_t> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned()
{
setBanned.clear();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip);
if (i != setBanned.end())
{
int64_t t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Misbehaving(int howmuch)
{
if (addr.IsLocal())
{
printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
return false;
}
nMisbehavior += howmuch;
if (nMisbehavior >= GetArg("-banscore", 100))
{
int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
CloseSocketDisconnect();
return true;
} else
printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
return false;
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats &stats)
{
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(strSubVer);
X(fInbound);
X(nStartingHeight);
X(nMisbehavior);
}
#undef X
// requires LOCK(cs_vRecvMsg)
bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes)
{
while (nBytes > 0) {
// get current incomplete message, or create a new one
if (vRecvMsg.empty() ||
vRecvMsg.back().complete())
vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
CNetMessage& msg = vRecvMsg.back();
// absorb network data
int handled;
if (!msg.in_data)
handled = msg.readHeader(pch, nBytes);
else
handled = msg.readData(pch, nBytes);
if (handled < 0)
return false;
pch += handled;
nBytes -= handled;
}
return true;
}
int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
{
// copy data to temporary parsing buffer
unsigned int nRemaining = 24 - nHdrPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&hdrbuf[nHdrPos], pch, nCopy);
nHdrPos += nCopy;
// if header incomplete, exit
if (nHdrPos < 24)
return nCopy;
// deserialize to CMessageHeader
try {
hdrbuf >> hdr;
}
catch (std::exception &e) {
return -1;
}
// reject messages larger than MAX_SIZE
if (hdr.nMessageSize > MAX_SIZE)
return -1;
// switch state to reading message data
in_data = true;
return nCopy;
}
int CNetMessage::readData(const char *pch, unsigned int nBytes)
{
unsigned int nRemaining = hdr.nMessageSize - nDataPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
if (vRecv.size() < nDataPos + nCopy) {
// Allocate up to 256 KiB ahead, but never more than the total message size.
vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
}
memcpy(&vRecv[nDataPos], pch, nCopy);
nDataPos += nCopy;
return nCopy;
}
// requires LOCK(cs_vSend)
void SocketSendData(CNode *pnode)
{
std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
while (it != pnode->vSendMsg.end()) {
const CSerializeData &data = *it;
assert(data.size() > pnode->nSendOffset);
int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0) {
pnode->nLastSend = GetTime();
pnode->nSendOffset += nBytes;
if (pnode->nSendOffset == data.size()) {
pnode->nSendOffset = 0;
pnode->nSendSize -= data.size();
it++;
} else {
// could not send full message; stop sending more
break;
}
} else {
if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
printf("socket send error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
// couldn't send anything at all
break;
}
}
if (it == pnode->vSendMsg.end()) {
assert(pnode->nSendOffset == 0);
assert(pnode->nSendSize == 0);
}
pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
}
void ThreadSocketHandler(void* parg)
{
// Make this thread recognisable as the networking thread
RenameThread("pyrocoin-net");
try
{
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
ThreadSocketHandler2(parg);
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
PrintException(&e, "ThreadSocketHandler()");
} catch (...) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
throw; // support pthread_cancel()
}
printf("ThreadSocketHandler exited\n");
}
void ThreadSocketHandler2(void* parg)
{
printf("ThreadSocketHandler started\n");
list<CNode*> vNodesDisconnected;
unsigned int nPrevNodeCount = 0;
while (true)
{
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty()))
{
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
// hold in disconnected pool until all refs are released
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0)
{
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
TRY_LOCK(pnode->cs_mapRequests, lockReq);
if (lockReq)
{
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
}
if (fDelete)
{
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if (vNodes.size() != nPrevNodeCount)
{
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(vNodes.size());
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
bool have_fds = false;
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
have_fds = true;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->hSocket == INVALID_SOCKET)
continue;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend) {
// do not read, if draining write queue
if (!pnode->vSendMsg.empty())
FD_SET(pnode->hSocket, &fdsetSend);
else
FD_SET(pnode->hSocket, &fdsetRecv);
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
have_fds = true;
}
}
}
}
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
int nSelect = select(have_fds ? hSocketMax + 1 : 0,
&fdsetRecv, &fdsetSend, &fdsetError, &timeout);
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
if (fShutdown)
return;
if (nSelect == SOCKET_ERROR)
{
if (have_fds)
{
int nErr = WSAGetLastError();
printf("socket select error %d\n", nErr);
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
MilliSleep(timeout.tv_usec/1000);
}
//
// Accept new connections
//
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
{
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
printf("Warning: Unknown socket family\n");
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET)
{
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
printf("socket error accept failed: %d\n", nErr);
}
else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
{
closesocket(hSocket);
}
else if (CNode::IsBanned(addr))
{
printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
closesocket(hSocket);
}
else
{
printf("accepted connection %s\n", addr.ToString().c_str());
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (fShutdown)
return;
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
if (pnode->GetTotalRecvSize() > ReceiveFloodSize()) {
if (!pnode->fDisconnect)
printf("socket recv flood control disconnect (%u bytes)\n", pnode->GetTotalRecvSize());
pnode->CloseSocketDisconnect();
}
else {
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0)
{
if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
pnode->CloseSocketDisconnect();
pnode->nLastRecv = GetTime();
}
else if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect)
printf("socket closed\n");
pnode->CloseSocketDisconnect();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
printf("socket recv error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend))
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SocketSendData(pnode);
}
//
// Inactivity checking
//
if (pnode->vSendMsg.empty())
pnode->nLastSendEmpty = GetTime();
if (GetTime() - pnode->nTimeConnected > 60)
{
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
{
printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
{
printf("socket not sending\n");
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastRecv > 90*60)
{
printf("socket inactivity timeout\n");
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
MilliSleep(10);
}
}
#ifdef USE_UPNP
void ThreadMapPort(void* parg)
{
// Make this thread recognisable as the UPnP thread
RenameThread("pyrocoin-UPnP");
try
{
vnThreadsRunning[THREAD_UPNP]++;
ThreadMapPort2(parg);
vnThreadsRunning[THREAD_UPNP]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_UPNP]--;
PrintException(&e, "ThreadMapPort()");
} catch (...) {
vnThreadsRunning[THREAD_UPNP]--;
PrintException(NULL, "ThreadMapPort()");
}
printf("ThreadMapPort exited\n");
}
void ThreadMapPort2(void* parg)
{
printf("ThreadMapPort started\n");
std::string port = strprintf("%u", GetListenPort());
const char * multicastif = 0;
const char * minissdpdpath = 0;
struct UPNPDev * devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#else
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1)
{
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if(r != UPNPCOMMAND_SUCCESS)
printf("UPnP: GetExternalIPAddress() returned %d\n", r);
else
{
if(externalIPAddress[0])
{
printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
}
else
printf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "PyroCoin " + FormatFullVersion();
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
else
printf("UPnP Port Mapping successful.\n");
int i = 1;
while (true)
{
if (fShutdown || !fUseUPnP)
{
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
printf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist); devlist = 0;
FreeUPNPUrls(&urls);
return;
}
if (i % 600 == 0) // Refresh every 20 minutes
{
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
else
printf("UPnP Port Mapping successful.\n");;
}
MilliSleep(2000);
i++;
}
} else {
printf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist); devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
while (true)
{
if (fShutdown || !fUseUPnP)
return;
MilliSleep(2000);
}
}
}
void MapPort()
{
if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1)
{
if (!NewThread(ThreadMapPort, NULL))
printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
}
}
#else
void MapPort()
{
// Intentionally left blank.
}
#endif
// DNS seeds
// Each pair gives a source name and a seed name.
// The first name is used as information source for addrman.
// The second name should resolve to a list of seed addresses.
static const char *strDNSSeed[][2] = {
{"seed1.pyrocoin.org", "seed1.pyrocoin.org"},
{"seed2.pyrocoin.org", "seed2.pyrocoin.org"}
};
void ThreadDNSAddressSeed(void* parg)
{
// Make this thread recognisable as the DNS seeding thread
RenameThread("pyrocoin-dnsseed");
try
{
vnThreadsRunning[THREAD_DNSSEED]++;
ThreadDNSAddressSeed2(parg);
vnThreadsRunning[THREAD_DNSSEED]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_DNSSEED]--;
PrintException(&e, "ThreadDNSAddressSeed()");
} catch (...) {
vnThreadsRunning[THREAD_DNSSEED]--;
throw; // support pthread_cancel()
}
printf("ThreadDNSAddressSeed exited\n");
}
void ThreadDNSAddressSeed2(void* parg)
{
printf("ThreadDNSAddressSeed started\n");
int found = 0;
if (!fTestNet)
{
printf("Loading addresses from DNS seeds (could take a while)\n");
for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
if (HaveNameProxy()) {
AddOneShot(strDNSSeed[seed_idx][1]);
} else {
vector<CNetAddr> vaddr;
vector<CAddress> vAdd;
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
{
BOOST_FOREACH(CNetAddr& ip, vaddr)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
}
}
}
printf("%d addresses found from DNS seeds\n", found);
}
unsigned int pnSeed[] =
{
};
void DumpAddresses()
{
int64_t nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
printf("Flushed %d addresses to peers.dat %"PRId64"ms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void ThreadDumpAddress2(void* parg)
{
vnThreadsRunning[THREAD_DUMPADDRESS]++;
while (!fShutdown)
{
DumpAddresses();
vnThreadsRunning[THREAD_DUMPADDRESS]--;
MilliSleep(600000);
vnThreadsRunning[THREAD_DUMPADDRESS]++;
}
vnThreadsRunning[THREAD_DUMPADDRESS]--;
}
void ThreadDumpAddress(void* parg)
{
// Make this thread recognisable as the address dumping thread
RenameThread("pyrocoin-adrdump");
try
{
ThreadDumpAddress2(parg);
}
catch (std::exception& e) {
PrintException(&e, "ThreadDumpAddress()");
}
printf("ThreadDumpAddress exited\n");
}
void ThreadOpenConnections(void* parg)
{
// Make this thread recognisable as the connection opening thread
RenameThread("pyrocoin-opencon");
try
{
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
ThreadOpenConnections2(parg);
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(&e, "ThreadOpenConnections()");
} catch (...) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(NULL, "ThreadOpenConnections()");
}
printf("ThreadOpenConnections exited\n");
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void static ThreadStakeMiner(void* parg)
{
printf("ThreadStakeMiner started\n");
CWallet* pwallet = (CWallet*)parg;
try
{
vnThreadsRunning[THREAD_STAKE_MINER]++;
StakeMiner(pwallet);
vnThreadsRunning[THREAD_STAKE_MINER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_STAKE_MINER]--;
PrintException(&e, "ThreadStakeMiner()");
} catch (...) {
vnThreadsRunning[THREAD_STAKE_MINER]--;
PrintException(NULL, "ThreadStakeMiner()");
}
printf("ThreadStakeMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_STAKE_MINER]);
}
void ThreadOpenConnections2(void* parg)
{
printf("ThreadOpenConnections started\n");
// Connect to specific addresses
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
{
for (int64_t nLoop = 0;; nLoop++)
{
ProcessOneShot();
BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
{
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++)
{
MilliSleep(500);
if (fShutdown)
return;
}
}
MilliSleep(500);
}
}
// Initiate network connections
int64_t nStart = GetTime();
while (true)
{
ProcessOneShot();
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
MilliSleep(500);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CSemaphoreGrant grant(*semOutbound);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
// Add seed nodes if IRC isn't working
if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
{
std::vector<CAddress> vAdd;
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vAdd.push_back(addr);
}
addrman.Add(vAdd, CNetAddr("127.0.0.1"));
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64_t nANow = GetAdjustedTime();
int nTries = 0;
while (true)
{
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
// If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
// stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
// already-connected network ranges, ...) before trying new addrman addresses.
nTries++;
if (nTries > 100)
break;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections(void* parg)
{
// Make this thread recognisable as the connection opening thread
RenameThread("pyrocoin-opencon");
try
{
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
ThreadOpenAddedConnections2(parg);
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(&e, "ThreadOpenAddedConnections()");
} catch (...) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(NULL, "ThreadOpenAddedConnections()");
}
printf("ThreadOpenAddedConnections exited\n");
}
void ThreadOpenAddedConnections2(void* parg)
{
printf("ThreadOpenAddedConnections started\n");
if (mapArgs.count("-addnode") == 0)
return;
if (HaveNameProxy()) {
while(!fShutdown) {
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
MilliSleep(500);
}
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
MilliSleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
}
return;
}
vector<vector<CService> > vservAddressesToAdd(0);
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
{
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
{
vservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH(CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
while (true)
{
vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
BOOST_FOREACH(CService& addrNode, *(it))
if (pnode->addr == addrNode)
{
it = vservConnectAddresses.erase(it);
it--;
break;
}
}
BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
{
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
MilliSleep(500);
if (fShutdown)
return;
}
if (fShutdown)
return;
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
MilliSleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
if (fShutdown)
return;
}
}
// if successful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
if (fShutdown)
return false;
if (!strDest)
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort().c_str()))
return false;
if (strDest && FindNode(strDest))
return false;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CNode* pnode = ConnectNode(addrConnect, strDest);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return false;
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
void ThreadMessageHandler(void* parg)
{
// Make this thread recognisable as the message handling thread
RenameThread("pyrocoin-msghand");
try
{
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
ThreadMessageHandler2(parg);
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(&e, "ThreadMessageHandler()");
} catch (...) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(NULL, "ThreadMessageHandler()");
}
printf("ThreadMessageHandler exited\n");
}
void ThreadMessageHandler2(void* parg)
{
printf("ThreadMessageHandler started\n");
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (!fShutdown)
{
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect)
continue;
// Receive messages
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
if (!ProcessMessages(pnode))
pnode->CloseSocketDisconnect();
}
if (fShutdown)
return;
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SendMessages(pnode, pnode == pnodeTrickle);
}
if (fShutdown)
return;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
// Wait and allow messages to bunch up.
// Reduce vnThreadsRunning so StopNode has permission to exit while
// we're sleeping, but we must always check fShutdown after doing this.
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
MilliSleep(100);
if (fRequestShutdown)
StartShutdown();
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
if (fShutdown)
return;
}
}
bool BindListenPort(const CService &addrBind, string& strError)
{
strError = "";
int nOne = 1;
#ifdef WIN32
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR)
{
strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
printf("%s\n", strError.c_str());
return false;
}
#endif
// Create socket for listening for incoming connections
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
printf("%s\n", strError.c_str());
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
#ifndef WIN32
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows.
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
// Set to non-blocking, incoming connections will also inherit this
if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
#else
if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
#ifdef WIN32
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
#else
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#endif
#ifdef WIN32
int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
// this call is allowed to fail
setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
#endif
}
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. PyroCoin is probably already running."), addrBind.ToString().c_str());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
printf("%s\n", strError.c_str());
return false;
}
printf("Bound to %s\n", addrBind.ToString().c_str());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
vhListenSocket.push_back(hListenSocket);
if (addrBind.IsRoutable() && fDiscover)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover()
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[1000] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr))
{
BOOST_FOREACH (const CNetAddr &addr, vaddr)
{
AddLocal(addr, LOCAL_IF);
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0)
{
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
}
freeifaddrs(myaddrs);
}
#endif
// Don't use external IPv4 discovery, when -onlynet="IPv6"
if (!IsLimited(NET_IPV4))
NewThread(ThreadGetMyExternalIP, NULL);
}
void StartNode(void* parg)
{
// Make this thread recognisable as the startup thread
RenameThread("pyrocoin-start");
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover();
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
printf("DNS seeding disabled\n");
else
if (!NewThread(ThreadDNSAddressSeed, NULL))
printf("Error: NewThread(ThreadDNSAddressSeed) failed\n");
// Map ports with UPnP
if (fUseUPnP)
MapPort();
// Get addresses from IRC and advertise ours
if (!NewThread(ThreadIRCSeed, NULL))
printf("Error: NewThread(ThreadIRCSeed) failed\n");
// Send and receive from sockets, accept connections
if (!NewThread(ThreadSocketHandler, NULL))
printf("Error: NewThread(ThreadSocketHandler) failed\n");
// Initiate outbound connections from -addnode
if (!NewThread(ThreadOpenAddedConnections, NULL))
printf("Error: NewThread(ThreadOpenAddedConnections) failed\n");
// Initiate outbound connections
if (!NewThread(ThreadOpenConnections, NULL))
printf("Error: NewThread(ThreadOpenConnections) failed\n");
// Process messages
if (!NewThread(ThreadMessageHandler, NULL))
printf("Error: NewThread(ThreadMessageHandler) failed\n");
// Dump network addresses
if (!NewThread(ThreadDumpAddress, NULL))
printf("Error; NewThread(ThreadDumpAddress) failed\n");
// Mine proof-of-stake blocks in the background
if (!GetBoolArg("-staking", true))
printf("Staking disabled\n");
else
if (!NewThread(ThreadStakeMiner, pwalletMain))
printf("Error: NewThread(ThreadStakeMiner) failed\n");
}
bool StopNode()
{
printf("StopNode()\n");
fShutdown = true;
nTransactionsUpdated++;
int64_t nStart = GetTime();
if (semOutbound)
for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
do
{
int nThreadsRunning = 0;
for (int n = 0; n < THREAD_MAX; n++)
nThreadsRunning += vnThreadsRunning[n];
if (nThreadsRunning == 0)
break;
if (GetTime() - nStart > 20)
break;
MilliSleep(20);
} while(true);
if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
#ifdef USE_UPNP
if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
#endif
if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
if (vnThreadsRunning[THREAD_STAKE_MINER] > 0) printf("ThreadStakeMiner still running\n");
while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0)
MilliSleep(20);
MilliSleep(50);
DumpAddresses();
return true;
}
class CNetCleanup
{
public:
CNetCleanup()
{
}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
closesocket(pnode->hSocket);
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET)
if (closesocket(hListenSocket) == SOCKET_ERROR)
printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
}
instance_of_cnetcleanup;
void RelayTransaction(const CTransaction& tx, const uint256& hash)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(10000);
ss << tx;
RelayTransaction(tx, hash, ss);
}
void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
{
CInv inv(MSG_TX, hash);
{
LOCK(cs_mapRelay);
// Expire old relay messages
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
{
mapRelay.erase(vRelayExpiration.front().second);
vRelayExpiration.pop_front();
}
// Save original serialized message so newer versions are preserved
mapRelay.insert(std::make_pair(inv, ss));
vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
}
RelayInventory(inv);
}
| [
"git@paulo.im"
] | git@paulo.im |
76b447396d34215c4bd5bd4f0a8227225048d900 | 45e1b8c5455283decddac77c92cdb2566c4f673f | /verilog/tools/formatter/verilog_format.cc | bfdc2cb7ba270e77b159583eecde3bb94df51502 | [
"Apache-2.0"
] | permissive | niszet/verible | 556a47b45b49b8c998b8c5bf63d85ace8d99bfb5 | 8177dd80cff4ba2ae884451e6c5316edb2b4dbe7 | refs/heads/master | 2022-05-31T21:42:43.551775 | 2020-04-28T21:46:41 | 2020-04-28T21:48:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,533 | cc | // Copyright 2017-2020 The Verible Authors.
//
// 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.
// verilog_format is a command-line utility to format verilog source code
// for a given file.
//
// Example usage:
// verilog_format original-file > new-file
//
// Exit code:
// 0: stdout output can be used to replace original file
// nonzero: stdout output (if any) should be discarded
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream> // IWYU pragma: keep // for ostringstream
#include <string> // for string, allocator, etc
#include <vector>
#include "absl/flags/flag.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "common/util/file_util.h"
#include "common/util/init_command_line.h"
#include "common/util/interval_set.h"
#include "common/util/logging.h" // for operator<<, LOG, LogMessage, etc
#include "verilog/formatting/format_style.h"
#include "verilog/formatting/formatter.h"
using absl::StatusCode;
using verilog::formatter::ExecutionControl;
using verilog::formatter::FormatStyle;
using verilog::formatter::FormatVerilog;
// Pseudo-singleton, so that repeated flag occurrences accumulate values.
// --flag x --flag y yields [x, y]
struct LineRanges {
// need to copy string, cannot just use string_view
typedef std::vector<std::string> storage_type;
static storage_type values;
};
LineRanges::storage_type LineRanges::values; // global initializer
bool AbslParseFlag(absl::string_view flag_arg, LineRanges* /* unused */,
std::string* error) {
auto& values = LineRanges::values;
// Pre-split strings, so that "--flag v1,v2" and "--flag v1 --flag v2" are
// equivalent.
const std::vector<absl::string_view> tokens = absl::StrSplit(flag_arg, ',');
values.reserve(values.size() + tokens.size());
for (const auto& token : tokens) {
// need to copy string, cannot just use string_view
values.push_back(std::string(token.begin(), token.end()));
}
// Range validation done later.
return true;
}
std::string AbslUnparseFlag(LineRanges /* unused */) {
const auto& values = LineRanges::values;
return absl::StrJoin(values.begin(), values.end(), ",",
absl::StreamFormatter());
}
// TODO(fangism): Provide -i alias, as it is canonical to many formatters
ABSL_FLAG(bool, inplace, false,
"If true, overwrite the input file on successful conditions.");
ABSL_FLAG(std::string, stdin_name, "<stdin>",
"When using '-' to read from stdin, this gives an alternate name for "
"diagnostic purposes. Otherwise this is ignored.");
ABSL_FLAG(LineRanges, lines, {},
"Specific lines to format, 1-based, comma-separated, inclusive N-M "
"ranges, N is short for N-N. By default, left unspecified, "
"all lines are enabled for formatting. (repeatable, cumulative)");
ABSL_FLAG(bool, failsafe_success, true,
"If true, always exit with 0 status, even if there were input errors "
"or internal errors. In all error conditions, the original text is "
"always preserved. This is useful in deploying services where "
"fail-safe behaviors should be considered a success.");
ABSL_FLAG(int, show_largest_token_partitions, 0,
"If > 0, print token partitioning and then "
"exit without formatting output.");
ABSL_FLAG(bool, show_token_partition_tree, false,
"If true, print diagnostics after token partitioning and then "
"exit without formatting output.");
ABSL_FLAG(bool, show_inter_token_info, false,
"If true, along with show_token_partition_tree, include inter-token "
"information such as spacing and break penalties.");
ABSL_FLAG(bool, show_equally_optimal_wrappings, false,
"If true, print when multiple optimal solutions are found (stderr), "
"but continue to operate normally.");
ABSL_FLAG(int, max_search_states, 100000,
"Limits the number of search states explored during "
"line wrap optimization.");
// These flags exist in the short term to disable formatting of some regions.
ABSL_FLAG(bool, format_module_port_declarations, false,
// TODO(b/70310743): format module port declarations in aligned manner
"If true, format module declarations' list of port declarations, "
"else leave them unformatted. This is a short-term workaround.");
ABSL_FLAG(bool, format_module_instantiations, false,
// TODO(b/152805837): format module instances' ports in aligned manner
"If true, format module instantiations (data declarations), "
"else leave them unformatted. This is a short-term workaround.");
int main(int argc, char** argv) {
const auto usage = absl::StrCat("usage: ", argv[0],
" [options] <file>\n"
"To pipe from stdin, use '-' as <file>.");
const auto file_args = verible::InitCommandLine(usage, &argc, &argv);
// Currently accepts only one file positional argument.
// TODO(fangism): Support multiple file names.
QCHECK_GT(file_args.size(), 1)
<< "Missing required positional argument (filename).";
const absl::string_view filename = file_args[1];
const bool inplace = absl::GetFlag(FLAGS_inplace);
const bool is_stdin = filename == "-";
const auto& stdin_name = absl::GetFlag(FLAGS_stdin_name);
if (inplace && is_stdin) {
std::cerr << "--inplace is incompatible with stdin. Ignoring --inplace "
"and writing to stdout."
<< std::endl;
}
absl::string_view diagnostic_filename = filename;
if (is_stdin) {
diagnostic_filename = stdin_name;
}
// Parse LineRanges into a line set, to validate the --lines flag(s)
verilog::formatter::LineNumberSet lines_to_format;
if (!verible::ParseInclusiveRanges(
&lines_to_format, LineRanges::values.begin(),
LineRanges::values.end(), &std::cerr, '-')) {
std::cerr << "Error parsing --lines." << std::endl;
std::cerr << "Got: --lines=" << AbslUnparseFlag(LineRanges()) << std::endl;
return 1;
}
// Read contents into memory first.
std::string content;
if (!verible::file::GetContents(filename, &content)) return 1;
// TODO(fangism): When requesting --inplace, verify that file
// is write-able, and fail-early if it is not.
// TODO(fangism): support style configuration from flags.
FormatStyle format_style;
// Handle special debugging modes.
ExecutionControl formatter_control;
{
// execution control flags
formatter_control.stream = &std::cout; // for diagnostics only
formatter_control.show_largest_token_partitions =
absl::GetFlag(FLAGS_show_largest_token_partitions);
formatter_control.show_token_partition_tree =
absl::GetFlag(FLAGS_show_token_partition_tree);
formatter_control.show_inter_token_info =
absl::GetFlag(FLAGS_show_inter_token_info);
formatter_control.show_equally_optimal_wrappings =
absl::GetFlag(FLAGS_show_equally_optimal_wrappings);
formatter_control.max_search_states =
absl::GetFlag(FLAGS_max_search_states);
// formatting style flags
format_style.format_module_port_declarations =
absl::GetFlag(FLAGS_format_module_port_declarations);
format_style.format_module_instantiations =
absl::GetFlag(FLAGS_format_module_instantiations);
}
std::ostringstream stream;
const auto format_status =
FormatVerilog(content, diagnostic_filename, format_style, stream,
lines_to_format, formatter_control);
const std::string& formatted_output(stream.str());
if (!format_status.ok()) {
if (!inplace) {
// Fall back to printing original content regardless of error condition.
std::cout << content;
}
// Print the error message last so it shows up in user's console.
std::cerr << format_status.message() << std::endl;
switch (format_status.code()) {
case StatusCode::kCancelled:
case StatusCode::kInvalidArgument:
break;
case StatusCode::kDataLoss:
std::cerr << "Problematic formatter output is:\n"
<< formatted_output << "<<EOF>>" << std::endl;
break;
default:
std::cerr << "[other error status]" << std::endl;
break;
}
if (absl::GetFlag(FLAGS_failsafe_success)) {
// original text was preserved, and --inplace modification is skipped.
return 0;
}
return 1;
}
// Safe to write out result, having passed above verification.
if (inplace && !is_stdin) {
if (!verible::file::SetContents(filename, formatted_output)) {
std::cerr << "Error writing to file: " << filename << std::endl;
std::cerr << "Printing to stdout instead." << std::endl;
std::cout << formatted_output;
return 1;
}
} else {
std::cout << formatted_output;
}
return 0;
}
| [
"h.zeller@acm.org"
] | h.zeller@acm.org |
d285c53cac212a6e928e2f58b835369deddc6faa | 399de70b61317b86b34fbedace07bb3f3545fdc7 | /diagonaldiff.cpp | c5cd8c583a87f0e4a8e79b163759e13030d849fa | [] | no_license | mhdSharuk/foss-hackerank | b5ec70ff62f94970e11e6685eabb15c7abf73d34 | 12bc436e175381e347bba3896611b27f7186d33b | refs/heads/master | 2020-04-03T05:10:59.317074 | 2018-10-28T05:11:32 | 2018-10-28T05:11:32 | 155,037,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 431 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
long int a[1000][1000],i,j,k=0,p=0,n;
cin>>n;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
cin>>a[i][j];
}
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(i==j){
k=k+a[i][j];
}
if((i+j)==n-1)
{
p=p+a[i][j];
}
}
}
int w;
w=k-p;
cout<<abs(w);
}
| [
"noreply@github.com"
] | noreply@github.com |
1272f73aed598815288b75fcccb6de2b718fb334 | 452c4ea6adac131bf84a33110a7f37f8ad8d1abb | /source/octf/utils/Exception.cpp | bfd49d0ae7212023f170ea4e00a12305fc71e51c | [
"BSD-3-Clause-Clear"
] | permissive | tomaszrybicki/open-cas-telemetry-framework | 1bae628be1424750fafbe9627cf2a5a38787c9a6 | f654c8db92a3deaaef1779a24b44ab7ef8f61634 | refs/heads/master | 2020-04-30T01:48:05.861632 | 2019-05-30T08:40:51 | 2019-05-30T08:40:51 | 176,539,684 | 0 | 0 | null | 2019-03-19T15:13:36 | 2019-03-19T15:13:35 | null | UTF-8 | C++ | false | false | 417 | cpp | /*
* Copyright(c) 2012-2018 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause-Clear
*/
#include "Exception.h"
#include <system_error>
namespace octf {
Exception::Exception(const std::string &message)
: m_message(message) {}
const char *Exception::what() const noexcept {
return m_message.c_str();
}
const std::string &Exception::getMessage() {
return m_message;
}
} // namespace octf
| [
"mariusz.barczak@intel.com"
] | mariusz.barczak@intel.com |
25ee410e902a56b94cc750f8eee902f309046b78 | 5248f5cbdf14b7010679f5835ccd89f23736a522 | /lua/luacocos/Cocos2dxLuaLoader.cpp | 255bbb216326f81528bed69497160f4702787218 | [] | no_license | misschuer/arpgSourceNew | 55a4a3f1fe2fb0458c9fb2207c19838897e4a748 | 798e72b5681a368686628ab8a1ddeecb4d73fcd7 | refs/heads/master | 2021-05-16T07:16:27.319377 | 2018-01-31T04:41:52 | 2018-01-31T04:41:52 | 103,722,226 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,554 | cpp | /****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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 "Cocos2dxLuaLoader.h"
#include <string>
#include <algorithm>
#include "CCLuaStack.h"
#ifdef WIN32
#include <io.h>
#else
#include <unistd.h>
#include <fcntl.h>
#endif // WIN32
#include <stdio.h>
#include <zlib/zlib.h>
#include <assert.h>
struct unzip_tool
{
unzip_tool()
{
uncompress_size_ = 256;
buff_ = malloc(uncompress_size_);
zlib_stream_ = (struct z_stream_s *)malloc(sizeof(struct z_stream_s));
zlib_stream_->zalloc = (alloc_func)0;
zlib_stream_->zfree = (free_func)0;
zlib_stream_->opaque = (voidpf)0;
//速度取Z_BEST_SPEED到Z_BEST_COMPRESSION之间(1到9)
//Z_DEFAULT_COMPRESSION压缩率与速度的平衡(相当于6)
int z_res = deflateInit(zlib_stream_, Z_DEFAULT_COMPRESSION);
assert(z_res == Z_OK);
}
~unzip_tool()
{
if(zlib_stream_){
deflateEnd(zlib_stream_);
free(zlib_stream_);
zlib_stream_ = NULL;
}
if(buff_){
free(buff_);
buff_ = NULL;
}
}
int unCompress(const char* inputf,int len,char **out)
{
int err = 0;
uLongf unc_size = 0;
Bytef *ptr = (Bytef*)malloc(uncompress_size_);
//从压缩包中取得解压后在大小,如果返回包的大小不一致,则取大的为准
do
{
//扩展空间
unc_size = uncompress_size_;
err = uncompress(ptr, &unc_size, (Bytef *)inputf, len);
if(err != Z_OK)
{
if(err == Z_BUF_ERROR){
uncompress_size_ <<= 1;
ptr = (Bytef*)realloc(ptr,uncompress_size_);
}else {
free(ptr);
return -1;
}
}
}while(err != Z_OK);
*out = (char*)ptr;
return unc_size;
}
struct z_stream_s *zlib_stream_; //zlib压缩流
void *buff_;
int uncompress_size_;
};
extern "C"
{
static int read_file(const char* inputf,char **out)
{
char *p = NULL;
int total = 0;
char temp[8096];
FILE *f = fopen(inputf, "rb");
if(!f) {
printf("open file:%s failed!",inputf);
return -1;
}
p = (char*)malloc(1);
while(!feof(f)){
int n = fread(temp,1,sizeof(temp),f);
total += n;
p = (char*)realloc(p,total + 1);
memcpy(p + total - n,temp, n);
}
fclose(f);
*out = p;
return total;
}
int cocos2dx_lua_loader(lua_State *L)
{
static const std::string BYTECODE_FILE_EXT = ".luac";
static const std::string NOT_BYTECODE_FILE_EXT = ".lua";
static const std::string LUA_ZIP_EXT = ".luaz";
std::string filename(luaL_checkstring(L, 1));
size_t pos = filename.rfind(NOT_BYTECODE_FILE_EXT);
if (pos != std::string::npos)
{
filename = filename.substr(0, pos);
}
pos = filename.find_first_of(".");
while (pos != std::string::npos)
{
filename.replace(pos, 1, "/");
pos = filename.find_first_of(".");
}
// search file in package.path
unsigned char* chunk = nullptr;
uint32_t chunkSize = 0;
std::string chunkName;
lua_getglobal(L, "package");
lua_getfield(L, -1, "path");
std::string searchpath(lua_tostring(L, -1));
lua_pop(L, 1);
size_t begin = 0;
size_t next = searchpath.find_first_of(";", 0);
do
{
if (next == std::string::npos)
next = searchpath.length();
std::string prefix = searchpath.substr(begin, next);
if (prefix[0] == '.' && prefix[1] == '/')
{
prefix = prefix.substr(2);
}
pos = prefix.find("?.lua");
chunkName = prefix.substr(0, pos) + filename + BYTECODE_FILE_EXT;
if (access(chunkName.c_str(), 4/*"rb"*/) == 0)
{
chunkSize = read_file(chunkName.c_str(),(char**)&chunk);
break;
}
else
{
chunkName = prefix.substr(0, pos) + filename + NOT_BYTECODE_FILE_EXT;
if (access(chunkName.c_str(), 4/*"rb"*/) == 0)
{
chunkSize = read_file(chunkName.c_str(),(char**)&chunk);
break;
}
else
{
chunkName = prefix.substr(0, pos) + filename + LUA_ZIP_EXT;
if (access(chunkName.c_str(), 4/*"rb"*/) == 0)
{
char *file_content = NULL;
int content_len = 0;
//先把文件内容读出来
content_len = read_file(chunkName.c_str(),(char**)&file_content);
//调用zip解压缩
static unzip_tool _unzip_tool;
chunkSize = _unzip_tool.unCompress(file_content,content_len,(char**)&chunk);
if(file_content)
{
free(file_content);
file_content = 0;
}
break;
}
}
}
begin = next + 1;
next = searchpath.find_first_of(";", begin);
} while (begin < (int)searchpath.length());
if (chunk)
{
LuaStack* stack = LuaStack::getInstance(L);
stack->luaLoadBuffer(L, (char*)chunk, (int)chunkSize, chunkName.c_str());
free(chunk);
}
else
{
printf("can not get file data of %s\n", chunkName.c_str());
return 0;
}
return 1;
}
}
| [
"arpg@Center.(none)"
] | arpg@Center.(none) |
4b84e9446e6a2db7e108e5cca4a52a240ec5f7cc | 41c7836da77c95250949d908f3e6235597b40e6b | /Old experimental/test_folder/Pizza_parlor_00/data/OrderRepo.cpp | 99577b9c2161ee365d61f110651a5837eb2291a8 | [] | no_license | brynjarorng/TeamEagle | 22aa24d1e30dcce5acb41dcec7afd2eaab92ebf9 | d13d40349718d838fa0fb861205b957452b07ff4 | refs/heads/master | 2021-08-30T03:53:51.876127 | 2017-12-15T23:18:41 | 2017-12-15T23:18:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,374 | cpp | #include "OrderRepo.h"
#include <cstdlib>
OrderRepo::OrderRepo() {
//list = new Order[0];
}
OrderRepo::~OrderRepo() {
//delete[] list;
}
void OrderRepo::current_write(Order order) {
ofstream fout("current_orders.dat", ios::binary|ios::app);
fout.write((char*)(&order), sizeof(Order));
fout.close();
}
void OrderRepo::overwrite_list(Order* order, int list_count) {
ofstream fout("current_orders.dat", ios::binary);
fout.seekp(ios::beg);
fout.write((char*)(order), sizeof(Order)*list_count);
fout.close();
}
//Order* OrderRepo::archived_read() {
//read(archived);
//return list;
//}
Order* OrderRepo::current_read() {
read();
return list;
}
void OrderRepo::read() {
this ->current_list_count = get_current_count();
ifstream fin("current_orders.dat", ios::binary);
if (fin.is_open()) {
this ->list = new Order[current_list_count];
fin.read((char*)(this ->list), sizeof(Order)*current_list_count);
fin.close();
}
}
int OrderRepo::get_current_count() const{
int record_count;
ifstream fin("current_orders.dat", ios::binary);
if (fin.is_open()) {
fin.seekg(0, fin.end);
record_count = fin.tellg() / sizeof(Order);
fin.seekg(0, fin.beg);
fin.close();
}
else {
record_count = 0;
}
return record_count;
}
int OrderRepo::get_archived_count() const {
return this-> archived_list_count;
}
| [
"viktorsveins@gmail.com"
] | viktorsveins@gmail.com |
9d4184ac64af04667b69b3bd52791c8f9bf4517d | c0f0941e3d6f62dbe6932da3d428ae2afed53b43 | /offline/packages/NodeDump/DumpTpcSeedTrackMap.h | dde202c7f1f257cb48cb4f273751315df43a15a6 | [] | no_license | sPHENIX-Collaboration/coresoftware | ffbb1bd5c107f45c1b3574996aba6693169281ea | 19748d09d1997dfc21522e8e3816246691f46512 | refs/heads/master | 2023-08-03T15:55:20.018519 | 2023-08-01T23:33:03 | 2023-08-01T23:33:03 | 34,742,432 | 39 | 208 | null | 2023-09-14T20:25:46 | 2015-04-28T16:29:55 | C++ | UTF-8 | C++ | false | false | 362 | h | #ifndef NODEDUMP_DUMPTPCSEEDTRACKMAP_H
#define NODEDUMP_DUMPTPCSEEDTRACKMAP_H
#include "DumpObject.h"
#include <string>
class PHNode;
class DumpTpcSeedTrackMap : public DumpObject
{
public:
explicit DumpTpcSeedTrackMap(const std::string &NodeName);
~DumpTpcSeedTrackMap() override {}
protected:
int process_Node(PHNode *mynode) override;
};
#endif
| [
"pinkenburg@bnl.gov"
] | pinkenburg@bnl.gov |
f22c77c8d2088b1323ce5ec7e2922c6c5ba2251c | 560e2f789865953fabd58d20d5d6bc4015b8201f | /Obsolete/TerrainRenderer.h | 60678c99d7799aab19df40d59dfdb65ccbcb4591 | [
"MIT"
] | permissive | Tymec/OpenGL-Game | 0d54e0c74c57a7db473e9c509462ffd454e1028e | ecfb11acdbba2fc74ceb1166da17b143d51ffe2a | refs/heads/master | 2021-07-22T00:26:02.105910 | 2020-05-04T01:04:53 | 2020-05-04T01:04:53 | 154,524,717 | 0 | 1 | MIT | 2019-02-19T16:36:49 | 2018-10-24T15:27:30 | C | UTF-8 | C++ | false | false | 581 | h | #pragma once
#include "TerrainShader.h"
#include "Terrain.h"
#include "TerrainTexturePack.h"
#include <iostream>
#include <list>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
class TerrainRenderer
{
public:
TerrainRenderer(TerrainShader* shader);
void render(std::list<Terrain*> terrains);
private:
TerrainShader* shader;
void prepareTerrain(Terrain* terrain);
void unbindTexturedModel();
glm::mat4 createModelMatrix(Terrain* terrain);
void loadModelMatrix(glm::mat4 modelMatrix);
void bindTextures(Terrain* terrain);
};
| [
"tymek1rt@hotmail.com"
] | tymek1rt@hotmail.com |
9d5fbafb407e8fb205f27b5ce893441070de0a52 | 6f874ccb136d411c8ec7f4faf806a108ffc76837 | /code/VCSamples/VC2008Samples/MFC/ole/oleview/iviewers/tlbodl.cpp | 6fb7650111097a90a9b0fd83ebdc98ff6e38089f | [
"MIT"
] | permissive | JetAr/ZDoc | c0f97a8ad8fd1f6a40e687b886f6c25bb89b6435 | e81a3adc354ec33345e9a3303f381dcb1b02c19d | refs/heads/master | 2022-07-26T23:06:12.021611 | 2021-07-11T13:45:57 | 2021-07-11T13:45:57 | 33,112,803 | 8 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 64,696 | cpp | // tlbodl.cpp : implementation file
//
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "iviewers.h"
#include "iview.h"
#include "util.h"
#include "iviewers.h"
#include "iviewer.h"
#include "typelib.h"
#include "tree.h"
#include "tlbodl.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
#define MAX_NAMES 64 // max parameters to a function
IStream* CreateMemoryStream();
int StringFromGUID2T(REFGUID rguid, LPTSTR lpszGUID, int nSize, int cbMax);
// if defined, when typedefs are written out a tag is created
// by concatinating "tag" with the typedef name.
#define _WRITE_TAG 1
/////////////////////////////////////////////////////////////////////////////
// CTypeLibODLView
IMPLEMENT_DYNCREATE(CTypeLibODLView, CEditView)
CTypeLibODLView::CTypeLibODLView()
{
}
CTypeLibODLView::~CTypeLibODLView()
{
}
BEGIN_MESSAGE_MAP(CTypeLibODLView, CEditView)
//{{AFX_MSG_MAP(CTypeLibODLView)
ON_WM_DESTROY()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTypeLibODLView drawing
void CTypeLibODLView::OnDraw(CDC* pDC)
{
}
/////////////////////////////////////////////////////////////////////////////
// CTypeLibODLView diagnostics
#ifdef _DEBUG
void CTypeLibODLView::AssertValid() const
{
CEditView::AssertValid();
}
void CTypeLibODLView::Dump(CDumpContext& dc) const
{
CEditView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CTypeLibODLView message handlers
BOOL CTypeLibODLView::PreCreateWindow(CREATESTRUCT& cs)
{
cs.style |= ES_READONLY | ES_MULTILINE | WS_VSCROLL | WS_HSCROLL ;
return CEditView::PreCreateWindow(cs);
}
void CTypeLibODLView::OnInitialUpdate()
{
m_Font.CreateFont( -11, 0, 0, 0, 0, 0,
0, 0, ANSI_CHARSET, 0, 0, 0,
FIXED_PITCH | FF_DONTCARE, _T("Courier New") ) ;
SetFont( &m_Font );
CEditView::OnInitialUpdate();
}
void CTypeLibODLView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint)
{
CTypeLibWnd* pFrame = (CTypeLibWnd*)GetParent()->GetParent() ;
ASSERT(pFrame->IsKindOf(RUNTIME_CLASS(CTypeLibWnd)));
if (pFrame->m_pSelectedItem == NULL)
{
SetWindowText(_T("")) ;
return ;
}
SetRedraw( FALSE ) ;
BeginWaitCursor() ;
CString sText;
HRESULT hr = S_OK ;
IStream* pstm = NULL ;
TRY
{
pstm = CreateMemoryStream() ;
switch(pFrame->m_pSelectedItem->m_Type)
{
case CTreeItem::typeTypeLib:
case CTreeItem::typeTypeLib2:
hr = DeCompileTypeLib( pstm, pFrame->m_pSelectedItem->GetTypeLib() ) ;
break ;
case CTreeItem::typeEnum:
case CTreeItem::typeRecord:
case CTreeItem::typeModule:
case CTreeItem::typeInterface:
case CTreeItem::typeDispinterface:
case CTreeItem::typeCoClass:
case CTreeItem::typeAlias:
case CTreeItem::typeUnion:
case CTreeItem::typeTypeInfo:
case CTreeItem::typeTypeInfo2:
switch(pFrame->m_pSelectedItem->GetTypeKind())
{
case TKIND_ENUM:
case TKIND_RECORD:
case TKIND_UNION:
case TKIND_ALIAS:
hr = DeCompileTypedef( pstm, pFrame->m_pSelectedItem->GetTypeInfo() ) ;
break ;
case TKIND_MODULE:
hr = DeCompileModule( pstm, pFrame->m_pSelectedItem->GetTypeInfo() ) ;
break ;
case TKIND_INTERFACE:
hr = DeCompileInterface( pstm, pFrame->m_pSelectedItem->GetTypeInfo() ) ;
break ;
case TKIND_DISPATCH:
hr = DeCompileDispinterface( pstm, pFrame->m_pSelectedItem->GetTypeInfo() ) ;
break ;
case TKIND_COCLASS:
hr = DeCompileCoClass( pstm, pFrame->m_pSelectedItem->GetTypeInfo() ) ;
break ;
default:
sText = _T("<<unclassified typeinfo>>");
break ;
}
break ;
case CTreeItem::typeMethod:
hr = DeCompileFunc( pstm, pFrame->m_pSelectedItem->GetTypeInfo(), pFrame->m_pSelectedItem->m_uiMemid ) ;
break ;
case CTreeItem::typeProperty:
hr = DeCompileVar( pstm, pFrame->m_pSelectedItem->GetTypeInfo(), pFrame->m_pSelectedItem->m_uiMemid ) ;
break ;
case CTreeItem::typeConstant:
hr = DeCompileConst( pstm, pFrame->m_pSelectedItem->GetTypeInfo(), pFrame->m_pSelectedItem->m_uiMemid ) ;
break ;
case CTreeItem::typeUnknown:
case CTreeItem::typeUnknown2:
case CTreeItem::typeEnums:
case CTreeItem::typeRecords:
case CTreeItem::typeModules:
case CTreeItem::typeInterfaces:
case CTreeItem::typeDispinterfaces:
case CTreeItem::typeCoClasses:
case CTreeItem::typeAliases:
case CTreeItem::typeUnions:
case CTreeItem::typeMethods:
case CTreeItem::typeMethods2:
case CTreeItem::typeProperties:
case CTreeItem::typeProperties2:
case CTreeItem::typeConstants:
case CTreeItem::typeConstants2:
case CTreeItem::typeImplTypes:
case CTreeItem::typeImplTypes2:
default:
//bstr = ::SysAllocString(OLESTR(""));
break ;
}
if (hr != S_OK)
AfxThrowOleException( hr ) ;
if (pstm)
{
STATSTG statstg ;
if (FAILED(hr = pstm->Stat( &statstg,STATFLAG_NONAME )))
AfxThrowOleException( hr ) ;
// Seek to beginning
LARGE_INTEGER li ;
LISet32( li, 0 ) ;
if (FAILED(hr = pstm->Seek( li, STREAM_SEEK_SET, NULL )))
AfxThrowOleException( hr ) ;
// Read into string
LPSTR lpszBuf = sText.GetBuffer(statstg.cbSize.LowPart+1);
if (FAILED(hr = pstm->Read( lpszBuf, statstg.cbSize.LowPart, NULL )))
AfxThrowOleException( hr ) ;
lpszBuf[statstg.cbSize.LowPart] = '\0';
sText.ReleaseBuffer();
SetWindowText(sText);
pstm->Release() ;
}
}
CATCH(CException, pException)
{
SetWindowText( _T("// Could not decompile selected item") ) ;
if (pstm)
pstm->Release() ;
if (pException->IsKindOf(RUNTIME_CLASS(COleException)))
hr = ((COleException*)pException)->m_sc ;
else if (pException->IsKindOf(RUNTIME_CLASS(COleException)))
hr = E_OUTOFMEMORY ;
if (hr == S_OK)
hr = GetLastError() ;
ErrorMessage( "Could not decompile selected item", hr ) ;
}
END_CATCH
SetRedraw( TRUE ) ;
EndWaitCursor() ;
SendMessage(EM_SETSEL, 0, 0) ;
}
void CTypeLibODLView::OnDestroy()
{
CEditView::OnDestroy();
m_Font.DeleteObject() ;
}
// Write string s with no indent and no CR
#define WRITE( s ) WriteLine( pstm, s, 0, FALSE )
// Write string s with indent and no CR
#define WRITE1( s ) WriteLine( pstm, s, uiIndent, FALSE )
#define WRITE2( s, ui ) WriteLine( pstm, s, uiIndent+ui, FALSE )
// Write string s with indent and CR
#define WRITELINE( s ) WriteLine( pstm, s, uiIndent, TRUE )
#define WRITELINE2( s, ui ) WriteLine( pstm, s, uiIndent+ui, TRUE )
#define WRITECR( s ) WriteLine( pstm, s, 0, TRUE )
#define WRITERAW( p, len ) WriteRaw( pstm, p, len )
#define WRITEBSTR( p ) WriteBSTR( pstm, p )
inline void WriteRaw( IStream* pstm, const void* pv, UINT cb )
{
HRESULT hr ;
if (FAILED(hr = pstm->Write( pv, cb, NULL )))
AfxThrowOleException( hr ) ;
}
inline void WriteLine( IStream* pstm, const CString &rstr, UINT uiIndent, BOOL fNewLine )
{
while(uiIndent--)
{
WriteRaw( pstm, _T(" "), 4 * sizeof(TCHAR));
}
WriteRaw( pstm, rstr, rstr.GetLength() * sizeof(TCHAR)) ;
if (fNewLine)
WriteRaw(pstm, _T("\r\n"), 2 * sizeof(TCHAR)) ;
}
inline void WriteBSTR( IStream* pstm, BSTR bstr )
{
UINT len = ::SysStringLen(bstr) ;
if (!len)
return ;
COLE2T lpszSource(bstr);
TCHAR *pstrTemp = new TCHAR[((len + 1) * sizeof(TCHAR)) * 2];
LPTSTR lpD, lpS = lpszSource ;
lpD = pstrTemp;
for (UINT n = 0 ; n < len ; n++)
{
#pragma warning (suppress: 6328) // unexpected type mismatch warning
if (!isprint(*lpS) || (*lpS) == '\"' || (*lpS) == '\\')
{
// \" \\ \a \b \f \n \r \t \v
*lpD++ = '\\' ;
switch(*lpS)
{
case '\"':
*lpD++ = '\"' ;
break ;
case '\\':
*lpD++ = '\\' ;
break ;
case '\a':
*lpD++ = 'a' ;
break ;
case '\b':
*lpD++ = 'b' ;
break ;
case '\f':
*lpD++ = 'f' ;
break ;
case '\n':
*lpD++ = 'n' ;
break ;
case '\r':
*lpD++ = 'r' ;
break ;
case '\t':
*lpD++ = 't' ;
break ;
case '\v':
*lpD++ = 'v' ;
break ;
case '\0':
*lpD++ = '0' ;
break ;
default:
lpD += _stprintf_s( lpD, ((len + 1) * sizeof(TCHAR)) * 2, _T("x%02X"), (UINT)*lpS );
break ;
}
lpS++;
}
else
*lpD++ = *lpS++;
}
*lpD = '\0';
#pragma warning(suppress: 6387) // pstrTemp will always be null terminated.
WriteRaw( pstm, pstrTemp, lstrlen(pstrTemp)*sizeof(TCHAR) ) ;
delete []pstrTemp ;
}
// // typelib.tlb
// [
// uuid(<00026b00-0000-0000-C000-000000000046>),
// version (<major>.<minor>),
// helpfile ("<helpfile.hlp>"),
// helpstring("<helpstring>"),
// helpcontext(<helpcontext>)
// ]
// library <libname>
// {
// importlib("<import.tlb>");
//
// };
HRESULT CTypeLibODLView::DeCompileTypeLib( IStream* pstm, ITypeLib* ptlb, UINT uiIndent /* = 0 */ )
{
HRESULT hr = S_OK ;
BSTR bstrName = NULL ;
BSTR bstrDoc = NULL ;
BSTR bstrHelp = NULL ;
DWORD dwHelpID ;
TLIBATTR* plibattr = NULL ;
ITypeInfo* pti = NULL ;
TYPEATTR* pattr = NULL ;
ASSERT(ptlb) ;
TRY
{
TCHAR szGUID[64] ;
CString str;
ENSURE(ptlb);
hr = ptlb->GetLibAttr(&plibattr);
if (FAILED(hr))
AfxThrowOleException( hr ) ;
// write header with library filename
WRITELINE(_T("// Generated .ODL file (by Ole2View)"));
WRITELINE(_T("// "));
WRITE1(_T("// typelib filename: "));
hr = ::QueryPathOfRegTypeLib(plibattr->guid, plibattr->wMajorVerNum, plibattr->wMinorVerNum, plibattr->lcid, &bstrName);
if (SUCCEEDED(hr))
{
COLE2CT lpszName(bstrName);
::SysFreeString(bstrName);
bstrName = NULL;
LPCTSTR p = _tcsrchr(lpszName, '\\');
if (p != NULL && *p && *(p+1))
WRITECR( p+1 ) ;
else
WRITECR( (LPCTSTR)lpszName ) ;
}
else
{
// It's possible we're viewing a type lib that was never registered
WRITECR( _T("<could not determine filename>") ) ;
}
WRITELINE( _T("[") ) ;
StringFromGUID2T( plibattr->guid, szGUID, 64, sizeof(szGUID) );
WRITE1(_T(" uuid(")) ;
WRITE(szGUID);
WRITECR(_T("),")) ;
str.Format( _T(" version(%d.%d)"), plibattr->wMajorVerNum, plibattr->wMinorVerNum ) ;
WRITE1(str) ;
hr = ptlb->GetDocumentation( MEMBERID_NIL, &bstrName, &bstrDoc, &dwHelpID, &bstrHelp );
if (FAILED(hr))
AfxThrowOleException( hr ) ;
if (bstrDoc && *bstrDoc)
{
WRITECR(_T(",")) ;
WRITE1(_T(" helpstring(\"")) ;
WRITEBSTR( bstrDoc ) ;
WRITE(_T("\")")) ;
}
if (bstrHelp && *bstrHelp)
{
WRITECR(",") ;
COLE2CT lpszHelp(bstrHelp);
::SysFreeString(bstrHelp);
bstrHelp = NULL;
LPCTSTR p = _tcsrchr(lpszHelp, '\\');
if (p != NULL && *p && *(p+1))
str.Format( _T(" helpfile(\"%s\"),"), p+1 ) ;
else
str.Format( _T(" helpfile(\"%s\"),"), lpszHelp ) ;
WRITELINE( str ) ;
str.Format( _T(" helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE1( str ) ;
}
WRITECR(_T("")) ;
WRITELINE(_T("]") ) ;
WRITE1( _T("library ") ) ;
WRITEBSTR(bstrName) ;
WRITECR(_T("")) ;
WRITELINE( _T("(") ) ;
// TODO: Grovel through all typeinfos for any referenced types
// that are defined in imported libs
//uiInfos = ptlb->GetTypeInfoCount() ;
//for (UINT n = 0 ; n < uiInfos ; n++)
//{
//}
WRITELINE(_T("// BUGBUG: There most likely were \"importlib()\" statements in"));
WRITELINE(_T("// in the source. While it appears possible to be able"));
WRITELINE(_T("// to identify them, it is non-trivial and is currently"));
WRITELINE(_T("// not supported."));
WRITELINE(_T("// "));
UINT uiInfos = ptlb->GetTypeInfoCount() ;
for (UINT n = 0 ; n < uiInfos ; n++)
{
if (FAILED(hr = ptlb->GetTypeInfo( n, &pti )))
AfxThrowOleException(hr) ;
if (FAILED(hr = pti->GetTypeAttr( &pattr )))
AfxThrowOleException(hr) ;
switch(pattr->typekind)
{
case TKIND_ENUM:
case TKIND_RECORD:
case TKIND_UNION:
case TKIND_ALIAS:
hr = DeCompileTypedef( pstm, pti, uiIndent + 1 ) ;
break ;
case TKIND_MODULE:
hr = DeCompileModule( pstm, pti, uiIndent + 1 ) ;
break ;
case TKIND_INTERFACE:
hr = DeCompileInterface( pstm, pti, uiIndent + 1 ) ;
break ;
case TKIND_DISPATCH:
hr = DeCompileDispinterface( pstm, pti, uiIndent + 1 ) ;
break ;
case TKIND_COCLASS:
hr = DeCompileCoClass( pstm, pti, uiIndent + 1 ) ;
break ;
}
if (n != uiInfos - 1)
WRITECR(_T("")) ;
pti->ReleaseTypeAttr( pattr ) ;
pti->Release() ;
pti = NULL ;
pattr = NULL ;
}
// Last line of the .ODL file
WRITELINE( ");" ) ;
SysFreeString( bstrName ) ;
bstrName = NULL ;
SysFreeString( bstrDoc ) ;
bstrDoc = NULL ;
SysFreeString( bstrHelp ) ;
bstrHelp = NULL ;
if (plibattr)
ptlb->ReleaseTLibAttr( plibattr ) ;
}
CATCH(CException, pException)
{
if (pti)
{
if (pattr)
pti->ReleaseTypeAttr( pattr ) ;
pti->Release() ;
}
if (plibattr)
ptlb->ReleaseTLibAttr( plibattr ) ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
THROW_LAST() ;
}
END_CATCH
return hr ;
}
// if typekind == TKIND_ALIAS
// typedef [attributes] basetype aliasname;
//
// if typekind == TKIND_ENUM
// typedef [attributes] enum [tag] {
// enumlist
// } enumname;
// enumlist is made up of members of the form
// name = value,
// or "= value" can be ommitted
//
// if typekind == TKIND_UNION or TKIND_RECORD
// typedef [attributes] union/struct [tag] {
// memberlist
// } union/structname;
//
// attributes can be
// [uuid(<00026b00-0000-0000-C000-000000000046>), version (<major>.<minor>),
// helpstring("<helpstring>"), helpcontext(<id), hidden, restricted,
// public]
//
// memberlist is made up of members of the form
// type name[bounds];
//
HRESULT CTypeLibODLView::DeCompileTypedef( IStream* pstm, ITypeInfo* pti, UINT uiIndent /* = 0 */ )
{
HRESULT hr = S_OK ;
TYPEATTR* pattr = NULL ;
BSTR bstrName = NULL ;
BSTR bstrDoc = NULL ;
BSTR bstrHelp = NULL ;
DWORD dwHelpID ;
WRITE1("typedef ") ;
TRY
{
if (FAILED(hr = pti->GetTypeAttr( &pattr)))
AfxThrowOleException( hr ) ;
BOOL fAttributes = FALSE ; // any attributes?
BOOL fAttribute = FALSE ; // at least one (insert ",")
// Was 'uuid' specified?
if (!IsEqualGUID( pattr->guid, GUID_NULL ))
{
TCHAR szGUID[64] ;
StringFromGUID2T( pattr->guid, szGUID, 64, sizeof(szGUID) ) ;
fAttributes = TRUE ;
WRITE("[uuid(") ;
WRITE(szGUID) ;
WRITE(")") ;
fAttribute = TRUE ;
}
// was version specified
if (pattr->wMajorVerNum || pattr->wMinorVerNum)
{
if (fAttributes == FALSE)
WRITE("[") ;
fAttributes = TRUE ;
if (fAttribute)
WRITE(", ") ;
CString str ;
str.Format(_T("version(%d.%d)"), pattr->wMajorVerNum, pattr->wMinorVerNum) ;
WRITE(str) ;
fAttribute = TRUE ;
}
if (SUCCEEDED(pti->GetDocumentation( MEMBERID_NIL, &bstrName, &bstrDoc, &dwHelpID, &bstrHelp )))
{
CString str ;
if (bstrDoc && *bstrDoc)
{
if (fAttributes == FALSE) WRITE("[") ;
fAttributes = TRUE ;
if (fAttribute)
WRITE(", ") ;
COLE2CT lpszDoc(bstrDoc);
::SysFreeString(bstrDoc);
bstrDoc = NULL;
str.Format( _T("helpstring(\"%s\")"), lpszDoc );
WRITE( str ) ;
if (dwHelpID > 0)
{
str.Format( _T(", helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE( str ) ;
}
}
else if (dwHelpID > 0)
{
if (fAttributes == FALSE) WRITE("[") ;
fAttributes = TRUE ;
if (fAttribute)
WRITE(", ") ;
str.Format( _T("helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE( str ) ;
fAttribute = TRUE ;
}
}
if (pattr->typekind == TKIND_ALIAS)
{
if (fAttributes == FALSE) WRITE("[") ;
fAttributes = TRUE ;
if (fAttribute)
WRITE(", ") ;
WRITE("public") ; // if it's in the tlb it had public
}
if (fAttributes)
WRITE("] ") ;
switch(pattr->typekind)
{
case TKIND_RECORD:
#ifdef _WRITE_TAG
WRITE("struct tag") ;
WRITEBSTR(bstrName) ;
#else
WRITE("struct ") ;
#endif
WRITECR(" {" );
break ;
case TKIND_UNION:
#ifdef _WRITE_TAG
WRITE("union tag") ;
WRITEBSTR(bstrName) ;
#else
WRITE("union ") ;
#endif
WRITECR(" {" );
break ;
case TKIND_ALIAS: //typedef
// write base type
WRITE(TYPEDESCtoString( pti, &pattr->tdescAlias )) ;
WRITE(" ") ;
// write aliasname
break ;
case TKIND_ENUM:
WRITECR("enum {" );
break ;
default:
ASSERT(0) ;
break ;
}
if (pattr->typekind == TKIND_RECORD || pattr->typekind == TKIND_UNION)
{
for (UINT n = 0 ; n < pattr->cVars ; n++)
DumpVar( pstm, pti, pattr, n, uiIndent + 1 ) ;
WRITE1("} ");
}
if (pattr->typekind == TKIND_ENUM)
{
for (int n = 0 ; n < pattr->cVars ; n++)
{
DumpConst( pstm, pti, pattr, n, uiIndent + 1, FALSE ) ;
if (n < pattr->cVars-1)
WRITECR(",") ;
else
WRITECR("") ;
}
WRITE1("} ");
}
WRITEBSTR(bstrName) ;
WRITECR(";") ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
pti->ReleaseTypeAttr( pattr ) ;
}
CATCH(CException, pException)
{
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
if (pattr)
pti->ReleaseTypeAttr( pattr ) ;
THROW_LAST();
}
END_CATCH
return hr ;
}
// [
// attributes
// ]
// module modulename {
// elementlist
// };
// attributes are
// uuid, version, helpstring, helpcontext, dllname
// The dllname attribute is required.
//
// [attributes] returntype [calling convention] funcname(params);
// [attributes] const constname = constval;
//
HRESULT CTypeLibODLView::DeCompileModule( IStream* pstm, ITypeInfo* pti, UINT uiIndent /* = 0 */ )
{
HRESULT hr = S_OK ;
TYPEATTR* pattr = NULL ;
BSTR bstrName = NULL ;
BSTR bstrDoc = NULL ;
BSTR bstrHelp = NULL ;
DWORD dwHelpID ;
TRY
{
if (FAILED(hr = pti->GetTypeAttr( &pattr)))
AfxThrowOleException( hr ) ;
WRITELINE(_T("// BUGBUG: There appears to be no way to retrieve the dllname of"));
WRITELINE(_T("// a module via ITypeInfo in a reliable way. "));
WRITELINE(_T("// ITypeInfo::GetDllEntry offers a possibility, but it will"));
WRITELINE(_T("// only work if the module has entries in it."));
WRITELINE(_T("// "));
WRITELINE(_T("[")) ;
WRITE1( _T(" dllname(")) ;
/*
if (FAILED(hr = pti->GetDllEntry(MEMBERID_NIL, INVOKE_FUNC, &bstrName, NULL, NULL)))
AfxThrowOleException( hr ) ;
WRITEBSTR(bstrName) ;
SysFreeString(bstrName) ;
bstrName = NULL ;
*/
WRITE(_T(")")) ;
// Was 'uuid' specified?
if (!IsEqualGUID( pattr->guid, GUID_NULL ))
{
TCHAR szGUID[64] ;
StringFromGUID2T( pattr->guid, szGUID, 64, sizeof(szGUID) ) ;
WRITECR(",") ;
WRITE1(" uuid(") ;
WRITE(szGUID) ;
WRITE(")") ;
}
// was version specified
if (pattr->wMajorVerNum || pattr->wMinorVerNum)
{
WRITECR(",") ;
CString str ;
str.Format(_T(" version(%d.%d)"), pattr->wMajorVerNum, pattr->wMinorVerNum) ;
WRITE1(str) ;
}
if (SUCCEEDED(pti->GetDocumentation( MEMBERID_NIL, &bstrName, &bstrDoc, &dwHelpID, &bstrHelp )))
{
CString str ;
if (bstrDoc && *bstrDoc)
{
WRITECR(",") ;
COLE2CT lpszDoc(bstrDoc);
::SysFreeString(bstrDoc);
bstrDoc = NULL;
str.Format( _T(" helpstring(\"%s\")"), lpszDoc ) ;
WRITE1( str ) ;
if (dwHelpID > 0)
{
WRITECR(",") ;
str.Format( _T(" helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE1( str ) ;
}
}
else if (dwHelpID > 0)
{
WRITECR(",") ;
str.Format( _T(" helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE1( str ) ;
}
}
WRITECR("") ;
WRITELINE(_T("]")) ;
WRITE1(_T("module ")) ;
WRITEBSTR( bstrName ) ;
WRITECR( _T(" {")) ;
int n;
for (n = 0 ; n < pattr->cFuncs ; n++)
DumpFunc( pstm, pti, pattr, n, uiIndent + 1 ) ;
for (n = 0 ; n < pattr->cVars ; n++)
DumpConst( pstm, pti, pattr, n, uiIndent + 1, TRUE ) ;
WRITELINE("};") ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
pti->ReleaseTypeAttr( pattr ) ;
}
CATCH(CException, pException)
{
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
if (pattr)
pti->ReleaseTypeAttr( pattr ) ;
THROW_LAST();
}
END_CATCH
return hr ;
}
// [
// attributes
// ]
// interface interfacename [:baseinterface] {
// functionlist
// };
//
// attributes include source, default, and restricted
//
HRESULT CTypeLibODLView::DeCompileInterface( IStream* pstm, ITypeInfo* pti, UINT uiIndent /* = 0 */ )
{
HRESULT hr = S_OK ;
TYPEATTR* pattr = NULL ;
BSTR bstrName = NULL ;
BSTR bstrDoc = NULL ;
BSTR bstrHelp = NULL ;
DWORD dwHelpID ;
ITypeInfo* ptiImpl = NULL ;
TRY
{
if (FAILED(hr = pti->GetTypeAttr( &pattr)))
AfxThrowOleException( hr ) ;
WRITELINE(_T("[")) ;
WRITE1( _T(" odl")) ;
TCHAR szGUID[64] ;
StringFromGUID2T( pattr->guid, szGUID, 64, sizeof(szGUID) ) ;
WRITECR(",") ;
WRITE1(" uuid(") ;
WRITE(szGUID) ;
WRITE(")") ;
// was version specified
if (pattr->wMajorVerNum || pattr->wMinorVerNum)
{
WRITECR(",") ;
CString str ;
str.Format(_T(" version(%d.%d)"), pattr->wMajorVerNum, pattr->wMinorVerNum) ;
WRITE1(str) ;
}
if (SUCCEEDED(pti->GetDocumentation( MEMBERID_NIL, &bstrName, &bstrDoc, &dwHelpID, &bstrHelp )))
{
CString str ;
if (bstrDoc && *bstrDoc)
{
WRITECR(",") ;
COLE2CT lpszDoc(bstrDoc);
::SysFreeString(bstrDoc);
bstrDoc = NULL;
str.Format( _T(" helpstring(\"%s\")"), lpszDoc ) ;
WRITE1( str ) ;
if (dwHelpID > 0)
{
WRITECR(",") ;
str.Format( _T(" helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE1( str ) ;
}
}
else if (dwHelpID > 0)
{
WRITECR(",") ;
str.Format( _T(" helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE1( str ) ;
}
}
// source, default, or restricted
if (pattr->wTypeFlags == TYPEFLAG_FHIDDEN)
{
WRITECR(",") ;
WRITE1(" hidden") ;
}
/*
int implflags = NULL ;
if (FAILED(hr = pti->GetImplTypeFlags(0, &implflags )))
AfxThrowOleException(hr) ;
if (implflags & IMPLTYPEFLAG_FDEFAULT)
{
WRITECR(",") ;
WRITE1(" default") ;
}
if (implflags & IMPLTYPEFLAG_FSOURCE)
{
WRITECR(",") ;
WRITE1(" source") ;
}
if (implflags & IMPLTYPEFLAG_FRESTRICTED)
{
WRITECR(",") ;
WRITE1(" restricted") ;
}
*/
WRITECR("") ;
WRITELINE(_T("]")) ;
WRITE1(_T("interface ")) ;
// interface name
WRITEBSTR( bstrName ) ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
bstrName = bstrDoc = bstrHelp = NULL ;
// is there a base interface?
UINT n;
for (n = 0 ; n < pattr->cImplTypes; n++)
{
HREFTYPE href = NULL ;
if (FAILED(hr = pti->GetRefTypeOfImplType(n, &href)))
AfxThrowOleException(hr) ;
if (FAILED(hr = pti->GetRefTypeInfo( href, &ptiImpl )))
AfxThrowOleException(hr) ;
if (FAILED(hr = ptiImpl->GetDocumentation( MEMBERID_NIL, &bstrName, &bstrDoc, &dwHelpID, &bstrHelp )))
AfxThrowOleException(hr) ;
WRITE(_T(" : ")) ;
WRITEBSTR( bstrName ) ;
SysFreeString( bstrName ) ;
bstrName = NULL ;
SysFreeString( bstrDoc ) ;
bstrDoc = NULL ;
SysFreeString( bstrHelp ) ;
bstrHelp = NULL ;
ptiImpl->Release() ;
ptiImpl = NULL ;
}
WRITECR(_T(" {")) ;
for (n = 0 ; n < pattr->cFuncs ; n++)
DumpFunc( pstm, pti, pattr, n, uiIndent + 1 ) ;
WRITELINE("};") ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
pti->ReleaseTypeAttr( pattr ) ;
}
CATCH(CException, pException)
{
if (ptiImpl)
ptiImpl->Release() ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
if (pattr)
pti->ReleaseTypeAttr( pattr ) ;
THROW_LAST();
}
END_CATCH
return hr ;
}
// Syntax 1
//
// [
// attributes
// ]
// dispinterface intfname {
// properties:
// proplist
// methods:
// methlist
// };
//
// Syntax 2
//
// [
// attributes
// ]
// dispinterface intfname {
// interface interfacename
// };
//
HRESULT CTypeLibODLView::DeCompileDispinterface( IStream* pstm, ITypeInfo* pti, UINT uiIndent /* = 0 */ )
{
HRESULT hr = S_OK ;
TYPEATTR* pattr = NULL ;
BSTR bstrName = NULL ;
BSTR bstrDoc = NULL ;
BSTR bstrHelp = NULL ;
DWORD dwHelpID ;
ITypeInfo* ptiImpl = NULL ;
TRY
{
if (FAILED(hr = pti->GetTypeAttr( &pattr)))
AfxThrowOleException( hr ) ;
WRITELINE(_T("[")) ;
TCHAR szGUID[64] ;
StringFromGUID2T( pattr->guid, szGUID, 64, sizeof(szGUID) ) ;
WRITE1(" uuid(") ;
WRITE(szGUID) ;
WRITE(")") ;
// was version specified
if (pattr->wMajorVerNum || pattr->wMinorVerNum)
{
WRITECR(",") ;
CString str ;
str.Format(_T(" version(%d.%d)"), pattr->wMajorVerNum, pattr->wMinorVerNum) ;
WRITE1(str) ;
}
if (SUCCEEDED(pti->GetDocumentation( MEMBERID_NIL, &bstrName, &bstrDoc, &dwHelpID, &bstrHelp )))
{
CString str ;
if (bstrDoc && *bstrDoc)
{
WRITECR(",") ;
COLE2CT lpszDoc(bstrDoc);
::SysFreeString(bstrDoc);
bstrDoc = NULL;
str.Format( _T(" helpstring(\"%s\")"), lpszDoc ) ;
WRITE1( str ) ;
if (dwHelpID > 0)
{
WRITECR(",") ;
str.Format( _T(" helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE1( str ) ;
}
}
else if (dwHelpID > 0)
{
WRITECR(",") ;
str.Format( _T(" helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE1( str ) ;
}
}
// source, default, or restricted
if (pattr->wTypeFlags == TYPEFLAG_FHIDDEN)
{
WRITECR(",") ;
WRITE1(" hidden") ;
}
if (pattr->wTypeFlags == TYPEFLAG_FDUAL)
{
WRITECR(",") ;
WRITE1(" dual") ;
}
WRITECR("") ;
WRITELINE(_T("]")) ;
WRITE1(_T("dispinterface ")) ;
// interface name
WRITEBSTR( bstrName ) ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
bstrName = bstrDoc = bstrHelp = NULL ;
WRITECR(_T(" {")) ;
WRITELINE2(_T("properties:"), 1) ;
UINT n;
for (n = 0 ; n < pattr->cVars ; n++)
DumpVar( pstm, pti, pattr, n, uiIndent + 2 ) ;
WRITELINE2(_T("methods:"), 1) ;
for (n = 0 ; n < pattr->cFuncs ; n++)
DumpFunc( pstm, pti, pattr, n, uiIndent + 2 ) ;
WRITELINE("};") ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
pti->ReleaseTypeAttr( pattr ) ;
}
CATCH(CException, pException)
{
if (ptiImpl)
ptiImpl->Release() ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
if (pattr)
pti->ReleaseTypeAttr( pattr ) ;
}
END_CATCH
return hr ;
}
// [
// attributes
// ]
// coclass classname {
// [attributes2] [interface | dispinterface] interfacename;
// ...
// };
//
// attributes
// uuid, helpstring, helpcontext, licensed, version, and appobject
//
HRESULT CTypeLibODLView::DeCompileCoClass( IStream* pstm, ITypeInfo* pti, UINT uiIndent /* = 0 */ )
{
HRESULT hr = S_OK ;
TYPEATTR* pattr = NULL ;
BSTR bstrName = NULL ;
BSTR bstrDoc = NULL ;
BSTR bstrHelp = NULL ;
DWORD dwHelpID ;
ITypeInfo* ptiImpl = NULL ;
TYPEATTR* pattrImpl = NULL ;
TRY
{
if (FAILED(hr = pti->GetTypeAttr( &pattr)))
AfxThrowOleException( hr ) ;
WRITELINE(_T("[")) ;
TCHAR szGUID[64] ;
StringFromGUID2T( pattr->guid, szGUID, 64, sizeof(szGUID) ) ;
WRITE1(" uuid(") ;
WRITE(szGUID) ;
WRITE(")") ;
// was version specified
if (pattr->wMajorVerNum || pattr->wMinorVerNum)
{
WRITECR(",") ;
CString str ;
str.Format(_T(" version(%d.%d)"), pattr->wMajorVerNum, pattr->wMinorVerNum) ;
WRITE1(str) ;
}
if (SUCCEEDED(pti->GetDocumentation( MEMBERID_NIL, &bstrName, &bstrDoc, &dwHelpID, &bstrHelp )))
{
CString str ;
if (bstrDoc && *bstrDoc)
{
WRITECR(",") ;
COLE2CT lpszDoc(bstrDoc);
::SysFreeString(bstrDoc);
bstrDoc = NULL;
str.Format( _T(" helpstring(\"%s\")"), lpszDoc ) ;
WRITE1( str ) ;
if (dwHelpID > 0)
{
WRITECR(",") ;
str.Format( _T(" helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE1( str ) ;
}
}
else if (dwHelpID > 0)
{
WRITECR(",") ;
str.Format( _T(" helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE1( str ) ;
}
}
if (pattr->wTypeFlags == TYPEFLAG_FAPPOBJECT)
{
WRITECR(",") ;
WRITE1(" appobject") ;
}
if (pattr->wTypeFlags == TYPEFLAG_FHIDDEN)
{
WRITECR(",") ;
WRITE1(" hidden") ;
}
if (pattr->wTypeFlags == TYPEFLAG_FLICENSED)
{
WRITECR(",") ;
WRITE1(" licensed") ;
}
if (pattr->wTypeFlags == TYPEFLAG_FCONTROL)
{
WRITECR(",") ;
WRITE1(" control") ;
}
WRITECR("") ;
WRITELINE(_T("]")) ;
WRITE1(_T("coclass ")) ;
// coclass name
WRITEBSTR( bstrName ) ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
bstrName = bstrDoc = bstrHelp = NULL ;
WRITECR(_T(" {")) ;
// [attributes2] [interface | dispinterface] interfacename;
for (UINT n = 0 ; n < pattr->cImplTypes ; n++)
{
HREFTYPE href = NULL ;
int impltype = NULL ;
if (FAILED(hr = pti->GetImplTypeFlags( n, &impltype )))
AfxThrowOleException(hr) ;
if (FAILED(hr = pti->GetRefTypeOfImplType(n, &href)))
AfxThrowOleException(hr) ;
if (FAILED(hr = pti->GetRefTypeInfo( href, &ptiImpl )))
AfxThrowOleException(hr) ;
if (FAILED(hr = ptiImpl->GetDocumentation( MEMBERID_NIL, &bstrName, &bstrDoc, &dwHelpID, &bstrHelp )))
AfxThrowOleException(hr) ;
if (FAILED(hr = ptiImpl->GetTypeAttr( &pattrImpl)))
AfxThrowOleException( hr ) ;
WRITE2(_T(""), 1 ) ;
if (impltype)
{
WRITE(_T("[")) ;
BOOL fComma = FALSE ;
if (impltype & IMPLTYPEFLAG_FDEFAULT)
{
WRITE(_T("default")) ;
fComma = TRUE ;
}
if (impltype & IMPLTYPEFLAG_FSOURCE)
{
if (fComma)
WRITE(_T(", ")) ;
WRITE(_T("source")) ;
fComma = TRUE ;
}
if (impltype & IMPLTYPEFLAG_FRESTRICTED)
{
if (fComma)
WRITE(_T(", ")) ;
WRITE(_T("restricted")) ;
}
WRITE(_T("] "));
}
if (pattrImpl->typekind == TKIND_INTERFACE)
WRITE(_T("interface ")) ;
if (pattrImpl->typekind == TKIND_DISPATCH)
WRITE(_T("dispinterface ")) ;
WRITE( bstrName ) ;
WRITECR(_T(";")) ;
SysFreeString( bstrName ) ;
bstrName = NULL ;
SysFreeString( bstrDoc ) ;
bstrDoc = NULL ;
SysFreeString( bstrHelp ) ;
bstrHelp = NULL ;
ptiImpl->ReleaseTypeAttr( pattrImpl ) ;
pattrImpl = NULL ;
ptiImpl->Release() ;
ptiImpl = NULL ;
}
WRITELINE("};") ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
pti->ReleaseTypeAttr( pattr ) ;
}
CATCH(CException, pException)
{
if (ptiImpl)
{
if (pattrImpl)
ptiImpl->ReleaseTypeAttr( pattrImpl ) ;
ptiImpl->Release() ;
}
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
if (pattr)
pti->ReleaseTypeAttr( pattr ) ;
THROW_LAST();
}
END_CATCH
return hr ;
}
HRESULT CTypeLibODLView::DeCompileFunc( IStream* pstm, ITypeInfo* pti, MEMBERID memid, UINT uiIndent /* = 0 */ )
{
HRESULT hr = S_OK ;
TYPEATTR* pattr = NULL ;
ASSERT(pti) ;
TRY
{
ENSURE(pti);
if (FAILED(hr = pti->GetTypeAttr( &pattr)))
AfxThrowOleException( hr ) ;
if (FAILED(hr = DumpFunc( pstm, pti, pattr, memid, uiIndent )))
AfxThrowOleException( hr ) ;
pti->ReleaseTypeAttr( pattr ) ;
}
CATCH(CException, pException)
{
if (pattr)
pti->ReleaseTypeAttr( pattr ) ;
THROW_LAST();
}
END_CATCH
return hr ;
}
HRESULT CTypeLibODLView::DumpFunc( IStream* pstm, ITypeInfo* pti, TYPEATTR* pattr, MEMBERID memid, UINT uiIndent /* = 0 */ )
{
HRESULT hr = S_OK ;
FUNCDESC* pfuncdesc = NULL ;
BSTR rgbstrNames[MAX_NAMES] ;
BSTR bstrName = NULL ;
BSTR bstrDoc = NULL ;
BSTR bstrHelp = NULL ;
DWORD dwHelpID ;
ASSERT(pti) ;
for (UINT ui = 0 ; ui < MAX_NAMES ; ui++)
rgbstrNames[ui] = NULL ;
TRY
{
ENSURE(pti);
if (FAILED(hr = pti->GetFuncDesc( memid, &pfuncdesc )))
AfxThrowOleException( hr ) ;
// If pattr->typekind == TKIND_DISPATCH (dispinterface)
// [attributes] returntype methname(params);
// where attributes can be
// id(<id>), propput, propget,
// propputref, bindable, defaultbind, displaybind,
// requestedit, source, vararg, hidden, helpstring("<helpstring>"),
// helpcontext(<id>)
//
// If pattr->typekind == TKIND_INTERFACE || TKIND_MODULE
// [attributes] returntype [calling convention] funcname(params);
// where attributes can be
// restricted, bindable, defaultbind, displaybind,
// requestedit, source, vararg, hidden, helpstring("<helpstring>"),
// helpcontext(<id>)
// and calling convention can be
// pascal, cdecl, stdcall
//
// Write [attributes]
//
BOOL fAttributes = FALSE ; // any attributes?
BOOL fAttribute = FALSE ; // at least one (insert ",")
WRITE1("") ; // indent
CString str ;
if (pattr->typekind == TKIND_DISPATCH)
{
fAttributes = TRUE ;
fAttribute = TRUE ;
str.Format(_T("[id(%d)"), memid) ;
WRITE(str) ;
}
else if (pattr->typekind == TKIND_MODULE)
{
fAttributes = TRUE ;
fAttribute = TRUE ;
str.Format(_T("[entry(%d)"), memid) ;
WRITE(str) ;
}
else
// if there are some attributes
if ((pfuncdesc->invkind > 1)|| pfuncdesc->wFuncFlags || pfuncdesc->cParamsOpt == -1)
{
WRITE("[") ;
fAttributes = TRUE ;
}
if (pfuncdesc->invkind & INVOKE_PROPERTYGET)
{
if (fAttribute)
WRITE(", ") ;
fAttribute = TRUE ;
WRITE("propget") ;
}
if (pfuncdesc->invkind & INVOKE_PROPERTYPUT)
{
if (fAttribute)
WRITE(", ") ;
fAttribute = TRUE ;
WRITE("propput") ;
}
if (pfuncdesc->invkind & INVOKE_PROPERTYPUTREF)
{
if (fAttribute)
WRITE(", ") ;
fAttribute = TRUE ;
WRITE("propputref") ;
}
if (pfuncdesc->wFuncFlags & FUNCFLAG_FRESTRICTED)
{
if (fAttribute)
WRITE(", ") ;
fAttribute = TRUE ;
WRITE("restricted") ;
}
if (pfuncdesc->wFuncFlags & FUNCFLAG_FSOURCE)
{
if (fAttribute)
WRITE(", ") ;
fAttribute = TRUE ;
WRITE("source") ;
}
if (pfuncdesc->wFuncFlags & FUNCFLAG_FBINDABLE)
{
if (fAttribute)
WRITE(", ") ;
fAttribute = TRUE ;
WRITE("bindable") ;
}
if (pfuncdesc->wFuncFlags & FUNCFLAG_FREQUESTEDIT)
{
if (fAttribute)
WRITE(", ") ;
fAttribute = TRUE ;
WRITE("requestedit") ;
}
if (pfuncdesc->wFuncFlags & FUNCFLAG_FDISPLAYBIND)
{
if (fAttribute)
WRITE(", ") ;
fAttribute = TRUE ;
WRITE("displaybind") ;
}
if (pfuncdesc->wFuncFlags & FUNCFLAG_FDEFAULTBIND)
{
if (fAttribute)
WRITE(", ") ;
fAttribute = TRUE ;
WRITE("defaultbind") ;
}
if (pfuncdesc->wFuncFlags & FUNCFLAG_FHIDDEN)
{
if (fAttribute)
WRITE(", ") ;
fAttribute = TRUE ;
WRITE("hidden") ;
}
if (pfuncdesc->cParamsOpt == -1) // cParamsOpt > 0 indicates VARIANT style
{
if (fAttribute)
WRITE(", ") ;
fAttribute = TRUE ;
WRITE("vararg") ; // optional params
}
if (SUCCEEDED(pti->GetDocumentation( pfuncdesc->memid, &bstrName, &bstrDoc, &dwHelpID, &bstrHelp )))
{
if (bstrDoc && *bstrDoc)
{
if (fAttributes == FALSE) WRITE("[") ;
fAttributes = TRUE ;
if (fAttribute)
WRITE(", ") ;
COLE2CT lpszDoc(bstrDoc);
::SysFreeString(bstrDoc);
bstrDoc = NULL;
str.Format( _T("helpstring(\"%s\")"), lpszDoc ) ;
WRITE( str ) ;
if (dwHelpID > 0)
{
str.Format( _T(", helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE( str ) ;
}
}
else if (dwHelpID > 0)
{
if (fAttributes == FALSE) WRITE("[") ;
if (fAttribute)
WRITE(", ") ;
fAttributes = TRUE ;
str.Format( _T("helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE( str ) ;
}
}
if (fAttributes)
WRITE("] ") ;
// Write return type
WRITE(TYPEDESCtoString( pti, &pfuncdesc->elemdescFunc.tdesc )) ;
WRITE(" ") ;
if (pattr->typekind != TKIND_DISPATCH)
{
// Write calling convention
switch(pfuncdesc->callconv)
{
case CC_CDECL:
WRITE("_cdecl ") ;
break ;
//case CC_MSCPASCAL: WRITE("_mspascal ") ; break ;
case CC_PASCAL:
WRITE("_pascal ") ;
break ;
case CC_MACPASCAL:
WRITE("_macpascal ") ;
break ;
case CC_STDCALL :
WRITE("_stdcall ") ;
break ;
//case CC_RESERVED: WRITE("_reserved ") ; break ;
case CC_SYSCALL:
WRITE("_syscall ") ;
break ;
case CC_MPWCDECL:
WRITE("_mpwcdecl ") ;
break ;
case CC_MPWPASCAL:
WRITE("_mpwpascal ") ;
break ;
}
}
// Write methodname
// Problem: If a property has the propput or propputref attributes the
// 'right hand side' (rhs) is *always* the last parameter and MkTypeLib
// strips the parameter name. Thus you will always get 1 less name
// back from ::GetNames than normal.
//
// Thus for the example below
// [propput] void Color([in] VARIANT rgb, [in] VARIANT rgb2 );
// without taking this into consderation the output would be
// [propput] void Color([in] VARIANT rgb, [in] VARIANT );
// when it should be
// [propput] void Color([in] VARIANT rgb, [in] VARIANT rhs );
//
// Another weirdness comes from a bug (which will never be fixed)
// where optional parameters on property functions were allowed.
// Because they were allowed by accident people used them, so they
// are still allowed.
//
UINT cNames = 0 ;
if (FAILED( hr = pti->GetNames( pfuncdesc->memid, rgbstrNames, MAX_NAMES, &cNames )))
AfxThrowOleException( hr ) ;
// fix for 'rhs' problem
if ((int)cNames < pfuncdesc->cParams + 1)
{
rgbstrNames[cNames] = ::SysAllocString(OLESTR("rhs")) ;
cNames++ ;
}
ASSERT((int)cNames == pfuncdesc->cParams+1) ;
WRITEBSTR( rgbstrNames[0] ) ;
WRITE("(") ;
// params have the format
// [attributes] type paramname
// where attributes can be
// in, out, optional, string (string is not valid for TKIND_MODULE)
//
if (pfuncdesc->cParams > 1)
WRITECR("") ;
for ( int n = 0 ; n < pfuncdesc->cParams ; n++ )
{
if (pfuncdesc->cParams > 1)
WRITE2("", 4 ) ; // indent 4
fAttributes = FALSE ;
fAttribute = FALSE ;
if (pfuncdesc->lprgelemdescParam[n].idldesc.wIDLFlags)
{
WRITE("[") ;
fAttributes = TRUE ;
}
if (pfuncdesc->lprgelemdescParam[n].idldesc.wIDLFlags & IDLFLAG_FIN)
{
if (fAttribute)
WRITE(", ") ;
WRITE("in") ;
fAttribute = TRUE ;
}
if (pfuncdesc->lprgelemdescParam[n].idldesc.wIDLFlags & IDLFLAG_FOUT)
{
if (fAttribute)
WRITE(", ") ;
WRITE("out") ;
fAttribute = TRUE ;
}
if (pfuncdesc->lprgelemdescParam[n].idldesc.wIDLFlags & IDLFLAG_FLCID)
{
if (fAttribute)
WRITE(", ") ;
WRITE("lcid") ;
fAttribute = TRUE ;
}
if (pfuncdesc->lprgelemdescParam[n].idldesc.wIDLFlags & IDLFLAG_FRETVAL)
{
if (fAttribute)
WRITE(", ") ;
WRITE("retval") ;
fAttribute = TRUE ;
}
// If we have an optional last parameter and we're on the last paramter
// or we are into the optional parameters...
if ((pfuncdesc->cParamsOpt == -1 && n == pfuncdesc->cParams - 1) ||
(n > (pfuncdesc->cParams - pfuncdesc->cParamsOpt)))
{
if (fAttribute)
WRITE(", ") ;
if (!fAttributes)
WRITE("[") ;
WRITE("optional") ;
fAttributes = TRUE ;
fAttribute = TRUE ;
}
if (fAttributes)
WRITE("] ") ;
// type
if ((pfuncdesc->lprgelemdescParam[n].tdesc.vt & 0x0FFF) == VT_CARRAY)
{
// type name[n]
WRITE(TYPEDESCtoString( pti, &pfuncdesc->lprgelemdescParam[n].tdesc.lpadesc->tdescElem )) ;
WRITE(" ") ;
WRITEBSTR(rgbstrNames[n+1]) ;
// Allocate cDims * lstrlen("[123456]")
for (USHORT n1 = 0 ; n1 < pfuncdesc->lprgelemdescParam[n1].tdesc.lpadesc->cDims ; n1++)
{
str.Format( _T("[%d]"), pfuncdesc->lprgelemdescParam[n1].tdesc.lpadesc->rgbounds[n1].cElements ) ;
WRITE(str) ;
}
}
else
{
WRITE(TYPEDESCtoString( pti, &pfuncdesc->lprgelemdescParam[n].tdesc ) + " " ) ;
WRITEBSTR(rgbstrNames[n+1]) ;
}
if (n < pfuncdesc->cParams - 1)
WRITECR(", ") ;
}
WRITECR(");") ;
for (UINT ui = 0 ; ui < MAX_NAMES ; ui++)
if (rgbstrNames[ui])
SysFreeString(rgbstrNames[ui]) ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
pti->ReleaseFuncDesc( pfuncdesc ) ;
}
CATCH(CException, pException)
{
for (UINT ui = 0 ; ui < MAX_NAMES ; ui++)
if (rgbstrNames[ui])
SysFreeString(rgbstrNames[ui]) ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
if (pfuncdesc)
pti->ReleaseFuncDesc( pfuncdesc ) ;
THROW_LAST();
}
END_CATCH
return hr ;
}
HRESULT CTypeLibODLView::DeCompileVar( IStream* pstm, ITypeInfo* pti, MEMBERID memid, UINT uiIndent /* = 0 */)
{
HRESULT hr = S_OK ;
TYPEATTR* pattr = NULL ;
ASSERT(pti) ;
TRY
{
ENSURE(pti);
if (FAILED(hr = pti->GetTypeAttr( &pattr)))
AfxThrowOleException( hr ) ;
if (FAILED(hr = DumpVar( pstm, pti, pattr, memid, uiIndent )))
AfxThrowOleException( hr ) ;
pti->ReleaseTypeAttr( pattr ) ;
}
CATCH(CException, pException)
{
if (pattr)
pti->ReleaseTypeAttr( pattr ) ;
THROW_LAST();
}
END_CATCH
return hr ;
}
HRESULT CTypeLibODLView::DumpVar( IStream* pstm, ITypeInfo* pti, TYPEATTR* pattr, MEMBERID memid, UINT uiIndent /* = 0 */)
{
HRESULT hr = S_OK ;
VARDESC* pvardesc = NULL ;
BSTR rgbstrNames[1] ;
BSTR bstrName = NULL ;
BSTR bstrDoc = NULL ;
BSTR bstrHelp = NULL ;
DWORD dwHelpID ;
ASSERT(pti) ;
TRY
{
ENSURE(pti);
if (FAILED(hr = pti->GetVarDesc( memid, &pvardesc )))
AfxThrowOleException( hr ) ;
ASSERT(pvardesc->varkind != VAR_CONST) ; // must not be a const
// If pattr->typekind == TKIND_RECORD (struct) || TKIND_UNION
// type name[array];
//
// If pattr->typekind == TKIND_DISPATCH (dispinterface)
// [id(<id>), bindable, defaultbind, displaybind, readonly,
// requestedit, source, hidden, helpstring("<helpstring>"),
// helpcontext(<id>)] type name;
//
BOOL fAttributes = FALSE ;
WRITE1("") ; // indent
if (pattr->typekind == TKIND_DISPATCH)
{
CString str ;
fAttributes = TRUE ;
str.Format(_T("[id(%d)"), memid) ;
WRITE(str) ;
if (pvardesc->wVarFlags & VARFLAG_FREADONLY)
WRITE(", readonly") ;
if (pvardesc->wVarFlags & VARFLAG_FSOURCE)
WRITE(", source") ;
if (pvardesc->wVarFlags & VARFLAG_FBINDABLE)
WRITE(", bindable") ;
if (pvardesc->wVarFlags & VARFLAG_FREQUESTEDIT)
WRITE(", requestedit") ;
if (pvardesc->wVarFlags & VARFLAG_FDISPLAYBIND)
WRITE(", displaybind") ;
if (pvardesc->wVarFlags & VARFLAG_FDEFAULTBIND)
WRITE(", defaultbind") ;
if (pvardesc->wVarFlags & VARFLAG_FHIDDEN)
WRITE(", hidden") ;
}
if (SUCCEEDED(pti->GetDocumentation( pvardesc->memid, &bstrName, &bstrDoc, &dwHelpID, &bstrHelp )))
{
CString str ;
if (bstrDoc && *bstrDoc)
{
if (fAttributes == FALSE)
WRITE("[") ;
else
WRITE(", ") ;
fAttributes = TRUE ;
COLE2CT lpszDoc(bstrDoc);
::SysFreeString(bstrDoc);
bstrDoc = NULL;
str.Format( _T("helpstring(\"%s\")"), lpszDoc ) ;
WRITE( str ) ;
if (dwHelpID > 0)
{
str.Format( _T(", helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE( str ) ;
}
}
else if (dwHelpID > 0)
{
if (fAttributes == FALSE)
WRITE("[") ;
else
WRITE(", ") ;
fAttributes = TRUE ;
str.Format( _T("helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE( str ) ;
}
}
if (fAttributes)
WRITE("] ") ;
UINT cNames ;
if (FAILED( hr = pti->GetNames( pvardesc->memid, rgbstrNames, 1, (UINT FAR*)&cNames )))
AfxThrowOleException( hr ) ;
CString str ;
if ((pvardesc->elemdescVar.tdesc.vt & 0x0FFF) == VT_CARRAY)
{
// type name[n]
WRITE(TYPEDESCtoString( pti, &pvardesc->elemdescVar.tdesc.lpadesc->tdescElem )) ;
WRITE(" ") ;
if (rgbstrNames[0])
WRITEBSTR(rgbstrNames[0]);
else
WRITE(_T("(nameless)")) ;
// Allocate cDims * lstrlen("[123456]")
for (USHORT n = 0 ; n < pvardesc->elemdescVar.tdesc.lpadesc->cDims ; n++)
{
str.Format( _T("[%d]"), pvardesc->elemdescVar.tdesc.lpadesc->rgbounds[n].cElements ) ;
WRITE(str) ;
}
}
else
{
WRITE(TYPEDESCtoString( pti, &pvardesc->elemdescVar.tdesc ) + _T(" "));
if (rgbstrNames[0])
WRITEBSTR(rgbstrNames[0]);
else
WRITE(_T("(nameless)")) ;
}
WRITECR(";") ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
pti->ReleaseVarDesc( pvardesc ) ;
}
CATCH(CException, pException)
{
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
if (pvardesc)
pti->ReleaseVarDesc( pvardesc ) ;
THROW_LAST();
}
END_CATCH
return hr ;
}
// if fConst == TURE
// const type name = value ;
// else
// name = value (no commas)
//
HRESULT CTypeLibODLView::DeCompileConst( IStream* pstm, ITypeInfo* pti, MEMBERID memid, UINT uiIndent /* = 0 */, BOOL fConst /* = TRUE */ )
{
HRESULT hr = S_OK ;
TYPEATTR* pattr = NULL ;
ASSERT(pti) ;
TRY
{
ENSURE(pti);
if (FAILED(hr = pti->GetTypeAttr( &pattr)))
AfxThrowOleException( hr ) ;
if (FAILED(hr = DumpConst( pstm, pti, pattr, memid, uiIndent, fConst )))
AfxThrowOleException( hr ) ;
pti->ReleaseTypeAttr( pattr ) ;
}
CATCH(CException, pException)
{
if (pattr)
pti->ReleaseTypeAttr( pattr ) ;
THROW_LAST();
}
END_CATCH
return hr ;
}
HRESULT CTypeLibODLView::DumpConst( IStream* pstm, ITypeInfo* pti, TYPEATTR* pattr, MEMBERID memid, UINT uiIndent /* = 0 */, BOOL fConst /* = TRUE */ )
{
HRESULT hr = S_OK ;
VARDESC* pvardesc = NULL ;
BSTR rgbstrNames[1] ;
BSTR bstrName = NULL ;
BSTR bstrDoc = NULL ;
BSTR bstrHelp = NULL ;
DWORD dwHelpID ;
ASSERT(pti) ;
VARIANT varValue ;
VariantInit( &varValue ) ;
TRY
{
ENSURE(pti);
if (FAILED(hr = pti->GetVarDesc( memid, &pvardesc )))
AfxThrowOleException( hr ) ;
ASSERT(pvardesc->varkind == VAR_CONST) ;
CString str = TYPEDESCtoString( pti, &pvardesc->elemdescVar.tdesc ) ;
if (FAILED(hr = VariantChangeType( &varValue, pvardesc->lpvarValue, 0, VT_BSTR )))
{
if (pvardesc->lpvarValue->vt == VT_ERROR || pvardesc->lpvarValue->vt == VT_HRESULT)
{
varValue.vt = VT_BSTR ;
varValue.bstrVal = ::SysAllocString(CT2OLE(_GetScodeString(pvardesc->lpvarValue->scode))) ;
hr = S_OK ;
}
else
AfxThrowOleException( hr ) ;
}
BOOL fIndent = FALSE ;
if (fConst)
{
if (pattr->typekind == TKIND_MODULE)
{
str.Format(_T("[entry(%d)"), memid) ;
WRITE1(str) ;
fIndent = TRUE ;
}
// [helpstring("<helpstring>"), helpcontext(<id>)] const type name = expression ;
if (SUCCEEDED(pti->GetDocumentation( pvardesc->memid, &bstrName, &bstrDoc, &dwHelpID, &bstrHelp )))
{
if (bstrDoc && *bstrDoc)
{
if (!fIndent)
WRITE1("[") ;
else
WRITE(", ") ;
COLE2CT lpszDoc(bstrDoc);
::SysFreeString(bstrDoc);
bstrDoc = NULL;
str.Format( _T("helpstring(\"%s\")"), lpszDoc ) ;
WRITE( str ) ;
if (dwHelpID > 0)
{
str.Format( _T(", helpcontext(%#08.8x)"), dwHelpID ) ;
WRITE( str ) ;
}
WRITE("] ");
fIndent = TRUE ;
}
else if (dwHelpID > 0)
{
if (!fIndent)
WRITE1("[") ;
else
WRITE(", ") ;
str.Format( _T("helpcontext(%#08.8x)] "), dwHelpID ) ;
WRITE( str ) ;
fIndent = TRUE ;
}
}
}
UINT cNames ;
if (FAILED( hr = pti->GetNames( pvardesc->memid, rgbstrNames, 1, (UINT FAR*)&cNames )))
AfxThrowOleException( hr ) ;
if (fConst)
{
if (!fIndent)
WRITE1(_T("")) ;
WRITE("const ") ;
WRITE( str ) ;
WRITE( " " ) ;
}
else
WRITE1("") ;
WRITEBSTR( rgbstrNames[0] ) ;
WRITE( " = " ) ;
if (pvardesc->lpvarValue->vt == VT_BSTR)
{
WRITE( "\"" ) ;
WRITEBSTR( varValue.bstrVal ) ;
WRITE( "\"" ) ;
}
else
WRITEBSTR( varValue.bstrVal) ;
if (fConst)
WRITECR(";") ;
VariantClear( &varValue ) ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
pti->ReleaseVarDesc( pvardesc ) ;
}
CATCH(CException, pException)
{
VariantClear( &varValue ) ;
if (bstrName)
SysFreeString( bstrName ) ;
if (bstrDoc)
SysFreeString( bstrDoc ) ;
if (bstrHelp)
SysFreeString( bstrHelp ) ;
if (pvardesc)
pti->ReleaseVarDesc( pvardesc ) ;
THROW_LAST();
}
END_CATCH
return hr ;
}
IStream* CreateMemoryStream()
{
LPSTREAM lpStream = NULL;
// Create a stream object on a memory block.
HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE|GMEM_SHARE, 0);
if (hGlobal != NULL)
{
HRESULT hr ;
if (FAILED(hr = CreateStreamOnHGlobal(hGlobal, TRUE, &lpStream)))
{
TRACE0("CreateStreamOnHGlobal failed.\n");
GlobalFree(hGlobal);
AfxThrowOleException( hr ) ;
}
}
else
{
#pragma warning (suppress: 6255)
TRACE0("Failed to allocate memory for stream.\n");
AfxThrowMemoryException() ;
}
return lpStream;
}
int StringFromGUID2T(REFGUID rguid, LPTSTR lpszGUID, int nSize, int cbMax )
{
OLECHAR* lpszOle = (OLECHAR*)_malloca(cbMax*sizeof(OLECHAR));
int nCount = ::StringFromGUID2(rguid,lpszOle, cbMax*sizeof(OLECHAR));
if (nCount == 0)
{
lpszGUID[0] = '\0';
_freea(lpszOle);
return 0; // buffer too small for the returned string
}
COLE2T lpszRes(lpszOle);
_tcscpy_s(lpszGUID, nSize, lpszRes);
_freea(lpszOle);
return 0;
}
| [
"126.org@gmail.com"
] | 126.org@gmail.com |
ef0431b693ecc4a45608f88d7bb6d4e9d33da213 | e8b9861a7d1189f831019022fd4fc8ded074ba5b | /CSCI10/Hw2/hw2-2.cpp | 7998954fa05bfe9aabc8ade0903732e0ffc49e95 | [] | no_license | Carsonhom/CSCI10 | ec50d0399b0de2a400be57395f3412ddc2cdbcc5 | 40c5142721dba8cc4a29d86b366ed8e048574e60 | refs/heads/master | 2020-07-03T08:00:06.425272 | 2019-08-12T02:51:38 | 2019-08-12T02:51:38 | 201,845,859 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,007 | cpp | //Carson Hom, Hw 2.2, CSCI10-03
#include <iostream>
#include <string>
using namespace std;
int main(){
//2
int num; //Input variable
cout << "Input a number between 0 and 6 : " << endl; //Prompt user to input a number
cin >> num; //Assign user input to int num
switch (num) {
case 0: cout << "Sunday" << endl; //If input equals 0, print out Sunday
break;
case 1: cout << "Monday" << endl; //If input equals 1, print out Monday
break;
case 2: cout << "Teusday" << endl; //If inut equals 2, print out Teusday
break;
case 3: cout << "Wednesday" << endl; //If input equals 3, print out Wednesday
break;
case 4: cout << "Thursday" << endl; //If input equals 4, print out Thursday
break;
case 5: cout << "Friday" << endl; //If input equals 5, print out Friday
break;
case 6: cout << "Saturday" << endl; //if input equals 6, print out Saturday
break;
default: cout << "Error, number is not within 0 and 6" << endl; //If input is not within 0 and 6, print out an error
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
ad0afcd8e4efedff0b8e4369831bfdff7e7b4834 | feda0a3b9d801184424c8e328c5867a52142e4dc | /binary_translator/pp_routines/begin_only.cpp | 4b14e9fd6da638d598865a929f1d5889043c4fbf | [] | no_license | bnestere/progress_analysis | d34bb95f942efd49a992bcef9acd4502618ff67f | 4e593eba6edee68b5535e78a2b430d54f1f8734a | refs/heads/master | 2020-04-15T19:26:16.285963 | 2019-01-09T23:25:27 | 2019-01-09T23:25:27 | 164,949,727 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,550 | cpp | // Generated by llvm2cpp - DO NOT MODIFY!
Function* define_pp_begin(Module *mod) {
// Type Definitions
std::vector<Type*>FuncTy_0_args;
StructType *StructTy_struct__pp_user_t = mod->getTypeByName("struct._pp_user_t");
if (!StructTy_struct__pp_user_t) {
StructTy_struct__pp_user_t = StructType::create(mod->getContext(), "struct._pp_user_t");
}
std::vector<Type*>StructTy_struct__pp_user_t_fields;
StructTy_struct__pp_user_t_fields.push_back(IntegerType::get(mod->getContext(), 32));
StructTy_struct__pp_user_t_fields.push_back(IntegerType::get(mod->getContext(), 32));
StructTy_struct__pp_user_t_fields.push_back(IntegerType::get(mod->getContext(), 32));
if (StructTy_struct__pp_user_t->isOpaque()) {
StructTy_struct__pp_user_t->setBody(StructTy_struct__pp_user_t_fields, /*isPacked=*/false);
}
PointerType* PointerTy_1 = PointerType::get(StructTy_struct__pp_user_t, 0);
FuncTy_0_args.push_back(PointerTy_1);
FuncTy_0_args.push_back(IntegerType::get(mod->getContext(), 32));
FunctionType* FuncTy_0 = FunctionType::get(
/*Result=*/IntegerType::get(mod->getContext(), 64),
/*Params=*/FuncTy_0_args,
/*isVarArg=*/false);
PointerType* PointerTy_2 = PointerType::get(IntegerType::get(mod->getContext(), 64), 0);
PointerType* PointerTy_3 = PointerType::get(PointerTy_1, 0);
PointerType* PointerTy_4 = PointerType::get(IntegerType::get(mod->getContext(), 32), 0);
StructType *StructTy_struct_timespec = mod->getTypeByName("struct.timespec");
if (!StructTy_struct_timespec) {
StructTy_struct_timespec = StructType::create(mod->getContext(), "struct.timespec");
}
std::vector<Type*>StructTy_struct_timespec_fields;
StructTy_struct_timespec_fields.push_back(IntegerType::get(mod->getContext(), 64));
StructTy_struct_timespec_fields.push_back(IntegerType::get(mod->getContext(), 64));
if (StructTy_struct_timespec->isOpaque()) {
StructTy_struct_timespec->setBody(StructTy_struct_timespec_fields, /*isPacked=*/false);
}
PointerType* PointerTy_6 = PointerType::get(StructTy_struct_timespec, 0);
PointerType* PointerTy_5 = PointerType::get(PointerTy_6, 0);
std::vector<Type*>FuncTy_8_args;
FuncTy_8_args.push_back(IntegerType::get(mod->getContext(), 64));
FunctionType* FuncTy_8 = FunctionType::get(
/*Result=*/IntegerType::get(mod->getContext(), 64),
/*Params=*/FuncTy_8_args,
/*isVarArg=*/true);
PointerType* PointerTy_7 = PointerType::get(FuncTy_8, 0);
ArrayType* ArrayTy_10 = ArrayType::get(IntegerType::get(mod->getContext(), 64), 128);
PointerType* PointerTy_9 = PointerType::get(ArrayTy_10, 0);
ArrayType* ArrayTy_12 = ArrayType::get(StructTy_struct_timespec, 128);
PointerType* PointerTy_11 = PointerType::get(ArrayTy_12, 0);
ArrayType* ArrayTy_14 = ArrayType::get(ArrayTy_12, 1024);
PointerType* PointerTy_13 = PointerType::get(ArrayTy_14, 0);
std::vector<Type*>FuncTy_16_args;
FuncTy_16_args.push_back(IntegerType::get(mod->getContext(), 32));
FuncTy_16_args.push_back(PointerTy_6);
FunctionType* FuncTy_16 = FunctionType::get(
/*Result=*/IntegerType::get(mod->getContext(), 32),
/*Params=*/FuncTy_16_args,
/*isVarArg=*/false);
PointerType* PointerTy_15 = PointerType::get(FuncTy_16, 0);
ArrayType* ArrayTy_18 = ArrayType::get(ArrayTy_10, 1024);
PointerType* PointerTy_17 = PointerType::get(ArrayTy_18, 0);
PointerType* PointerTy_19 = PointerType::get(IntegerType::get(mod->getContext(), 8), 0);
// Function Declarations
Function* func_syscall = mod->getFunction("syscall");
if (!func_syscall) {
func_syscall = Function::Create(
/*Type=*/FuncTy_8,
/*Linkage=*/GlobalValue::ExternalLinkage,
/*Name=*/"syscall", mod); // (external, no body)
func_syscall->setCallingConv(CallingConv::C);
}
AttributeSet func_syscall_PAL;
{
SmallVector<AttributeSet, 4> Attrs;
AttributeSet PAS;
{
AttrBuilder B;
B.addAttribute(Attribute::NoUnwind);
PAS = AttributeSet::get(mod->getContext(), ~0U, B);
}
Attrs.push_back(PAS);
func_syscall_PAL = AttributeSet::get(mod->getContext(), Attrs);
}
func_syscall->setAttributes(func_syscall_PAL);
Function* func_clock_gettime = mod->getFunction("clock_gettime");
if (!func_clock_gettime) {
func_clock_gettime = Function::Create(
/*Type=*/FuncTy_16,
/*Linkage=*/GlobalValue::ExternalLinkage,
/*Name=*/"clock_gettime", mod); // (external, no body)
func_clock_gettime->setCallingConv(CallingConv::C);
}
AttributeSet func_clock_gettime_PAL;
{
SmallVector<AttributeSet, 4> Attrs;
AttributeSet PAS;
{
AttrBuilder B;
B.addAttribute(Attribute::NoUnwind);
PAS = AttributeSet::get(mod->getContext(), ~0U, B);
}
Attrs.push_back(PAS);
func_clock_gettime_PAL = AttributeSet::get(mod->getContext(), Attrs);
}
func_clock_gettime->setAttributes(func_clock_gettime_PAL);
// Global Variable Declarations
GlobalVariable* gvar_array_trust_pp_nos = new GlobalVariable(/*Module=*/*mod,
/*Type=*/ArrayTy_10,
/*isConstant=*/false,
/*Linkage=*/GlobalValue::ExternalLinkage,
/*Initializer=*/0,
/*Name=*/"trust_pp_nos");
GlobalVariable* gvar_array_duration_check_pp_nos = new GlobalVariable(/*Module=*/*mod,
/*Type=*/ArrayTy_14,
/*isConstant=*/false,
/*Linkage=*/GlobalValue::ExternalLinkage,
/*Initializer=*/0,
/*Name=*/"duration_check_pp_nos");
GlobalVariable* gvar_array_active_pps = new GlobalVariable(/*Module=*/*mod,
/*Type=*/ArrayTy_18,
/*isConstant=*/false,
/*Linkage=*/GlobalValue::ExternalLinkage,
/*Initializer=*/0,
/*Name=*/"active_pps");
// Constant Definitions
ConstantInt* const_int32_20 = ConstantInt::get(mod->getContext(), APInt(32, StringRef("1"), 10));
ConstantInt* const_int64_21 = ConstantInt::get(mod->getContext(), APInt(64, StringRef("186"), 10));
ConstantInt* const_int64_22 = ConstantInt::get(mod->getContext(), APInt(64, StringRef("1023"), 10));
ConstantInt* const_int64_23 = ConstantInt::get(mod->getContext(), APInt(64, StringRef("-1"), 10));
ConstantInt* const_int32_24 = ConstantInt::get(mod->getContext(), APInt(32, StringRef("0"), 10));
ConstantInt* const_int64_25 = ConstantInt::get(mod->getContext(), APInt(64, StringRef("0"), 10));
ConstantInt* const_int64_26 = ConstantInt::get(mod->getContext(), APInt(64, StringRef("329"), 10));
// Global Variable Definitions
Function* func_pp_begin = mod->getFunction("pp_begin");
if (!func_pp_begin) {
func_pp_begin = Function::Create(
/*Type=*/FuncTy_0,
/*Linkage=*/GlobalValue::InternalLinkage,
/*Name=*/"pp_begin", mod);
func_pp_begin->setCallingConv(CallingConv::C);
}
AttributeSet func_pp_begin_PAL;
{
SmallVector<AttributeSet, 4> Attrs;
AttributeSet PAS;
{
AttrBuilder B;
B.addAttribute(Attribute::NoUnwind);
B.addAttribute(Attribute::UWTable);
PAS = AttributeSet::get(mod->getContext(), ~0U, B);
}
Attrs.push_back(PAS);
func_pp_begin_PAL = AttributeSet::get(mod->getContext(), Attrs);
}
func_pp_begin->setAttributes(func_pp_begin_PAL);
Function::arg_iterator args = func_pp_begin->arg_begin();
Value* ptr_user_d = args++;
ptr_user_d->setName("user_d");
Value* int32_pp_no = args++;
int32_pp_no->setName("pp_no");
BasicBlock* label_entry = BasicBlock::Create(mod->getContext(), "entry",func_pp_begin,0);
BasicBlock* label_if_then = BasicBlock::Create(mod->getContext(), "if.then",func_pp_begin,0);
BasicBlock* label_if_else = BasicBlock::Create(mod->getContext(), "if.else",func_pp_begin,0);
BasicBlock* label_if_then6 = BasicBlock::Create(mod->getContext(), "if.then6",func_pp_begin,0);
BasicBlock* label_if_end = BasicBlock::Create(mod->getContext(), "if.end",func_pp_begin,0);
BasicBlock* label_if_end12 = BasicBlock::Create(mod->getContext(), "if.end12",func_pp_begin,0);
BasicBlock* label_if_then19 = BasicBlock::Create(mod->getContext(), "if.then19",func_pp_begin,0);
BasicBlock* label_if_end25 = BasicBlock::Create(mod->getContext(), "if.end25",func_pp_begin,0);
BasicBlock* label_return = BasicBlock::Create(mod->getContext(), "return",func_pp_begin,0);
// Block entry (label_entry)
AllocaInst* ptr_retval = new AllocaInst(IntegerType::get(mod->getContext(), 64), "retval", label_entry);
ptr_retval->setAlignment(8);
AllocaInst* ptr_user_d_addr = new AllocaInst(PointerTy_1, "user_d.addr", label_entry);
ptr_user_d_addr->setAlignment(8);
AllocaInst* ptr_pp_no_addr = new AllocaInst(IntegerType::get(mod->getContext(), 32), "pp_no.addr", label_entry);
ptr_pp_no_addr->setAlignment(4);
AllocaInst* ptr_tid = new AllocaInst(IntegerType::get(mod->getContext(), 32), "tid", label_entry);
ptr_tid->setAlignment(4);
AllocaInst* ptr_pp_id = new AllocaInst(IntegerType::get(mod->getContext(), 64), "pp_id", label_entry);
ptr_pp_id->setAlignment(8);
AllocaInst* ptr_spec = new AllocaInst(PointerTy_6, "spec", label_entry);
ptr_spec->setAlignment(8);
StoreInst* void_27 = new StoreInst(ptr_user_d, ptr_user_d_addr, false, label_entry);
void_27->setAlignment(8);
StoreInst* void_28 = new StoreInst(int32_pp_no, ptr_pp_no_addr, false, label_entry);
void_28->setAlignment(4);
CallInst* int64_call = CallInst::Create(func_syscall, const_int64_21, "call", label_entry);
int64_call->setCallingConv(CallingConv::C);
int64_call->setTailCall(false);
AttributeSet int64_call_PAL;
{
SmallVector<AttributeSet, 4> Attrs;
AttributeSet PAS;
{
AttrBuilder B;
B.addAttribute(Attribute::NoUnwind);
PAS = AttributeSet::get(mod->getContext(), ~0U, B);
}
Attrs.push_back(PAS);
int64_call_PAL = AttributeSet::get(mod->getContext(), Attrs);
}
int64_call->setAttributes(int64_call_PAL);
BinaryOperator* int64_and = BinaryOperator::Create(Instruction::And, int64_call, const_int64_22, "and", label_entry);
CastInst* int32_conv = new TruncInst(int64_and, IntegerType::get(mod->getContext(), 32), "conv", label_entry);
StoreInst* void_29 = new StoreInst(int32_conv, ptr_tid, false, label_entry);
void_29->setAlignment(4);
StoreInst* void_30 = new StoreInst(const_int64_23, ptr_pp_id, false, label_entry);
void_30->setAlignment(8);
LoadInst* int32_31 = new LoadInst(ptr_pp_no_addr, "", false, label_entry);
int32_31->setAlignment(4);
CastInst* int64_idxprom = new SExtInst(int32_31, IntegerType::get(mod->getContext(), 64), "idxprom", label_entry);
std::vector<Value*> ptr_arrayidx_indices;
ptr_arrayidx_indices.push_back(const_int32_24);
ptr_arrayidx_indices.push_back(int64_idxprom);
Instruction* ptr_arrayidx = GetElementPtrInst::Create(gvar_array_trust_pp_nos, ptr_arrayidx_indices, "arrayidx", label_entry);
LoadInst* int64_32 = new LoadInst(ptr_arrayidx, "", false, label_entry);
int64_32->setAlignment(8);
ICmpInst* int1_cmp = new ICmpInst(*label_entry, ICmpInst::ICMP_EQ, int64_32, const_int64_23, "cmp");
BranchInst::Create(label_if_then, label_if_else, int1_cmp, label_entry);
// Block if.then (label_if_then)
StoreInst* void_34 = new StoreInst(const_int64_23, ptr_retval, false, label_if_then);
BranchInst::Create(label_return, label_if_then);
// Block if.else (label_if_else)
LoadInst* int32_36 = new LoadInst(ptr_pp_no_addr, "", false, label_if_else);
int32_36->setAlignment(4);
CastInst* int64_idxprom2 = new SExtInst(int32_36, IntegerType::get(mod->getContext(), 64), "idxprom2", label_if_else);
std::vector<Value*> ptr_arrayidx3_indices;
ptr_arrayidx3_indices.push_back(const_int32_24);
ptr_arrayidx3_indices.push_back(int64_idxprom2);
Instruction* ptr_arrayidx3 = GetElementPtrInst::Create(gvar_array_trust_pp_nos, ptr_arrayidx3_indices, "arrayidx3", label_if_else);
LoadInst* int64_37 = new LoadInst(ptr_arrayidx3, "", false, label_if_else);
int64_37->setAlignment(8);
ICmpInst* int1_cmp4 = new ICmpInst(*label_if_else, ICmpInst::ICMP_EQ, int64_37, const_int64_25, "cmp4");
BranchInst::Create(label_if_then6, label_if_end, int1_cmp4, label_if_else);
// Block if.then6 (label_if_then6)
LoadInst* int32_39 = new LoadInst(ptr_pp_no_addr, "", false, label_if_then6);
int32_39->setAlignment(4);
CastInst* int64_idxprom7 = new SExtInst(int32_39, IntegerType::get(mod->getContext(), 64), "idxprom7", label_if_then6);
LoadInst* int32_40 = new LoadInst(ptr_tid, "", false, label_if_then6);
int32_40->setAlignment(4);
CastInst* int64_idxprom8 = new SExtInst(int32_40, IntegerType::get(mod->getContext(), 64), "idxprom8", label_if_then6);
std::vector<Value*> ptr_arrayidx9_indices;
ptr_arrayidx9_indices.push_back(const_int32_24);
ptr_arrayidx9_indices.push_back(int64_idxprom8);
Instruction* ptr_arrayidx9 = GetElementPtrInst::Create(gvar_array_duration_check_pp_nos, ptr_arrayidx9_indices, "arrayidx9", label_if_then6);
std::vector<Value*> ptr_arrayidx10_indices;
ptr_arrayidx10_indices.push_back(const_int32_24);
ptr_arrayidx10_indices.push_back(int64_idxprom7);
Instruction* ptr_arrayidx10 = GetElementPtrInst::Create(ptr_arrayidx9, ptr_arrayidx10_indices, "arrayidx10", label_if_then6);
StoreInst* void_41 = new StoreInst(ptr_arrayidx10, ptr_spec, false, label_if_then6);
void_41->setAlignment(8);
LoadInst* ptr_42 = new LoadInst(ptr_spec, "", false, label_if_then6);
ptr_42->setAlignment(8);
std::vector<Value*> int32_call11_params;
int32_call11_params.push_back(const_int32_24);
int32_call11_params.push_back(ptr_42);
CallInst* int32_call11 = CallInst::Create(func_clock_gettime, int32_call11_params, "call11", label_if_then6);
int32_call11->setCallingConv(CallingConv::C);
int32_call11->setTailCall(false);
AttributeSet int32_call11_PAL;
{
SmallVector<AttributeSet, 4> Attrs;
AttributeSet PAS;
{
AttrBuilder B;
B.addAttribute(Attribute::NoUnwind);
PAS = AttributeSet::get(mod->getContext(), ~0U, B);
}
Attrs.push_back(PAS);
int32_call11_PAL = AttributeSet::get(mod->getContext(), Attrs);
}
int32_call11->setAttributes(int32_call11_PAL);
BranchInst::Create(label_if_end, label_if_then6);
// Block if.end (label_if_end)
BranchInst::Create(label_if_end12, label_if_end);
// Block if.end12 (label_if_end12)
LoadInst* int32_45 = new LoadInst(ptr_pp_no_addr, "", false, label_if_end12);
int32_45->setAlignment(4);
CastInst* int64_idxprom13 = new SExtInst(int32_45, IntegerType::get(mod->getContext(), 64), "idxprom13", label_if_end12);
LoadInst* int32_46 = new LoadInst(ptr_tid, "", false, label_if_end12);
int32_46->setAlignment(4);
CastInst* int64_idxprom14 = new SExtInst(int32_46, IntegerType::get(mod->getContext(), 64), "idxprom14", label_if_end12);
std::vector<Value*> ptr_arrayidx15_indices;
ptr_arrayidx15_indices.push_back(const_int32_24);
ptr_arrayidx15_indices.push_back(int64_idxprom14);
Instruction* ptr_arrayidx15 = GetElementPtrInst::Create(gvar_array_active_pps, ptr_arrayidx15_indices, "arrayidx15", label_if_end12);
std::vector<Value*> ptr_arrayidx16_indices;
ptr_arrayidx16_indices.push_back(const_int32_24);
ptr_arrayidx16_indices.push_back(int64_idxprom13);
Instruction* ptr_arrayidx16 = GetElementPtrInst::Create(ptr_arrayidx15, ptr_arrayidx16_indices, "arrayidx16", label_if_end12);
LoadInst* int64_47 = new LoadInst(ptr_arrayidx16, "", false, label_if_end12);
int64_47->setAlignment(8);
ICmpInst* int1_cmp17 = new ICmpInst(*label_if_end12, ICmpInst::ICMP_EQ, int64_47, const_int64_25, "cmp17");
BranchInst::Create(label_if_then19, label_if_end25, int1_cmp17, label_if_end12);
// Block if.then19 (label_if_then19)
LoadInst* ptr_49 = new LoadInst(ptr_user_d_addr, "", false, label_if_then19);
ptr_49->setAlignment(8);
CastInst* ptr_50 = new BitCastInst(ptr_49, PointerTy_19, "", label_if_then19);
std::vector<Value*> int64_call20_params;
int64_call20_params.push_back(const_int64_26);
int64_call20_params.push_back(ptr_50);
CallInst* int64_call20 = CallInst::Create(func_syscall, int64_call20_params, "call20", label_if_then19);
int64_call20->setCallingConv(CallingConv::C);
int64_call20->setTailCall(false);
AttributeSet int64_call20_PAL;
{
SmallVector<AttributeSet, 4> Attrs;
AttributeSet PAS;
{
AttrBuilder B;
B.addAttribute(Attribute::NoUnwind);
PAS = AttributeSet::get(mod->getContext(), ~0U, B);
}
Attrs.push_back(PAS);
int64_call20_PAL = AttributeSet::get(mod->getContext(), Attrs);
}
int64_call20->setAttributes(int64_call20_PAL);
StoreInst* void_51 = new StoreInst(int64_call20, ptr_pp_id, false, label_if_then19);
void_51->setAlignment(8);
LoadInst* int64_52 = new LoadInst(ptr_pp_id, "", false, label_if_then19);
int64_52->setAlignment(8);
LoadInst* int32_53 = new LoadInst(ptr_pp_no_addr, "", false, label_if_then19);
int32_53->setAlignment(4);
CastInst* int64_idxprom21 = new SExtInst(int32_53, IntegerType::get(mod->getContext(), 64), "idxprom21", label_if_then19);
LoadInst* int32_54 = new LoadInst(ptr_tid, "", false, label_if_then19);
int32_54->setAlignment(4);
CastInst* int64_idxprom22 = new SExtInst(int32_54, IntegerType::get(mod->getContext(), 64), "idxprom22", label_if_then19);
std::vector<Value*> ptr_arrayidx23_indices;
ptr_arrayidx23_indices.push_back(const_int32_24);
ptr_arrayidx23_indices.push_back(int64_idxprom22);
Instruction* ptr_arrayidx23 = GetElementPtrInst::Create(gvar_array_active_pps, ptr_arrayidx23_indices, "arrayidx23", label_if_then19);
std::vector<Value*> ptr_arrayidx24_indices;
ptr_arrayidx24_indices.push_back(const_int32_24);
ptr_arrayidx24_indices.push_back(int64_idxprom21);
Instruction* ptr_arrayidx24 = GetElementPtrInst::Create(ptr_arrayidx23, ptr_arrayidx24_indices, "arrayidx24", label_if_then19);
StoreInst* void_55 = new StoreInst(int64_52, ptr_arrayidx24, false, label_if_then19);
void_55->setAlignment(8);
BranchInst::Create(label_if_end25, label_if_then19);
// Block if.end25 (label_if_end25)
LoadInst* int64_57 = new LoadInst(ptr_pp_id, "", false, label_if_end25);
int64_57->setAlignment(8);
StoreInst* void_58 = new StoreInst(int64_57, ptr_retval, false, label_if_end25);
BranchInst::Create(label_return, label_if_end25);
// Block return (label_return)
LoadInst* int64_60 = new LoadInst(ptr_retval, "", false, label_return);
ReturnInst::Create(mod->getContext(), int64_60, label_return);
return func_pp_begin;
}
| [
"bnestere@uccs.edu"
] | bnestere@uccs.edu |
f90d6b4c288995094b3ba2912aa6aa671aee4e01 | 477c8309420eb102b8073ce067d8df0afc5a79b1 | /VTK/Rendering/vtkFrustumCoverageCuller.cxx | 9107fbd6c09fe57bd4659df1e9e1ca441fa2f80a | [
"LicenseRef-scancode-paraview-1.2",
"BSD-3-Clause"
] | permissive | aashish24/paraview-climate-3.11.1 | e0058124e9492b7adfcb70fa2a8c96419297fbe6 | c8ea429f56c10059dfa4450238b8f5bac3208d3a | refs/heads/uvcdat-master | 2021-07-03T11:16:20.129505 | 2013-05-10T13:14:30 | 2013-05-10T13:14:30 | 4,238,077 | 1 | 0 | NOASSERTION | 2020-10-12T21:28:23 | 2012-05-06T02:32:44 | C++ | UTF-8 | C++ | false | false | 12,621 | cxx | /*=========================================================================
Program: Visualization Toolkit
Module: vtkFrustumCoverageCuller.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkFrustumCoverageCuller.h"
#include "vtkCamera.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkProp.h"
#include "vtkRenderer.h"
vtkStandardNewMacro(vtkFrustumCoverageCuller);
// Create a frustum coverage culler with default values
vtkFrustumCoverageCuller::vtkFrustumCoverageCuller()
{
this->MinimumCoverage = 0.0;
this->MaximumCoverage = 1.0;
this->SortingStyle = VTK_CULLER_SORT_NONE;
}
// The coverage is computed for each prop, and a resulting allocated
// render time is computed. This is multiplied by the current allocated
// render time of the prop. After this, props with no allocated time are
// removed from the list (and the list length is shortened) to make sure
// that they are not considered again by another culler or for rendering.
double vtkFrustumCoverageCuller::Cull( vtkRenderer *ren,
vtkProp **propList,
int& listLength,
int& initialized )
{
vtkProp *prop;
double total_time;
double *bounds, center[3];
double radius = 0.0;
double planes[24], d;
double coverage, screen_bounds[4];
double previous_time;
int i, propLoop;
double full_w, full_h, part_w, part_h;
double *allocatedTimeList;
double *distanceList;
int index1, index2;
double tmp;
// We will create a center distance entry for each prop in the list
// If SortingStyle is set to BackToFront or FrontToBack we will then
// sort the props that have a non-zero AllocatedRenderTime by their
// center distance
distanceList = new double[listLength];
// We will return the total time of all props. This is used for
// normalization.
total_time = 0;
// Get the view frustum planes from the active camera
ren->GetActiveCamera()->GetFrustumPlanes(
ren->GetTiledAspectRatio(), planes );
// Keep a list of allocated times to help with sorting / removing
// props later
allocatedTimeList = new double[listLength];
// For each prop, compute coverage
for ( propLoop = 0; propLoop < listLength; propLoop++ )
{
// Get the prop out of the list
prop = propList[propLoop];
// If allocated render time has not been initialized yet (if this
// is the first culler, it hasn't) then the previous time is set
// to 0.0
if ( !initialized )
{
previous_time = 1.0;
}
else
{
previous_time = prop->GetRenderTimeMultiplier();
}
// Get the bounds of the prop and compute an enclosing sphere
bounds = prop->GetBounds();
// We start with a coverage of 1.0 and set it to zero if the prop
// is culled during the plane tests
coverage = 1.0;
// make sure the bounds are defined - they won't be for a 2D prop which
// means that they will never be culled. Maybe this should be changed in
// the future?
if (bounds)
{
// a duff dataset like a polydata with no cells will have bad bounds
if (!vtkMath::AreBoundsInitialized(bounds))
{
coverage = 0.0;
}
else
{
center[0] = (bounds[0] + bounds[1]) / 2.0;
center[1] = (bounds[2] + bounds[3]) / 2.0;
center[2] = (bounds[4] + bounds[5]) / 2.0;
radius = 0.5 * sqrt( ( bounds[1] - bounds[0] ) *
( bounds[1] - bounds[0] ) +
( bounds[3] - bounds[2] ) *
( bounds[3] - bounds[2] ) +
( bounds[5] - bounds[4] ) *
( bounds[5] - bounds[4] ) );
for ( i = 0; i < 6; i++ )
{
// Compute how far the center of the sphere is from this plane
d =
planes[i*4 + 0] * center[0] +
planes[i*4 + 1] * center[1] +
planes[i*4 + 2] * center[2] +
planes[i*4 + 3];
// If d < -radius the prop is not within the view frustum
if ( d < -radius )
{
coverage = 0.0;
i = 7;
}
// The first four planes are the ones bounding the edges of the
// view plane (the last two are the near and far planes) The
// distance from the edge of the sphere to these planes is stored
// to compute coverage.
if ( i < 4 )
{
screen_bounds[i] = d - radius;
}
// The fifth plane is the near plane - use the distance to
// the center (d) as the value to sort by
if ( i == 4 )
{
distanceList[propLoop] = d;
}
}
}
// If the prop wasn't culled during the plane tests...
if ( coverage > 0.0 )
{
// Compute the width and height of this slice through the
// view frustum that contains the center of the sphere
full_w = screen_bounds[0] + screen_bounds[1] + 2.0 * radius;
full_h = screen_bounds[2] + screen_bounds[3] + 2.0 * radius;
// Subtract from the full width to get the width of the square
// enclosing the circle slice from the sphere in the plane
// through the center of the sphere. If the screen bounds for
// the left and right planes (0,1) are greater than zero, then
// the edge of the sphere was a positive distance away from the
// plane, so there is a gap between the edge of the plane and
// the edge of the box.
part_w = full_w;
if ( screen_bounds[0] > 0.0 )
{
part_w -= screen_bounds[0];
}
if ( screen_bounds[1] > 0.0 )
{
part_w -= screen_bounds[1];
}
// Do the same thing for the height with the top and bottom
// planes (2,3).
part_h = full_h;
if ( screen_bounds[2] > 0.0 )
{
part_h -= screen_bounds[2];
}
if ( screen_bounds[3] > 0.0 )
{
part_h -= screen_bounds[3];
}
// Prevent a single point from being culled if we
// are not culling based on screen coverage
if ( ((full_w*full_h == 0.0) ||
(part_w*part_h/(full_w*full_h) <= 0.0)) && this->MinimumCoverage == 0.0 )
{
coverage = 0.0001;
}
// Compute the fraction of coverage
else if ((full_w * full_h)!=0.0)
{
coverage = (part_w * part_h) / (full_w * full_h);
}
else
{
coverage = 0;
}
// Convert this to an allocated render time - coverage less than
// the minumum result in 0.0 time, greater than the maximum result in
// 1.0 time, and in between a linear ramp is used
if ( coverage < this->MinimumCoverage )
{
coverage = 0;
}
else if ( coverage > this->MaximumCoverage )
{
coverage = 1.0;
}
else
{
coverage = (coverage-this->MinimumCoverage) /
this->MaximumCoverage;
}
}
}
// This is a 2D prop - keep them at the beginning of the list in the same
// order they came in (by giving them all the same distance) and set
// the coverage to something small so that they won't get much
// allocated render time (because they aren't LOD it doesn't matter,
// and they generally do draw fast so you don't want to take too much
// time away from the 3D prop because you added a title to your
// window for example) They are put at the beginning of the list so
// that when sorted back to front they will be rendered last.
else
{
distanceList[propLoop] = -VTK_DOUBLE_MAX;
coverage = 0.001;
}
// Multiply the new allocated time by the previous allocated time
coverage *= previous_time;
prop->SetRenderTimeMultiplier( coverage );
// Save this in our array of allocated times which matches the
// prop array. Also save the center distance
allocatedTimeList[propLoop] = coverage;
// Add the time for this prop to the total time
total_time += coverage;
}
// Now traverse the list from the beginning, swapping any zero entries back
// in the list, while preserving the order of the non-zero entries. This
// requires two indices for the two items we are comparing at any step.
// The second index always moves back by one, but the first index moves back
// by one only when it is pointing to something that has a non-zero value.
index1 = 0;
for ( index2 = 1; index2 < listLength; index2++ )
{
if ( allocatedTimeList[index1] == 0.0 )
{
if ( allocatedTimeList[index2] != 0.0 )
{
allocatedTimeList[index1] = allocatedTimeList[index2];
distanceList[index1] = distanceList[index2];
propList[index1] = propList[index2];
propList[index2] = NULL;
allocatedTimeList[index2] = 0.0;
distanceList[index2] = 0.0;
}
else
{
propList[index1] = propList[index2] = NULL;
allocatedTimeList[index1] = allocatedTimeList[index2] = 0.0;
distanceList[index1] = distanceList[index2] = 0.0;
}
}
if ( allocatedTimeList[index1] != 0.0 )
{
index1++;
}
}
// Compute the new list length - index1 is always pointing to the
// first 0.0 entry or the last entry if none were zero (in which case
// we won't change the list length)
listLength = (allocatedTimeList[index1] == 0.0)?(index1):listLength;
// Now reorder the list if sorting is on
// Do it by a simple bubble sort - there probably aren't that
// many props....
if ( this->SortingStyle == VTK_CULLER_SORT_FRONT_TO_BACK )
{
for ( propLoop = 1; propLoop < listLength; propLoop++ )
{
index1 = propLoop;
while ( (index1 - 1) >= 0 &&
distanceList[index1] < distanceList[index1-1] )
{
tmp = distanceList[index1-1];
distanceList[index1-1] = distanceList[index1];
distanceList[index1] = tmp;
prop = propList[index1-1];
propList[index1-1] = propList[index1];
propList[index1] = prop;
index1--;
}
}
}
if ( this->SortingStyle == VTK_CULLER_SORT_BACK_TO_FRONT )
{
for ( propLoop = 1; propLoop < listLength; propLoop++ )
{
index1 = propLoop;
while ( (index1 - 1) >= 0 &&
distanceList[index1] > distanceList[index1-1] )
{
tmp = distanceList[index1-1];
distanceList[index1-1] = distanceList[index1];
distanceList[index1] = tmp;
prop = propList[index1-1];
propList[index1-1] = propList[index1];
propList[index1] = prop;
index1--;
}
}
}
// The allocated render times are now initialized
initialized = 1;
delete [] allocatedTimeList;
delete [] distanceList;
return total_time;
}
// Description:
// Return the sorting style as a descriptive character string.
const char *vtkFrustumCoverageCuller::GetSortingStyleAsString(void)
{
if( this->SortingStyle == VTK_CULLER_SORT_NONE )
{
return "None";
}
if( this->SortingStyle == VTK_CULLER_SORT_FRONT_TO_BACK )
{
return "Front To Back";
}
if( this->SortingStyle == VTK_CULLER_SORT_BACK_TO_FRONT )
{
return "Back To Front";
}
else
{
return "Unknown";
}
}
void vtkFrustumCoverageCuller::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Minimum Coverage: "
<< this->MinimumCoverage << endl;
os << indent << "Maximum Coverage: "
<< this->MaximumCoverage << endl;
os << indent << "Sorting Style: "
<< this->GetSortingStyleAsString() << endl;
}
| [
"aashish.chaudhary@kitware.com"
] | aashish.chaudhary@kitware.com |
b2d81b253cdcc268cfa5a32ac7e7ed254014d864 | 3411e29f72a38d61223662245753877b6c7850e5 | /src/breslin/serverside/combatant/combatant.cpp | 5bd034ce3ab11d06c9d2ac7f57474cc431068b98 | [] | no_license | sanan1986/baseapplication | 4550bfa62ad85af316f4db9ce5cd73892cd694ae | f9be781782d92b139d3504cb52010ad6609f338b | refs/heads/master | 2020-12-29T23:24:49.036361 | 2013-11-02T22:07:18 | 2013-11-02T22:07:18 | 238,774,855 | 1 | 0 | null | 2020-02-06T20:09:57 | 2020-02-06T20:09:56 | null | UTF-8 | C++ | false | false | 952 | cpp | #include "combatant.h"
#include "../tdreamsock/dreamSockLog.h"
#include <string>
//Ogre headers
#include "Ogre.h"
using namespace Ogre;
//states
#include "states/combatantStates.h"
//battle
#include "../battle/battle.h"
//shapes
#include "../client/robust/partido/clientPartido.h"
//quiz
#include "../quiz/quiz.h"
Combatant::Combatant(Battle* battle, ClientPartido* clientPartido)
{
mBattle = battle;
mClientPartido = clientPartido;
mQuiz = new Quiz(this);
mFoe = NULL;
//score
mScore = 0;
//combatant states
mStateMachine = new StateMachine<Combatant>(this);
mStateMachine->setCurrentState (INIT_COMBATANT::Instance());
mStateMachine->setPreviousState (INIT_COMBATANT::Instance());
mStateMachine->setGlobalState (GLOBAL_COMBATANT::Instance());
mWrittenToDisk = false;
}
Combatant::~Combatant()
{
delete mQuiz;
delete mStateMachine;
}
void Combatant::update()
{
mStateMachine->update();
mQuiz->update();
}
| [
"jbreslin33@localhost"
] | jbreslin33@localhost |
d38bbebaf8c56fc4b39037dc2a7b7cb3bd4202e2 | 5e3501001c63d70f4e4e466541f5bd5e27d3ebe3 | /PP3/ProyectoPP3/CodigoProyecto/CodigoControlTanque/ProyectoControlTanque/FuncionRele.ino | 2e9b59cafcc290cb66f8a367bd69ce79d3c9714d | [] | no_license | Barzizzag/Material_de_Estudio | 63838061c6a90695a083f8a95858f62a1192a8de | 1bdc1ca280c89905b76937fdbc88edbe0bcfa08c | refs/heads/master | 2023-08-11T06:14:28.164415 | 2021-10-08T15:30:04 | 2021-10-08T15:30:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,031 | ino |
void releBombaAgua(){
//--Inicio--
if(inicioSistema==0){//Cada vez que reiniciamos el sistema entra a la fase inicio(experimental)
if(volumen <= 1.50){//seria la altura maxima del sensor de agua,fijarse
digitalWrite(pinRele,HIGH);
if(volumen == 1.50){//Nos aseguramos haber pasado por todas las etapas de la señal preventiva
inicioSistema ++;//aumentamos la variable
digitalWrite(pinRele,LOW);//Apagamos el rele
}
}else{
digitalWrite(pinRele,LOW);
}
}
//--Estabilizacion del sistema--
if(inicioSistema==1){//Nos aseguramos que se halla mostrado el inicio del sistema antes de llegar a la estabilizacion del mismo
if(volumen < 0.60 || volumen < 0.75){//En esa franja estara prendido
digitalWrite(pinRele,HIGH);
}else if(volumen >= 0.75 && volumen <= 1.50){//En esa franja siempre estara apagado
digitalWrite(pinRele,LOW);
}else{
digitalWrite(pinRele,LOW);//En caso de algun problema, apagamos la bomba
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
13ecf6708b8c1b6be250c5bdeef1db51ad97d754 | 9f38ba222dec136c0220efe2cf7cb0ec21db0f84 | /Main.cpp | 244da94eee9aeb2c50a3d09dd23b6d253ac42d61 | [] | no_license | SubWarZone/Puissance4 | 3acdd9ada82d68e9b963306b74b0c940b81e32e8 | e5252da7e5644b6c5af6455c1c05da9348d77f7a | refs/heads/master | 2021-01-17T09:38:15.450321 | 2013-05-18T16:37:14 | 2013-05-18T16:37:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 168 | cpp | #include <iostream>
#include "Puissance4.h"
using namespace std;
int main() {
Puissance4* puissance4 = new Puissance4();
puissance4->launch();
return 0;
}
| [
"hugo@mint"
] | hugo@mint |
6425711a32a36e8933a9b12a89f60c0fa490cb54 | d13fe22aac6bfb9497af552fdc0641fd297116d6 | /Persist/Persist.h | 624135111530146c0b14db6742c184fb2ca301d1 | [] | no_license | DushyantSheoran/Remote-Repository-for-No-Sql-Database | a16a1455d036bafd6a25e37f033b9a73626b0143 | 09edddc8e491579c86e65011ca45379a7506f80b | refs/heads/master | 2020-05-18T11:30:44.436849 | 2019-05-01T07:34:56 | 2019-05-01T07:34:56 | 184,381,430 | 0 | 0 | null | 2019-05-01T07:34:57 | 2019-05-01T07:11:31 | C++ | UTF-8 | C++ | false | false | 7,893 | h | #pragma once
/////////////////////////////////////////////////////////////////////////////////
// Persist.h - persist DbCore<P> to and from XML file //
// ver 1.0 //
// Language: Visual C# 2017 //
// Platform: Lenovo Z580 Windows 10 //
// Application : Key/Value DataBase , S18 //
// Author : Dushyant Sheoran, CSE687 //
// dsheoran@syr.edu +1(704)-957-2519 //
// Source : Jim Fawcett, CSE687 - Object Oriented Design, Spring 18 //
////////////////////////////////////////////////////////////////////////////////
/*
* Package Operations:
* -------------------
* This package defines a single Persist class that:
* - accepts a DbCore<P> instance when constructed
* - persists its database to an XML string
* - creates an instance of DbCore<P> from a persisted XML string
*
* Required Files:
* ---------------
* Persist.h, Persist.cpp
* DbCore.h, DbCore.cpp
* Query.h, Query.cpp
* PayLoad.h
* XmlDocument.h, XmlDocument.cpp
* XmlElement.h, XmlElement.cpp
* Build Process:
---------------------
* CL /EHsc Persist.cpp ../DateTime/DateTime.cpp ../XmlDocument/XmlDocument/XmlDocument.cpp
* ../XmlDocument/XmlElement/XmlElement.cpp
* ../XmlDocument/XmlParser/XmlParser.cpp ../XmlDocument/XmlElementParts/XmlElementParts.cpp
* ../XmlDocument/XmlElementParts/Tokenizer.cpp
*
*
*
* Maintenance History:
* --------------------
* ver 1.0 : 12 Feb 2018
* - first release
*/
#include "../DbCore/DbCore.h"
#include "../Queries/Queries.h"
#include "../DateTime/DateTime.h"
#include "../XmlDocument/XmlDocument/XmlDocument.h"
#include "../XmlDocument/XmlElement/XmlElement.h"
#include "../StringUtilities/StringUtilities.h"
#include <string>
#include <iostream>
#include <fstream>
using namespace Utilities;
namespace NoSqlDb
{
using namespace XmlProcessing;
using Xml = std::string;
using Sptr = std::shared_ptr<AbstractXmlElement>;
const bool augment = true; // do augment
const bool rebuild = false; // don't augment
/////////////////////////////////////////////////////////////////////
// Persist<P> class
// - persist DbCore<P> to XML string
template<typename P>
class Persist
{
public:
Persist(DbCore<P>& db);
virtual ~Persist() {}
static void identify(std::ostream& out = std::cout);
Persist<P>& shard(const Keys& keys);
Persist<P>& addShardKey(const Key& key);
Persist<P>& removeShard();
Xml toXml();
bool fromXml(const Xml& xml, bool augment = true); // will clear and reload db if augment is false !!!
bool loadfromFile(const std::string &filename);
private:
DbCore<P>& db_;
Keys shardKeys_;
bool containsKey(const Key& key);
void toXmlRecord(Sptr pDb, const Key& key, DbElement<P>& dbElem);
};
//----< constructor >------------------------------------------------
template<typename P>
Persist<P>::Persist(DbCore<P>& db) : db_(db) {}
//----< show file name >---------------------------------------------
template<typename P>
void Persist<P>::identify(std::ostream& out)
{
out << "\n \"" << __FILE__ << "\"";
}
//----< add key to shard collection >--------------------------------
/*
* - when sharding, a db record is persisted if, and only if, its key
is contained in the shard collection
*/
template<typename P>
Persist<P>& Persist<P>::addShardKey(const Key& key)
{
shardKeys_.push_back(key);
return *this;
}
//----< does the shard key collection contain key? >-----------------
template<typename P>
bool Persist<P>::containsKey(const Key& key)
{
Keys::iterator start = shardKeys_.begin();
Keys::iterator end = shardKeys_.end();
return std::find(start, end, key) != end;
}
//----< set the shardKeys collection >-------------------------------
template<typename P>
Persist<P>& Persist<P>::shard(const Keys& keys)
{
shardKeys_ = keys;
return *this;
}
//----< empty the shardKeys collection >-----------------------------
template<typename P>
Persist<P>& Persist<P>::removeShard()
{
shardKeys_.clear();
}
//----< persist database record to XML string >----------------------
template<typename P>
void Persist<P>::toXmlRecord(Sptr pDb, const Key& key, DbElement<P>& dbElem)
{
Sptr pRecord = makeTaggedElement("dbRecord");
pDb->addChild(pRecord);
Sptr pKey = makeTaggedElement("key", key);
pRecord->addChild(pKey);
Sptr pValue = makeTaggedElement("value");
pRecord->addChild(pValue);
Sptr pName = makeTaggedElement("name", dbElem.name());
pValue->addChild(pName);
Sptr pDescrip = makeTaggedElement("description", dbElem.descrip());
pValue->addChild(pDescrip);
Sptr pChildren = makeTaggedElement("children");
pValue->addChild(pChildren);
for (auto child : dbElem.children())
{
Sptr pChild = makeTaggedElement("child", child);
pChildren->addChild(pChild);
}
Sptr pPayLoad = dbElem.payLoad().toXmlElement();
pValue->addChild(pPayLoad);
}
//----< persist, possibly sharded, database to XML string >----------
/*
* - database is sharded if the shardKeys collection is non-empty
*/
template<typename P>
Xml Persist<P>::toXml()
{
Sptr pDb = makeTaggedElement("db");
pDb->addAttrib("type", "fromQuery");
Sptr pDocElem = makeDocElement(pDb);
XmlDocument xDoc(pDocElem);
if (shardKeys_.size() > 0)
{
for (auto key : shardKeys_)
{
DbElement<P> elem = db_[key];
toXmlRecord(pDb, key, elem);
}
}
else
{
for (auto item : db_)
{
toXmlRecord(pDb, item.first, item.second);
}
}
std::string xml = xDoc.toString();
return xml;
}
//----< retrieve database from XML string >--------------------------
/*
* - Will clear db and reload if augment is false
*/
template<typename P>
bool Persist<P>::fromXml(const Xml& xml, bool augment)
{
XmlProcessing::XmlDocument doc(xml);
std::vector<Sptr> pRecords = doc.descendents("dbRecord").select();
for (auto pRecord : pRecords)
{
Key key;
DbElement<P> elem;
P pl;
std::vector<Sptr> pChildren = pRecord->children();
for (auto pChild : pChildren)
{
if (pChild->tag() == "key")
key = trim(pChild->children()[0]->value());
else
{
std::vector<Sptr> pValueChildren = pChild->children();
std::string valueOfTextNode;
for (auto pValueChild : pValueChildren)
{
std::string tag = pValueChild->tag();
if (pValueChild->children().size() > 0)
valueOfTextNode = trim(pValueChild->children()[0]->value());
else
valueOfTextNode = "";
if (tag == "name")
elem.name(valueOfTextNode);
else if (tag == "description")
elem.descrip(valueOfTextNode);
else if (tag == "dateTime")
elem.dateTime(valueOfTextNode);
else if (tag == "children")
{
for (auto pChild : pValueChild->children())
{
valueOfTextNode = trim(pChild->children()[0]->value());
elem.children().push_back(valueOfTextNode);
}
}
else if (tag == "payload")
{
pl = PayLoad::fromXmlElement(pValueChild);
elem.payLoad(pl);
}
}
}
db_[key] = elem;
}
}
return true;
}
template<typename P>
bool Persist<P>::loadfromFile(const std::string &fileName)
{
std::ifstream in(fileName);
if (!in.good())
{
std::cout << "\n failed to open file";
return false;
}
Xml xmlString;
while (in.good())
{
char ch = in.get();
if (!in.good())
break;
xmlString += ch;
}
in.close();
fromXml(xmlString);
return true;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
f0ff1f2063c7ac7a58f9588a0baf4e1422bab060 | 937aa541d6eb8b9d1be60737322b2edeff9ff25b | /src/IBM2.cpp | a9340994ee4a439ddd8bc91f0e7659917c3d6b22 | [] | no_license | hitochan777/IBMModel | 70611f9d1f214c8d76154b514df180305f0533b1 | f843d7a3a0d4e55698a4836a63ad3bb9a09931ba | refs/heads/master | 2021-01-01T15:17:42.401285 | 2014-06-23T12:14:37 | 2014-06-23T12:14:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,672 | cpp | #include "IBM2.h"
IBM2::IBM2(char* ffilename, char* efilename) :
IBM1(ffilename, efilename) { //call constructor to base function
this->getSentenceLengthPairs();
initializeAlignmentDistributionTable();
EM();
}
IBM2::~IBM2() {
}
void IBM2::EM() {
int n = 0;
double LL[2] = { 0 }; //log likelihood
pair<vector<string>, vector<string> > spair;
//while (n < 2 || LL[(n - 1) % 2] < LL[n % 2]) { //while not converged
while (n < 2 || LL[n % 2] - LL[(n-1) % 2] > 0.1) { //while not converged
n++;
LL[n % 2] = 0;
initializeCountTable(); //init every element of count table to zero
initializeTotalTable();
initializeCountAlignmentTable();
initializeTotalAlignmentTable();
fsrefresh();
int cnt = 0;
while (true) {
spair = getSentencePair();
if (spair.first.empty() || spair.second.empty()) {
break;
}
vector<double> z;
vector<string> fv(spair.second), ev(spair.first);
for (ui j = 0; j < ev.size(); ++j) {
double tmpZ = 0.0;
for (ui k = 0; k < fv.size(); ++k) {
tmpZ += this->getAlignmentProbability(k, j + 1, ev.size(),
fv.size()-1)
* this->getTranslationProbability(ev[j], fv[k]);
}
z.push_back(tmpZ);
}
int i = 0;
for (ui j = 0; j < ev.size(); ++j) {
for (ui k = 0; k < fv.size(); ++k) {
double p_jk_div_z = this->getAlignmentProbability(k, j + 1,
ev.size(), fv.size()-1)
* this->getTranslationProbability(ev[j], fv[k])
/ z[i];
this->setWordCount(ev[j], fv[k],
this->getWordCount(ev[j], fv[k]) + p_jk_div_z);
this->setWordTotal(fv[k],
this->getWordTotal(fv[k]) + p_jk_div_z);
this->setCountAlignment(k, j + 1, ev.size(), fv.size()-1,
this->getCountAlignment(k, j + 1, ev.size(),
fv.size()-1) + p_jk_div_z);
this->setTotalAlignment(j + 1, ev.size(), fv.size()-1,
this->getTotalAlignment(j + 1, ev.size(), fv.size()-1)
+ p_jk_div_z);
}
LL[n % 2] += log(z[i]);
i++;
}
cnt++;
}
for (SS::iterator fit = fs.begin(); fit != fs.end(); ++fit) {
for (SS::iterator eit = es.begin(); eit != es.end(); ++eit) {
double newval = this->getWordCount(*eit, *fit)
/ this->getWordTotal(*fit);
this->setTranslationProbability(*eit, *fit, newval);
}
}
for (ui i = 0; i < slp.size(); ++i) {
ui le = slp[i].first;
ui lf = slp[i].second;
for (ui j = 0; j <= lf; ++j) {
for (ui k = 1; k <= le; ++k) {
this->setAlignmentProbability(j, k, le, lf,
this->getCountAlignment(j, k, le, lf)
/ this->getTotalAlignment(k, le, lf));
}
}
}
cout << LL[n % 2] << endl;
}
return;
}
void IBM2::initializeCountAlignmentTable() {
for (ui i = 0; i < slp.size(); ++i) {
ui le = slp[i].first;
ui lf = slp[i].second;
for (ui j = 0; j <= lf; ++j) {
for (ui k = 1; k <= le; ++k) {
setCountAlignment(j, k, le, lf, 0.0);
}
}
}
return;
}
void IBM2::initializeTotalAlignmentTable() {
for (ui i = 0; i < slp.size(); ++i) {
ui le = slp[i].first;
ui lf = slp[i].second;
for (ui j = 1; j <= le; ++j) {
setTotalAlignment(j, le, lf, 0.0);
}
}
}
void IBM2::initializeAlignmentDistributionTable() {
for (ui i = 0; i < slp.size(); ++i) {
ui le = slp[i].first;
ui lf = slp[i].second;
for (ui j = 0; j <= lf; ++j) {
for (ui k = 1; k <= le; ++k) {
setAlignmentProbability(j, k, le, lf, 1.0 / (lf + 1));
}
}
}
return;
}
void IBM2::getSentenceLengthPairs() {
ui le, lf;
fsrefresh();
string es, fs;
while (getline(ffin, fs) && getline(efin, es)) {
lf = Utility::split(fs, ' ');
le = Utility::split(es, ' ');
pair<ui, ui> p(le, lf);
slp.push_back(p);
}
return;
}
double IBM2::getTotalAlignment(ui j, ui le, ui lf) {
pair<ui, ui> p1(le, lf);
pair<ui, pair<ui, ui> > p(j, p1);
return tat[p];
}
void IBM2::setTotalAlignment(ui j, ui le, ui lf, double val) {
pair<ui, ui> p1(le, lf);
pair<ui, pair<ui, ui> > p(j, p1);
tat[p] = val;
return;
}
double IBM2::getCountAlignment(ui k, ui i, ui I, ui K) {
pair<ui, ui> p1(I, K);
pair<ui, ui> p2(i, k);
pair<pair<ui, ui>, pair<ui, ui> > p(p2, p1);
return cat[p];
}
void IBM2::setCountAlignment(ui k, ui i, ui I, ui K, double prob) {
pair<ui, ui> p1(I, K);
pair<ui, ui> p2(i, k);
pair<pair<ui, ui>, pair<ui, ui> > p(p2, p1);
cat[p] = prob;
return;
}
double IBM2::getAlignmentProbability(ui k, ui i, ui I, ui K) {
pair<ui, ui> p1(I, K);
pair<ui, ui> p2(i, k);
pair<pair<ui, ui>, pair<ui, ui> > p(p2, p1);
return adt[p];
}
void IBM2::setAlignmentProbability(ui k, ui i, ui I, ui K, double prob) {
pair<ui, ui> p1(I, K);
pair<ui, ui> p2(i, k);
pair<pair<ui, ui>, pair<ui, ui> > p(p2, p1);
adt[p] = prob;
return;
}
| [
"ilikestars55@yahoo.co.jp"
] | ilikestars55@yahoo.co.jp |
528fe5c607bb099b79069af4e7ce51c31c9a4e59 | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/chromium_org/chrome/browser/thumbnails/thumbnailing_context.h | 877a2eafee08afb0ba2d4508ca6ec48ed41d0ff8 | [
"BSD-3-Clause",
"MIT"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 2,007 | h | // Copyright (c) 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 CHROME_BROWSER_THUMBNAILS_THUMBNAILING_CONTEXT_H_
#define CHROME_BROWSER_THUMBNAILS_THUMBNAILING_CONTEXT_H_
#include "base/basictypes.h"
#include "base/memory/ref_counted.h"
#include "chrome/browser/thumbnails/thumbnail_service.h"
#include "chrome/common/thumbnail_score.h"
#include "content/public/browser/web_contents.h"
#include "ui/gfx/size.h"
namespace thumbnails {
// The result of clipping. This can be used to determine if the
// generated thumbnail is good or not.
enum ClipResult {
// Clipping is not done yet.
CLIP_RESULT_UNPROCESSED,
// The source image is smaller.
CLIP_RESULT_SOURCE_IS_SMALLER,
// Wider than tall by twice or more, clip horizontally.
CLIP_RESULT_MUCH_WIDER_THAN_TALL,
// Wider than tall, clip horizontally.
CLIP_RESULT_WIDER_THAN_TALL,
// Taller than wide, clip vertically.
CLIP_RESULT_TALLER_THAN_WIDE,
// The source and destination aspect ratios are identical.
CLIP_RESULT_NOT_CLIPPED,
// The source and destination are identical.
CLIP_RESULT_SOURCE_SAME_AS_TARGET,
};
// Holds the information needed for processing a thumbnail.
struct ThumbnailingContext : base::RefCountedThreadSafe<ThumbnailingContext> {
ThumbnailingContext(content::WebContents* web_contents,
ThumbnailService* receiving_service,
bool load_interrupted);
// Create an instance for use with unit tests.
static ThumbnailingContext* CreateThumbnailingContextForTest() {
return new ThumbnailingContext();
}
scoped_refptr<ThumbnailService> service;
GURL url;
ClipResult clip_result;
gfx::Size requested_copy_size;
ThumbnailScore score;
private:
ThumbnailingContext();
~ThumbnailingContext();
friend class base::RefCountedThreadSafe<ThumbnailingContext>;
};
}
#endif // CHROME_BROWSER_THUMBNAILS_THUMBNAILING_CONTEXT_H_
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
82cbce6810e9ab04a39df2968f8e227f8cd56730 | 3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c | /zju.finished/2362.cpp | a365f8289508026a43f38e9902feeea67bb7eef2 | [] | no_license | usherfu/zoj | 4af6de9798bcb0ffa9dbb7f773b903f630e06617 | 8bb41d209b54292d6f596c5be55babd781610a52 | refs/heads/master | 2021-05-28T11:21:55.965737 | 2009-12-15T07:58:33 | 2009-12-15T07:58:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,775 | cpp | #include<iostream>
#include<vector>
#include<cstdlib>
#include<cstring>
using namespace std;
enum {
SZ = 804,
};
struct Node {
int p, v;
};
bool cmp_p(const Node&a, const Node&b){
return a.p < b.p;
}
bool cmp_v(const Node&a, const Node&b){
return a.v >= b.v;
}
int num;
Node tree[SZ];
vector<int> tab[SZ];
int mat[SZ];
int vis[SZ];
int dfs(int p){
int i, t, g;
for(i=0;i<tab[p].size();++i) {
g = tab[p][i];
if(!vis[g]){
vis[g] = 1;
t = mat[g];
mat[g] = p;
if(t==-1)
return g;
int v = dfs(t);
if (v >= 0) {
return v;
}
mat[g] = t;
}
}
return -1;
}
void fun(){
sort(tree, tree+num, cmp_v);
memset(mat, -1, sizeof(mat));
for (int i=0; i<num; ++i){
memset(vis, 0, sizeof(vis));
int t = dfs(tree[i].p);
if (t == -1){
tree[i].v = 0;
} else {
tree[i].v = t - num + 1;
}
}
sort(tree, tree+num, cmp_p);
for (int i=0; i<num; ++i){
if (i) printf(" ");
printf("%d", tree[i].v);
}
printf("\n");
}
void readIn(){
int i,t;
int a,b;
for (i=0; i<SZ; ++i)
tab[i].clear();
cin>>num;
for (i=0; i<num; ++i){
tree[i].p = i;
scanf("%d ", &tree[i].v);
}
for (i=0; i<num; ++i){
scanf("%d ", &t);
while(t--){
scanf("%d ", &a);
a += num - 1;
tab[i].push_back(a);
tab[a].push_back(i);
}
}
}
int main(){
int tst;
scanf("%d ", &tst);
while(tst-- > 0){
readIn();
fun();
if (tst){
printf("\n");
}
}
return 0;
}
| [
"zhouweikuan@gmail.com"
] | zhouweikuan@gmail.com |
09498ba9ff4108a03ab799b01988c490e0636532 | afe05da7b29d825c872bd146ecc23c258163c5d9 | /cpp/apiTest/formtwolegstrategy.cpp | b4dc74da8c394266048476e77e22337d7c0df647 | [] | no_license | valmac/muTradeApi | 4e3de0b01ebb0fd0f777e72b154374da7d2f3309 | 3514d6a92a911cb7fb57e135059333b680768290 | refs/heads/master | 2021-01-22T18:18:19.034518 | 2014-06-04T09:28:43 | 2014-06-04T09:28:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,858 | cpp | #include "formtwolegstrategy.h"
#include "ui_formtwolegstrategy.h"
#include "processapiresponses.h"
FormtwoLegStrategy::FormtwoLegStrategy(QWidget *parent) :
QWidget(parent),
ui(new Ui::FormtwoLegStrategy)
{
ui->setupUi(this);
initStrategy();
}
FormtwoLegStrategy::~FormtwoLegStrategy()
{
delete ui;
}
void FormtwoLegStrategy::initStrategy()
{
sd = new mutrade::SymbolData();
sd->firstLegSymbol = "";
sd->secondLegSymbol = "";
sd->minProfit = 0;
sd->avgPriceFirstLeg = 0;
sd->avgPriceSecondLeg = 0;
sd->firstLegSide = mutrade::Side_SELL;
sd->secondLegSide = mutrade::Side_BUY;
sd->bidPlaced = false;
sd->firstLegMode = 1;
sd->secondLegMode = -1;
sd->orderPriceFirstLeg = 0;
sd->qty = 0;
sd->firstLegOrder = new mutrade::Order();
sd->secondLegOrder = new mutrade::Order();
sd->filledQtyFirstLeg = 0;
sd->filledQtySecondLeg = 0;
sd->isOrderPending = false;
}
void FormtwoLegStrategy::on_pushButton_clicked()
{
ui->comboBox1LSymbol->clear();
ui->comboBox2LSymbol->clear();
foreach(QString symbol,mutrade::ProcessApiResponses::getInstance()->getLoadedInstrumentList() )
{
ui->comboBox1LSymbol->addItem(symbol);
ui->comboBox2LSymbol->addItem(symbol);
}
}
void FormtwoLegStrategy::on_pushButtonStart_clicked()
{
ui->pushButtonStart->setEnabled(false);
ui->pushButtonStop->setEnabled(true);
initStrategy();
sd->firstLegSymbol = ui->comboBox1LSymbol->currentText().toStdString();
sd->secondLegSymbol = ui->comboBox2LSymbol->currentText().toStdString();
sd->minProfit = ui->doubleSpinBoxMinProfit->value()*100;
sd->avgPriceFirstLeg = 0;
sd->avgPriceSecondLeg = 0;
sd->firstLegSide = ui->comboBox1LSide->currentIndex()==1
?
mutrade::Side_SELL
:
mutrade::Side_BUY
;
sd->secondLegSide = ui->comboBox2LSide->currentIndex()==1
?
mutrade::Side_SELL
:
mutrade::Side_BUY
;
sd->bidPlaced = false;
sd->firstLegMode = ui->comboBox1LSide->currentIndex()==1
?
1:
-1;
sd->secondLegMode = ui->comboBox1LSide->currentIndex()==1
?
1:
-1;
sd->orderPriceFirstLeg = 0;
sd->qty = ui->spinBoxLots->value();
sd->firstLegOrder = new mutrade::Order();
sd->secondLegOrder = new mutrade::Order();
sd->filledQtyFirstLeg = 0;
sd->filledQtySecondLeg = 0;
sd->isOrderPending = false;
mutrade::TestStrategy::getInstance()->startStrategy(sd);
}
void FormtwoLegStrategy::on_pushButtonStop_clicked()
{
mutrade::TestStrategy::getInstance()->stopStrategy();
ui->pushButtonStart->setEnabled(true);
ui->pushButtonStop->setEnabled(false);
}
| [
"lenovo@ubuntu.ubuntu-domain"
] | lenovo@ubuntu.ubuntu-domain |
0613dff04f921e969447fdce9290ce3edf104979 | 3ceb9d6e2cbdacbe7d2dadefa8ed14772d7e7da4 | /T11/11-1.cpp | 7a0028b7bc1511b06d0f2a36d64afb8d6f23b4a5 | [] | no_license | forgotton-wind/CPP | 2daa52110cd8cbb4c4a955ddbd0297578ca4ee38 | 8b138c9bf1a4a506913f7c8204fbe4faa0cfba65 | refs/heads/master | 2022-11-14T10:09:21.243292 | 2020-07-04T09:51:56 | 2020-07-04T09:51:56 | 254,782,979 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 658 | cpp | #include <iostream>
using namespace std;
class A {
public:
int a;
A(int ta, int tb, int tc) :a(ta), b(tb), c(tc) {}
void show() { cout << "A::a = " << a << " A::b = " << b << " A::c = " << c << endl; }
protected:
int b;
private:
int c;
};
class B {
public:
int a;
B(int ta, int tb, int tc) :a(ta), b(tb), c(tc) {}
void show() { cout << "B::a = " << a << " B::b = " << b << " B::c = " << c << endl; }
protected:
int b;
private:
int c;
};
class C :public A, public B {
public:
C(int a1, int b1, int c1, int a2, int b2, int c2) :A(a1, b1, c1), B(a2, b2, c2) {}
};
int main()
{
C c(1, 2, 3, 4, 5, 6);
c.A::show();
c.B::show();
return 0;
} | [
"forgotton.wind@gmail.com"
] | forgotton.wind@gmail.com |
e82cc19333f23773f7530e2163f2f659992863f7 | 9d0c22c1491f42e3f3949b51381fb86560d8d8bd | /src/common/cmmobj/buf/SmartBuffer.cpp | 2a88388da3a0605c57c5b85044bf90219ac9ee1f | [] | no_license | Morgan-Gan/Perception_CPP | 9db1ab935e0be01bec46fd0c237672b25374662b | 67a3d86cb58f5e116b5793173a2c051c12f1cc89 | refs/heads/master | 2023-01-02T19:18:53.574955 | 2020-10-31T08:06:09 | 2020-10-31T08:06:09 | 277,734,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,655 | cpp | #include "SmartBuffer.h"
using namespace common_cmmobj;
CSmartBuffer::CSmartBuffer( int step_size /*1024*/ )
{
memset( &m_Data, 0, sizeof(m_Data) );
m_Data.step_size = step_size;
}
CSmartBuffer::CSmartBuffer( int allocated_size, int step_size /*1024*/ )
{
memset( &m_Data, 0, sizeof(m_Data) );
m_Data.step_size = step_size;
m_Data.allocated_size = allocated_size;
m_Data.buffer = new char[ allocated_size ];
memset( m_Data.buffer, 0, m_Data.allocated_size );
}
CSmartBuffer::CSmartBuffer( const CSmartBuffer& copy )
{
memcpy( &m_Data, ©.m_Data, sizeof(m_Data) );
m_Data.buffer = new char[ m_Data.allocated_size ];
memcpy( m_Data.buffer, copy.m_Data.buffer, m_Data.allocated_size );
}
CSmartBuffer::~CSmartBuffer()
{
if ( m_Data.buffer != NULL )
{
delete[] m_Data.buffer;
m_Data.buffer = NULL;
}
}
const char* CSmartBuffer::append( const char* buf, int len )
{
if ( m_Data.data_size + len > m_Data.allocated_size )
{
int new_allocated_size = m_Data.data_size + len + m_Data.step_size;
char* temp_buffer = new char[ new_allocated_size ];
memset( temp_buffer, 0, new_allocated_size );
if ( m_Data.data_size > 0 )
{
memcpy( temp_buffer, m_Data.buffer, m_Data.data_size );
}
if ( m_Data.buffer != NULL )
{
delete[] m_Data.buffer;
}
m_Data.buffer = temp_buffer;
m_Data.allocated_size = new_allocated_size;
}
memcpy( m_Data.buffer + m_Data.data_size, buf, len );
m_Data.data_size += len;
return m_Data.buffer;
}
const char* CSmartBuffer::append( const char single )
{
return append( &single, 1 );
}
const char* CSmartBuffer::append( const CSmartBuffer& buffer )
{
return append( buffer.data(), buffer.length() );
}
int CSmartBuffer::length() const
{
return m_Data.data_size;
}
const char* CSmartBuffer::data() const
{
return m_Data.buffer;
}
const char* CSmartBuffer::data( const char* buf, int len )
{
empty();
return append( buf, len );
}
void CSmartBuffer::empty()
{
if(NULL != m_Data.buffer)
{
delete []m_Data.buffer;
m_Data.buffer = NULL;
}
m_Data.allocated_size = 0;
m_Data.data_size = 0;
}
bool CSmartBuffer::isEmpty() const
{
return m_Data.data_size == 0;
}
// += operator. Maps to append
CSmartBuffer& CSmartBuffer::operator += (const char * suffix)
{
append( suffix, strlen(suffix) );
return *this;
}
// += operator. Maps to append
CSmartBuffer& CSmartBuffer::operator += (char single)
{
append( &single, 1 );
return *this;
}
// += operator. Maps to append
CSmartBuffer& CSmartBuffer::operator += (const CSmartBuffer& src)
{
append( src.data(), src.length() );
return *this;
}
// = operator. Map to copy construct
CSmartBuffer& CSmartBuffer::operator = (const CSmartBuffer& copy )
{
data( copy.data(), copy.length() );
return *this;
}
// = operator. Map to copy construct
CSmartBuffer& CSmartBuffer::operator = (const char single )
{
data( &single, 1 );
return *this;
}
int CSmartBuffer::find ( const void* data, int length, int from_index /* = 0 */ )
{
if ( (length <= 0) || (from_index >= m_Data.data_size) || (length > m_Data.data_size) )
{
return Error;
}
int search_depth = m_Data.data_size - length;
const char* search_for = (const char*) data;
for ( int i = from_index; i <= search_depth; i++ )
{
if ( search_for[ 0 ] != m_Data.buffer[ i ] )
{
continue;
}
if ( memcmp(search_for, m_Data.buffer + i, length ) == 0 )
{
return i;
}
}
return Error;
}
int CSmartBuffer::find (char& value)
{
for (int i = 0; i < m_Data.data_size; i++)
{
if (value == m_Data.buffer[i])
{
return i;
}
}
return -1;
}
void CSmartBuffer::truncate( int length )
{
if ( m_Data.data_size < length )
{
empty();
return;
}
int left = m_Data.data_size - length;
memcpy( m_Data.buffer, m_Data.buffer + length, left );
m_Data.data_size = left;
}
void CSmartBuffer::substr(int nStartIndex,int nEndIndex)
{
if(0 > nStartIndex || 0 > nEndIndex || nEndIndex < nStartIndex)
{
return;
}
int nLen = nEndIndex - nStartIndex + 1;
if(m_Data.data_size > nLen)
{
memcpy(m_Data.buffer,m_Data.buffer + nStartIndex,nLen);
int right = m_Data.data_size - nLen;
if(0 < right)
{
memset(m_Data.buffer + nLen,0,right);
}
m_Data.data_size = nLen;
}
}
void CSmartBuffer::ends()
{
char string_end = '\0';
append( &string_end, 1 );
}
void CSmartBuffer::endl()
{
char string_end_line = '\n';
append( &string_end_line, 1 );
}
bool CSmartBuffer::at( char& value, int index )
{
if ( (index < 0) || (m_Data.data_size <= index) )
{
return false;
}
value = m_Data.buffer[ index ];
return true;
}
| [
"2545732723@qq.com"
] | 2545732723@qq.com |
a17b436cd27ea4a93f716c21befb9e8198d28ade | 72d9009d19e92b721d5cc0e8f8045e1145921130 | /heuristicsmineR/inst/testfiles/count_precedence_lifecycle/count_precedence_lifecycle_DeepState_TestHarness.cpp | b494e63bd4b1b516d3753640513c86617894b03f | [] | no_license | akhikolla/TestedPackages-NoIssues | be46c49c0836b3f0cf60e247087089868adf7a62 | eb8d498cc132def615c090941bc172e17fdce267 | refs/heads/master | 2023-03-01T09:10:17.227119 | 2021-01-25T19:44:44 | 2021-01-25T19:44:44 | 332,027,727 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,688 | cpp | // AUTOMATICALLY GENERATED BY RCPPDEEPSTATE PLEASE DO NOT EDIT BY HAND, INSTEAD EDIT
// count_precedence_lifecycle_DeepState_TestHarness_generation.cpp and count_precedence_lifecycle_DeepState_TestHarness_checks.cpp
#include <fstream>
#include <RInside.h>
#include <iostream>
#include <RcppDeepState.h>
#include <qs.h>
#include <DeepState.hpp>
DataFrame count_precedence_lifecycle(CharacterVector cases, IntegerVector activities, IntegerVector lifecycle);
TEST(heuristicsmineR_deepstate_test,count_precedence_lifecycle_test){
RInside R;
std::cout << "input starts" << std::endl;
CharacterVector cases = RcppDeepState_CharacterVector();
qs::c_qsave(cases,"/home/akhila/fuzzer_packages/fuzzedpackages/heuristicsmineR/inst/testfiles/count_precedence_lifecycle/inputs/cases.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "cases values: "<< cases << std::endl;
IntegerVector activities = RcppDeepState_IntegerVector();
qs::c_qsave(activities,"/home/akhila/fuzzer_packages/fuzzedpackages/heuristicsmineR/inst/testfiles/count_precedence_lifecycle/inputs/activities.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "activities values: "<< activities << std::endl;
IntegerVector lifecycle = RcppDeepState_IntegerVector();
qs::c_qsave(lifecycle,"/home/akhila/fuzzer_packages/fuzzedpackages/heuristicsmineR/inst/testfiles/count_precedence_lifecycle/inputs/lifecycle.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "lifecycle values: "<< lifecycle << std::endl;
std::cout << "input ends" << std::endl;
try{
count_precedence_lifecycle(cases,activities,lifecycle);
}
catch(Rcpp::exception& e){
std::cout<<"Exception Handled"<<std::endl;
}
}
| [
"akhilakollasrinu424jf@gmail.com"
] | akhilakollasrinu424jf@gmail.com |
922141506532e6e3e17900071cf0727afaa06418 | 334558bf31b6a8fd3caaf09c24898ff331c7e2da | /GenieWindow/plugins/genie_module/src/inc/Interface/IPropertyListener.h | cf738351d930c6bdbdea059cdcf064b64bbe9849 | [] | no_license | roygaogit/Bigit_Genie | e38bac558e81d9966ec6efbdeef0a7e2592156a7 | 936a56154a5f933b1e9c049ee044d76ff1d6d4db | refs/heads/master | 2020-03-31T04:20:04.177461 | 2013-12-09T03:38:15 | 2013-12-09T03:38:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 418 | h | #ifndef IPROPERTYLISTENER
#define IPROPERTYLISTENER
#include <QObject>
class IPropertyListener
{
public:
/**
* Indicates that a property has changed.
*
* @param source the object whose property has changed
* @param propId the id of the property which has changed; property ids
* are generally defined as constants on the source class
*/
virtual void propertyChanged(QObject* source, int propId)=0;
};
#endif | [
"raylq@qq.com"
] | raylq@qq.com |
27c54d29ff53dd5473b4a7ff4ecf555944721ecb | 50c43898c5e561f2469d118073100c305ee7a35b | /test/vertex_range_eg.cpp | bad50410e1daabfecbe9970831b45dd8db99c445 | [
"BSD-3-Clause"
] | permissive | pnnl/NWGraph | a6d1171b188c4e5547cd63f43de1ec2a2584cedc | 977cb839d1d2fc05fe0f5315b243fc79baf7a424 | refs/heads/master | 2023-08-23T00:05:09.626250 | 2023-03-23T05:46:13 | 2023-03-23T05:46:13 | 440,329,946 | 78 | 7 | NOASSERTION | 2023-04-09T05:05:46 | 2021-12-20T23:06:22 | C++ | UTF-8 | C++ | false | false | 1,321 | cpp | /**
* @file vertex_range_eg.cpp
*
* @copyright SPDX-FileCopyrightText: 2022 Battelle Memorial Institute
* @copyright SPDX-FileCopyrightText: 2022 University of Washington
*
* SPDX-License-Identifier: BSD-3-Clause
*
* @authors
* Tony Liu
*
*/
#include <iostream>
#include <queue>
#include "nwgraph/adaptors/vertex_range.hpp"
#include "nwgraph/adaptors/edge_range.hpp"
#include "nwgraph/containers/compressed.hpp"
#include "nwgraph/edge_list.hpp"
#include "nwgraph/io/mmio.hpp"
using namespace nw::graph;
using namespace nw::util;
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " adj.mmio" << std::endl;
return -1;
}
auto aos_a = read_mm<directedness::directed>(argv[1]);
adjacency<0> A(aos_a);
using vertex_id_type = vertex_id_t<adjacency<0>>;
vertex_id_type max = A.size();
std::for_each(counting_iterator<vertex_id_type>(0), counting_iterator<vertex_id_type>(max), [](auto i) {
std::cout << i << " ";
});
std::cout << std::endl;
for (auto& i : vertex_range<adjacency<0>>(A.size()))
std::cout << i << " ";
std::cout << std::endl;
auto range = vertex_range<adjacency<0>>(A.size());
std::for_each(range.begin(), range.end(), [](auto i) {
std::cout << i << " ";
});
std::cout << std::endl;
return 0;
}
| [
"xu.liu2@wsu.edu"
] | xu.liu2@wsu.edu |
d4c7c1e3a0e12df47106bfdbb6a43cd8ff90ccfd | 6953ba98fa153dfd717373de0297768d3489b2b9 | /ZoyeeStudioDesignModel/Decorate/decorator.hpp | ef6b58109584f4ac8b86b0751e698c9413bfe00e | [] | no_license | cnsuhao/ZoyeeStudio | dfbad9788b61b44f88bb9ebd1f10d88010a49ce4 | f557b532ec3c541905df57819c1773d6f661d387 | refs/heads/master | 2021-08-23T14:20:50.915373 | 2017-11-02T09:44:05 | 2017-11-02T09:44:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 678 | hpp | #ifndef __DECORATOR_H__
#define __DECORATOR_H__
#include "player.hpp"
class IDecorator
{
public:
IDecorator(MediaPlayer* pMediaPlayer){
this->pMediaPlayer = pMediaPlayer;
};
virtual void BeforePlay(){};
protected:
MediaPlayer* pMediaPlayer;
};
class PlayAdv : public IDecorator
{
public:
PlayAdv(MediaPlayer* pPlayer) : IDecorator(pPlayer){ };
void BeforePlay(){
printf("Play a advertisement\n");
pMediaPlayer->Play();
};
};
class PlayCopyright : public IDecorator
{
public:
PlayCopyright(MediaPlayer* pPlayer) : IDecorator(pPlayer){ };
void BeforePlay(){
printf("Play a copyright\n");
pMediaPlayer->Play();
}
};
#endif | [
"fatezhou@1f32d0c8-6060-4c7c-b718-6400a953a10a"
] | fatezhou@1f32d0c8-6060-4c7c-b718-6400a953a10a |
4407a0422edb4f15f31af4bad4190e61a032efcb | 700dde126f7320eff85539ca25dfdc8bc18146da | /src/yukino/env.h | 20c5d4e68746a689298fac27ecebe60f2bfef325 | [
"BSD-2-Clause"
] | permissive | YukinoDB/YukinoDB | feb1718cc42c51fec79b256512e0e5a28cd2c900 | 74be184d7e2adae4d070f11bcbabdac5697705b7 | refs/heads/master | 2021-01-21T21:48:30.225604 | 2016-05-17T02:27:04 | 2016-05-17T02:27:04 | 23,211,585 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,093 | h | #ifndef YUKINO_API_ENV_H_
#define YUKINO_API_ENV_H_
#include "base/status.h"
#include "base/base.h"
#include <string>
#include <vector>
namespace yukino {
namespace base {
class Writer;
class AppendFile;
class FileIO;
class MappedMemory;
class FileLock;
} // namespace base
class Env : public base::DisableCopyAssign {
public:
Env() { }
virtual ~Env();
// Return a default environment suitable for the current operating
// system. Sophisticated users may wish to provide their own Env
// implementation instead of relying on this default environment.
//
// The result of Default() belongs to leveldb and must never be deleted.
static Env* Default();
// Create an object that writes to a new file with the specified
// name. Deletes any existing file with the same name and creates a
// new file. On success, stores a pointer to the new file in
// *result and returns OK. On failure stores NULL in *result and
// returns non-OK.
//
// The returned file will only be accessed by one thread at a time.
virtual base::Status CreateAppendFile(const std::string &fname,
base::AppendFile **file) = 0;
// Create an object that writes to a new file with the specified
// name. Deletes any existing file with the same name and creates a
// new file. On success, stores a pointer to the new file in
// *result and returns OK. On failure stores NULL in *result and
// returns non-OK.
//
// The returned file will only be accessed by one thread at a time.
virtual base::Status CreateFileIO(const std::string &fname,
base::FileIO **file) = 0;
// Create a brand new random access read-only file with the
// specified name. On success, stores a pointer to the new file in
// *result and returns OK. On failure stores NULL in *result and
// returns non-OK. If the file does not exist, returns a non-OK
// status.
//
// The returned file may be concurrently accessed by multiple threads.
virtual base::Status CreateRandomAccessFile(const std::string &fname,
base::MappedMemory **file) = 0;
// Returns true iff the named file exists.
virtual bool FileExists(const std::string& fname) = 0;
// Delete the named file or directory.
virtual base::Status DeleteFile(const std::string& fname, bool deep) = 0;
// Store in *result the names of the children of the specified directory.
// The names are relative to "dir".
// Original contents of *results are dropped.
virtual base::Status GetChildren(const std::string& dir,
std::vector<std::string>* result) = 0;
// Create the specified directory.
virtual base::Status CreateDir(const std::string& dirname) = 0;
// Store the size of fname in *file_size.
virtual base::Status GetFileSize(const std::string& fname,
uint64_t* file_size) = 0;
// Rename file src to target.
virtual base::Status RenameFile(const std::string& src,
const std::string& target) = 0;
// Lock the specified file. Used to prevent concurrent access to
// the same db by multiple processes. On failure, stores NULL in
// *lock and returns non-OK.
//
// On success, stores a pointer to the object that represents the
// acquired lock in *lock and returns OK. The caller should call
// UnlockFile(*lock) to release the lock. If the process exits,
// the lock will be automatically released.
//
// If somebody else already holds the lock, finishes immediately
// with a failure. I.e., this call does not wait for existing locks
// to go away.
//
// May create the named file if it does not already exist.
virtual base::Status LockFile(const std::string& fname,
base::FileLock** lock) = 0;
}; // class Env
} // namespace yukino
#endif // YUKINO_API_ENV_H_
| [
"cjvoid@gmail.com"
] | cjvoid@gmail.com |
3328af55fc482572cf5279bec7faa164e0be46dd | ed637a6ceece8ff5ecad8987fc6b813cd56c6dac | /Cyphox/Cypher.h | 33bc708d325101b2b55695c40fc955125c2ee0b9 | [
"Apache-2.0"
] | permissive | Mike430/Cyphox | 4861c7a3d5da192624b580507c0b3318dcf5fa1e | 7fd5f1f1bbb1fafc765d4a816fc4452ed2e9f5a4 | refs/heads/master | 2021-01-21T14:16:41.596392 | 2017-09-11T15:52:05 | 2017-09-11T15:52:05 | 95,260,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 317 | h | #pragma once
#include <iostream>
#include <string>
using namespace std;
class Cypher
{
protected:
static const string DecryptionErrorMSG;
public:
Cypher();
~Cypher();
virtual string Encrypt( uint64_t seed, string decMsg ) = 0;
virtual string Decrypt( uint64_t seed, string encMsg ) = 0;
};
| [
"ymike2045@gmail.com"
] | ymike2045@gmail.com |
14a1f65ea9a0defc53df092079310538b4e27fd1 | a3a116b0a5af335b27b76c6e0b1c1cf82dbc1816 | /Part 6 - Arrays, Vectors, Matrices, Collections/Array_Basics.cpp | c58345ec9fc87c47334540e559da042919d63566 | [
"MIT"
] | permissive | rudrajit1729/CPP-Learning-Course | cbbec93e1d007159e8a3d262e4e1b5e83393f1e7 | 3c39b2f31b10b5e8dfd3214f924c6d8af021dc94 | refs/heads/master | 2022-05-22T10:40:40.005894 | 2020-04-29T12:42:04 | 2020-04-29T12:42:04 | 259,903,793 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 676 | cpp | #include<iostream>
using namespace std;
void print_array(int ar[], int size)
{
//cout<<sizeof(ar)/sizeof(ar[0])<<endl;//Doesnt know the size
for(int i =0;i < size; i++)//Printing elements of array
cout<<ar[i]<<"\t";
}
int main()
{
int ar[] ={1,2,3,4,5};
/* Ways to declare arrays
int ar[size];
int ar[]={elements,.....};
*/
int size = sizeof(ar)/sizeof(ar[0]);
//for(int i =0; i < size; i++)// The Default elements are 0 when some are elements are defined and garbage value when nothing is defined
// cout<<ar[i]<<"\t";
cout<<size<<endl;
print_array(ar,size); //Passing array to a function
} | [
"noreply@github.com"
] | noreply@github.com |
3782a32334f6803d0ee3575e37f3a84a77fb6144 | 44b10c15d61fd8c7fa5a5ad773ca9aebffab2009 | /external/FreeImage/Examples/Generic/CloneMultiPage.cpp | 2124998136f97ad381fa6e35c46ffec291696eac | [
"GPL-2.0-only",
"GPL-3.0-only",
"FreeImage",
"MIT"
] | permissive | falichs/Depixelizing-Pixel-Art-on-GPUs | 804fb324368d2a87a741541d4908ab2a8b7412d0 | ac7f42f978d7a0ba1a11a4668af4a187f64714fd | refs/heads/master | 2023-07-06T11:32:17.643344 | 2023-07-04T13:03:24 | 2023-07-04T13:03:24 | 42,049,921 | 72 | 16 | MIT | 2021-01-29T22:41:28 | 2015-09-07T11:45:24 | GLSL | WINDOWS-1250 | C++ | false | false | 3,302 | cpp | // ==========================================================
// Multipage functions demonstration
//
// Design and implementation by
// - Hervé Drolon
//
// This file is part of FreeImage 3
//
// COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
// THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
// OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
// CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
// THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
// SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
// PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// Use at own risk!
// ==========================================================
// This sample shows how to clone a multipage TIFF
//
// Functions used in this sample :
// FreeImage_OpenMultiBitmap, FreeImage_GetPageCount, FreeImage_LockPage,
// FreeImage_AppendPage, FreeImage_UnlockPage, FreeImage_CloseMultiBitmap;
// FreeImage_SetOutputMessage
//
// ==========================================================
#include <iostream.h>
#include <stdio.h>
#include <string.h>
#include "FreeImage.h"
// ----------------------------------------------------------
/**
FreeImage error handler
*/
void MyMessageFunc(FREE_IMAGE_FORMAT fif, const char *message) {
cout << "\n*** " << message << " ***\n";
cout.flush();
}
// ----------------------------------------------------------
bool CloneMultiPage(FREE_IMAGE_FORMAT fif, char *input, char *output, int output_flag) {
BOOL bMemoryCache = TRUE;
// Open src file (read-only, use memory cache)
FIMULTIBITMAP *src = FreeImage_OpenMultiBitmap(fif, input, FALSE, TRUE, bMemoryCache);
if(src) {
// Open dst file (creation, use memory cache)
FIMULTIBITMAP *dst = FreeImage_OpenMultiBitmap(fif, output, TRUE, FALSE, bMemoryCache);
// Get src page count
int count = FreeImage_GetPageCount(src);
// Clone src to dst
for(int page = 0; page < count; page++) {
// Load the bitmap at position 'page'
FIBITMAP *dib = FreeImage_LockPage(src, page);
if(dib) {
// add a new bitmap to dst
FreeImage_AppendPage(dst, dib);
// Unload the bitmap (do not apply any change to src)
FreeImage_UnlockPage(src, dib, FALSE);
}
}
// Close src
FreeImage_CloseMultiBitmap(src, 0);
// Save and close dst
FreeImage_CloseMultiBitmap(dst, output_flag);
return true;
}
return false;
}
int
main(int argc, char *argv[]) {
char *input_filename = "images\\input.tif";
char *output_filename = "images\\clone.tif";
// call this ONLY when linking with FreeImage as a static library
#ifdef FREEIMAGE_LIB
FreeImage_Initialise();
#endif // FREEIMAGE_LIB
// initialize our own FreeImage error handler
FreeImage_SetOutputMessage(MyMessageFunc);
// Copy 'input.tif' to 'clone.tif'
CloneMultiPage(FIF_TIFF, input_filename, output_filename, 0);
// call this ONLY when linking with FreeImage as a static library
#ifdef FREEIMAGE_LIB
FreeImage_DeInitialise();
#endif // FREEIMAGE_LIB
return 0;
}
| [
"falichs@gmail.com"
] | falichs@gmail.com |
3b28a7fe8131f8d045274fcee7aaa8a650572c55 | e0e50fcb9fb59167964e6897aa7b70e3d6d39e42 | /yandex-cpp-02-yellow/w02/test_rational.cpp | d895f9a020785ff083d576e5e8f05e9c2fa7af43 | [] | no_license | chlos/yandex-cpp | b90bfbdbec6641cf01229e2ac7f1b149384e7152 | 1f84ccbbd848b3850bb1ad61772cc7dfa2e0e7d1 | refs/heads/master | 2020-07-30T10:24:35.509552 | 2019-11-06T10:22:21 | 2019-11-06T10:22:21 | 210,191,601 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,434 | cpp | #include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
template <class T>
ostream& operator << (ostream& os, const vector<T>& s) {
os << "{";
bool first = true;
for (const auto& x : s) {
if (!first) {
os << ", ";
}
first = false;
os << x;
}
return os << "}";
}
template <class T>
ostream& operator << (ostream& os, const set<T>& s) {
os << "{";
bool first = true;
for (const auto& x : s) {
if (!first) {
os << ", ";
}
first = false;
os << x;
}
return os << "}";
}
template <class K, class V>
ostream& operator << (ostream& os, const map<K, V>& m) {
os << "{";
bool first = true;
for (const auto& kv : m) {
if (!first) {
os << ", ";
}
first = false;
os << kv.first << ": " << kv.second;
}
return os << "}";
}
template<class T, class U>
void AssertEqual(const T& t, const U& u, const string& hint = {}) {
if (t != u) {
ostringstream os;
os << "Assertion failed: " << t << " != " << u;
if (!hint.empty()) {
os << " hint: " << hint;
}
throw runtime_error(os.str());
}
}
void Assert(bool b, const string& hint) {
AssertEqual(b, true, hint);
}
class TestRunner {
public:
template <class TestFunc>
void RunTest(TestFunc func, const string& test_name) {
try {
func();
cerr << test_name << " OK" << endl;
} catch (exception& e) {
++fail_count;
cerr << test_name << " fail: " << e.what() << endl;
} catch (...) {
++fail_count;
cerr << "Unknown exception caught" << endl;
}
}
~TestRunner() {
if (fail_count > 0) {
cerr << fail_count << " unit tests failed. Terminate" << endl;
exit(1);
}
}
private:
int fail_count = 0;
};
//class Rational {
//public:
// Rational();
// Rational(int numerator, int denominator) {
// }
//
// int Numerator() const {
// }
//
// int Denominator() const {
// }
//};
void TestDefaultNumerator() {
Rational r = {};
AssertEqual(r.Numerator(), 0, "TestDefaultNumerator");
}
void TestDefaultDenominator() {
Rational r = {};
AssertEqual(r.Denominator(), 1, "TestDefaultDenominator");
}
void TestDefaultReduction() {
Rational r = {2, 4};
AssertEqual(r.Numerator(), 1, "TestDefaultReduction: num");
AssertEqual(r.Denominator(), 2, "TestDefaultReduction: denom");
}
void TestNegative() {
Rational r1 = {-1, 2};
AssertEqual(r1.Numerator(), -1, "TestNegative: num: -1/2");
AssertEqual(r1.Denominator(), 2, "TestNegative: denom: -1/2");
Rational r2 = {1, -2};
AssertEqual(r2.Numerator(), -1, "TestNegative: num: 1/-2");
AssertEqual(r2.Denominator(), 2, "TestNegative: denom: 1/-2");
Rational r3 = {-1, -2};
AssertEqual(r3.Numerator(), 1, "TestNegative: num: -1/-2");
AssertEqual(r3.Denominator(), 2, "TestNegative: denom: -1/-2");
}
void TestZero() {
Rational r = {0, 2};
AssertEqual(r.Numerator(), 0, "TestZero: num: 0/2");
AssertEqual(r.Denominator(), 1, "TestZero: denom: 0/2");
}
int main() {
TestRunner runner;
runner.RunTest(TestDefaultNumerator, "Test default numerator");
runner.RunTest(TestDefaultDenominator, "Test default denominator");
runner.RunTest(TestDefaultReduction, "Test default reduction");
runner.RunTest(TestNegative, "Test negative");
runner.RunTest(TestZero, "Test zero");
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
1f27aa63a89a664bc48214400c6e02e366d75e71 | 3efc50ba20499cc9948473ee9ed2ccfce257d79a | /data/others/files/waylandinterface.cpp | b2589cacf8af61f8844ba422db3546e876ff6c16 | [
"Apache-2.0"
] | permissive | arthurherbout/crypto_code_detection | 7e10ed03238278690d2d9acaa90fab73e52bab86 | 3c9ff8a4b2e4d341a069956a6259bf9f731adfc0 | refs/heads/master | 2020-07-29T15:34:31.380731 | 2019-12-20T13:52:39 | 2019-12-20T13:52:39 | 209,857,592 | 9 | 4 | null | 2019-12-20T13:52:42 | 2019-09-20T18:35:35 | C | UTF-8 | C++ | false | false | 11,539 | cpp | /*
* Copyright 2016 Smith AR <audoban@openmailbox.org>
* Michail Vourlakos <mvourlakos@gmail.com>
*
* This file is part of Latte-Dock
*
* Latte-Dock is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* Latte-Dock is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "waylandinterface.h"
#include "dockcorona.h"
#include "dock/dockview.h"
#include "dock/screenedgeghostwindow.h"
#include "../liblattedock/extras.h"
#include <QDebug>
#include <QTimer>
#include <QApplication>
#include <QSignalMapper>
#include <QtX11Extras/QX11Info>
#include <QRasterWindow>
#include <KWindowSystem>
#include <KWindowInfo>
#include <NETWM>
#include <KWayland/Client/surface.h>
using namespace KWayland::Client;
namespace Latte {
class Private::GhostWindow : public QRasterWindow {
Q_OBJECT
public:
GhostWindow(WaylandInterface *waylandInterface)
: m_waylandInterface(waylandInterface) {
setFlags(Qt::FramelessWindowHint
| Qt::WindowStaysOnTopHint
| Qt::NoDropShadowWindowHint
| Qt::WindowDoesNotAcceptFocus);
setupWaylandIntegration();
show();
}
~GhostWindow() {
delete m_shellSurface;
}
void setGeometry(const QRect &rect) {
QWindow::setGeometry(rect);
setMaximumSize(rect.size());
m_shellSurface->setPosition(rect.topLeft());
}
void setupWaylandIntegration() {
using namespace KWayland::Client;
if (m_shellSurface)
return;
Surface *s{Surface::fromWindow(this)};
if (!s)
return;
m_shellSurface = m_waylandInterface->waylandDockCoronaInterface()->createSurface(s, this);
qDebug() << "wayland ghost window surface was created...";
m_shellSurface->setSkipTaskbar(true);
m_shellSurface->setPanelTakesFocus(false);
m_shellSurface->setRole(PlasmaShellSurface::Role::Panel);
m_shellSurface->setPanelBehavior(PlasmaShellSurface::PanelBehavior::AlwaysVisible);
}
KWayland::Client::PlasmaShellSurface *m_shellSurface{nullptr};
WaylandInterface *m_waylandInterface{nullptr};
};
WaylandInterface::WaylandInterface(QObject *parent)
: AbstractWindowInterface(parent)
{
m_corona = qobject_cast<DockCorona *>(parent);
m_activities = new KActivities::Consumer(this);
connect(m_activities.data(), &KActivities::Consumer::currentActivityChanged
, this, &WaylandInterface::currentActivityChanged);
}
WaylandInterface::~WaylandInterface()
{
}
void WaylandInterface::init()
{
}
void WaylandInterface::initWindowManagement(KWayland::Client::PlasmaWindowManagement *windowManagement)
{
m_windowManagement = windowManagement;
connect(m_windowManagement, &PlasmaWindowManagement::windowCreated, this, &WaylandInterface::windowCreatedProxy);
connect(m_windowManagement, &PlasmaWindowManagement::activeWindowChanged, this, [&]() noexcept {
auto w = m_windowManagement->activeWindow();
emit activeWindowChanged(w ? w->internalId() : 0);
}, Qt::QueuedConnection);
}
KWayland::Client::PlasmaShell *WaylandInterface::waylandDockCoronaInterface() const
{
return m_corona->waylandDockCoronaInterface();
}
void WaylandInterface::setDockExtraFlags(QWindow &view)
{
Q_UNUSED(view)
}
void WaylandInterface::setDockStruts(QWindow &view, const QRect &rect , Plasma::Types::Location location)
{
if (!m_ghostWindows.contains(view.winId()))
m_ghostWindows[view.winId()] = new Private::GhostWindow(this);
auto w = m_ghostWindows[view.winId()];
switch (location) {
case Plasma::Types::TopEdge:
case Plasma::Types::BottomEdge:
w->setGeometry({rect.x() + rect.width() / 2, rect.y(), 1, rect.height()});
break;
case Plasma::Types::LeftEdge:
case Plasma::Types::RightEdge:
w->setGeometry({rect.x(), rect.y() + rect.height() / 2, rect.width(), 1});
break;
default:
break;
}
}
void WaylandInterface::setWindowOnActivities(QWindow &window, const QStringList &activities)
{
//! needs to updated to wayland case
// KWindowSystem::setOnActivities(view.winId(), activities);
}
void WaylandInterface::removeDockStruts(QWindow &view) const
{
delete m_ghostWindows.take(view.winId());
}
WindowId WaylandInterface::activeWindow() const
{
if (!m_windowManagement) {
return 0;
}
auto wid = m_windowManagement->activeWindow();
return wid ? wid->internalId() : 0;
}
const std::list<WindowId> &WaylandInterface::windows() const
{
return m_windows;
}
void WaylandInterface::setKeepAbove(const QDialog &dialog, bool above) const
{
if (above) {
KWindowSystem::setState(dialog.winId(), NET::KeepAbove);
} else {
KWindowSystem::clearState(dialog.winId(), NET::KeepAbove);
}
}
void WaylandInterface::skipTaskBar(const QDialog &dialog) const
{
KWindowSystem::setState(dialog.winId(), NET::SkipTaskbar);
}
void WaylandInterface::slideWindow(QWindow &view, AbstractWindowInterface::Slide location) const
{
auto slideLocation = KWindowEffects::NoEdge;
switch (location) {
case Slide::Top:
slideLocation = KWindowEffects::TopEdge;
break;
case Slide::Bottom:
slideLocation = KWindowEffects::BottomEdge;
break;
case Slide::Left:
slideLocation = KWindowEffects::LeftEdge;
break;
case Slide::Right:
slideLocation = KWindowEffects::RightEdge;
break;
default:
break;
}
KWindowEffects::slideWindow(view.winId(), slideLocation, -1);
}
void WaylandInterface::enableBlurBehind(QWindow &view) const
{
KWindowEffects::enableBlurBehind(view.winId());
}
void WaylandInterface::setEdgeStateFor(QWindow *view, bool active) const
{
ScreenEdgeGhostWindow *window = qobject_cast<ScreenEdgeGhostWindow *>(view);
if (!window) {
return;
}
if (window->parentDock()->surface() && window->parentDock()->visibility()
&& (window->parentDock()->visibility()->mode() == Dock::DodgeActive
|| window->parentDock()->visibility()->mode() == Dock::DodgeMaximized
|| window->parentDock()->visibility()->mode() == Dock::DodgeAllWindows
|| window->parentDock()->visibility()->mode() == Dock::AutoHide)) {
if (active) {
window->showWithMask();
window->surface()->requestHideAutoHidingPanel();
} else {
window->hideWithMask();
window->surface()->requestShowAutoHidingPanel();
}
}
}
WindowInfoWrap WaylandInterface::requestInfoActive() const
{
if (!m_windowManagement) {
return {};
}
auto w = m_windowManagement->activeWindow();
if (!w) return {};
WindowInfoWrap winfoWrap;
winfoWrap.setIsValid(true);
winfoWrap.setWid(w->internalId());
winfoWrap.setIsActive(w->isActive());
winfoWrap.setIsMinimized(w->isMinimized());
winfoWrap.setIsMaxVert(w->isMaximized());
winfoWrap.setIsMaxHoriz(w->isMaximized());
winfoWrap.setIsFullscreen(w->isFullscreen());
winfoWrap.setIsShaded(w->isShaded());
winfoWrap.setGeometry(w->geometry());
winfoWrap.setIsKeepAbove(w->isKeepAbove());
return winfoWrap;
}
bool WaylandInterface::isOnCurrentDesktop(WindowId wid) const
{
if (!m_windowManagement) {
return false;
}
auto it = std::find_if(m_windowManagement->windows().constBegin(), m_windowManagement->windows().constEnd(), [&wid](PlasmaWindow * w) noexcept {
return w->isValid() && w->internalId() == wid;
});
//qDebug() << "desktop:" << (it != m_windowManagement->windows().constEnd() ? (*it)->virtualDesktop() : -1) << KWindowSystem::currentDesktop();
//return true;
return it != m_windowManagement->windows().constEnd() && ((*it)->virtualDesktop() == KWindowSystem::currentDesktop() || (*it)->isOnAllDesktops());
}
bool WaylandInterface::isOnCurrentActivity(WindowId wid) const
{
auto it = std::find_if(m_windowManagement->windows().constBegin(), m_windowManagement->windows().constEnd(), [&wid](PlasmaWindow * w) noexcept {
return w->isValid() && w->internalId() == wid;
});
//TODO: Not yet implemented
return it != m_windowManagement->windows().constEnd() && true;
}
WindowInfoWrap WaylandInterface::requestInfo(WindowId wid) const
{
auto it = std::find_if(m_windowManagement->windows().constBegin(), m_windowManagement->windows().constEnd(), [&wid](PlasmaWindow * w) noexcept {
return w->isValid() && w->internalId() == wid;
});
if (it == m_windowManagement->windows().constEnd())
return {};
WindowInfoWrap winfoWrap;
auto w = *it;
if (isValidWindow(w)) {
winfoWrap.setIsValid(true);
winfoWrap.setWid(wid);
winfoWrap.setIsActive(w->isActive());
winfoWrap.setIsMinimized(w->isMinimized());
winfoWrap.setIsMaxVert(w->isMaximized());
winfoWrap.setIsMaxHoriz(w->isMaximized());
winfoWrap.setIsFullscreen(w->isFullscreen());
winfoWrap.setIsShaded(w->isShaded());
winfoWrap.setGeometry(w->geometry());
} else if (w->appId() == QLatin1String("org.kde.plasmashell")) {
winfoWrap.setIsValid(true);
winfoWrap.setIsPlasmaDesktop(true);
winfoWrap.setWid(wid);
}
return winfoWrap;
}
inline bool WaylandInterface::isValidWindow(const KWayland::Client::PlasmaWindow *w) const
{
return w->isValid() && !w->skipTaskbar();
}
void WaylandInterface::windowCreatedProxy(KWayland::Client::PlasmaWindow *w)
{
if (!isValidWindow(w)) return;
if (!mapper) mapper = new QSignalMapper(this);
mapper->setMapping(w, w);
connect(w, &PlasmaWindow::unmapped, this, [ &, win = w]() noexcept {
mapper->removeMappings(win);
m_windows.remove(win->internalId());
emit windowRemoved(win->internalId());
});
connect(w, SIGNAL(activeChanged()), mapper, SLOT(map()));
connect(w, SIGNAL(fullscreenChanged()), mapper, SLOT(map()));
connect(w, SIGNAL(geometryChanged()), mapper, SLOT(map()));
connect(w, SIGNAL(maximizedChanged()), mapper, SLOT(map()));
connect(w, SIGNAL(minimizedChanged()), mapper, SLOT(map()));
connect(w, SIGNAL(shadedChanged()), mapper, SLOT(map()));
connect(w, SIGNAL(skipTaskbarChanged()), mapper, SLOT(map()));
connect(w, SIGNAL(onAllDesktopsChanged()), mapper, SLOT(map()));
connect(w, SIGNAL(virtualDesktopChanged()), mapper, SLOT(map()));
connect(mapper, static_cast<void (QSignalMapper::*)(QObject *)>(&QSignalMapper::mapped)
, this, [&](QObject * w) noexcept {
//qDebug() << "window changed:" << qobject_cast<PlasmaWindow *>(w)->appId();
emit windowChanged(qobject_cast<PlasmaWindow *>(w)->internalId());
});
m_windows.push_back(w->internalId());
emit windowAdded(w->internalId());
}
}
#include "waylandinterface.moc"
| [
"arthurherbout@gmail.com"
] | arthurherbout@gmail.com |
95b3630acb2fd8cc90b05a7f7897f97cae9aa874 | 6d79857585559b15336ee11152702dcee72dee7a | /2104.cpp | 8272294832a4bd427c2768a17917213edcd5a369 | [] | no_license | okuraofvegetable/PKU | 4279464c8b092a5380a81ff873b8150479a1ff78 | 24e067b0cf56b24b4d1c5b47a9f914c9889032e0 | refs/heads/master | 2021-01-19T16:50:55.059054 | 2015-02-23T08:45:36 | 2015-02-23T08:45:36 | 22,372,308 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 973 | cpp | #include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
#define pb push_back
const int B=1000;
int a[100100];
int A[100100];
vector<int> bucket[1005];
int n,q;
int query(int s,int t,int k)
{
int l=-1,r=n-1;
s--;t--;
int L=s/B+1,R=t/B;
while(r-l>1)
{
int mid=(l+r)/2;
int ret=0;
for(int i=L;i<R;i++)ret+=upper_bound(bucket[i].begin(),bucket[i].end(),A[mid])-bucket[i].begin();
if(L>=R)
{
for(int i=s;i<=t;i++)if(a[i]<=A[mid])ret++;
}
else
{
for(int i=s;i<L*B;i++)if(a[i]<=A[mid])ret++;
for(int i=R*B;i<=t;i++)if(a[i]<=A[mid])ret++;
}
if(ret>=k)r=mid;
else l=mid;
}
return A[r];
}
int main()
{
scanf("%d %d",&n,&q);
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
A[i]=a[i];
}
sort(A,A+n);
for(int i=0;i<n;i++)bucket[i/B].pb(a[i]);
for(int i=0;i<n/B;i++)sort(bucket[i].begin(),bucket[i].end());
for(int i=0;i<q;i++)
{
int s,t,k;
scanf("%d %d %d",&s,&t,&k);
printf("%d\n",query(s,t,k));
}
return 0;
}
| [
"shinji@shinji-PC.(none)"
] | shinji@shinji-PC.(none) |
4f6355550e4361136af4a703891678e247d9654b | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14121/function14121_schedule_27/function14121_schedule_27_wrapper.cpp | a73e801ac091d8259e588ca600abc923dcc3107c | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,131 | cpp | #include "Halide.h"
#include "function14121_schedule_27_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(512, 256);
Halide::Buffer<int32_t> buf01(512, 256);
Halide::Buffer<int32_t> buf02(512);
Halide::Buffer<int32_t> buf03(256);
Halide::Buffer<int32_t> buf0(512, 512, 256);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14121_schedule_27(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14121/function14121_schedule_27/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
9543b6b39260a8cb1804e261b1a746d1858d2c56 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_old_new_old_log_940.cpp | 2c6d9e441131204c0cf32fa0c71e365ab9cb34b9 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 80 | cpp | archive_set_error(_a, ARCHIVE_ERRNO_MISC,
"Using external gunzip program"); | [
"993273596@qq.com"
] | 993273596@qq.com |
68d8fa95d58512a7b9c8371730b08a0df56da54d | 40b1f533772e02a1b6b567b2b275dddaae5c167a | /Application.cpp | e3d8d4c736e9511a62f4d7bc81eb9e541d2ae1a8 | [] | no_license | XiaozhenChen/opengl | d49c147eb4040dbe635615c7038b9336e1ec1655 | 1cd1c7ef2b3551cdd89105772011e4fbafe76430 | refs/heads/master | 2020-04-10T03:22:39.033689 | 2018-12-22T16:07:14 | 2018-12-22T16:07:14 | 160,768,349 | 0 | 0 | null | null | null | null | IBM852 | C++ | false | false | 1,897 | cpp | #include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "Renderer.h"
#include "VertexBufferLayout.h"
#include "IndexBuffer.h"
#include "VertexBuffer.h"
#include "VertexArray.h"
#include "Shader.h"
#include "Texture.h"
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "src\vendor\imgui\imgui.h"
#include "src\vendor\imgui\imgui_impl_glfw_gl3.h"
#include "Project1\src\test\TestClearCode.h"
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_COMPAT_PROFILE );
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(960, 540, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
if (glewInit() != GLEW_OK) // #¤╚Ëđwindow ▓┼─▄init
std::cout << "Error glew_ok" << std::endl;
std::cout << glGetString(GL_VERSION) << std::endl;
GLCall(glEnable(GL_BLEND));
GLCall(glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA));
Renderer renderer;
ImGui::CreateContext();
ImGui_ImplGlfwGL3_Init(window, true);
ImGui::StyleColorsDark();
test::TestClearColor test;
while (!glfwWindowShouldClose(window))
{
renderer.Clear();
test.OnUpdate(0.0f);
test.OnRender();
ImGui_ImplGlfwGL3_NewFrame();
test.OnImGuiRender();
ImGui::Render();
ImGui_ImplGlfwGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
ImGui_ImplGlfwGL3_Shutdown();
ImGui::DestroyContext();
// glDeleteProgram(shader);
glfwTerminate();
return 0;
} | [
"littlepearl@hotmail.com"
] | littlepearl@hotmail.com |
1c26c5bd1d345574cad4764f352095839c7b417d | ca835018b4e61c7ac77c106102ece8d6882b2ff2 | /mainwindow.cpp | 9c3f2f4d38e210b1ab4403d560560d6ba8b38b7d | [
"MIT"
] | permissive | Jerry88/testpaint | c979345245fe13ff9065e57d00000c8e31bf8854 | 390146ed1ef00229f05201322fffa025732cd873 | refs/heads/master | 2020-03-27T00:12:20.747881 | 2018-08-21T19:14:38 | 2018-08-21T19:15:19 | 145,603,560 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 974 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(this->ui->actionOpen, SIGNAL(triggered(bool)), this, SLOT(ActionOpen_activated()));
connect(this->ui->actionClose, SIGNAL(triggered(bool)), this, SLOT(ActionClose_activated()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::ActionOpen_activated()
{
QString filename = QFileDialog::getOpenFileName(this, "Open map", QString(), "*.sitx");
if (filename.isEmpty() == false)
{
MapHandle = mapOpenAnyData(filename.utf16());
if (MapHandle == 0)
{
QMessageBox::information(this, "Error open map", QString("Map open failed") + filename, "Ok");
}
}
}
void MainWindow::ActionClose_activated()
{
if (MapHandle)
mapCloseData(MapHandle);
MapHandle = 0;
}
| [
"Jerry88@users.noreply.github.com"
] | Jerry88@users.noreply.github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.