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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
58aa1379708ac1441f3b06f87d036cb1ddd1d1c1 | 6aa9dfba2a7b05f33a042b7b35d5e030ac5e3c65 | /filesearcher.h | 55a3e47233d358be722b1e5e120160d85adec91d | [] | no_license | BabajotaUA/DublicatesDetector | ec6d920f0ad8b28e0bb51e1900976a9db82945b4 | d3aec6ecdd1fae08f5f3fe0a604b37c0afd7f413 | refs/heads/master | 2016-09-15T19:51:04.996094 | 2013-07-09T16:16:20 | 2013-07-09T16:16:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | h | #pragma once
#include <QObject>
class FileSearcher : public QObject
{
Q_OBJECT
public:
explicit FileSearcher(QObject *parent = 0);
virtual ~FileSearcher() {}
QList<QString> getDirectoryList() const;
void setDirectoryList(const QList<QString> &value);
QList<QString> getFileList() const;
void runFileSearch(QList<QString> directories);
private:
QList<QString> directoryList;
QList<QString> fileList;
};
| [
"yfshaolin@gmail.com"
] | yfshaolin@gmail.com |
9cce45dba79e7b20da6689bad23c8ed9e45e4e2b | 62811a1a8c56b10d71f7e857040582b1bf78882c | /3-Computer-Network/lab1-Socket编程/Server/lock.cpp | 09bf7ce0965e39f7b003901d74ad43cd1a3dc376 | [
"MIT"
] | permissive | ftxj/5th-Semester | 9ebbfa10bc0bcd5008ef47bbb7524e81c01963ba | 37410c3497b5392ba74616fe34f7635acca67bae | refs/heads/master | 2021-09-05T13:37:03.185061 | 2018-01-28T09:28:23 | 2018-01-28T09:28:23 | 119,241,213 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 518 | cpp | #include "lock.h"
#include<QFile>
#include <QMessageBox>
#include <QTextCodec>
lock::lock()
{
}
QString lock::encryption(const QString &st){
QByteArray ba = st.toUtf8().toBase64();
QString DataAsString = QTextCodec::codecForMib(106)->toUnicode(ba);
return DataAsString;
}
QString lock::Deciphering(const QString &ds){
QByteArray tt;
tt.append(ds);
QByteArray sb = QByteArray::fromBase64(tt);
QString DataAsString = QTextCodec::codecForMib(106)->toUnicode(sb);
return DataAsString;
}
| [
"932141413@qq.com"
] | 932141413@qq.com |
5c9ad35b47a52254c225c21a29e12b24868e807b | 5ea09a949bdcf7ef5c3ea504fb14751f57d3f328 | /Project2/fish.h | a5af7fa5f7c39a059dde6dbf1110063d108e1b2f | [] | no_license | staatsty/CSE_335 | 0e4600e7748b8a42c057fa2f64947bc4c080aaf7 | 53d32188869a3a58a4b259b974f217ac7df5f588 | refs/heads/master | 2020-04-01T05:48:08.654789 | 2018-10-13T22:45:26 | 2018-10-13T22:45:26 | 152,920,091 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,086 | h | /*
* Derived from Pet base class
*/
/*
* File: Fish.h
* Author: Tyler Staats, Samuel Batali
*
*
*/
#ifndef FISH_H
#define FISH_H
#include <QTableWidget>
#include <string>
#include <iostream>
#include <iomanip>
#include "visitor.h"
#include "pet.h"
using namespace std;
class Fish: public Pet{
public:
Fish(string a,double c,string b, string d, string e):Pet(a,c,b,d),m_Water(e){ //ctor of Fish
};
Fish(const Fish& fish) = default; //copy ctor
Fish& operator=(const Fish& fish) = default; //assign overload
virtual ~Fish(){ //dtor of fish
}
string GetWater()const{ //returns water type
return m_Water;
}
void SetWater(const string& water){ //sets water type
m_Water = water;
}
virtual vector<string> getVec() const{
vector<string> blank_vec;
return blank_vec;
}
void addtotable(QTableWidget* table,int i)const{ //adds fish to given table
QString qstr = QString::fromStdString(m_Name);
QString qstr1 = QString::fromStdString(m_Class);
QString qstr2 = QString::fromStdString(m_Water)+" "+QString::fromStdString(m_Type);
QString qstr3 = QString::number(m_Price);
QTableWidgetItem *itab,*itab1,*itab2,*itab3;
itab = new QTableWidgetItem;
itab1 = new QTableWidgetItem;
itab2 = new QTableWidgetItem;
itab3 = new QTableWidgetItem;
itab->setFlags(itab->flags() & ~Qt::ItemIsEditable);
itab1->setFlags(itab1->flags() & ~Qt::ItemIsEditable);
itab2->setFlags(itab2->flags() & ~Qt::ItemIsEditable);
itab3->setFlags(itab3->flags() & ~Qt::ItemIsEditable);
itab->setText(qstr);
itab1->setText(qstr1);
itab2->setText(qstr2);
itab3->setData(Qt::DisplayRole,m_Price);
table->setItem(i, 0, itab);
table->setItem(i, 1, itab1);
table->setItem(i, 3, itab2);
table->setItem(i, 2, itab3);
}
virtual void Accept(Visitor* v){v->visitFish(this);}
protected:
Fish()=default; //default ctor protected so client cant access
string m_Water;
};
#endif /* FISH_H */
| [
"noreply@github.com"
] | noreply@github.com |
2dbe1251aabda67b791440c00869200432fc056f | a95ecfd2d1d6d01aad3257dba5876b9be4295faf | /Calculator.cpp | ff0ee63a9cadaea75411cf001197ca8eb5751200 | [] | no_license | Revan20911/Calculator | 4877db46a060b5a7edb586461b4c068b1d78de33 | 50fef104044c93974bf109f63ccbff547f12f3d3 | refs/heads/master | 2020-04-26T18:55:06.146135 | 2019-03-04T14:23:57 | 2019-03-04T14:23:57 | 173,759,089 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,025 | cpp | // ConsoleApplication1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
using namespace std;
int add(int num1,int num2);
int sub(int num1,int num2);
int divv(int num1,int num2);
int mul(int num1,int num2);
void calc()
{
int num1, num2;
char op;
cout << "enter a number:";
cin >> num1 >> num2;
cout << "Enter an operator";
cin >> op;
switch(op)
{
case '+':
cout << "Result: " << add(num1, num2);
break;
case '-':
cout << "Result: " << sub(num1, num2);
break;
case '/':
cout << "Result: " << divv(num1, num2);
break;
case '*':
cout << "Result: " << mul(num1, num2);
}
}
int main()
{
calc();
return 0;
}
int add(int num1, int num2) {
return num1 + num2;
}
int sub(int num1, int num2) {
return num1 - num2;
}
int mul(int num1, int num2) {
return num1 * num2;
}
int divv(int num1, int num2) {
return num1 / num2;
}
| [
"noreply@github.com"
] | noreply@github.com |
9c80e00de860f5c4e15e366ed05ad22c11fbf477 | d4d085e130b60726d7167f537856da6820f1c6b4 | /2-algorithms/lca-sparse-matrix.cpp | 8b5f2684edfc7e7d63a998af153ff1dbc430f411 | [] | no_license | RobertYL/USACO | 8962864484e8cdd9eb49d01280ec20f363db879a | b585a98521053fd997bf5051ceb4f42d3cf9984a | refs/heads/master | 2021-10-16T16:27:25.305499 | 2019-02-12T06:25:45 | 2019-02-12T06:25:45 | 109,755,583 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,495 | cpp | #define REP(i, a, b) for (int i = int(a); i < int(b); i++)
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
using namespace std;
int N = 5;
int LOG = 2;
vector<int> tree[1000];
int depth[1000], parent[1000][10];
void addEdge(int n, int m){
tree[n].push_back(m);
tree[m].push_back(n);
}
void dfs(int cur, int prev){
depth[cur] = depth[prev] + 1;
parent[cur][0] = prev;
REP(i, 0, tree[cur].size())
if(tree[cur][i] != prev)
dfs(tree[cur][i], cur);
}
void fillMatrix(){
REP(i, 0, LOG)
REP(j, 1, N+1)
if(parent[j][i - 1] != -1)
parent[j][i] = parent[parent[j][i - 1]][i - 1];
}
int lca(int n, int m){
if(depth[n] < depth[m])
swap(n, m);
int diff = depth[n] - depth[m];
REP(i, 0, LOG)
if((diff>>i)&1)
n = parent[n][i];
if(n == m)
return n;
for(int i = LOG - 1; i >= 0; i--)
if(parent[n][i] != parent[m][i]){
n = parent[n][i];
m = parent[m][i];
}
return parent[n][0];
}
int main(){
memset(parent, -1, sizeof(parent));
addEdge(3, 4);
addEdge(1, 5);
addEdge(4, 2);
addEdge(5, 4);
1
|
5
|
4
|\
3 2
depth[0] = 0;
dfs(1, 0);
fillMatrix();
cout << lca(2, 3) << endl;
cout << lca(5, 2) << endl;
return 0;
}
| [
"rob3rtyl33@gmail.com"
] | rob3rtyl33@gmail.com |
698d6c11c7ca7842bdfb6ff2061aae34ec4f6cc7 | 1270b15e0d93b6686592c6f909f062722c57dcce | /src/MarkEmptyDirs/Api/markemptydirsapi_global.hpp | 0fab01a588f9ff89f353b1aca4ed4314db607698 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | jonnydee/markemptydirs-cpp | 7b951add303345c560054cebd2f6387876118eb5 | b2d9ea2e518fc7bb39e480af6a832749a562ec73 | refs/heads/master | 2021-05-28T09:07:33.781753 | 2014-01-24T21:51:51 | 2014-01-24T21:51:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,019 | hpp | // Copyright 2013-2014 Johann Duscher (a.k.a. Jonny Dee). All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY JOHANN DUSCHER ''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 <COPYRIGHT HOLDER> 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.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Johann Duscher.
#pragma once
#ifndef MARKEMPTYDIRS_API_GLOBAL_HPP
#define MARKEMPTYDIRS_API_GLOBAL_HPP
#include <QtCore/qglobal.h>
#if !defined(MARKEMPTYDIRSAPISTATIC)
# if defined(MARKEMPTYDIRSAPI_LIBRARY)
# define MARKEMPTYDIRSAPISHARED_EXPORT Q_DECL_EXPORT
# else
# define MARKEMPTYDIRSAPISHARED_EXPORT Q_DECL_IMPORT
# endif
#else
# define MARKEMPTYDIRSAPISHARED_EXPORT
#endif
#endif // MARKEMPTYDIRS_API_GLOBAL_HPP
| [
"jonny.dee@gmx.net"
] | jonny.dee@gmx.net |
fb751903116079cb9fda51f4be90d86e0e4a94af | 42b50020d2914500979fe0143dc7b60c94697c15 | /App1/Scripts/CameraInputScript.h | 2308c18fc3e3f0c4becee078d09574bf9223fe6d | [] | no_license | 999eagle/cga | 6eb2bff1f82ead9cfd20afd2009aeb6d33a19118 | 5d8786c46c049e0187001a9449901e60f742c42c | refs/heads/master | 2021-01-19T13:14:50.902182 | 2017-12-15T17:10:59 | 2017-12-15T17:10:59 | 88,075,815 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,606 | h | #pragma once
#include "..\ECS\Components\ScriptComponent.h"
#include "..\ECS\Components\TransformComponent.h"
namespace Scripts
{
class CameraInputScript : public ECS::Components::Script
{
public:
CameraInputScript(GLFWwindow * window)
{
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwGetCursorPos(window, &this->lastX, &this->lastY);
}
void Start()
{
auto entity = this->component->GetEntity();
this->transformComponent = entity->GetComponent<ECS::Components::TransformComponent>();
this->position = this->transformComponent->GetWorldTransform() * glm::vec4(0.f, 0.f, 0.f, 1.f);
}
void FixedUpdate(const AppTime & time) { }
void Update(const AppTime & time)
{
float rotationSpeed = (float)(time.GetElapsedSeconds() * 0.05);
float moveSpeed = (float)(time.GetElapsedSeconds() * 2);
auto window = this->data->GetWindow();
double mouseX, mouseY;
glfwGetCursorPos(window, &mouseX, &mouseY);
float yaw = (float)(mouseX - this->lastX) * rotationSpeed;
float pitch = (float)(mouseY - this->lastY) * rotationSpeed;
pitch = glm::clamp(this->currentPitch + pitch, -this->maxPitch, this->maxPitch) - this->currentPitch;
this->lastX = mouseX;
this->lastY = mouseY;
this->currentPitch += pitch;
this->currentYaw += yaw;
glm::vec3 up = glm::vec3(0.f, 1.f, 0.f);
glm::vec3 forward = glm::rotate(glm::mat4(), -this->currentYaw, up) * glm::vec4(0.f, 0.f, -1.f, 0.f);
glm::vec3 right = glm::cross(forward, up);
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
this->position += forward * moveSpeed;
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
this->position -= forward * moveSpeed;
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
this->position += right * moveSpeed;
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
this->position -= right * moveSpeed;
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
this->position += up * moveSpeed;
if (glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS)
this->position -= up * moveSpeed;
auto newTransform = glm::translate(glm::mat4(), this->position);
newTransform = glm::rotate(newTransform, -this->currentYaw, glm::vec3(0.f, 1.f, 0.f));
newTransform = glm::rotate(newTransform, -this->currentPitch, glm::vec3(1.f, 0.f, 0.f));
this->transformComponent->SetWorldTransform(newTransform);
}
private:
double lastX, lastY;
float currentPitch = 0.f, currentYaw = 0.f;
const float maxPitch = 0.99f * glm::half_pi<float>();
glm::vec3 position;
ECS::Components::TransformComponent * transformComponent;
};
}
| [
"erik@tauchert.de"
] | erik@tauchert.de |
3c2b8e935060f628be8c5f14e66118c1a382cb40 | e4390f57196dfbdb8a8bcc6071464d537f7edf72 | /src/domain/World.cpp | e2bd202c5d7ffd8cc6408048b35610e333a55ef6 | [] | no_license | janpene/RPG_game | 1f2e43db106574a5c4b5a76f7224f7a4887d6f5a | 4da1e4306ba27a5491ac892c5f024d651cf5442f | refs/heads/master | 2023-04-20T11:41:25.758586 | 2021-05-07T18:25:34 | 2021-05-07T18:25:34 | 365,317,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 58 | cpp | //
// Created by 71M3 on 7.5.2021.
//
#include "World.h"
| [
"janpene11@gmail.com"
] | janpene11@gmail.com |
0c3e597db7ee0a12ad85aee9c3ffb53d827c8c92 | 614650a63543180d0d2b5cb12851868e93a0820a | /book.cpp | 09235a2a098c8cd0c27be94f10c116554e576d07 | [] | no_license | LDercher/AVL_tree | 8f81096c33f6d8fb45fc647489ec13db31e77634 | 46abd1f81ab60ae8d66f0909262ac3c2a755f578 | refs/heads/master | 2021-08-31T14:29:39.069312 | 2017-12-21T17:44:00 | 2017-12-21T17:44:00 | 115,031,518 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | cpp | #include "book.hpp"
#include "util.hpp"
Book::Book(int id, std::string name, std::string publisher, int copyCount) {
this->id = id;
this->name = name;
this->publisher = publisher;
this->currentCount = copyCount;
this->totalCount = copyCount;
}
int Book::getId() { return this->id; }
std::string Book::getName() { return this->name; }
std::string Book::getPublisher() { return this->publisher; }
int Book::getCurrentCount() { return this->currentCount; }
void Book::setCurrentCount(int count) { this->currentCount = count; }
int Book::getTotalCount() { return this->totalCount; }
void Book::setTotalCount(int count) { this->totalCount = count; }
| [
"luke.dercher@gmail.com"
] | luke.dercher@gmail.com |
a2107018276a87a74c3ded1c45ee35a718421501 | e6c9769aea608f8adc946e546d5efa80cee8c58b | /include/SSVBloodshed/GUI/Controls/FormBar.hpp | 5bfc5f7e7b416ce587bba7fbafdddce7a6dc9e15 | [
"AFL-3.0",
"AFL-2.1",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | maxlimitz/SSVBloodshed | c49b1dc1c2c78a345e4c446d18256c1eca5def7a | 63800034a0cfa9d61f9406001072b38f1268883a | refs/heads/master | 2021-01-20T00:08:45.777950 | 2016-10-05T23:19:14 | 2016-10-05T23:19:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,098 | hpp | // Copyright (c) 2013-2015 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
#ifndef SSVOB_GUI_CONTROLS_FORMBAR
#define SSVOB_GUI_CONTROLS_FORMBAR
#include "SSVBloodshed/OBCommon.hpp"
#include "SSVBloodshed/GUI/Widget.hpp"
#include "SSVBloodshed/GUI/Controls/Label.hpp"
#include "SSVBloodshed/GUI/Controls/Button.hpp"
#include "SSVBloodshed/GUI/Controls/Strip.hpp"
namespace ob
{
namespace GUI
{
class FormBar : public Widget
{
private:
Strip& wsBtns;
Button& btnClose;
Button& btnMinimize;
Button& btnCollapse;
Label& lblTitle;
public:
FormBar(Context& mContext, std::string mTitle)
: Widget{mContext},
wsBtns(create<Strip>(At::Right, At::Left, At::Left)),
btnClose(wsBtns.create<Button>(
"x", getStyle().getBtnSquareSize())),
btnMinimize(wsBtns.create<Button>(
"_", getStyle().getBtnSquareSize())),
btnCollapse(wsBtns.create<Button>(
"^", getStyle().getBtnSquareSize())),
lblTitle(create<Label>(ssvu::mv(mTitle)))
{
external = true;
setFillColor(sf::Color::Black);
wsBtns.setWidgetOffset(getStyle().outlineThickness);
wsBtns.attach(At::Right, *this, At::Right,
Vec2f{-getStyle().padding, 0.f});
lblTitle.attach(
At::NW, *this, At::NW, Vec2f{0.f, getStyle().padding});
}
inline Button& getBtnClose() const noexcept { return btnClose; }
inline Button& getBtnMinimize() const noexcept
{
return btnMinimize;
}
inline Button& getBtnCollapse() const noexcept
{
return btnCollapse;
}
inline Label& getTitle() noexcept { return lblTitle; }
};
}
}
#endif
| [
"vittorio.romeo@outlook.com"
] | vittorio.romeo@outlook.com |
3a8a6c0fad9136fee2cdf510e09b67ae6000aa69 | be93022a5982f31658793b2ac15243b458f9ea49 | /DecisionTreeClassification/hp0010DTFileWriter.h | 9b6f79c467f687f0a05af59b8466c29fd22cb154 | [] | no_license | haripradhan/DataMiningAlgorithms | 182011c8da87c3c3d51e9f70e90128e6734c0d6d | 7f4eb1bf37ee8e1925652ba3e2282bb96cb3eefc | refs/heads/master | 2021-01-19T08:16:23.277292 | 2013-09-11T00:21:22 | 2013-09-11T00:21:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,161 | h | /* -------------------
** hp0010DTFileWriter.cpp
** Hari Pradhan
** 09/22/2012
** ------------------*/
#ifndef FILEWRITER_H
#define FILEWRITER_H
#include <iostream>
#include <ostream>
#include <fstream>
#include <vector>
#include "hp0010DTParser.h"
using namespace std;
/**FileWriter writes the contents to the file
*/
class FileWriter{
private:
string fileName; //Name of the file
ofstream outStream; //Output stream
public:
//Default Constructor
FileWriter();
//Destructor
~FileWriter(){};
//Opens the specified file
void openFile(string);
//Writes contents to the file
void writeFile(vector< vector<double> >);
//Writes contents to the file along with some header contents
void writeFile(vector< vector<double> >, string);
//Gets line of fixed width
string getLine(int);
//Gets star of fixed width
string getStar(int);
//Gets blank space of fixed width
string getBlankSpace(int);
//Writes decision tree in the file
void writeTree(node *nd,int level);
//Closes the file stream
void closeStream();
//Writes Confusion Matrix in the file
void writeConfusionMatrix(vector<vector<double> >,vector<int>);
};
#endif
| [
"starling.lucky@gmail.com"
] | starling.lucky@gmail.com |
780863cefcb87544b50510d9f98fa6c28194aec6 | fc38a55144a0ad33bd94301e2d06abd65bd2da3c | /thirdparty/cgal/CGAL-4.13/include/CGAL/Modular_arithmetic/Residue_type.h | d2ddb6a8dcc874d1d5234bcc7c6707480f7f112f | [
"LGPL-3.0-only",
"GPL-3.0-only",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"LicenseRef-scancode-free-unknown",
"LGPL-2.0-or-later",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"MIT-0",
"MIT",
"LGPL-3.0-or-later",
"LicenseRef-scancode-warranty-disc... | permissive | bobpepin/dust3d | 20fc2fa4380865bc6376724f0843100accd4b08d | 6dcc6b1675cb49ef3fac4a58845f9c9025aa4c9f | refs/heads/master | 2022-11-30T06:00:10.020207 | 2020-08-09T09:54:29 | 2020-08-09T09:54:29 | 286,051,200 | 0 | 0 | MIT | 2020-08-08T13:45:15 | 2020-08-08T13:45:14 | null | UTF-8 | C++ | false | false | 8,084 | h | // Copyright (c) 2007 INRIA Sophia-Antipolis (France), Max-Planck-Institute
// Saarbruecken (Germany).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org); you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 3 of the License,
// or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
// SPDX-License-Identifier: LGPL-3.0+
//
// Author(s) : Sylvain Pion, Michael Hemmer, Alexander Kobel
#ifndef CGAL_RESIDUE_TYPE_H
#define CGAL_RESIDUE_TYPE_H
#include <CGAL/basic.h>
#include <CGAL/tss.h>
#include <cfloat>
#include <boost/operators.hpp>
namespace CGAL {
class Residue;
Residue operator + (const Residue&);
Residue operator - (const Residue&);
std::ostream& operator << (std::ostream& os, const Residue& p);
std::istream& operator >> (std::istream& is, Residue& p);
/*! \ingroup CGAL_Modular_traits
* \brief This class represents the Field Z mod p.
*
* This class uses the type double for representation.
* Therefore the value of p is restricted to primes less than 2^26.
* By default p is set to 67108859.
*
* It provides the standard operators +,-,*,/ as well as in&output.
*
* \see Modular_traits
*/
class Residue:
boost::ordered_field_operators1< Residue,
boost::ordered_field_operators2< Residue, int > >{
public:
typedef Residue Self;
typedef Residue NT;
private:
static const double& get_static_CST_CUT()
{
static const double CST_CUT = std::ldexp( 3., 51 );
return CST_CUT;
}
static int& prime_int_internal()
{
CGAL_STATIC_THREAD_LOCAL_VARIABLE(int, prime_int, 67111067);
return prime_int;
}
static inline int get_prime_int(){
return prime_int_internal();
}
static double& prime_internal()
{
CGAL_STATIC_THREAD_LOCAL_VARIABLE(double, prime, 67111067.0);
return prime;
}
static inline double get_prime(){
return prime_internal();
}
static double& prime_inv_internal()
{
CGAL_STATIC_THREAD_LOCAL_VARIABLE(double, prime_inv, 0.000000014900672045640400859667452463541);
return prime_inv;
}
static inline double get_prime_inv(){
return prime_inv_internal();
}
/* Quick integer rounding, valid if a<2^51. for double */
static inline
double RES_round (double a){
// call CGAL::Protect_FPU_rounding<true> pfr(CGAL_FE_TONEAREST)
// before using modular arithmetic
CGAL_assertion(FPU_get_cw() == CGAL_FE_TONEAREST);
return ( (a + get_static_CST_CUT()) - get_static_CST_CUT());
}
/* Big modular reduction (e.g. after multiplication) */
static inline
double RES_reduce (double a){
double result = a - get_prime() * RES_round(a * get_prime_inv());
CGAL_postcondition(2*result < get_prime());
CGAL_postcondition(2*result > -get_prime());
return result;
}
/* Little modular reduction (e.g. after a simple addition). */
static inline
double RES_soft_reduce (double a){
double p = get_prime();
double b = 2*a;
return (b>p) ? a-p :
((b<-p) ? a+p : a);
}
/* -a */
static inline
double RES_negate(double a){
return RES_soft_reduce(-a);
}
/* a*b */
static inline
double RES_mul (double a, double b){
double c = a*b;
return RES_reduce(c);
}
/* a+b */
static inline
double RES_add (double a, double b){
double c = a+b;
return RES_soft_reduce(c);
}
/* a^-1, using Bezout (extended Euclidian algorithm). */
static inline
double RES_inv (double ri1){
CGAL_precondition (ri1 != 0.0);
double bi = 0.0;
double bi1 = 1.0;
double ri = get_prime();
double p, tmp, tmp2;
Real_embeddable_traits<double>::Abs double_abs;
while (double_abs(ri1) != 1.0)
{
p = RES_round(ri/ri1);
tmp = bi - p * bi1;
tmp2 = ri - p * ri1;
bi = bi1;
ri = ri1;
bi1 = tmp;
ri1 = tmp2;
};
return ri1 * RES_soft_reduce(bi1); /* Quicker !!!! */
}
/* a/b */
static inline
double RES_div (double a, double b){
return RES_mul(a, RES_inv(b));
}
public:
/*! \brief sets the current prime.
*
* Note that you are going to change a static member!
* \pre p is prime, but we abstained from such a test.
* \pre 0 < p < 2^26
*
*/
static int
set_current_prime(int p){
int old_prime = get_prime_int();
prime_int_internal() = p;
prime_internal() = double(p);
prime_inv_internal() = 1.0 / double(p);
return old_prime;
}
/*! \brief return the current prime. */
static int get_current_prime(){
return get_prime_int();
}
int get_value() const{
CGAL_precondition(2*x_ < get_prime());
CGAL_precondition(2*x_ > -get_prime());
return int(x_);
}
private:
double x_;
public:
//! constructor of Residue, from int
Residue(int n = 0){
x_= RES_reduce(n);
}
//! constructor of Residue, from long
Residue (long n) {
x_= RES_soft_reduce (static_cast< double > (n % get_prime_int()));
}
//! constructor of Residue, from long long
Residue (long long n) {
x_= RES_soft_reduce (static_cast< double > (n % get_prime_int()));
}
//! Access operator for x, \c const
const double& x() const { return x_; }
//! Access operator for x
double& x() { return x_; }
Self& operator += (const Self& p2) {
x() = RES_add(x(),p2.x());
return (*this);
}
Self& operator -= (const Self& p2){
x() = RES_add(x(),RES_negate(p2.x()));
return (*this);
}
Self& operator *= (const Self& p2){
x() = RES_mul(x(),p2.x());
return (*this);
}
Self& operator /= (const Self& p2) {
x() = RES_div(x(),p2.x());
return (*this);
}
//
Self& operator += (int p2) {
x() = RES_add(x(),Residue(p2).x());
return (*this);
}
Self& operator -= (int p2){
x() = RES_add(x(),Residue(-p2).x());
return (*this);
}
Self& operator *= (int p2){
x() = RES_mul(x(),Residue(p2).x());
return (*this);
}
Self& operator /= (int p2) {
x() = RES_div(x(),Residue(p2).x());
return (*this);
}
friend Self operator + (const Self&);
friend Self operator - (const Self&);
};
inline Residue operator + (const Residue& p1)
{ return p1; }
inline Residue operator - (const Residue& p1){
typedef Residue RES;
Residue r;
r.x() = RES::RES_negate(p1.x());
return r;
}
inline bool operator == (const Residue& p1, const Residue& p2)
{ return ( p1.x()==p2.x() ); }
inline bool operator == (const Residue& p1, int p2)
{ return ( p1 == Residue(p2) ); }
inline bool operator < (const Residue& p1, const Residue& p2)
{ return ( p1.x() < p2.x() ); }
inline bool operator < (const Residue& p1, int p2)
{ return ( p1.x() < Residue(p2).x() ); }
// I/O
inline std::ostream& operator << (std::ostream& os, const Residue& p) {
typedef Residue RES;
os <<"("<< int(p.x())<<"%"<<RES::get_current_prime()<<")";
return os;
}
inline std::istream& operator >> (std::istream& is, Residue& p) {
char ch;
int prime;
is >> p.x();
is >> ch; // read the %
is >> prime; // read the prime
CGAL_precondition(prime==Residue::get_current_prime());
return is;
}
} //namespace CGAL
#endif // CGAL_RESIDUE_TYPE_H
| [
"huxingyi@msn.com"
] | huxingyi@msn.com |
8ce0348d1c750de99a76cb0bdcfd8718e7d3c931 | 2f557f60fc609c03fbb42badf2c4f41ef2e60227 | /CommonTools/Utils/interface/RangeObjectPairSelector.h | 7eacdb0b753ed878911a7aa6e08327ce2e6eb11c | [
"Apache-2.0"
] | permissive | CMS-TMTT/cmssw | 91d70fc40a7110832a2ceb2dc08c15b5a299bd3b | 80cb3a25c0d63594fe6455b837f7c3cbe3cf42d7 | refs/heads/TMTT_1060 | 2020-03-24T07:49:39.440996 | 2020-03-04T17:21:36 | 2020-03-04T17:21:36 | 142,576,342 | 3 | 5 | Apache-2.0 | 2019-12-05T21:16:34 | 2018-07-27T12:48:13 | C++ | UTF-8 | C++ | false | false | 745 | h | #ifndef RecoAlgos_RangeObjectPairSelector_h
#define RecoAlgos_RangeObjectPairSelector_h
/* \class RangeObjectPairSelector
*
* \author Luca Lista, INFN
*
* $Id: RangeObjectPairSelector.h,v 1.4 2007/06/18 18:33:54 llista Exp $
*/
template<typename F>
struct RangeObjectPairSelector {
typedef F function;
RangeObjectPairSelector( double min, double max, const F & fun ) :
min_( min ), max_( max ), fun_( fun ) { }
RangeObjectPairSelector( double min, double max ) :
min_( min ), max_( max ), fun_() { }
template<typename T1, typename T2>
bool operator()( const T1 & t1, const T2 & t2 ) const {
double x = fun_( t1, t2 );
return ( min_ <= x && x <= max_ );
}
private:
double min_, max_;
F fun_;
};
#endif
| [
"sha1-73801ca8ca16918e053d407e1ed9c2469728f170@cern.ch"
] | sha1-73801ca8ca16918e053d407e1ed9c2469728f170@cern.ch |
0c14ad8b7f8326875f98f312422382e418d49c21 | 5ac3ae1f74d9a53ef8083387bf594c06690b56da | /TDARecordFile.h | 225714b3802f725bc4a01977c300fa8bff0a19e4 | [] | no_license | MatamorosF3/RecordsFiles | 5dc8e2b4f30998f36d72f3b7d2c1e0f3342d8eb1 | c1226c66bd0411cef970af007134cc655484319a | refs/heads/master | 2020-03-29T12:56:20.435532 | 2014-03-24T15:32:46 | 2014-03-24T15:32:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 501 | h | #ifndef TDARECORDFILE
#define TDARECORDFILE
#include "tdafile.h"
using namespace::std;
class TDARecordFile : public TDAFile
{
public:
TDARecordFile();
~TDARecordFile();
virtual int readrecord(char*,int)=0;
virtual int writerecord(const char*,int ind)=0;
virtual int findrecord(int)=0;
virtual int findrecord(char*,int)=0;
virtual void seek(int)=0;
virtual int tell()=0;
virtual int eraserecord(int)=0;
virtual int updaterecord(const char*,int offset)=0;
};
#endif
| [
"matamorosf3@gmail.com"
] | matamorosf3@gmail.com |
e0610b24857b304f8b31cae68fb90d6324586193 | 970f500658a3dfc7cfdbfd8ac626cd422985f67b | /src/MPEG4LATMAudioRTPSink.cpp | 6075aec7614a73151a21f0853a5c0e0f1736d644 | [] | no_license | jianghaibobo2016/RTSP_CLIENT | 1e214adc56aa3c344803475ffcd39a6ab12d732c | 50ec7bf5bbee3266a906c24302978c777bae9c80 | refs/heads/master | 2020-03-27T13:38:12.034715 | 2018-09-30T06:39:57 | 2018-09-30T06:39:57 | 146,620,149 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,436 | cpp | /*
* MPEG4LATMAudioRTPSink.cpp
*
* Created on: Aug 13, 2018
* Author: jhb
*/
#include "strDup.h"
#include "MPEG4LATMAudioRTPSink.h"
MPEG4LATMAudioRTPSink::MPEG4LATMAudioRTPSink(UsageEnvironment& env,
CommonPlay *cpObj, Groupsock* RTPgs, u_int8_t rtpPayloadFormat,
u_int32_t rtpTimestampFrequency, char const* streamMuxConfigString,
unsigned numChannels, Boolean allowMultipleFramesPerPacket) :
AudioRTPSink(env, cpObj, RTPgs, rtpPayloadFormat, rtpTimestampFrequency,
"MP4A-LATM", numChannels), fStreamMuxConfigString(
strDup(streamMuxConfigString)), fAllowMultipleFramesPerPacket(
allowMultipleFramesPerPacket) {
// Set up the "a=fmtp:" SDP line for this stream:
char const* fmtpFmt = "a=fmtp:%d "
"cpresent=0;config=%s\r\n";
unsigned fmtpFmtSize = strlen(fmtpFmt) + 3 /* max char len */
+ strlen(fStreamMuxConfigString);
char* fmtp = new char[fmtpFmtSize];
sprintf(fmtp, fmtpFmt, rtpPayloadType(), fStreamMuxConfigString);
fFmtpSDPLine = strDup(fmtp);
delete[] fmtp;
}
MPEG4LATMAudioRTPSink::~MPEG4LATMAudioRTPSink() {
delete[] fFmtpSDPLine;
delete[] (char*) fStreamMuxConfigString;
}
MPEG4LATMAudioRTPSink*
MPEG4LATMAudioRTPSink::createNew(UsageEnvironment& env, CommonPlay *cpObj,
Groupsock* RTPgs, u_int8_t rtpPayloadFormat,
u_int32_t rtpTimestampFrequency, char const* streamMuxConfigString,
unsigned numChannels, Boolean allowMultipleFramesPerPacket) {
return new MPEG4LATMAudioRTPSink(env, cpObj, RTPgs, rtpPayloadFormat,
rtpTimestampFrequency, streamMuxConfigString, numChannels,
allowMultipleFramesPerPacket);
}
Boolean MPEG4LATMAudioRTPSink::frameCanAppearAfterPacketStart(
DP_U8 const* /*frameStart*/,
unsigned /*numBytesInFrame*/) const {
return fAllowMultipleFramesPerPacket;
}
void MPEG4LATMAudioRTPSink::doSpecialFrameHandling(unsigned fragmentationOffset,
DP_U8* frameStart, unsigned numBytesInFrame,
struct timeval framePresentationTime, unsigned numRemainingBytes) {
if (numRemainingBytes == 0) {
// This packet contains the last (or only) fragment of the frame.
// Set the RTP 'M' ('marker') bit:
setMarkerBit();
}
// Important: Also call our base class's doSpecialFrameHandling(),
// to set the packet's timestamp:
MultiFramedRTPSink::doSpecialFrameHandling(fragmentationOffset, frameStart,
numBytesInFrame, framePresentationTime, numRemainingBytes);
}
char const* MPEG4LATMAudioRTPSink::auxSDPLine() {
return fFmtpSDPLine;
}
| [
"jianghaibobo2007@126.com"
] | jianghaibobo2007@126.com |
5a746c41dd4552e39dd8c7dd07c6f216c3266c83 | b13b51704390ee6af926a85ab8e7890b6aa8976e | /LRU_Cache.cpp | eadfa51970865429e13fe1b775573eb245603da1 | [] | no_license | kxingit/LeetCode | 7308eb306fe899e3f68a7cf90b43a37da46416cc | a0ef8e5454bd29076b50ffedc5b1720dd7273a9d | refs/heads/master | 2021-01-14T08:03:20.811221 | 2017-03-20T19:25:56 | 2017-03-20T19:25:56 | 35,183,062 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,513 | cpp | /*
* tag
* Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
* get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
* set(key, value) - Set or insert the value if the key is not already present.
* When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
*/
class LRUCache{
public:
struct CacheEntry {
public:
int key;
int value;
CacheEntry(int k, int v) :key(k), value(v) {}
};
LRUCache(int capacity) {
m_capacity = capacity;
}
int get(int key) {
if(m_map.find(key) == m_map.end()) {
return -1;
}
moveToHead(key);
return m_map[key]->value;
}
void set(int key, int value) {
if(m_map.find(key) == m_map.end()) {
CacheEntry newItem(key, value);
if(m_LRU_cache.size() >= m_capacity) {
m_map.erase(m_LRU_cache.back().key);
m_LRU_cache.pop_back();
}
m_LRU_cache.push_front(newItem);
m_map[key] = m_LRU_cache.begin();
return;
}
m_map[key]->value = value;
moveToHead(key);
}
private:
unordered_map<int, list<CacheEntry>::iterator> m_map;
list<CacheEntry> m_LRU_cache;
int m_capacity;
void moveToHead(int key) {
auto updateEntry = *m_map[key];
m_LRU_cache.erase(m_map[key]);
m_LRU_cache.push_front(updateEntry);
m_map[key] = m_LRU_cache.begin();
}
};
| [
"kxin@me.com"
] | kxin@me.com |
8c484a5e26e74d0538f6ecc0654e7b09d181bf09 | bd9d40d0bd8a4759b3db20e10d2dda616a411c48 | /Include/Graphics/DX11/GteDX11Texture1.h | 5dba151efe541a6aef409677c74c2e5548e297ff | [] | no_license | lai3d/GeometricToolsEngine3p16 | d07f909da86e54aa597abd49c57d17981f3dc72f | 50a6096e1b9f021483cf42aaf244587ff9a81f5b | refs/heads/master | 2020-04-01T19:28:22.495042 | 2018-10-18T06:27:05 | 2018-10-18T06:27:05 | 153,555,419 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,249 | h | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2018
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.0.0 (2016/06/19)
#pragma once
#include <Graphics/GteTexture1.h>
#include <Graphics/DX11/GteDX11TextureSingle.h>
namespace gte
{
class GTE_IMPEXP DX11Texture1 : public DX11TextureSingle
{
public:
// Construction.
DX11Texture1(ID3D11Device* device, Texture1 const* texture);
static std::shared_ptr<GEObject> Create(void* device, GraphicsObject const* object);
// Member access.
inline Texture1* GetTexture() const;
inline ID3D11Texture1D* GetDXTexture() const;
private:
// Support for construction.
void CreateStaging(ID3D11Device* device, D3D11_TEXTURE1D_DESC const& tx);
void CreateSRView(ID3D11Device* device, D3D11_TEXTURE1D_DESC const& tx);
void CreateUAView(ID3D11Device* device, D3D11_TEXTURE1D_DESC const& tx);
};
inline Texture1* DX11Texture1::GetTexture() const
{
return static_cast<Texture1*>(mGTObject);
}
inline ID3D11Texture1D* DX11Texture1::GetDXTexture() const
{
return static_cast<ID3D11Texture1D*>(mDXObject);
}
}
| [
"larry@qjt.sg"
] | larry@qjt.sg |
d6609ac5d8b0bd0c2b44abe08642d790f113d00f | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/dom/deprecated/DeepNodeListImpl.hpp | bf703a7d8a0cd27346980792408a6f4ae0b30b53 | [
"Apache-2.0"
] | permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,574 | hpp | #ifndef DeepNodeListImpl_HEADER_GUARD_
#define DeepNodeListImpl_HEADER_GUARD_
/*
* Copyright 1999-2002,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id: DeepNodeListImpl.hpp,v 1.5 2004/09/08 13:55:43 peiyongz Exp $
*/
//
// This file is part of the internal implementation of the C++ XML DOM.
// It should NOT be included or used directly by application programs.
//
// Applications should include the file <xercesc/dom/deprecated/DOM.hpp> for the entire
// DOM API, or DOM_*.hpp for individual DOM classes, where the class
// name is substituded for the *.
//
#include <xercesc/util/XercesDefs.hpp>
#include "NodeListImpl.hpp"
#include "DOMString.hpp"
#include "NodeImpl.hpp"
XERCES_CPP_NAMESPACE_BEGIN
class NodeImpl;
class NodeVector;
class DEPRECATED_DOM_EXPORT DeepNodeListImpl: public NodeListImpl {
private:
NodeImpl *rootNode;
DOMString tagName;
bool matchAll;
int changes;
NodeVector *nodes;
//DOM Level 2
DOMString namespaceURI;
bool matchAllURI;
bool matchURIandTagname; //match both namespaceURI and tagName
public:
DeepNodeListImpl(NodeImpl *rootNode, const DOMString &tagName);
DeepNodeListImpl(NodeImpl *rootNode, //DOM Level 2
const DOMString &namespaceURI, const DOMString &localName);
virtual ~DeepNodeListImpl();
virtual unsigned int getLength();
virtual NodeImpl *item(unsigned int index);
// -----------------------------------------------------------------------
// Notification that lazy data has been deleted
// -----------------------------------------------------------------------
static void reinitDeepNodeListImpl();
private:
virtual NodeImpl *nextMatchingElementAfter(NodeImpl *current);
virtual void unreferenced();
};
XERCES_CPP_NAMESPACE_END
#endif
| [
"aburke@bitflood.org"
] | aburke@bitflood.org |
de0634e5bf2ebaff4cb0fe3b7842d48ab6a1bc1c | d24fdcbb7da3c74d49399a154ff66e88564fa4bb | /Laba2/Laba2/Laba2.cpp | dbf4d0f2f75fe959f450f5953f8ff706403b3291 | [] | no_license | Nazyrick/OAP_2 | 57e180686821049b0feee8efb659ce31fe288162 | 28c4902f36317b47d143c60e00a3513b858c9828 | refs/heads/master | 2021-05-18T04:42:50.435310 | 2020-03-31T19:30:27 | 2020-03-31T19:30:27 | 251,112,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | cpp | // Скопировать из файла F1 в файл F2 все строки, в которых есть слова,
// совпадающие с первым словом.
// Определить количество согласных букв в последней строке файла F2.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
setlocale(LC_ALL, "Russian");
/*ifstream in("f1.txt");
ofstream out("f2.txt");
string line, firstWord, word ;
while (getline(in, line))
{
stringstream ss(line);
bool hasEquals = false;
ss >> firstWord;
while (ss >> word)
{
if (word == firstWord)
{
hasEquals = true;
break;
}
}
if (hasEquals) out << line << endl;
}
string consonants("bcdfghjklmnpqrstvwxz");
int consCount = 0;
for (auto it = line.begin(); it != line.end(); it++)
if (consonants.find(*it) != string::npos)
consCount++;
cout << "Количество согласных букв: " << consCount;
in.close();
out.close();
return 0;*/
char a[255];
char simvol;
int j = 0;
cout << "Введите стороку" << endl;
cin >> a ;
ofstream out("number2.txt");
out << a;
out.close();
ifstream in("number2.txt");
in >> a;
in.close();
cout << "Введите искомый символ: ";
cin >> simvol;
for (int i = 0; a[i] != '\0'; i++)
{
if (a[i] == simvol)
{
j++;
}
}
cout << "Символ " << simvol << " встречается " << j << " раз." << endl;
return 0;
}
| [
"ulasevich_nazar@mail.ru"
] | ulasevich_nazar@mail.ru |
a7f6100ebfac6a5561d5d9d224a746b3c6fb02c1 | 4d20bc226477d3ce2a82f17eb4c5d78e7adb59ef | /Source/Platform/FileDirectory.cpp | e76ba016379d37e823e730a0a89f73bf5dac6f6b | [] | no_license | destinydai/Chaos | 82150a3e3cd77c4e2d93ad4cc5c8e87af0da6414 | 17baa4db5b918bafbb90eb829479fc9c0b76057b | refs/heads/master | 2016-09-01T19:26:11.299398 | 2013-04-24T10:45:03 | 2013-04-25T03:01:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | cpp | #include "stdafx.h"
NS_CH_BEG
FileDirectory::FileDirectory( const string &szPath):
m_szDirectoryPath(szPath)
{
if(m_szDirectoryPath.size()==0)
{
CH_ERROR("[pl] szPath length is zero.");
return;
}
if(m_szDirectoryPath[m_szDirectoryPath.size()-1]!='/')
{
m_szDirectoryPath.push_back('/');
}
}
FileDirectory::~FileDirectory( void )
{
}
const char* FileDirectory::GetDirectoryPath()
{
return &m_szDirectoryPath[0];
}
NS_CH_END | [
"dairba@qq.com"
] | dairba@qq.com |
277eb439d25aec4150c069a80f71b2e12c8cf8e3 | c36f0407b9199e7d859e98acfc4f30f1e790eba1 | /ImageProcessingUsingResultTable/ImageProcessingSolarization.cpp | 543e3073e37ec72b6e8383d3776a7b25ff3eaaa2 | [] | no_license | astrowidow/ImageProcessing | 03eb27962ddad90ff60dd9326d7c89d5a8b15265 | 2ff5c48f241fedf9355cf2601a3499c7bc1ae823 | refs/heads/master | 2020-03-28T14:35:09.123979 | 2018-11-05T13:20:52 | 2018-11-05T13:20:52 | 148,501,686 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 967 | cpp | //
// Created by 俵京佑 on 2018/10/22.
//
#include "ImageProcessingSolarization.h"
ImageProcessingSolarization::ImageProcessingSolarization
(Image* src_image,
Image* dst_image,
double wave_num)
: ImageProcessingUsingResultTable(src_image,
dst_image),
wave_num(wave_num)
{
double wave_width = (double)BYTE_MAX/wave_num;
double saw_width = wave_width/2;
int j;
double result_temp;
for(int i = 0; i < EIGHT_BITS_GRADATION_NUM; i++){
j = i%(int)wave_width;
if(j <= saw_width) {
result_temp = (double)(j * BYTE_MAX) / saw_width;
}
else{
result_temp = -((j - wave_width)*BYTE_MAX)/saw_width;
}
result_temp > BYTE_MAX ? result_temp = BYTE_MAX : result_temp;
result_temp < 0 ? result_temp = 0 : result_temp;
result_table[i] = (BYTE) result_temp;
}
} | [
"astrowidow@gmail.com"
] | astrowidow@gmail.com |
cf957a523b27b335395c7ad09b0691de57707632 | 387549ab27d89668e656771a19c09637612d57ed | /DRGLib UE project/Source/FSD/Private/FSDAudioComponent.cpp | e4661783f14197b3f9e3c02ad8c990109d14076b | [
"MIT"
] | permissive | SamsDRGMods/DRGLib | 3b7285488ef98b7b22ab4e00fec64a4c3fb6a30a | 76f17bc76dd376f0d0aa09400ac8cb4daad34ade | refs/heads/main | 2023-07-03T10:37:47.196444 | 2023-04-07T23:18:54 | 2023-04-07T23:18:54 | 383,509,787 | 16 | 5 | MIT | 2023-04-07T23:18:55 | 2021-07-06T15:08:14 | C++ | UTF-8 | C++ | false | false | 78 | cpp | #include "FSDAudioComponent.h"
UFSDAudioComponent::UFSDAudioComponent() {
}
| [
"samamstar@gmail.com"
] | samamstar@gmail.com |
23460b7fd419afb300ae31c9b2623bba0ed1beb8 | 5f85bc10ebeebab64e670b6be98d9f1946b3b28b | /main.cpp | 7367d8a0347591655437b8df5f0aa020279a3bf0 | [
"MIT"
] | permissive | pengge/RPAutoBuild | bee871213ff11cdc499bf7e09f32ed22b5887a31 | 00a5e7abf57f561547745479cffeb7b0705cdcbd | refs/heads/master | 2023-08-05T22:57:46.105812 | 2021-09-28T07:22:33 | 2021-09-28T07:22:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,700 | cpp | #include "rpauto.h"
#include "configman.h"
namespace fs = std::filesystem;
//uint8_t flags = 0b00000000;
int main(int argc, char** argv)
{
RPAutoManager* manager;
std::string cloneName = "";
std::string autofile = "";
if (argc < 2 || argc > 5)
{
std::cout << "Invalid Repo" << std::endl << "USAGE:" << std::endl << "autobuild (<git link> || (<directory> --local )) [-f] [<autofile>] " << std::endl;
exit(2);
}
if(argc > 4)
{
for(int i = 3; i < argc; i++)
{
if(Cstrcmp(argv[i],"-f"))
{
if(i+1 >= argc)
{
std::cout << "Invalid '-f'" << std::endl;
std::cout << "Invalid Repo" << std::endl << "USAGE:" << std::endl << "autobuild (<git link> || (<directory> --local )) [-f] [<autofile>] " << std::endl;
exit(2);
}
autofile = argv[i+1];
std::cout << "Using custom config at: " << autofile << std::endl;
}
}
}
if (Cstrcmp(argv[2], "--local"))
{
try{
//cloneName = GetRepoNameFromLink(argv[1]);
cloneName = argv[1];
}
catch(LinkParseException e)
{
std::cout << e.what() << std::endl;
exit(e.GetCode());
}
//manager = new RPAutoManager(cloneName);
}
else
{
//Usafe
std::string gitRepo = std::string(argv[1]);
if(gitRepo.find('&') != std::string::npos)
{
exit(0xFF0000FF); //We can't have a '&' in our input
}
std::string commandString = "git clone --recurse-submodules --remote-submodules " + gitRepo;
int err = system(commandString.c_str());
if (err != 0)
{
std::cout << "Could not clone " << argv[1] << std::endl;
exit(1);
}
std::string cloneName = "";
try{
cloneName = GetRepoNameFromLink(argv[1]);
}
catch(LinkParseException e)
{
std::cout << e.what() << std::endl;
exit(e.GetCode());
}
//manager = new RPAutoManager(cloneName);
}
if(autofile != "")
{
manager = new RPAutoManager(cloneName,autofile);
}
else
{
manager = new RPAutoManager(cloneName);
}
manager->ParseConfig();
if(!manager->ValidateTargets())
{
std::cout << "Failed to validate targets" << std::endl;
exit(1);
}
std::cout << TERMINAL_COLOR_GREEN << "Parse successful!" << TERMINAL_COLOR_RESET << std::endl;
manager->Build();
delete manager;
return 0;
}
| [
"antonr@live.dk"
] | antonr@live.dk |
26d8ce90ea67e790e23cbc2dda01b110b4f8dfb9 | 6c0e8ace1b3993cca54c096c28d013474e38a552 | /caffe-master/include/caffe/solver.hpp | 31084a5ce9c04c045390894e90514d811c7a4e19 | [
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause"
] | permissive | BarCodeReader/HRSOD | 4d408c94abf21c5888ddc928b38fd323884ba33b | 166e6d7f433277c1f55c08d145732b7219f675e5 | refs/heads/master | 2022-04-19T04:23:58.784934 | 2020-04-19T08:23:28 | 2020-04-19T08:23:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,720 | hpp | #ifndef CAFFE_SOLVER_HPP_
#define CAFFE_SOLVER_HPP_
#include <boost/function.hpp>
#include <string>
#include <vector>
#include "caffe/net.hpp"
#include "caffe/solver_factory.hpp"
namespace caffe {
/**
* @brief Enumeration of actions that a client of the Solver may request by
* implementing the Solver's action request function, which a
* a client may optionally provide in order to request early termination
* or saving a snapshot without exiting. In the executable caffe, this
* mechanism is used to allow the snapshot to be saved when stopping
* execution with a SIGINT (Ctrl-C).
*/
namespace SolverAction {
enum Enum {
NONE = 0, // Take no special action.
STOP = 1, // Stop training. snapshot_after_train controls whether a
// snapshot is created.
SNAPSHOT = 2 // Take a snapshot, and keep training.
};
}
/**
* @brief Type of a function that returns a Solver Action enumeration.
*/
typedef boost::function<SolverAction::Enum()> ActionCallback;
/**
* @brief An interface for classes that perform optimization on Net%s.
*
* Requires implementation of ApplyUpdate to compute a parameter update
* given the current state of the Net parameters.
*/
template <typename Dtype>
class Solver {
public:
explicit Solver(const SolverParameter& param,
const Solver* root_solver = NULL);
explicit Solver(const string& param_file, const Solver* root_solver = NULL);
void Init(const SolverParameter& param);
void InitTrainNet();
void InitTestNets();
// Client of the Solver optionally may call this in order to set the function
// that the solver uses to see what action it should take (e.g. snapshot or
// exit training early).
void SetActionFunction(ActionCallback func);
SolverAction::Enum GetRequestedAction();
// The main entry of the solver function. In default, iter will be zero. Pass
// in a non-zero iter number to resume training for a pre-trained net.
virtual void Solve(const char* resume_file = NULL);
inline void Solve(const string resume_file) { Solve(resume_file.c_str()); }
void Step(int iters);
// The Restore method simply dispatches to one of the
// RestoreSolverStateFrom___ protected methods. You should implement these
// methods to restore the state from the appropriate snapshot type.
void Restore(const char* resume_file);
// The Solver::Snapshot function implements the basic snapshotting utility
// that stores the learned net. You should implement the SnapshotSolverState()
// function that produces a SolverState protocol buffer that needs to be
// written to disk together with the learned net.
void Snapshot();
virtual ~Solver() {}
inline const SolverParameter& param() const { return param_; }
inline shared_ptr<Net<Dtype> > net() { return net_; }
inline const vector<shared_ptr<Net<Dtype> > >& test_nets() {
return test_nets_;
}
int iter() { return iter_; }
virtual void MatCaffeApplyUpdate() {};
virtual void MatCaffeSnapshot(const string& solver_name, const string& model_filename) {}
// Invoked at specific points during an iteration
class Callback {
protected:
virtual void on_start() = 0;
virtual void on_gradients_ready() = 0;
template <typename T>
friend class Solver;
};
const vector<Callback*>& callbacks() const { return callbacks_; }
void add_callback(Callback* value) {
callbacks_.push_back(value);
}
void CheckSnapshotWritePermissions();
/**
* @brief Returns the solver type.
*/
virtual inline const char* type() const { return ""; }
protected:
// Make and apply the update value for the current iteration.
virtual void ApplyUpdate() = 0;
string SnapshotFilename(const string extension);
string SnapshotToBinaryProto();
string SnapshotToHDF5();
// The test routine
void TestAll();
void Test(const int test_net_id = 0);
virtual void SnapshotSolverState(const string& model_filename) = 0;
virtual void RestoreSolverStateFromHDF5(const string& state_file) = 0;
virtual void RestoreSolverStateFromBinaryProto(const string& state_file) = 0;
void DisplayOutputBlobs(const int net_id);
void UpdateSmoothedLoss(Dtype loss, int start_iter, int average_loss);
virtual void UpdateSmooth() {}
SolverParameter param_;
int iter_;
int current_step_;
shared_ptr<Net<Dtype> > net_;
vector<shared_ptr<Net<Dtype> > > test_nets_;
vector<Callback*> callbacks_;
vector<Dtype> losses_;
Dtype smoothed_loss_;
// The root solver that holds root nets (actually containing shared layers)
// in data parallelism
const Solver* const root_solver_;
// A function that can be set by a client of the Solver to provide indication
// that it wants a snapshot saved and/or to exit early.
ActionCallback action_request_function_;
// True iff a request to stop early was received.
bool requested_early_exit_;
DISABLE_COPY_AND_ASSIGN(Solver);
};
/**
* @brief Solver that only computes gradients, used as worker
* for multi-GPU training.
*/
template <typename Dtype>
class WorkerSolver : public Solver<Dtype> {
public:
explicit WorkerSolver(const SolverParameter& param,
const Solver<Dtype>* root_solver = NULL)
: Solver<Dtype>(param, root_solver) {}
protected:
void ApplyUpdate() {}
void SnapshotSolverState(const string& model_filename) {
LOG(FATAL) << "Should not be called on worker solver.";
}
void RestoreSolverStateFromBinaryProto(const string& state_file) {
LOG(FATAL) << "Should not be called on worker solver.";
}
void RestoreSolverStateFromHDF5(const string& state_file) {
LOG(FATAL) << "Should not be called on worker solver.";
}
};
} // namespace caffe
#endif // CAFFE_SOLVER_HPP_
| [
"yi94code"
] | yi94code |
06ffadd45e58b37ccbfdebc790f44f826178a8fe | d3954d4770f72f6d8b1704b0c508903d6f74f0f5 | /graphics/skia_utility.c++ | 8b39cdfbe1a18d9bd7bda5f0536a06daa2e45ebf | [
"MIT"
] | permissive | skui-org/skui | 83b0779c63c9332e86f4e9e2f1f02ceb7aba501f | f04d74d1938f053dc876e85ae469a711ed2edbc5 | refs/heads/master | 2022-01-31T08:21:45.375334 | 2022-01-21T15:24:51 | 2022-01-21T15:24:51 | 85,348,438 | 382 | 57 | MIT | 2022-01-01T01:29:57 | 2017-03-17T19:37:28 | C++ | UTF-8 | C++ | false | false | 1,528 | /**
* The MIT License (MIT)
*
* Copyright © 2017-2020 Ruben Van Boxem
*
* 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 "graphics/skia_utility.h++"
namespace skui::graphics
{
template<>
SkPoint convert_to<SkPoint, scalar_position>(const scalar_position& position)
{
return SkPoint::Make(position.x, position.y);
}
template<>
SkColor convert_to<SkColor, color>(const color& color)
{
return SkColorSetARGB(color.alpha, color.red, color.green, color.blue);
}
}
| [
"vanboxem.ruben@gmail.com"
] | vanboxem.ruben@gmail.com | |
65bc20b6cf87c0e8ba5cee5fb028851b667960e3 | 5f1d38514f4b5fc113fb7a7e4c53e1325a936229 | /tools/map_maker/osm_converter/src/OsmJunctionProcessor.cpp | b4878157fea66109214d110bb17a309836d8c192 | [
"MIT"
] | permissive | sm-azure/map | 71b230263d1bbf0235e5ba286a46fc75dca11b06 | d950a21b79d052b0d6c90395511172afc1ad528b | refs/heads/master | 2021-01-15T06:06:23.974735 | 2020-01-27T15:12:03 | 2020-01-28T07:55:16 | 242,896,964 | 0 | 0 | null | 2020-02-25T03:05:22 | 2020-02-25T03:05:21 | null | UTF-8 | C++ | false | false | 18,814 | cpp | // ----------------- BEGIN LICENSE BLOCK ---------------------------------
//
// INTEL CONFIDENTIAL
//
// Copyright (c) 2017-2019 Intel Corporation
//
// This software and the related documents are Intel copyrighted materials, and
// your use of them is governed by the express license under which they were
// provided to you (License). Unless the License provides otherwise, you may not
// use, modify, copy, publish, distribute, disclose or transmit this software or
// the related documents without Intel's prior written permission.
//
// This software and the related documents are provided as is, with no express or
// implied warranties, other than those that are expressly stated in the License.
//
// ----------------- END LICENSE BLOCK -----------------------------------
#include "ad/map/maker/osm_converter/OsmJunctionProcessor.hpp"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
#include <osmium/osm/node.hpp>
#include <osmium/osm/way.hpp>
#pragma GCC diagnostic pop
#include <ad/map/maker/common/LogChannel.hpp>
#include <ad/map/maker/common/LogFactory.hpp>
#include <ad/map/maker/common/StringHelper.hpp>
#include "ad/map/maker/osm_converter/OsmHighwayType.hpp"
#include "ad/map/maker/osm_converter/OsmObjectStore.hpp"
#include "ad/map/maker/osm_converter/OsmWayIterator.hpp"
#include "ad/map/maker/osm_converter/PointStore.hpp"
namespace ad {
namespace map {
namespace maker {
namespace osm_converter {
OsmJunctionProcessor::OsmJunctionProcessor(common::LogFactory &logFactory, std::shared_ptr<OsmObjectStore> store)
: mLog(logFactory.logChannel("OsmJunctionProcessor"))
, mStore(store)
{
}
void OsmJunctionProcessor::setDefaultPriority(common::RightOfWay const rightOfWay)
{
mDefaultPriority = rightOfWay;
}
void OsmJunctionProcessor::extractJunctions()
{
mJunctionArms.clear();
for (auto wayId : mStore->allWayIds())
{
::osmium::Way const &way = mStore->way(wayId);
mLog(common::LogLevel::Info) << "Processing way: " << wayId << "\n";
// we assume that a way has at least two nodes
for (uint32_t index = 1u; index < way.nodes().size(); ++index)
{
// way.nodes()[index] is the center, index-1 leads into it
OsmJunctionArm in;
in.mArmId = way.nodes()[index - 1u].ref();
in.mCenterId = way.nodes()[index].ref();
in.mIndexOfCenter = index;
in.mIncoming = true;
in.mWayId = wayId;
mJunctionArms[way.nodes()[index].ref()].insert(in);
// way.nodes()[index-1] is the center, index leads out of it
OsmJunctionArm out;
out.mArmId = way.nodes()[index].ref();
out.mCenterId = way.nodes()[index - 1].ref();
out.mIndexOfCenter = index - 1;
out.mIncoming = false;
out.mWayId = wayId;
mJunctionArms[way.nodes()[index - 1].ref()].insert(out);
}
}
compileListOfJunctionCenters();
extractRightOfWay();
if (mLog.willLogBeWrittenAtLevel(common::LogLevel::Verbose))
{
for (auto entry : mJunctionArms)
{
logJunction(entry.first);
}
}
}
bool OsmJunctionProcessor::isJunctionCenter(::osmium::object_id_type const nodeId) const
{
if (mJunctionArms.count(nodeId) < 1)
{
return false;
}
if (mJunctionArms.at(nodeId).size() < 2)
{
return false;
}
if (mJunctionArms.at(nodeId).size() > 2)
{
return true;
}
auto it = mJunctionArms.at(nodeId).begin();
OsmJunctionArm const &arm1 = *(it);
++it;
OsmJunctionArm const &arm2 = *(it);
if (arm1.mIncoming != arm2.mIncoming)
{
return false;
}
if (mLog.willLogBeWrittenAtLevel(common::LogLevel::Verbose))
{
std::string reason{"end"};
if (arm1.mIncoming)
{
reason = "start";
}
mLog(common::LogLevel::Verbose) << " isJunctionCenter: Two ways " << reason << " at same node: " << nodeId << "\n";
}
return true;
}
bool OsmJunctionProcessor::junctionHasRamp(::osmium::object_id_type const &idOfCenter) const
{
if (!isJunctionCenter(idOfCenter))
{
return false;
}
auto junctionArms = mJunctionArms.at(idOfCenter);
for (auto arm : junctionArms)
{
if (armIsRamp(arm))
{
return true;
}
}
return false;
}
void OsmJunctionProcessor::compileListOfJunctionCenters()
{
mJunctionCenters.clear();
for (auto junctionId : mJunctionArms)
{
if (isJunctionCenter(junctionId.first))
{
mJunctionCenters.insert(junctionId.first);
}
}
}
std::unordered_set<::osmium::object_id_type> OsmJunctionProcessor::allJunctions() const
{
return mJunctionCenters;
}
bool OsmJunctionProcessor::uniqueSuccessorForWay(::osmium::object_id_type const wayId,
::osmium::object_id_type &successor) const
{
::osmium::Way const &way = mStore->way(wayId);
::osmium::object_id_type const &end = way.nodes().back().ref();
if (mJunctionArms.count(end) == 0)
{
return false;
}
if (mJunctionArms.at(end).size() != 2)
{
return false;
}
for (OsmJunctionArm const &entry : mJunctionArms.at(end))
{
::osmium::Way const &otherWay = mStore->way(entry.mWayId);
if (otherWay.nodes().front().ref() == end)
{
successor = entry.mWayId;
return true;
}
}
return false;
}
bool OsmJunctionProcessor::uniquePredecessorForWay(::osmium::object_id_type const wayId,
::osmium::object_id_type &predecessor) const
{
::osmium::Way const &way = mStore->way(wayId);
::osmium::object_id_type const &start = way.nodes().front().ref();
if (mJunctionArms.count(start) == 0)
{
return false;
}
if (mJunctionArms.at(start).size() != 2)
{
return false;
}
for (OsmJunctionArm const &entry : mJunctionArms.at(start))
{
::osmium::Way const &otherWay = mStore->way(entry.mWayId);
if (otherWay.nodes().back().ref() == start)
{
predecessor = entry.mWayId;
return true;
}
}
return false;
}
std::unordered_set<OsmJunctionArm>
OsmJunctionProcessor::junctionArms(::osmium::object_id_type const junctionCenter) const
{
return mJunctionArms.at(junctionCenter);
}
void OsmJunctionProcessor::logJunction(::osmium::object_id_type const junctionCenter)
{
auto entry = mJunctionArms.find(junctionCenter);
mLog(common::LogLevel::Verbose) << "Center: " << entry->first << "\n";
for (OsmJunctionArm const &arm : entry->second)
{
std::string dir = " <-- ";
if (arm.mIncoming)
{
dir = " --> ";
}
mLog(common::LogLevel::Verbose) << dir << arm.mArmId << " (" << arm.mWayId << ")" << dir << arm.mCenterId
<< " right of way: " << rowToString(arm.mRightOfWay) << "\n";
}
}
OsmJunctionArm OsmJunctionProcessor::getOsmArm(::osmium::object_id_type centerNode,
::osmium::object_id_type entryNode) const
{
auto osmJunctionEntries = junctionArms(centerNode);
for (auto osmArm : osmJunctionEntries)
{
if (osmArm.mArmId == entryNode)
{
return osmArm;
}
}
throw std::runtime_error("Unable to extract OsmJunctionArm for center " + std::to_string(centerNode)
+ std::string(" and entry ")
+ std::to_string(entryNode));
}
bool OsmJunctionProcessor::armIsRamp(OsmJunctionArm const &arm) const
{
::osmium::Way const &way = mStore->way(arm.mWayId);
const char *highway = way.tags()["highway"];
if (common::endsWith(highway, "_link"))
{
return true;
}
return false;
}
bool OsmJunctionProcessor::junctionIsOffRamp(::osmium::object_id_type const idOfCenter) const
{
auto junctionArms = mJunctionArms.at(idOfCenter);
for (auto arm : junctionArms)
{
if (armIsRamp(arm) && !arm.mIncoming)
{
return true;
}
}
return false;
}
OsmJunctionArm OsmJunctionProcessor::getRampForJunction(::osmium::object_id_type const idOfCenter) const
{
auto junctionArms = mJunctionArms.at(idOfCenter);
for (auto arm : junctionArms)
{
if (armIsRamp(arm))
{
return arm;
}
}
throw std::runtime_error("Unable to return OsmJunctionArm as ramp " + std::to_string(idOfCenter));
}
bool nodeIsTrafficSign(::osmium::Node const &node, bool isForward, const char *typeOfSign)
{
if (isForward)
{
const char *traffic_sign = node.tags()["traffic_sign"];
if (traffic_sign)
{
return (strstr(traffic_sign, typeOfSign) != nullptr);
}
const char *traffic_sign_forward = node.tags()["traffic_sign:forward"];
if (traffic_sign_forward)
{
return (strstr(traffic_sign_forward, typeOfSign) != nullptr);
}
return false;
}
else
{
const char *traffic_sign_backward = node.tags()["traffic_sign:backward"];
if (traffic_sign_backward)
{
return (strstr(traffic_sign_backward, typeOfSign) != nullptr);
}
return false;
}
}
bool nodeIsGiveWay(::osmium::Node const &node, bool isForward)
{
return nodeIsTrafficSign(node, isForward, "DE:205");
}
bool nodeIsStop(::osmium::Node const &node, bool isForward)
{
return nodeIsTrafficSign(node, isForward, "DE:206");
}
common::RightOfWay OsmJunctionProcessor::getRowDefinedByNode(OsmJunctionArm const &arm,
::osmium::Node const &node) const
{
const char *highway = node.tags()["highway"];
if (!highway)
{
mLog(common::LogLevel::Info) << "Given node " << node.id() << " has no attribute \"highway\".\n";
return common::RightOfWay::Undefined;
}
// check for attribute trafficsign:[forward:backward] = DE:205 (GiveWay) or DE:206 (Stop)
if (strcmp("give_way", highway) == 0)
{
if (nodeIsGiveWay(node, arm.mIncoming))
{
mLog(common::LogLevel::Verbose) << "Given node " << node.id() << " is GiveWay\n";
return common::RightOfWay::GiveWay;
}
mLog(common::LogLevel::Info) << "Given node " << node.id() << " is not GiveWay\n";
}
else if (strcmp("stop", highway) == 0)
{
const char *stop = node.tags()["stop"];
if (bool(stop) && (strcmp("all", stop) == 0))
{
if (nodeIsStop(node, arm.mIncoming))
{
mLog(common::LogLevel::Verbose) << "Given node " << node.id() << " is AllWayStop\n";
return common::RightOfWay::AllWayStop;
}
mLog(common::LogLevel::Info) << "Given node " << node.id() << " is not AllWayStop\n";
}
else
{
if (nodeIsStop(node, arm.mIncoming))
{
mLog(common::LogLevel::Verbose) << "Given node " << node.id() << " is Stop\n";
return common::RightOfWay::Stop;
}
mLog(common::LogLevel::Info) << "Given node " << node.id() << " is not Stop\n";
}
}
return common::RightOfWay::Undefined;
}
common::RightOfWay OsmJunctionProcessor::rowForArm(OsmJunctionArm const &arm) const
{
// extract node
if (!mStore->hasNode(arm.mArmId))
{
mLog(common::LogLevel::Warning) << "Given arm-node " << arm.mArmId << " is not a node! Return Undefined\n";
return common::RightOfWay::Undefined;
}
// get index of arm node within way
int32_t currentIndex = 0;
::osmium::Way const &way = mStore->way(arm.mWayId);
for (uint32_t i = 0; i < way.nodes().size(); i++)
{
if (way.nodes()[i].ref() == arm.mArmId)
{
currentIndex = i;
}
}
int32_t offset = 1;
if (arm.mIncoming)
{
offset = -1;
}
auto currentNodeId = arm.mArmId;
while (!isJunctionCenter(currentNodeId) && mStore->hasNode(currentNodeId))
{
auto const &node = mStore->node(currentNodeId);
auto row = getRowDefinedByNode(arm, node);
if (row != common::RightOfWay::Undefined)
{
mLog(common::LogLevel::Warning) << "Given arm-node " << arm.mArmId << " is " << rowToString(row) << "\n";
return row;
}
// update nodeid
currentIndex += offset;
if ((currentIndex == static_cast<int32_t>(way.nodes().size())) || (currentIndex < 0))
{
// Not really an error, we simply don't know the regulation
mLog(common::LogLevel::Info) << "No traffic regulation found. Reached end of way. Return undefined \n";
return common::RightOfWay::Undefined;
// @todo: change the way to predecessor/successor and continue iteration
// for now iterating over one way should be sufficient
}
currentNodeId = way.nodes()[currentIndex].ref();
}
return common::RightOfWay::Undefined;
}
OsmHighwayType getHighwayType(::osmium::Way const &way)
{
const char *highway = way.tags()["highway"];
if (!highway)
{
return OsmHighwayType::Invalid;
}
return highwayTypeFromString(std::string(highway));
}
void OsmJunctionProcessor::setRightOfWayRamp(::osmium::object_id_type const idOfCenter)
{
std::unordered_set<OsmJunctionArm> arms;
for (auto arm : junctionArms(idOfCenter))
{
auto newArm = arm;
newArm.mRightOfWay = common::RightOfWay::Ramp;
arms.insert(newArm);
}
mJunctionArms[idOfCenter] = arms;
mLog(common::LogLevel::Verbose) << " Detected off-ramp\n";
}
bool OsmJunctionProcessor::setRightOfWayNormalIntersectionFirstPass(::osmium::object_id_type const idOfCenter,
std::unordered_set<OsmJunctionArm> &arms) const
{
bool assignHasWay{false};
common::RightOfWay detectedRule{common::RightOfWay::Undefined};
std::unordered_set<OsmJunctionArm> intermediateArms;
for (auto const &arm : junctionArms(idOfCenter))
{
OsmJunctionArm newArm = arm;
auto regulation = rowForArm(arm);
mLog(common::LogLevel::Verbose) << " junction arm: " << arm.mArmId << " has priority " << rowToString(regulation)
<< "\n";
if ((regulation == common::RightOfWay::GiveWay) || (regulation == common::RightOfWay::Stop)
|| (regulation == common::RightOfWay::AllWayStop))
{
if ((regulation != detectedRule) && (detectedRule != common::RightOfWay::Undefined))
{
mLog(common::LogLevel::Warning) << " Inconsistent right of way for arm/center: " << arm.mArmId << "/"
<< arm.mCenterId << "\n";
}
assignHasWay = true;
detectedRule = regulation;
newArm.mRightOfWay = regulation;
}
// if regulation is undefined, and the arm is an on-ramp (off-ramps are handled elsewhere)
// set regulation for this arm to GiveWay
if (armIsRamp(arm) && (regulation == common::RightOfWay::Undefined))
{
assignHasWay = true;
newArm.mRightOfWay = common::RightOfWay::GiveWay;
}
intermediateArms.insert(newArm);
}
// if there is no traffic regulation detected, check if the connecting arms have different priorities
// provided through the OSM Highway type (primary, secondary, etc.)
if (detectedRule == common::RightOfWay::Undefined)
{
mLog(common::LogLevel::Verbose) << " No traffic rule found for junction " << idOfCenter
<< " Checking now the highway types\n";
// get highest priority of all roads in intersection
OsmHighwayType highwayType = OsmHighwayType::Invalid;
for (auto const &arm : junctionArms(idOfCenter))
{
const auto armHighwayType = getHighwayType(mStore->way(arm.mWayId));
if (highwayType > armHighwayType)
{
highwayType = armHighwayType;
}
}
mLog(common::LogLevel::Verbose) << " Found road with highest priority to be "
<< highwayTypeToString(highwayType) << "\n";
arms.clear();
for (auto const &arm : junctionArms(idOfCenter))
{
OsmJunctionArm newArm = arm;
const auto armHighwayType = getHighwayType(mStore->way(arm.mWayId));
if (highwayType < armHighwayType)
{
newArm.mRightOfWay = common::RightOfWay::GiveWay;
assignHasWay = true;
}
arms.insert(newArm);
mLog(common::LogLevel::Verbose) << " Updating arm " << arm.mArmId << " to have regulation "
<< rowToString(newArm.mRightOfWay) << "\n";
}
}
else
{
arms = intermediateArms;
}
return assignHasWay;
}
void OsmJunctionProcessor::setRightOfWayNormalIntersectionSecondPass(::osmium::object_id_type const idOfCenter,
bool const assignHasWay,
std::unordered_set<OsmJunctionArm> const &input,
std::unordered_set<OsmJunctionArm> &output) const
{
uint32_t numAssignedHasWay{0u};
for (auto &arm : input)
{
OsmJunctionArm newArm = arm;
if (arm.mRightOfWay == common::RightOfWay::Undefined)
{
newArm.mRightOfWay = (assignHasWay ? common::RightOfWay::HasWay : mDefaultPriority);
mLog(common::LogLevel::Verbose) << " adjusting regulation for junction arm: " << newArm.mArmId << " has "
<< rowToString(newArm.mRightOfWay) << "\n";
if (assignHasWay)
{
++numAssignedHasWay;
}
}
output.insert(newArm);
}
if ((numAssignedHasWay > 0) && (numAssignedHasWay != 2))
{
mLog(common::LogLevel::Error) << " Invalid number of arms (" << numAssignedHasWay
<< ") with HasWay for junction center: " << idOfCenter << "\n";
}
}
void OsmJunctionProcessor::setRightOfWayNormalIntersection(::osmium::object_id_type const idOfCenter)
{
// first run, extract all row of all arms and assign to the arms
// this means go over all arms, first check:
// -- if there are traffic rules assigned
// -- if an arm is an on-ramp --> will lead to GiveWay regulation
// -- if the connecting arms have different priorities (i.e. OSM Highway types)
std::unordered_set<OsmJunctionArm> firstFlush;
bool assignHasWay = setRightOfWayNormalIntersectionFirstPass(idOfCenter, firstFlush);
// second run, validity check: either assign HaveWay (if others have GiveWay or Stop) or assign default priority...
std::unordered_set<OsmJunctionArm> secondFlush;
setRightOfWayNormalIntersectionSecondPass(idOfCenter, assignHasWay, firstFlush, secondFlush);
mJunctionArms[idOfCenter] = secondFlush;
}
void OsmJunctionProcessor::extractRightOfWay()
{
mLog(common::LogLevel::Info) << "Setting up right of way for junctions\n";
for (auto const &junctionCenter : allJunctions())
{
mLog(common::LogLevel::Verbose) << " Processing junction center: " << junctionCenter << "\n";
// handle off-ramp intersections in a special way to avoid yielding on straight roads
if (junctionIsOffRamp(junctionCenter))
{
setRightOfWayRamp(junctionCenter);
}
else
{
setRightOfWayNormalIntersection(junctionCenter);
}
}
}
} // namespace osm_converter
} // namespace maker
} // namespace map
} // namespace ad
| [
"johannesquast@users.noreply.github.com"
] | johannesquast@users.noreply.github.com |
18fdaa07d7060a8b569f32e7b4d1c0b4b78ee59d | d0a3ceac982fd8ad5f7f18980eb31dcd51239de2 | /OpenGL/src/dynamics/Solver.cpp | a7d49b723e76145c508cfb56644191d0f6706500 | [] | no_license | apizon/InfoGraph | aa9cebf5980adf950da252198dcb4b4229933076 | b2dd14cfc7ee2a8ee9236f46b44ec0d88c5af8f8 | refs/heads/master | 2021-09-04T19:02:35.786260 | 2018-01-21T12:55:23 | 2018-01-21T12:55:23 | 111,242,656 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 155 | cpp | # include "../../include/dynamics/Solver.hpp"
void Solver::solve( const float& dt, std::vector<ParticlePtr>& particles )
{
do_solve( dt, particles );
}
| [
"pizon.antoine@gmail.com"
] | pizon.antoine@gmail.com |
5d2a01038486bf363ad7b04ca5a9e38aeba091de | f8ea7e042a62404b1f420a7cc84b7c3167191f57 | /SimLib/Median.h | e310f64be790ed640ab88913147481703ecfa859 | [] | no_license | alexbikfalvi/SimNet | 0a22d8bd0668e86bf06bfb72d123767f24248b48 | 20b24e15647db5467a1187f8be5392570023d670 | refs/heads/master | 2016-09-15T17:50:23.459189 | 2013-07-05T14:41:18 | 2013-07-05T14:41:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,090 | h | /*
* Copyright (C) 2011 Alex Bikfalvi
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#pragma once
namespace SimLib
{
class Median
{
public:
Median() { }
virtual ~Median() { }
static double Of(double* data, uint count);
static double Of(double* data, uint begin, uint end);
static double Of(std::vector<double>& data);
static double Of(std::vector<double>& data, uint begin, uint end);
};
}
| [
"alex@bikfalvi.com"
] | alex@bikfalvi.com |
cadc289cf45a08b2c43d8f4aaefe454d9c000393 | 0841c948188711d194835bb19cf0b4dae04a5695 | /gsdm/sources/gsdm/src/netio/unixacceptcmd.cpp | b58ccaf8dc5605b4fdb957aa9c861a84dd9de7da | [] | no_license | gjhbus/sh_project | 0cfd311b7c0e167e098bc4ec010822f1af2d0289 | 1d4d7df4e92cff93aba9d28226d3dbce71639ed6 | refs/heads/master | 2020-06-15T16:11:33.335499 | 2016-06-15T03:41:22 | 2016-06-15T03:41:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 643 | cpp | #include "netio/unixacceptcmd.h"
#include "netio/networker.h"
#include "netio/epoll/unixcarrier.h"
#include "netio/baseworkerex.h"
#include "logging/logger.h"
namespace gsdm {
UNIXAcceptCmd::UNIXAcceptCmd(int fd, const std::string &unix_path)
: BaseCmd(false),fd_(fd),unix_path_(unix_path) {
}
UNIXAcceptCmd::~UNIXAcceptCmd() {
}
bool UNIXAcceptCmd::Process(BaseWorkerEx *ex) {
BaseProcess *process = ex->CreateUNIXProcess(unix_path_);
if ( process ) {
new UNIXCarrier(fd_, ex->worker_->GetIOHandlerManager(), process);
return true;
} else {
WARN("BaseProcess is NULL");
close(fd_);
}
return false;
}
}
| [
"greatmiffa@gmail.com"
] | greatmiffa@gmail.com |
d694bebfd7a209a2e083952216156e881a130987 | 6ea7b412da513c1b0650d490de0e860c278ee9aa | /map-generator.hpp | 610aee6ab7fbabc389ebcee716c87ce19c280b13 | [] | no_license | gurmsc5/A_star-search | 06ce67ef2eeaafc724fe85d40acb278aa8860a9e | 6a47808c7b266c59fcb1de7aba8e3c3e98d98410 | refs/heads/master | 2020-03-17T23:01:30.208546 | 2018-05-21T14:41:45 | 2018-05-21T14:41:45 | 134,028,354 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,750 | hpp | #ifndef MAP_GENERATOR_HPP
#define MAP_GENERATOR_HPP
#include <vector>
#include <utility>
struct Coordinates {
int x, y;
Coordinates(int _x, int _y) :x(_x), y(_y) {};
Coordinates() {};
};
struct Cell {
/*first is x coordinate
second is y coordinate*/
Coordinates parent;
double F, G, H;
/*custom constructor*/
Cell( double f,
double g, double h, Coordinates _parent) : F(f),
G(g), H(h), parent(_parent) {};
Cell() {};
};
/*aliases for better code readability*/
using Pair = std::pair<int, int>;
using CoordinatesVec = std::vector<std::vector<int>>;
using CellVec = std::vector<std::vector<Cell>>;
using Coordinates_List = std::vector<Coordinates>;
class Map_Generator {
private:
/*2D map*/
CoordinatesVec *Map;
std::pair<int, int> Edges;
public:
/*custom constructor that sets the edges of the Map*/
Map_Generator(Pair edges);
~Map_Generator() {
delete Map;
Map = nullptr;
};
/*return a pointer to the constructed Map*/
CoordinatesVec * GetMap() const;
/*set up a blockade given a pair of coordinates
a value of 1 on Map represents a blockade
a value of 0 on Map represents clear passage*/
bool setBlockade_coord(Pair &block, CoordinatesVec &map);
/*set up blockade given a list of coordinates*/
/*returns a failed set of coordinates that were not blocked because of invalid
coordinates*/
Coordinates_List setBlockade_coordlist(Coordinates_List &blockvec, CoordinatesVec &map);
/*check if coordinates are within range
pair.first = x
pair.second = y*/
bool ValidCoordinates(Pair edges) const;
/*get the map edges*/
std::pair<int, int> getEdges() const;
/*check if there is a blocked coordinate on the map*/
bool checkUnblocked(CoordinatesVec *map, Pair coord);
};
#endif // !MAP-GENERATOR_HPP | [
"gurmsc5@vt.edu"
] | gurmsc5@vt.edu |
53078aacb00296c707ecc530c593b4700b99ba73 | 3b13eedb87e6545f832e1c62b8cb05b8428a897b | /src/main/avikodak/prep/company/google/geeksforgeeks/arrays/page16/sortedarraysgeneration.h | 859779afa1716715b38a52d44d71d2bf5ff5320a | [] | no_license | avikodak/algos_v2 | a9c66b2f2b862318f12feb216240a9a66249aa2b | e1c77f1064c83599d0e57f426319ab536a6eeb29 | refs/heads/master | 2021-01-19T20:43:29.366352 | 2017-03-25T17:15:22 | 2017-03-25T17:15:22 | 24,980,353 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,514 | h | /****************************************************************************************************************************************************
* File Name : sortedarraysgeneration.h
* File Location : /algos_v2/src/main/avikodak/prep/company/google/geeksforgeeks/arrays/page16/sortedarraysgeneration.h
* Created on : Mar 21, 2017 :: 9:04:40 PM
* Author : avikodak
* Testing Status : TODO
* URL : TODO
****************************************************************************************************************************************************/
/****************************************************************************************************************************************************/
/* NAMESPACE DECLARATION AND IMPORTS */
/****************************************************************************************************************************************************/
using namespace std;
using namespace __gnu_cxx;
/****************************************************************************************************************************************************/
/* INCLUDES */
/****************************************************************************************************************************************************/
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <numeric>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <hash_map>
#include <stack>
#include <queue>
#include <stdexcept>
#include <limits.h>
#include <stdint.h>
#include <libv2/common/commonincludes.h>
#include <libv2/constants/constants.h>
#include <libv2/ds/commonds.h>
#include <libv2/ds/graphds.h>
#include <libv2/ds/linkedlistds.h>
#include <libv2/ds/mathds.h>
#include <libv2/ds/treeds.h>
#include <libv2/utils/abtreeutil.h>
#include <libv2/utils/arrayutil.h>
#include <libv2/utils/avltreeutil.h>
#include <libv2/utils/bplustreeutil.h>
#include <libv2/utils/bstutil.h>
#include <libv2/utils/btreeutil.h>
#include <libv2/utils/commonutil.h>
#include <libv2/utils/dillutil.h>
#include <libv2/utils/graphutil.h>
#include <libv2/utils/ioutil.h>
#include <libv2/utils/mathutil.h>
#include <libv2/utils/redblacktreeutil.h>
#include <libv2/utils/sillutil.h>
#include <libv2/utils/treeutil.h>
#include <libv2/utils/trieutil.h>
#include <libv2/utils/twofourtreeutil.h>
/****************************************************************************************************************************************************/
/* USER DEFINED CONSTANTS */
/****************************************************************************************************************************************************/
/****************************************************************************************************************************************************/
/* MAIN CODE START */
/****************************************************************************************************************************************************/
#ifndef MAIN_AVIKODAK_PREP_COMPANY_GOOGLE_GEEKSFORGEEKS_ARRAYS_PAGE16_SORTEDARRAYSGENERATION_H_
#define MAIN_AVIKODAK_PREP_COMPANY_GOOGLE_GEEKSFORGEEKS_ARRAYS_PAGE16_SORTEDARRAYSGENERATION_H_
/****************************************************************************************************************************************************/
/* O(LOGN) Algorithm */
/****************************************************************************************************************************************************/
/****************************************************************************************************************************************************/
/* O(N) Algorithm */
/****************************************************************************************************************************************************/
/****************************************************************************************************************************************************/
/* O(N*LOGN) Algorithm */
/****************************************************************************************************************************************************/
/****************************************************************************************************************************************************/
/* O(N^2) Algorithm */
/****************************************************************************************************************************************************/
/****************************************************************************************************************************************************/
/* O(C^N) Algorithm */
/****************************************************************************************************************************************************/
void generateSortedArrays(vector<int> firstInput, vector<int> secondInput, vector<int> result, int firstIndex, int secondIndex, int resultIndex, bool pickFromFirst) {
if (pickFromFirst) {
if (resultIndex > 1) {
for (unsigned int counter = 0; counter < result.size(); counter++) {
printf("%d\t", result[counter]);
}
}
for (unsigned int counter = firstIndex; counter < firstInput.size(); counter++) {
if (resultIndex == 0 || result[resultIndex] < firstInput[firstIndex]) {
result[resultIndex] = firstInput[counter];
generateSortedArrays(firstInput, secondInput, result, counter + 1, secondIndex, resultIndex + 1, !pickFromFirst);
}
}
} else {
for (unsigned int counter = secondIndex; counter < secondInput.size(); counter++) {
if (result[resultIndex] < secondInput[secondIndex]) {
result[resultIndex] = secondInput[counter];
generateSortedArrays(firstInput, secondInput, result, firstIndex, counter + 1, resultIndex + 1, !pickFromFirst);
}
}
}
}
#endif /* MAIN_AVIKODAK_PREP_COMPANY_GOOGLE_GEEKSFORGEEKS_ARRAYS_PAGE16_SORTEDARRAYSGENERATION_H_ */
| [
"avikodak@gmail.com"
] | avikodak@gmail.com |
05867866cffa4ed9b503a25b2a0c379d1213574b | 544a465731b44638ad61a4afa4f341aecf66f3cd | /src/ivkapp/module/RenewalModelerWidget.h | 71bb2b0e0f59b6aedfaffd45ddd26f815cbf46e2 | [] | no_license | skempken/interverdikom | e13cbe592aa6dc5b67d8b2fbb4182bcb2b8bc15b | dde091ee71dc1d88bbedb5162771623f3ab8a6f4 | refs/heads/master | 2020-05-29T15:29:18.076702 | 2014-01-03T10:10:03 | 2014-01-03T10:10:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 797 | h | #ifndef ONESTATEMODELERWIDGET_H_
#define ONESTATEMODELERWIDGET_H_
#include "ModuleWidget.h"
#include "ui_RenewalModelerWidget.h"
#include "ComputationThread.hpp"
#include "data/Trace.h"
#include "computation/RenewalModeler.h"
using namespace ivk;
class RenewalModelerWidget : public ModuleWidget, private Ui::RenewalModelerWidget
{
Q_OBJECT
FACTORY_DECLARATIONS_FOR(RenewalModelerWidget)
public:
RenewalModelerWidget();
virtual ~RenewalModelerWidget();
protected:
void createActions();
void loadModel();
void initModel();
void postCreation();
void updateGUI();
private:
RenewalModeler *modeler;
ComputationThread<RenewalModeler> *thread;
private slots:
void spawnResultWidget();
void on_numdstepsEdit_valueChanged(int value);
};
#endif /*ONESTATEMODELERWIDGET_H_*/
| [
"sebastian@ivk-virtualbox.(none)"
] | sebastian@ivk-virtualbox.(none) |
a210c71faf75e83617b6199320a10dd7b7249d74 | 584165ef8b92e290cf549e510611d85d27c115c4 | /QUADTREE/lacti.cpp | 44defe5303485390b9d441bc507b6e6a1d821072 | [] | no_license | PoolC/algospot | 9a5fa2dd84cad6a64b21a9841b29896d78fdb0a1 | 3cd95b044ec91b131018b024bdc8ef545b238900 | refs/heads/master | 2021-01-13T01:17:21.059827 | 2014-08-12T12:46:57 | 2014-08-12T12:46:57 | 21,388,147 | 2 | 1 | null | 2014-08-05T11:03:31 | 2014-07-01T13:13:49 | C++ | UTF-8 | C++ | false | false | 1,003 | cpp | #include <iostream>
#include <vector>
typedef std::vector<char> result_t;
const int max_length = 1000;
static void reverse(const char*& input, result_t& output);
int main(int argc, char* argv[])
{
int count;
std::cin >> count;
std::cin.ignore(1024, '\n');
char buffer[max_length];
result_t output;
output.reserve(max_length);
while (--count >= 0)
{
std::cin.getline(buffer, max_length);
output.clear();
const char* iter = buffer;
reverse(iter, output);
output.push_back(0);
std::cout << &output.front() << std::endl;
}
return 0;
}
static void reverse(const char*& input, result_t& output)
{
char current = *input++;
if (current == 'w' || current == 'b')
{
output.push_back(current);
return;
}
output.push_back('x');
result_t uppers;
uppers.reserve(max_length);
/* 1 */ reverse(input, uppers); /* 2 */ reverse(input, uppers);
/* 3 */ reverse(input, output); /* 4 */ reverse(input, output);
output.insert(output.end(), uppers.begin(), uppers.end());
}
| [
"lactrious@gmail.com"
] | lactrious@gmail.com |
a140c15e9a2c7bf6da5392ddde0ffb7e475efc87 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/mutt/gumtree/mutt_repos_function_985_mutt-1.6.2.cpp | f1baa68f164068bb782aee0672bf8359932f7895 | [] | 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 | 1,983 | cpp | static int multipart_handler (BODY *a, STATE *s)
{
BODY *b, *p;
char length[5];
struct stat st;
int count;
int rc = 0;
if (a->encoding == ENCBASE64 || a->encoding == ENCQUOTEDPRINTABLE ||
a->encoding == ENCUUENCODED)
{
fstat (fileno (s->fpin), &st);
b = mutt_new_body ();
b->length = (long) st.st_size;
b->parts = mutt_parse_multipart (s->fpin,
mutt_get_parameter ("boundary", a->parameter),
(long) st.st_size, ascii_strcasecmp ("digest", a->subtype) == 0);
}
else
b = a;
for (p = b->parts, count = 1; p; p = p->next, count++)
{
if (s->flags & M_DISPLAY)
{
state_mark_attach (s);
state_printf (s, _("[-- Attachment #%d"), count);
if (p->description || p->filename || p->form_name)
{
state_puts (": ", s);
state_puts (p->description ? p->description :
p->filename ? p->filename : p->form_name, s);
}
state_puts (" --]\n", s);
mutt_pretty_size (length, sizeof (length), p->length);
state_mark_attach (s);
state_printf (s, _("[-- Type: %s/%s, Encoding: %s, Size: %s --]\n"),
TYPE (p), p->subtype, ENCODING (p->encoding), length);
if (!option (OPTWEED))
{
fseeko (s->fpin, p->hdr_offset, 0);
mutt_copy_bytes(s->fpin, s->fpout, p->offset-p->hdr_offset);
}
else
state_putc ('\n', s);
}
rc = mutt_body_handler (p, s);
state_putc ('\n', s);
if (rc)
{
mutt_error (_("One or more parts of this message could not be displayed"));
dprint (1, (debugfile, "Failed on attachment #%d, type %s/%s.\n", count, TYPE(p), NONULL (p->subtype)));
}
if ((s->flags & M_REPLYING)
&& (option (OPTINCLUDEONLYFIRST)) && (s->flags & M_FIRSTDONE))
break;
}
if (a->encoding == ENCBASE64 || a->encoding == ENCQUOTEDPRINTABLE ||
a->encoding == ENCUUENCODED)
mutt_free_body (&b);
/* make failure of a single part non-fatal */
if (rc < 0)
rc = 1;
return rc;
} | [
"993273596@qq.com"
] | 993273596@qq.com |
0fc007ebe925740d65bf17376d8da601b155dacc | 6b7cb5e1a66f4af9ea0a8b675a6abb8f6927b9fc | /src/06_Font1/NimotsuKunWithFont/Image.cpp | 6c55a3b3f8f1d2538bb296c950d1378548a4d167 | [] | no_license | supercaracal/game-programmer-book-build | dc405763ed255e81ea8244d2c48dc24a8d98293e | c9e1f65cab3f59a4d552128d0ee22233d79b2773 | refs/heads/master | 2022-06-10T14:17:00.122380 | 2020-04-29T04:03:14 | 2020-04-29T04:03:14 | 259,812,505 | 1 | 0 | null | 2020-04-29T03:14:35 | 2020-04-29T03:14:34 | null | SHIFT_JIS | C++ | false | false | 2,662 | cpp | #include "Image.h"
#include "File.h"
#include "GameLib/Framework.h"
using namespace GameLib;
Image::Image( const char* filename ) :
mWidth( 0 ),
mHeight( 0 ),
mData( 0 ){
File f( filename );
mHeight = f.getUnsigned( 12 );
mWidth = f.getUnsigned( 16 );
mData = new unsigned[ mWidth * mHeight ];
for ( int i = 0; i < mWidth * mHeight; ++i ){
mData[ i ] = f.getUnsigned( 128 + i * 4 );
}
}
Image::~Image(){
SAFE_DELETE( mData );
}
int Image::width() const {
return mWidth;
}
int Image::height() const {
return mHeight;
}
namespace{ //名前なし名前空間
unsigned blend( unsigned src, unsigned dst ){
unsigned srcA = ( src & 0xff000000 ) >> 24;
unsigned srcR = src & 0xff0000;
unsigned srcG = src & 0x00ff00;
unsigned srcB = src & 0x0000ff;
unsigned dstR = dst & 0xff0000;
unsigned dstG = dst & 0x00ff00;
unsigned dstB = dst & 0x0000ff;
unsigned r = ( srcR - dstR ) * srcA / 255 + dstR;
unsigned g = ( srcG - dstG ) * srcA / 255 + dstG;
unsigned b = ( srcB - dstB ) * srcA / 255 + dstB;
return ( r & 0xff0000 ) | ( g & 0x00ff00 ) | b;
}
}
//アルファブレンド付き
void Image::draw(
int dstX,
int dstY,
int srcX,
int srcY,
int width,
int height ) const {
unsigned* vram = Framework::instance().videoMemory();
int windowWidth = Framework::instance().width();
for ( int y = 0; y < height; ++y ){
for ( int x = 0; x < width; ++x ){
unsigned src = mData[ ( y + srcY ) * mWidth + ( x + srcX ) ];
unsigned* dst = &vram[ ( y + dstY ) * windowWidth + ( x + dstX ) ];
*dst = blend( src, *dst );
}
}
}
void Image::draw() const {
draw( 0, 0, 0, 0, mWidth, mHeight );
}
//色指定描画
void Image::drawWithFixedColor(
int dstX,
int dstY,
int srcX,
int srcY,
int width,
int height,
unsigned color ) const {
unsigned* vram = Framework::instance().videoMemory();
int windowWidth = Framework::instance().width();
unsigned srcR = color & 0xff0000;
unsigned srcG = color & 0x00ff00;
unsigned srcB = color & 0x0000ff;
for ( int y = 0; y < height; ++y ){
for ( int x = 0; x < width; ++x ){
unsigned src = mData[ ( y + srcY ) * mWidth + ( x + srcX ) ];
unsigned* dst = &vram[ ( y + dstY ) * windowWidth + ( x + dstX ) ];
unsigned srcA = ( src & 0xff000000 ) >> 24;
unsigned dstR = *dst & 0xff0000;
unsigned dstG = *dst & 0x00ff00;
unsigned dstB = *dst & 0x0000ff;
unsigned r = ( srcR - dstR ) * srcA / 255 + dstR;
unsigned g = ( srcG - dstG ) * srcA / 255 + dstG;
unsigned b = ( srcB - dstB ) * srcA / 255 + dstB;
*dst = ( r & 0xff0000 ) | ( g & 0x00ff00 ) | b;
}
}
}
| [
"slash@watery.dip.jp"
] | slash@watery.dip.jp |
16e84c7ca027f600c4460e2028397637557b8b86 | a86512404935e8bb4140886e87fd6ae953451f3e | /Horoscopes/src/data/horoscopedto.cc | b7ff3219fb5dff50d0dfa9f1a860cfc4b401e837 | [] | no_license | JasF/horo | 9b8bbc6caa21641db6e857849084ea8b48517c68 | 80e818cef0e453e4b6993cacbcc04282cd7df431 | refs/heads/master | 2021-09-05T01:47:27.977200 | 2018-01-23T09:50:09 | 2018-01-23T09:50:09 | 114,524,144 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 744 | cc | //
// horoscopedto.c
// Horoscopes
//
// Created by Jasf on 30.10.2017.
// Copyright © 2017 Mail.Ru. All rights reserved.
//
#include "horoscopedto.h"
namespace horo {
void _HoroscopeDTO::encode(Json::Value &coder) {
coder["type"] = type_;
coder["content"] = content_;
coder["date"] = (Json::UInt64) date_;
coder["zodiac"] = zodiac_;
}
void _HoroscopeDTO::decode(Json::Value &coder) {
type_ = (HoroscopeType) coder["type"].asInt();
content_= coder["content"].asString();
date_ = coder["date"].asUInt64();
zodiac_ = (ZodiacTypes) coder["zodiac"].asInt();
}
std::string _HoroscopeDTO::content() const {
return content_;
}
};
| [
"andreivoe@gmail.com"
] | andreivoe@gmail.com |
66bd18952a5fb9053d925ac2d4f5a4fbad448471 | c9706cd56d7f9a4c468aecdee9dc2a03e5c1aa42 | /publishglmaprenderer.cpp | ef4c72984a4c8bf893d1def68fd2f04a1c25a58e | [] | no_license | dm-helper/dm-helper-oglvideo | 78f9e259576c41f8fa18fa45d4cfb5a2948b9621 | 16962276c99a6827c1df1aed6af6f7d6e98bd16a | refs/heads/main | 2023-08-26T07:55:46.423389 | 2021-10-31T09:24:40 | 2021-10-31T09:24:40 | 423,102,773 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,568 | cpp | #include "publishglmaprenderer.h"
#include "map.h"
#include "videoplayerglplayer.h"
#include "battleglbackground.h"
#include "publishglobject.h"
#include "publishglimage.h"
#include <QOpenGLWidget>
#include <QOpenGLContext>
#include <QOpenGLFunctions>
#include <QMatrix4x4>
#include <QDebug>
PublishGLMapRenderer::PublishGLMapRenderer(Map* map, QObject *parent) :
PublishGLRenderer(parent),
_map(map),
_image(),
_videoPlayer(nullptr),
_targetSize(),
_color(),
_initialized(false),
_shaderProgram(0),
_backgroundObject(nullptr),
_partyToken(nullptr)
{
}
PublishGLMapRenderer::~PublishGLMapRenderer()
{
cleanup();
}
void PublishGLMapRenderer::cleanup()
{
_initialized = false;
delete _partyToken;
_partyToken = nullptr;
delete _backgroundObject;
_backgroundObject = nullptr;
delete _videoPlayer;
_videoPlayer = nullptr;
}
bool PublishGLMapRenderer::deleteOnDeactivation()
{
return true;
}
void PublishGLMapRenderer::setBackgroundColor(const QColor& color)
{
_color = color;
emit updateWidget();
}
void PublishGLMapRenderer::initializeGL()
{
if((_initialized) || (!_targetWidget) || (!_map))
return;
// Set up the rendering context, load shaders and other resources, etc.:
QOpenGLFunctions *f = _targetWidget->context()->functions();
if(!f)
return;
f->glEnable(GL_TEXTURE_2D); // Enable texturing
f->glEnable(GL_BLEND);// you enable blending function
f->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
const char *vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos; // the position variable has attribute position 0\n"
"layout (location = 1) in vec3 aColor; // the color variable has attribute position 1\n"
"layout (location = 2) in vec2 aTexCoord;\n"
"uniform mat4 model;\n"
"uniform mat4 view;\n"
"uniform mat4 projection;\n"
"out vec3 ourColor; // output a color to the fragment shader\n"
"out vec2 TexCoord;\n"
"void main()\n"
"{\n"
" // note that we read the multiplication from right to left\n"
" gl_Position = projection * view * model * vec4(aPos, 1.0); // gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
" ourColor = aColor; // set ourColor to the input color we got from the vertex data\n"
" TexCoord = aTexCoord;\n"
"}\0";
unsigned int vertexShader;
vertexShader = f->glCreateShader(GL_VERTEX_SHADER);
f->glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
f->glCompileShader(vertexShader);
int success;
char infoLog[512];
f->glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if(!success)
{
f->glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
qDebug() << "[PublishGLMapRenderer] ERROR::SHADER::VERTEX::COMPILATION_FAILED: " << infoLog;
return;
}
const char *fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"in vec3 ourColor;\n"
"in vec2 TexCoord;\n"
"uniform sampler2D texture1;\n"
"void main()\n"
"{\n"
" FragColor = texture(texture1, TexCoord); // FragColor = vec4(ourColor, 1.0f);\n"
"}\0";
unsigned int fragmentShader;
fragmentShader = f->glCreateShader(GL_FRAGMENT_SHADER);
f->glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
f->glCompileShader(fragmentShader);
f->glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if(!success)
{
f->glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
qDebug() << "[PublishGLMapRenderer] ERROR::SHADER::FRAGMENT::COMPILATION_FAILED: " << infoLog;
return;
}
_shaderProgram = f->glCreateProgram();
f->glAttachShader(_shaderProgram, vertexShader);
f->glAttachShader(_shaderProgram, fragmentShader);
f->glLinkProgram(_shaderProgram);
f->glGetProgramiv(_shaderProgram, GL_LINK_STATUS, &success);
if(!success) {
f->glGetProgramInfoLog(_shaderProgram, 512, NULL, infoLog);
qDebug() << "[PublishGLMapRenderer] ERROR::SHADER::PROGRAM::COMPILATION_FAILED: " << infoLog;
return;
}
f->glUseProgram(_shaderProgram);
f->glDeleteShader(vertexShader);
f->glDeleteShader(fragmentShader);
// Create the objects
_image.load(QString("C:\\Users\\turne\\Documents\\DnD\\DM Helper\\testdata\\Desert Stronghold.jpg"));
_backgroundObject = new BattleGLBackground(nullptr, _image, GL_NEAREST);
// Create the party token
if(_map->getShowParty())
{
QImage partyImage = _map->getPartyPixmap().toImage();
_partyToken = new PublishGLImage(partyImage, false);
_partyToken->setScale(0.04f * static_cast<float>(_map->getPartyScale()));
}
// Create the objects
_videoPlayer = new VideoPlayerGLPlayer(_map->getFileName(),
_targetWidget->context(),
_targetWidget->format(),
_targetSize,
true,
false);
connect(_videoPlayer, &VideoPlayerGLPlayer::frameAvailable, this, &PublishGLMapRenderer::updateWidget);
// Matrices
// Model
QMatrix4x4 modelMatrix;
f->glUniformMatrix4fv(f->glGetUniformLocation(_shaderProgram, "model"), 1, GL_FALSE, modelMatrix.constData());
// View
QMatrix4x4 viewMatrix;
viewMatrix.lookAt(QVector3D(0.f, 0.f, 500.f), QVector3D(0.f, 0.f, 0.f), QVector3D(0.f, 1.f, 0.f));
f->glUniformMatrix4fv(f->glGetUniformLocation(_shaderProgram, "view"), 1, GL_FALSE, viewMatrix.constData());
// Projection - note, this is set later when resizing the window
setOrthoProjection();
f->glUseProgram(_shaderProgram);
f->glUniform1i(f->glGetUniformLocation(_shaderProgram, "texture1"), 0); // set it manually
_initialized = true;
}
void PublishGLMapRenderer::resizeGL(int w, int h)
{
_targetSize = QSize(w, h);
qDebug() << "[PublishGLMapRenderer] Resize w: " << w << ", h: " << h;
setOrthoProjection();
if(_videoPlayer)
{
_videoPlayer->targetResized(_targetSize);
_videoPlayer->initializationComplete();
}
emit updateWidget();
}
void PublishGLMapRenderer::paintGL()
{
if((!_initialized) || (!_map))
return;
if((!_targetWidget) || (!_targetWidget->context()) || (!_videoPlayer))
return;
QOpenGLFunctions *f = _targetWidget->context()->functions();
QOpenGLExtraFunctions *e = _targetWidget->context()->extraFunctions();
if((!f) || (!e))
return;
// Draw the scene:
f->glClearColor(_color.redF(), _color.greenF(), _color.blueF(), 1.0f);
f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
f->glUseProgram(_shaderProgram);
f->glActiveTexture(GL_TEXTURE0); // activate the texture unit first before binding texture
QMatrix4x4 modelMatrix;
f->glUniformMatrix4fv(f->glGetUniformLocation(_shaderProgram, "model"), 1, GL_FALSE, modelMatrix.constData());
_videoPlayer->paintGL();
if(_partyToken)
{
QSize sceneSize = _videoPlayer->getSize();
_partyToken->setPosition(_map->getPartyIconPos().x() - (sceneSize.width() / 2), (sceneSize.height() / 2) - _map->getPartyIconPos().y());
f->glUniformMatrix4fv(f->glGetUniformLocation(_shaderProgram, "model"), 1, GL_FALSE, _partyToken->getMatrixData());
_partyToken->paintGL();
}
/*
if(_backgroundObject)
{
f->glUniformMatrix4fv(f->glGetUniformLocation(_shaderProgram, "model"), 1, GL_FALSE, _backgroundObject->getMatrixData());
_backgroundObject->paintGL();
}
*/
}
QImage PublishGLMapRenderer::getLastScreenshot()
{
if(!_videoPlayer)
return QImage();
return _videoPlayer->getLastScreenshot();
}
const QImage& PublishGLMapRenderer::getImage() const
{
return _image;
}
QColor PublishGLMapRenderer::getColor() const
{
return _color;
}
void PublishGLMapRenderer::setImage(const QImage& image)
{
if(image != _image)
{
_image = image;
// TBD
/*
if(_backgroundObject)
{
_backgroundObject->setImage(image);
setOrthoProjection();
emit updateWidget();
}
*/
}
}
/*
void PublishGLMapRenderer::setColor(QColor color)
{
_color = color;
emit updateWidget();
}*/
void PublishGLMapRenderer::setOrthoProjection()
{
if((_shaderProgram == 0) || (!_targetWidget) || (!_targetWidget->context()))
return;
QOpenGLFunctions *f = _targetWidget->context()->functions();
if(!f)
return;
// Update projection matrix and other size related settings:
/*
QSizeF rectSize = QSizeF(_scene.getTargetSize()).scaled(_scene.getSceneRect().size(), Qt::KeepAspectRatioByExpanding);
QMatrix4x4 projectionMatrix;
projectionMatrix.ortho(-rectSize.width() / 2, rectSize.width() / 2, -rectSize.height() / 2, rectSize.height() / 2, 0.1f, 1000.f);
f->glUniformMatrix4fv(f->glGetUniformLocation(_shaderProgram, "projection"), 1, GL_FALSE, projectionMatrix.constData());
*/
QMatrix4x4 projectionMatrix;
projectionMatrix.ortho(-_targetSize.width() / 2, _targetSize.width() / 2, -_targetSize.height() / 2, _targetSize.height() / 2, 0.1f, 1000.f);
f->glUniformMatrix4fv(f->glGetUniformLocation(_shaderProgram, "projection"), 1, GL_FALSE, projectionMatrix.constData());
}
| [
"44725987+dm-helper@users.noreply.github.com"
] | 44725987+dm-helper@users.noreply.github.com |
ef2b33ad2013bfaa653aaad835e4d904088d1d90 | 4c263bc119474aa771935f78d1cb21c8c1ec0163 | /Source/ajdr/Cabinet/AutoSet/AutoSetCabinet.h | 990332ff76d7492cdaf9761f8ca1571aa3210dd0 | [] | no_license | zhouchao0924/RTX_Render | bbed5d067550aeb6d6a82adbe4505ae40c17bf87 | 1d1bdcb7511dc22a1bd0ce30cc9e80e4fe753fbb | refs/heads/master | 2022-11-11T18:12:36.598745 | 2020-06-22T08:36:38 | 2020-06-22T08:36:38 | 268,670,065 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 159 | h | #pragma once
#include "CabinetSetBase.h"
namespace AutoSetCabinet
{
class FAutoSetCabinet :public FAutoSetBase
{
public:
SINGLE(FAutoSetCabinet);
};
} | [
"hl1282456555@outlook.com"
] | hl1282456555@outlook.com |
33fb8667071b382d2b50feaa3266cefe85adff4b | 56ac424e4e487d9af70f4dc4ffaf9d5ac314c826 | /src/wecook/LowLevelMotionNodes/GrabMotionNode.cpp | 0eca7eaa453980e7ca810c08d85a8a0e1b16730b | [
"BSD-3-Clause"
] | permissive | icaros-usc/wecook | 44bcf18ff78ba4aacabd7885e4c7029992e006bc | a29337484f3c4232559d2a2aafc3e9a0cf3b1c5a | refs/heads/master | 2023-06-23T19:36:22.598515 | 2023-06-07T06:43:23 | 2023-06-07T06:43:23 | 198,618,219 | 16 | 2 | BSD-3-Clause | 2022-07-06T06:13:29 | 2019-07-24T11:02:19 | C++ | UTF-8 | C++ | false | false | 420 | cpp | //
// Created by hejia on 8/6/19.
//
#include "wecook/LowLevelMotionNodes/GrabMotionNode.h"
using namespace wecook;
void GrabMotionNode::plan(const std::shared_ptr<ada::Ada> &ada, const std::shared_ptr<ada::Ada> &adaImg, Result *result) {
if (m_grab) {
ada->getHand()->grab(m_bodyToGrab);
} else {
ada->getHand()->ungrab();
}
if (result) {
result->setStatus(Result::StatusType::SUCCEEDED);
}
}
| [
"hjzh578@gmail.com"
] | hjzh578@gmail.com |
7c968df2c60e5f5690a5f3628975de43ea50db16 | 60805f5904764782c5e16f6bf49266ec4acc2af1 | /lib_eplayer/src/main/cpp/mediaplayer/source/render/filter/effect/header/GLFrameTwoFilter.h | 659e95d6f16ab726b63cbcc92963637403f73167 | [] | no_license | gaudiwen/EPlayer | 57fb606571998178035c183a7cdfec0dbc92cbea | f4b0556f3dc9f1c77fb293c7a2274c02278c0652 | refs/heads/master | 2023-03-16T00:12:41.796886 | 2020-05-23T04:19:42 | 2020-05-23T04:19:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 230 | h |
#ifndef GLFRAMETWOFILTER_H
#define GLFRAMETWOFILTER_H
#include "GLFilter.h"
/**
* 仿抖音两屏特效
*/
class GLFrameTwoFilter : public GLFilter {
public:
void initProgram() override;
};
#endif //GLFRAMETWOFILTER_H
| [
"lxrongdke@163.com"
] | lxrongdke@163.com |
496cd5c06b9341174818334125760fd439ed0e11 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /third_party/WebKit/Source/core/html/custom/CustomElementDescriptorTest.cpp | 85933b6b08f03ca91022896c4c43de489cd3e165 | [
"BSD-3-Clause",
"BSD-2-Clause",
"LGPL-2.1-only",
"LGPL-2.0-only",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 2,838 | cpp | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/html/custom/CustomElementDescriptor.h"
#include "core/html/custom/CustomElementDescriptorHash.h"
#include "core/html/custom/CustomElementTestHelpers.h"
#include "platform/wtf/HashSet.h"
#include "platform/wtf/text/AtomicString.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
class Element;
TEST(CustomElementDescriptorTest, equal) {
CustomElementDescriptor my_type_extension("my-button", "button");
CustomElementDescriptor again("my-button", "button");
EXPECT_TRUE(my_type_extension == again)
<< "two descriptors with the same name and local name should be equal";
}
TEST(CustomElementDescriptorTest, notEqual) {
CustomElementDescriptor my_type_extension("my-button", "button");
CustomElementDescriptor colliding_new_type("my-button", "my-button");
EXPECT_FALSE(my_type_extension == colliding_new_type)
<< "type extension should not be equal to a non-type extension";
}
TEST(CustomElementDescriptorTest, hashable) {
HashSet<CustomElementDescriptor> descriptors;
descriptors.insert(CustomElementDescriptor("foo-bar", "foo-bar"));
EXPECT_TRUE(
descriptors.Contains(CustomElementDescriptor("foo-bar", "foo-bar")))
<< "the identical descriptor should be found in the hash set";
EXPECT_FALSE(
descriptors.Contains(CustomElementDescriptor("bad-poetry", "blockquote")))
<< "an unrelated descriptor should not be found in the hash set";
}
TEST(CustomElementDescriptorTest, matches_autonomous) {
CustomElementDescriptor descriptor("a-b", "a-b");
Element* element = CreateElement("a-b");
EXPECT_TRUE(descriptor.Matches(*element));
}
TEST(CustomElementDescriptorTest,
matches_autonomous_shouldNotMatchCustomizedBuiltInElement) {
CustomElementDescriptor descriptor("a-b", "a-b");
Element* element = CreateElement("futuretag").WithIsAttribute("a-b");
EXPECT_FALSE(descriptor.Matches(*element));
}
TEST(CustomElementDescriptorTest, matches_customizedBuiltIn) {
CustomElementDescriptor descriptor("a-b", "button");
Element* element = CreateElement("button").WithIsAttribute("a-b");
EXPECT_TRUE(descriptor.Matches(*element));
}
TEST(CustomElementDescriptorTest,
matches_customizedBuiltIn_shouldNotMatchAutonomousElement) {
CustomElementDescriptor descriptor("a-b", "button");
Element* element = CreateElement("a-b");
EXPECT_FALSE(descriptor.Matches(*element));
}
TEST(CustomElementDescriptorTest,
matches_elementNotInHTMLNamespaceDoesNotMatch) {
CustomElementDescriptor descriptor("a-b", "a-b");
Element* element = CreateElement("a-b").InNamespace("data:text/plain,foo");
EXPECT_FALSE(descriptor.Matches(*element));
}
} // namespace blink
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
53dd8af71bc90302a0997ca4ed80a1d690b82eb9 | 534ab10a710ef5caa12f3b557bb782310aa8ae55 | /AbstractFactory/widget.h | 55e4b5aaa8f9849c66e4ddeccb4a7610ef62301f | [] | no_license | Matttteo/CPPDesignPattern | bad354bc93ecc49004a2b55b51637860fa04078b | c68e164b7b52fbc7d343b082f21835ae75a78085 | refs/heads/master | 2021-01-17T20:48:48.752570 | 2016-08-05T15:31:54 | 2016-08-05T15:31:54 | 64,854,967 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 189 | h | #pragma once
#include <string>
class Widget{
public:
Widget(std::string system) : style(system) {};
virtual void Click() = 0;
virtual void Insert() = 0;
protected:
std::string style;
}; | [
"baiyunhan.cs@gmail.com"
] | baiyunhan.cs@gmail.com |
b6b68f810e2ddf35666709bd9e95b215c96a4ef2 | b836d06a41172681fcf683eee1f26956999011a7 | /三角形.cpp | 5346ae7fd57b4488cfc8c11e6a3dc55632b69b05 | [] | no_license | xinlan1/zuoye | b3efd341bfbda50f0011d8e9786a82334b467332 | c2a9791e4c078568dfbd329fd1003e15172104e8 | refs/heads/main | 2023-04-05T06:19:48.482135 | 2021-04-05T04:32:24 | 2021-04-05T04:32:24 | 344,694,117 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,280 | cpp | //目的:让用户输入三个值,判断这三个数可不可以围成三角形,
//如果可以围成三角形,那么计算三角形的面积,
//并判断该三角形是不是等边三角形,或者等腰三角形
//编写人:唐嘉慧
//编写日期:4月1日
#include<stdio.h>//标准的输入和输出流
#include<stdlib.h>//system("pause")要用
#include<math.h>//因为sqrt()函数要用
int main(void)//主函数
{
float a, b, c, d, s;//定义三个双精度类型的变量
//为什么要定义为浮点数,因为用户输入的整数可能不是整数
//可能有小数点
printf("请输入三个数字");//提示用户输入三个整数
scanf_s("%f%f%f", &a, &b, &c);//将用户刚刚输入的三个数从缓冲区中读入
if (a + b > c && a + c > b && b + c > a)
{//只要满足所有的两边之和大于第三边的就可以三角形
//有一方不满足该条件都不能围城三角形
printf("能够构成三角形\n");
}
else
{//不进if循环说明不满足围成三角形的这个条件
//所以输出它不是三角形
printf("不能够构成三角形\n");
}
d = (a + b + c) / 2.0;//d必须定义为double类型,因为如果是定义为整形的话,可能会导致和内存的截断
s = sqrt(d * (d - a) * (d - b) * (d - c));//三角形面积的计算公式
printf("三角形的面积为%f\n", s);
if (a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a)
{//只要有一方满足两直角边的平方和等于斜边的平方的话,那么就可以围成直角三角形了
//所以条件为或
printf("构成了直角三角形");
}
if (a == b || b == c || a == c)
{//只要有两边相等就是等腰三角形了
printf("能够构成等腰三角形\n");
}
if (a == b&&b==c&&a==c)
{//三边相等就是就是等边三角形了
printf("能够构成等边三角形\n");
}
//补充:想输出一个变量的地址我们应该怎么做?
//利用%p的形式就可以输出一个变量的地址
printf("a,b,c的地址为");
printf("%p\t%p\t%p", &a, &b, &c);//利用%p的形式及输出变量的地址
system("pause");////将黑色窗口停留,用户按任意键后才会退出
return 0;//程序正常运行要返回一个0
} | [
"noreply@github.com"
] | noreply@github.com |
fce8a55e50156def09bc415dffd52d116dd61548 | 2f10f807d3307b83293a521da600c02623cdda82 | /deps/boost/win/debug/include/boost/graph/tree_traits.hpp | 5ccf9a5ea6667006700145a4a5628df8f27283f4 | [] | no_license | xpierrohk/dpt-rp1-cpp | 2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e | 643d053983fce3e6b099e2d3c9ab8387d0ea5a75 | refs/heads/master | 2021-05-23T08:19:48.823198 | 2019-07-26T17:35:28 | 2019-07-26T17:35:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:44dfaefbac08282023e1ffe31ef708e6b925dd89df40ac5f4b10b28abe442976
size 1351
| [
"YLiLarry@gmail.com"
] | YLiLarry@gmail.com |
d5fa1b2ced3970c0ec4975b672728a02a7d41229 | 883409877f109af6cbfb254cd7a4e9f9dee9d2fe | /WeeklyCode/week2/Reverse Linked List II/chenhao.cpp | 7d1ed90d608b4b65fd70c09c8f07ae41fc0bf7ed | [] | no_license | coderfengyun/TCSE2012 | f83b0256d7b1a7c8b906d6ca52c6b5cdfd6cd578 | 43aee67600f1a3c2f29922e827d05e6c6e8a9364 | refs/heads/master | 2021-01-22T20:34:40.911809 | 2014-09-30T03:09:34 | 2014-09-30T03:09:34 | 18,791,865 | 2 | 2 | null | 2014-05-13T09:27:44 | 2014-04-15T07:52:36 | Java | UTF-8 | C++ | false | false | 851 | cpp | #include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
ListNode vHead=ListNode(0);
vHead.next=head;
ListNode *cur=head, *pre=&vHead;
ListNode *preBegin, *begin;
for(int i=1;cur;i++){
ListNode* next=cur->next;
if(i==m){
preBegin=pre;
begin=cur;
}
if(i>m){
cur->next=pre;
}
if(i==n){
preBegin->next=cur;
begin->next=next;
break;
}
pre=cur;
cur=next;
}
return vHead.next;
}
}; | [
"chenh1024@gmail.com"
] | chenh1024@gmail.com |
ba4c2db0161e332a710ec1cf38f66e37d7a6eae2 | 9498e8ef4e21f240e7eb4c90a0719773bc92bcf5 | /coinramp.h | cf2b8b9895c1dfa77d7f614fda0248b68d4b62ba | [] | no_license | De-etz/Honors-Engineering-Robot-Project | df17514a29ab6f63ac012e1c795ea2438665fba2 | 66b724d53431a4bfd1b4d173e169214813f4b0fa | refs/heads/master | 2021-10-26T23:26:55.820710 | 2019-04-14T20:46:26 | 2019-04-14T20:46:26 | 171,723,286 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 946 | h | #ifndef COINRAMP_H
#define COINRAMP_H
#include <FEHServo.h>
/**
* @brief The CoinRamp class
*
* Used to control coinramp with a Futaba servo.
*/
class CoinRamp
{
private:
FEHServo servo;
float lower, reset;
public:
CoinRamp(FEHServo::FEHServoPort servoPort) :
servo(servoPort) {
servo.SetMin(1000);
servo.SetMax(2400);
lower = 0;
reset = 180;
}
/**
* @brief lower
*
* Lowers the coinramp.
*/
void lowerRamp();
/**
* @brief reset
*
* Brings servo back to its start position.
*/
void resetRamp();
/**
* @brief set
*
* Manually set the angle of the servo.
*
* @param degree Degree of the servo to set the arm to.
*/
void set(float degree);
/**
* @brief touchCalibrate
*
* Runs the FEH TouchCalibrate() program.
*/
void touchCalibrate();
};
#endif // COINRAMP_H
| [
"dialadityasingh@gmail.coom"
] | dialadityasingh@gmail.coom |
1801cd5e7bcac92aee02e09e165e9590ec05c046 | 2a88b58673d0314ed00e37ab7329ab0bbddd3bdc | /blazetest/src/mathtest/smatdmatadd/MCaUDa.cpp | 75dfbe447dba37eff8429622c89efecf09710ba1 | [
"BSD-3-Clause"
] | permissive | shiver/blaze-lib | 3083de9600a66a586e73166e105585a954e324ea | 824925ed21faf82bb6edc48da89d3c84b8246cbf | refs/heads/master | 2020-09-05T23:00:34.583144 | 2016-08-24T03:55:17 | 2016-08-24T03:55:17 | 66,765,250 | 2 | 1 | NOASSERTION | 2020-04-06T05:02:41 | 2016-08-28T11:43:51 | C++ | UTF-8 | C++ | false | false | 4,080 | cpp | //=================================================================================================
/*!
// \file src/mathtest/smatdmatadd/MCaUDa.cpp
// \brief Source file for the MCaUDa sparse matrix/dense matrix addition math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group 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 HOLDER 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/UpperMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/smatdmatadd/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'MCaUDa'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Matrix type definitions
typedef blaze::CompressedMatrix<TypeA> MCa;
typedef blaze::UpperMatrix< blaze::DynamicMatrix<TypeA> > UDa;
// Creator type definitions
typedef blazetest::Creator<MCa> CMCa;
typedef blazetest::Creator<UDa> CUDa;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=i*i; ++j ) {
RUN_SMATDMATADD_OPERATION_TEST( CMCa( i, i, j ), CUDa( i ) );
}
}
// Running tests with large matrices
RUN_SMATDMATADD_OPERATION_TEST( CMCa( 67UL, 67UL, 7UL ), CUDa( 67UL ) );
RUN_SMATDMATADD_OPERATION_TEST( CMCa( 128UL, 128UL, 16UL ), CUDa( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix addition:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
8bc69e0c5e231c7353a24853bf13f499993ef03c | 1a20961af3b03b46c109b09812143a7ef95c6caa | /ZGame/DX11/DirectX-Graphics-Samples/MiniEngine/ModelConverter/IndexOptimizePostTransform.h | f978e3f2e583ee7b2efc67073f884d26f71df3ee | [
"MIT"
] | permissive | JetAr/ZNginx | eff4ae2457b7b28115787d6af7a3098c121e8368 | 698b40085585d4190cf983f61b803ad23468cdef | refs/heads/master | 2021-07-16T13:29:57.438175 | 2017-10-23T02:05:43 | 2017-10-23T02:05:43 | 26,522,265 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,450 | h | //
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
// Developed by Minigraph
//
// Author(s): Alex Nankervis
//
#pragma once
namespace Graphics
{
//-----------------------------------------------------------------------------
// OptimizeFaces
//-----------------------------------------------------------------------------
// Parameters:
// indexList
// input index list
// indexCount
// the number of indices in the list
// newIndexList
// a pointer to a preallocated buffer the same size as indexList to
// hold the optimized index list
// lruCacheSize
// the size of the simulated post-transform cache (max:64)
//-----------------------------------------------------------------------------
template <typename IndexType>
void OptimizeFaces(const IndexType* indexList, uint32_t indexCount, IndexType* newIndexList, uint16_t lruCacheSize);
template void OptimizeFaces<uint16_t>(const uint16_t* indexList, uint32_t indexCount, uint16_t* newIndexList, uint16_t lruCacheSize);
template void OptimizeFaces<uint32_t>(const uint32_t* indexList, uint32_t indexCount, uint32_t* newIndexList, uint16_t lruCacheSize);
}
| [
"126.org@gmail.com"
] | 126.org@gmail.com |
7f0dcf505aec45ea62c727774a39e3a316e4534c | 321e09bac02b6a98df34e8ebef2fd05bcabf2c53 | /src/interpreter/abstract/Multiplexer.cpp | c6bb7b5c3f51e090c8e1cbed1e562dab1b2da180 | [
"MIT"
] | permissive | liamstask/joedb | ad42a3298b1f69825ff3888c5b9354f26f9a72af | 7e505464a6494acf5843753865b7c3db5ceff1f1 | refs/heads/master | 2021-09-01T12:10:29.684450 | 2017-12-18T20:35:11 | 2017-12-18T20:35:11 | 115,459,986 | 1 | 1 | null | 2017-12-26T22:44:10 | 2017-12-26T22:44:09 | null | UTF-8 | C++ | false | false | 4,496 | cpp | #include "Multiplexer.h"
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::add_writeable(Writeable &writeable)
/////////////////////////////////////////////////////////////////////////////
{
writeables.push_back(&writeable);
}
#define MULTIPLEX(x) do {for (auto w: writeables) w->x;} while(0)
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::create_table(const std::string &name)
/////////////////////////////////////////////////////////////////////////////
{
MULTIPLEX(create_table(name));
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::drop_table(Table_Id table_id)
/////////////////////////////////////////////////////////////////////////////
{
MULTIPLEX(drop_table(table_id));
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::rename_table
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
const std::string &name
)
{
MULTIPLEX(rename_table(table_id, name));
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::add_field
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
const std::string &name,
Type type
)
{
MULTIPLEX(add_field(table_id, name, type));
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::drop_field
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Field_Id field_id
)
{
MULTIPLEX(drop_field(table_id, field_id));
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::rename_field
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Field_Id field_id,
const std::string &name
)
{
MULTIPLEX(rename_field(table_id, field_id, name));
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::custom(const std::string &name)
/////////////////////////////////////////////////////////////////////////////
{
MULTIPLEX(custom(name));
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::comment(const std::string &comment)
/////////////////////////////////////////////////////////////////////////////
{
MULTIPLEX(comment(comment));
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::timestamp(int64_t timestamp)
/////////////////////////////////////////////////////////////////////////////
{
MULTIPLEX(timestamp(timestamp));
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::valid_data()
/////////////////////////////////////////////////////////////////////////////
{
MULTIPLEX(valid_data());
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::insert_into
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Record_Id record_id
)
{
MULTIPLEX(insert_into(table_id, record_id));
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::insert_vector
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Record_Id record_id,
Record_Id size
)
{
MULTIPLEX(insert_vector(table_id, record_id, size));
}
/////////////////////////////////////////////////////////////////////////////
void joedb::Multiplexer::delete_from
/////////////////////////////////////////////////////////////////////////////
(
Table_Id table_id,
Record_Id record_id
)
{
MULTIPLEX(delete_from(table_id, record_id));
}
#define TYPE_MACRO(type, return_type, type_id, R, W)\
void joedb::Multiplexer::update_##type_id\
(\
Table_Id table_id,\
Record_Id record_id,\
Field_Id field_id,\
return_type value\
)\
{\
MULTIPLEX(update_##type_id(table_id, record_id, field_id, value));\
}\
\
void joedb::Multiplexer::update_vector_##type_id\
(\
Table_Id table_id,\
Record_Id record_id,\
Field_Id field_id,\
Record_Id size,\
const type *value\
)\
{\
MULTIPLEX\
(\
update_vector_##type_id(table_id, record_id, field_id, size, value)\
);\
}
#include "TYPE_MACRO.h"
#undef TYPE_MACRO
#undef MULTIPLEX
| [
"remi.coulom@free.fr"
] | remi.coulom@free.fr |
622091e2fb240ce480366e53c129db04560bff2e | 6b260a7b47d7ffca423bef6e64f49f93f31c38ff | /components/animations/Plasma.cpp | 088ec7ea28765cab1bcf355f3b1ea0f1591eb0ef | [
"MIT"
] | permissive | fweiss/badge | 9c60525cc9580d27a7885a105fd49413728de0b9 | 86a7e8e473df32eb1e90aa29db0f35971cab1322 | refs/heads/master | 2023-05-26T03:57:52.127868 | 2023-04-30T14:03:45 | 2023-04-30T14:03:45 | 54,276,110 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,163 | cpp | #include "Plasma.h"
#include <math.h>
Plasma::Plasma(Display &display) : Animation(display, 100), phase(0) {
}
struct Point {
float x;
float y;
};
Point lissajous(float phase, float a, float b) {
const float rows = 8;
const float cols = 8;
const float scale = 1.0f;
float x = sinf(phase * a) * scale;
float y = sinf(phase * b) * scale;
// scale to fit in matrix
Point point = { (x + 1.0f) / 2.0f * rows, (y + 1.0f) / 2.0f * cols };
// Point point = { (x + 1.0f) / 2.0f * rows, y * cols * 0.0f };
// Point point = { x * 0.0f * rows, (y + 1.0f) / 2.0f * cols };
return point;
}
uint32_t xy(Point &p) {
return (int)p.x + (int)p.y * 8;
}
void Plasma::drawFrame() {
display.clear();
Point p1 = lissajous(phase, 1, 1.27);
Point p2 = lissajous(phase, 3, 4.2);
Point p3 = lissajous(phase, 5, 3.2);
const int p = xy(p1);
const int r = 160;
const int g = 150;
const int b = 10;
display.setPixel(p, r, g, b);
display.setPixel(xy(p2), 160, 10, 10);
display.setPixel(xy(p3), 10, 10, 220);
display.update();
frameIndex += 1;
phase = (float)frameIndex * 0.1;
}
| [
"feweiss@gmail.com"
] | feweiss@gmail.com |
722af4093d94ddfbee5b4079c951c1f37242e84b | dadd28571ab162cf87734357710be81cb27b6282 | /app/viscreator.cc | a2b1fea3915576a706c844c19921ab819de636fa | [] | no_license | Sophrinix/streams | cf30f75b662c2cb825f950f1d1b246212b6b9a64 | c222d01f909f9f3bddd6597d2e1fb346fd15b97d | refs/heads/master | 2021-01-15T18:59:40.754514 | 2009-08-24T16:12:09 | 2009-08-24T16:12:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 658 | cc | #include "viscreator.h"
#include "waveviswidget.h"
#include "pipelinegui.h"
VisCreator::VisCreator(PipelineGUI & pg) :
pipelineGUI_(pg)
{
}
VisCreator::~VisCreator()
{
}
void VisCreator::visit(VisBase * )
{
std::cout << "VisCreator: Visiting for VisBase" << std::endl;
}
void VisCreator::visit(SineVis* sv )
{
}
void VisCreator::visit(WaveVis * pwv)
{
WaveVisWidget * wv = new WaveVisWidget(pwv, pipelineGUI_.getSomaConfig());
wv->setPropertyPaneManager(pipelineGUI_.getPropertyPaneManager());
// tell pipeline gui that there's a new source, and let it
// position appropriately
pipelineGUI_.addNewVis(wv);
}
| [
"jonas@mit.edu"
] | jonas@mit.edu |
b40f7b201edc152f9b2606594003206587e2dfd7 | fcdea24e6466d4ec8d7798555358a9af8acf9b35 | /Engine/mrayEngine/src/TextureBank.cpp | 5234a71b1d805707d9acba7f9405108e96c66853 | [] | no_license | yingzhang536/mrayy-Game-Engine | 6634afecefcb79c2117cecf3e4e635d3089c9590 | 6b6fcbab8674a6169e26f0f20356d0708620b828 | refs/heads/master | 2021-01-17T07:59:30.135446 | 2014-11-30T16:10:54 | 2014-11-30T16:10:54 | 27,630,181 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 949 | cpp | #include "stdafx.h"
#include "TextureBank.h"
namespace mray{
namespace video{
TextureBank::TextureBank()
{
#ifdef ___DEBUG___
setDebugName("TextureBank");
#endif
}
TextureBank::~TextureBank()
{
textures.clear();
}
void TextureBank::addTexture(const ITexturePtr& tex){
textures.push_back(tex);
}
void TextureBank::insertTexture(const ITexturePtr& tex,int index)
{
while(index>=textures.size())
textures.push_back(0);
textures[index]=tex;
}
void TextureBank::replaceTexture(const ITexturePtr& tex,int index){
if(index>=0 && index <textures.size()){
textures[index]=tex;
}
}
void TextureBank::deleteTexture(int index){
if(index>=0 && index <textures.size()){
if(textures[index]){
textures[index]=0;
}
}
}
const ITexturePtr& TextureBank::getTexture(int index){
if(index>=0 && index <textures.size())
return textures[index];
else
return ITexturePtr::Null;
}
}
}
| [
"mrayyamen@gmail.com"
] | mrayyamen@gmail.com |
e358c13d0517d2daad9a572a8e2da208264f6a30 | 83b13e5504e884599a91ae0b37a3cee22f7c29e4 | /deps/v8/src/mksnapshot.cc | 97b8a7edf0082b914c011a68fe8f964510b573f8 | [
"Apache-2.0",
"BSD-3-Clause",
"bzip2-1.0.6"
] | permissive | alkhe/runtime | 9663982dc44138827970274a0955fba5087dee40 | acb6330185c1be88449198c28059d24bc4fb62c2 | refs/heads/master | 2021-05-28T03:00:41.745109 | 2015-01-21T02:09:51 | 2015-01-21T02:09:51 | 29,563,042 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,452 | cc | // Copyright 2006-2008 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include "src/v8.h"
#include "include/libplatform/libplatform.h"
#include "src/assembler.h"
#include "src/base/platform/platform.h"
#include "src/bootstrapper.h"
#include "src/flags.h"
#include "src/list.h"
#include "src/natives.h"
#include "src/serialize.h"
using namespace v8;
class SnapshotWriter {
public:
explicit SnapshotWriter(const char* snapshot_file)
: fp_(GetFileDescriptorOrDie(snapshot_file)),
raw_file_(NULL),
raw_context_file_(NULL),
startup_blob_file_(NULL) {}
~SnapshotWriter() {
fclose(fp_);
if (raw_file_) fclose(raw_file_);
if (raw_context_file_) fclose(raw_context_file_);
if (startup_blob_file_) fclose(startup_blob_file_);
}
void SetRawFiles(const char* raw_file, const char* raw_context_file) {
raw_file_ = GetFileDescriptorOrDie(raw_file);
raw_context_file_ = GetFileDescriptorOrDie(raw_context_file);
}
void SetStartupBlobFile(const char* startup_blob_file) {
if (startup_blob_file != NULL)
startup_blob_file_ = GetFileDescriptorOrDie(startup_blob_file);
}
void WriteSnapshot(const i::SnapshotData& sd,
const i::SnapshotData& csd) const {
WriteSnapshotFile(sd, csd);
MaybeWriteStartupBlob(sd, csd);
}
private:
void MaybeWriteStartupBlob(const i::SnapshotData& sd,
const i::SnapshotData& csd) const {
if (!startup_blob_file_) return;
i::SnapshotByteSink sink;
sink.PutBlob(sd.RawData(), "snapshot");
sink.PutBlob(csd.RawData(), "context");
const i::List<i::byte>& startup_blob = sink.data();
size_t written = fwrite(startup_blob.begin(), 1, startup_blob.length(),
startup_blob_file_);
if (written != static_cast<size_t>(startup_blob.length())) {
i::PrintF("Writing snapshot file failed.. Aborting.\n");
exit(1);
}
}
void WriteSnapshotFile(const i::SnapshotData& snapshot_data,
const i::SnapshotData& context_snapshot_data) const {
WriteFilePrefix();
WriteData("", snapshot_data.RawData(), raw_file_);
WriteData("context_", context_snapshot_data.RawData(), raw_context_file_);
WriteFileSuffix();
}
void WriteFilePrefix() const {
fprintf(fp_, "// Autogenerated snapshot file. Do not edit.\n\n");
fprintf(fp_, "#include \"src/v8.h\"\n");
fprintf(fp_, "#include \"src/base/platform/platform.h\"\n\n");
fprintf(fp_, "#include \"src/snapshot.h\"\n\n");
fprintf(fp_, "namespace v8 {\n");
fprintf(fp_, "namespace internal {\n\n");
}
void WriteFileSuffix() const {
fprintf(fp_, "} // namespace internal\n");
fprintf(fp_, "} // namespace v8\n");
}
void WriteData(const char* prefix,
const i::Vector<const i::byte>& source_data,
FILE* raw_file) const {
MaybeWriteRawFile(&source_data, raw_file);
WriteData(prefix, source_data);
}
void MaybeWriteRawFile(const i::Vector<const i::byte>* data,
FILE* raw_file) const {
if (!data || !raw_file) return;
// Sanity check, whether i::List iterators truly return pointers to an
// internal array.
DCHECK(data->end() - data->begin() == data->length());
size_t written = fwrite(data->begin(), 1, data->length(), raw_file);
if (written != static_cast<size_t>(data->length())) {
i::PrintF("Writing raw file failed.. Aborting.\n");
exit(1);
}
}
void WriteData(const char* prefix,
const i::Vector<const i::byte>& source_data) const {
fprintf(fp_, "const byte Snapshot::%sdata_[] = {\n", prefix);
WriteSnapshotData(source_data);
fprintf(fp_, "};\n");
fprintf(fp_, "const int Snapshot::%ssize_ = %d;\n", prefix,
source_data.length());
fprintf(fp_, "\n");
}
void WriteSnapshotData(const i::Vector<const i::byte>& data) const {
for (int i = 0; i < data.length(); i++) {
if ((i & 0x1f) == 0x1f) fprintf(fp_, "\n");
if (i > 0) fprintf(fp_, ",");
fprintf(fp_, "%u", static_cast<unsigned char>(data.at(i)));
}
fprintf(fp_, "\n");
}
FILE* GetFileDescriptorOrDie(const char* filename) {
FILE* fp = base::OS::FOpen(filename, "wb");
if (fp == NULL) {
i::PrintF("Unable to open file \"%s\" for writing.\n", filename);
exit(1);
}
return fp;
}
FILE* fp_;
FILE* raw_file_;
FILE* raw_context_file_;
FILE* startup_blob_file_;
};
void DumpException(Handle<Message> message) {
String::Utf8Value message_string(message->Get());
String::Utf8Value message_line(message->GetSourceLine());
fprintf(stderr, "%s at line %d\n", *message_string, message->GetLineNumber());
fprintf(stderr, "%s\n", *message_line);
for (int i = 0; i <= message->GetEndColumn(); ++i) {
fprintf(stderr, "%c", i < message->GetStartColumn() ? ' ' : '^');
}
fprintf(stderr, "\n");
}
#ifdef V8_OS_RUNTIMEJS
int mksnapshot_main(int argc, char** argv) {
#else
int main(int argc, char** argv) {
#endif
// By default, log code create information in the snapshot.
i::FLAG_log_code = true;
// Omit from the snapshot natives for features that can be turned off
// at runtime.
i::FLAG_harmony_shipping = false;
// Print the usage if an error occurs when parsing the command line
// flags or if the help flag is set.
int result = i::FlagList::SetFlagsFromCommandLine(&argc, argv, true);
if (result > 0 || argc != 2 || i::FLAG_help) {
::printf("Usage: %s [flag] ... outfile\n", argv[0]);
i::FlagList::PrintHelp();
return !i::FLAG_help;
}
i::CpuFeatures::Probe(true);
V8::InitializeICU();
v8::Platform* platform = v8::platform::CreateDefaultPlatform();
v8::V8::InitializePlatform(platform);
v8::V8::Initialize();
i::FLAG_logfile_per_isolate = false;
Isolate::CreateParams params;
params.enable_serializer = true;
Isolate* isolate = v8::Isolate::New(params);
{ Isolate::Scope isolate_scope(isolate);
i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
Persistent<Context> context;
{
HandleScope handle_scope(isolate);
context.Reset(isolate, Context::New(isolate));
}
if (context.IsEmpty()) {
fprintf(stderr,
"\nException thrown while compiling natives - see above.\n\n");
exit(1);
}
if (i::FLAG_extra_code != NULL) {
// Capture 100 frames if anything happens.
V8::SetCaptureStackTraceForUncaughtExceptions(true, 100);
HandleScope scope(isolate);
v8::Context::Scope cscope(v8::Local<v8::Context>::New(isolate, context));
const char* name = i::FLAG_extra_code;
FILE* file = base::OS::FOpen(name, "rb");
if (file == NULL) {
fprintf(stderr, "Failed to open '%s': errno %d\n", name, errno);
exit(1);
}
fseek(file, 0, SEEK_END);
int size = ftell(file);
rewind(file);
char* chars = new char[size + 1];
chars[size] = '\0';
for (int i = 0; i < size;) {
int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
if (read < 0) {
fprintf(stderr, "Failed to read '%s': errno %d\n", name, errno);
exit(1);
}
i += read;
}
fclose(file);
Local<String> source = String::NewFromUtf8(isolate, chars);
TryCatch try_catch;
Local<Script> script = Script::Compile(source);
if (try_catch.HasCaught()) {
fprintf(stderr, "Failure compiling '%s'\n", name);
DumpException(try_catch.Message());
exit(1);
}
script->Run();
if (try_catch.HasCaught()) {
fprintf(stderr, "Failure running '%s'\n", name);
DumpException(try_catch.Message());
exit(1);
}
}
// Make sure all builtin scripts are cached.
{ HandleScope scope(isolate);
for (int i = 0; i < i::Natives::GetBuiltinsCount(); i++) {
internal_isolate->bootstrapper()->NativesSourceLookup(i);
}
}
// If we don't do this then we end up with a stray root pointing at the
// context even after we have disposed of the context.
internal_isolate->heap()->CollectAllAvailableGarbage("mksnapshot");
i::Object* raw_context = *v8::Utils::OpenPersistent(context);
context.Reset();
// This results in a somewhat smaller snapshot, probably because it gets
// rid of some things that are cached between garbage collections.
i::SnapshotByteSink snapshot_sink;
i::StartupSerializer ser(internal_isolate, &snapshot_sink);
ser.SerializeStrongReferences();
i::SnapshotByteSink context_sink;
i::PartialSerializer context_ser(internal_isolate, &ser, &context_sink);
context_ser.Serialize(&raw_context);
ser.SerializeWeakReferences();
{
SnapshotWriter writer(argv[1]);
if (i::FLAG_raw_file && i::FLAG_raw_context_file)
writer.SetRawFiles(i::FLAG_raw_file, i::FLAG_raw_context_file);
if (i::FLAG_startup_blob)
writer.SetStartupBlobFile(i::FLAG_startup_blob);
i::SnapshotData sd(snapshot_sink, ser);
i::SnapshotData csd(context_sink, context_ser);
writer.WriteSnapshot(sd, csd);
}
}
isolate->Dispose();
V8::Dispose();
V8::ShutdownPlatform();
delete platform;
return 0;
}
| [
"iefserge@runtimejs.org"
] | iefserge@runtimejs.org |
9e96b84c12d3fbc35c89fec9aa6153354fa50163 | 07367bcd68c3c94a57376e5a3889c01f5ff70806 | /tag_estimator/src/estimator.cpp | 907172e17c57bfab37d11081d259577429a8155b | [] | no_license | manghuang/tightly_coupled_VLC_aided_visual_inertial_SLAM | efd2cd629e975d5c306f4a07f063044f0e05e409 | 34a0af429957fa4b7157e07111419878cc3d2a09 | refs/heads/master | 2021-09-15T16:41:01.718612 | 2018-06-07T00:54:00 | 2018-06-07T00:54:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 53,007 | cpp | #include "estimator.h"
#include "frame.h"
#include "feature.h"
#include "point.h"
#include "aprilTag.h"
namespace basic
{
Estimator::Estimator():
window_counter(0),
first_imu(true),
first_tag_img(true),
solver_flag(INITIAL),
initial_timestamp(0.0)
{
for (unsigned int i = 0; i <= WINDOW_SIZE; ++i)
frames[i].reset(new Frame());
}
Estimator::~Estimator()
{
for (unsigned int i = 0; i < window_counter; ++i) {
frames[i]->clear();
frames[i].reset();
}
for (auto it = pts_map.begin(); it != pts_map.end(); ++it) {
it->second->type = Point::TYPE_INIT;
delete(it->second);
}
for (auto it = tags_map.begin(); it != tags_map.end(); ++it) {
delete(it->second);
}
pts_map.clear();
tags_map.clear();
}
void Estimator::clearState()
{
for (unsigned int i = 0; i <= window_counter; ++i) {
frames[i]->clear();
frames[i].reset(new Frame());
}
for (auto it = pts_map.begin(); it != pts_map.end(); ++it) {
it->second->type = Point::TYPE_INIT;
delete(it->second);
}
for (auto it = tags_map.begin(); it != tags_map.end(); ++it) {
delete(it->second);
}
solver_flag = INITIAL;
first_imu = true;
first_tag_img = true;
window_counter = 0;
pts_map.clear();
tags_map.clear();
Frame::frame_counter = 0;
ROS_INFO("States have been cleared!\n");
#ifdef USE_DATA_RECORDER
file_true.close();
file_pnp.close();
file_go.close();
file_tag_num.close();
#endif
}
void Estimator::start()
{
if (solver_flag == INITIAL) {
if (window_counter == WINDOW_SIZE){
bool result = false;
if ((frames[window_counter]->timestamp - initial_timestamp) > 0.2) {
result = initialStructure();
initial_timestamp = frames[window_counter]->timestamp;
if (result) {
ROS_INFO("_________________Initialization successes!____________________\n");
if (frames[window_counter]->apriltag_fts.size() != 0) {
Matrix3d R_c_w;
Vector3d P_c;
if (!solveGlobalRT(window_counter, R_c_w, P_c, 1, false)) {
ROS_INFO("Fail solving position from tag");
return;
} else {
//ROS_INFO_STREAM("******AprilTag R_w_c : " << std::endl << R_c_w.transpose() * ric.transpose());
ROS_INFO_STREAM("******AprilTag P_w : " << (- R_c_w.transpose() * ric.transpose() * (ric * P_c + tic)).transpose());
}
}
for (unsigned int i = 0; i <= window_counter; ++i) {
Matrix3d R_w_b = frames[i]->R_w_b;
Vector3d t_w = frames[i]->P_w;
//ROS_INFO_STREAM("before******Global R_w_c : " << std::endl << R_w_b);
ROS_INFO_STREAM("before******Global P_w " << i << " : " << t_w.transpose());
}
// for (auto it = pts_map.begin(); it != pts_map.end(); ++it) {
// if ((*it).second->type == Point::TYPE_TRIANGULATED)
// ROS_INFO_STREAM("before****** Position: Point " << (*it).first << std::endl << (*it).second->P_w.transpose());
// }
if(!solveLocalization()) {
ROS_WARN("solveLocalization fails...!");
clearState();
return;
}
solver_flag = NON_LINEAR;
for (unsigned int i = 0; i <= window_counter; ++i) {
Matrix3d R_w_b = frames[i]->R_w_b;
Vector3d t_w = frames[i]->P_w;
//ROS_INFO_STREAM("before******Global R_w_c : " << std::endl << R_w_b);
ROS_INFO_STREAM("after******Global P_w " << i << " : " << t_w.transpose());
}
// for (auto it = pts_map.begin(); it != pts_map.end(); ++it) {
// if ((*it).second->type == Point::TYPE_TRIANGULATED)
// ROS_INFO_STREAM("after****** Position: Point " << (*it).first << std::endl << (*it).second->P_w.transpose());
// }
#ifdef USE_DATA_RECORDER
file_true.open(APRIL_VIO_OUTPUT+"ground_true.txt");
file_pnp.open(APRIL_VIO_OUTPUT+"pnp_data.txt");
file_go.open(APRIL_VIO_OUTPUT+"go_data.txt");
file_tag_num.open(APRIL_VIO_OUTPUT+"tag_num.txt");
#endif
} else {
ROS_INFO("Initialization fails!\n");
for (auto it = pts_map.begin(); it != pts_map.end(); ++it) {
it->second->type = Point::TYPE_INIT;
}
marginalization_flag = MARGIN_OLD;
}
}
slideWindow();
} else {
if (first_tag_img == true) {// no tag
if (frames[0]->apriltag_fts.empty()) {
frames[0]->clear();
frames[0].reset(new Frame());
int n_deleted_point = 0;
for (auto it = pts_map.begin(), it_next = pts_map.begin(); it != pts_map.end(); it = it_next) {
it_next++;
if (it->second->type == Point::TYPE_DELETED) {
n_deleted_point++;
pts_map.erase(it);
}
}
return;
} else {
first_tag_img = false;
Matrix3d R_c_w;
Vector3d t_c;
solveGlobalRT(0, R_c_w, t_c, 1, false);
}
}
window_counter++;
}
} else if (solver_flag == NON_LINEAR){
// clearState();
predict();
Vector3d t_w = frames[window_counter]->P_w;
ROS_INFO_STREAM("predict******Global P_w: " << t_w.transpose());
/*
for (unsigned int i = 0; i <= WINDOW_SIZE; ++i) {
Vector3d t_w = frames[i]->P_w;
ROS_INFO_STREAM("before******Global P_w " << i << " : " << t_w.transpose());
}*/
if(!solveLocalization()) {
vector<int> tag_index;
for (unsigned int i = 0; i <= WINDOW_SIZE; ++i) {
if (frames[i]->apriltag_fts.size() > 0) {
tag_index.push_back(i);
} else
continue;
}
ROS_WARN("solveLocalization fails...!, there are only %d tags ", tag_index.size());
clearState();
return;
}
/*
for (unsigned int i = 0; i <= WINDOW_SIZE; ++i) {
Vector3d t_w = frames[i]->P_w;
ROS_INFO_STREAM("after******Global P_w " << i << " : " << t_w.transpose());
}*/
if(failureDetection() || frames[window_counter]->apriltag_fts.size() < 1) {
ROS_WARN("failure detection!");
clearState();
return;
}
ROS_INFO_STREAM("Estimated position : " << frames[window_counter]->P_w.transpose());
slideWindow();
#ifdef USE_DATA_RECORDER
if (saveData(&file_go, frames[WINDOW_SIZE-1]->id, frames[WINDOW_SIZE-1]->R_w_b, frames[WINDOW_SIZE-1]->P_w))
ROS_INFO("saving data successess!");
#endif
ROS_INFO("__________________________location solved___________________________________________");
}
}
void Estimator::predict()
{
Matrix3d R_c_w;
Vector3d P_c;
if (!solveGlobalRT(window_counter, R_c_w, P_c, 1, false)) {
ROS_INFO("Fail solving position from tag");
return;
} else {
Matrix3d R_w_b = R_c_w.transpose() * ric.transpose();
Vector3d P_w = - R_c_w.transpose() * (ric.transpose() * tic + P_c);
ROS_INFO_STREAM("Multiple AprilTag P_w : " << P_w.transpose());
#ifdef USE_DATA_RECORDER
if (saveData(&file_true, frames[WINDOW_SIZE]->id, R_w_b, P_w))
ROS_INFO("saving data successess!");
if (file_tag_num.is_open()) {
try {
file_tag_num << frames[WINDOW_SIZE]->id << " " << frames[WINDOW_SIZE]->apriltag_fts.size() << "\n";
} catch (exception& e) {
ROS_ERROR("saving data fails...");
}
} else {
ROS_ERROR("saving data fails...");
}
#endif
}
if (frames[window_counter]->apriltag_fts.size() >= 4) {
#ifdef USE_LED_MODE
if (!solvePnPByLeds(window_counter, R_c_w, P_c, false)) {
ROS_INFO("Fail solving position from tag");
return;
}
#else
if (!solveGlobalRT(window_counter, R_c_w, P_c, 1, false)) {
ROS_INFO("Fail solving position from tag");
return;
}
#endif
Matrix3d R_w_b = R_c_w.transpose() * ric.transpose();
// Vector3d P_w = - R_c_w.transpose() * ric.transpose() * (ric * P_c + tic);
Vector3d P_w = - R_c_w.transpose() * (ric.transpose() * tic + P_c);
frames[window_counter]->setPosition(P_w);
frames[window_counter]->setRotation(R_w_b);
ROS_INFO_STREAM("AprilTag P_w : " << P_w.transpose());
#ifdef USE_DATA_RECORDER
if (saveData(&file_pnp, frames[WINDOW_SIZE]->id, R_w_b, P_w))
ROS_INFO("saving data successess!");
#endif
} else {
double dt = frames[window_counter]->pre_integration->sum_dt;
Vector3d delta_p = frames[window_counter]->pre_integration->delta_p;
Vector3d delta_v = frames[window_counter]->pre_integration->delta_v;
Matrix3d delta_r = frames[window_counter]->pre_integration->delta_q.toRotationMatrix();
//TODO predict P, V by pre-integration
Vector3d Pi = frames[window_counter-1]->P_w;
Vector3d Vi = frames[window_counter-1]->V_w;
Matrix3d Ri = frames[window_counter-1]->R_w_b;
Vector3d Pj_hat = Pi + Vi * dt - 0.5 / SCALE_TO_METRIC * g * dt * dt + 1.0 / SCALE_TO_METRIC * Ri * delta_p;
Vector3d Vj_hat = Vi - 1.0 / SCALE_TO_METRIC * g * dt + 1.0 / SCALE_TO_METRIC * Ri * delta_v;
Matrix3d Rj_hat = Ri * delta_r;
frames[window_counter]->setPosition(Pj_hat);
frames[window_counter]->setRotation(Rj_hat);
frames[window_counter]->setVelocity(Vj_hat);
}
}
bool Estimator::initialStructure()
{
vector<int> tag_index;
for (unsigned int i = 0; i <= WINDOW_SIZE; ++i) {
if (frames[i]->apriltag_fts.size() > 0) {
tag_index.push_back(i);
} else
continue;
}
if (tag_index.size() < 2) {
ROS_INFO("Less than two tag frame in the window");
return false;
}
if (tag_index.size() < 1) {
ROS_INFO("non tag frame in the window");
clearState();
return false;
}
int idx;
if(!getTriangulateCandidate(tag_index, idx))
return false;
else
ROS_INFO("Get two Tag frame: %d and %d ", idx, tag_index.back());
// construct: setRotation setPosition setPoints
if(!construct(idx, tag_index.back())) {
ROS_INFO("Global SFM fails!");
marginalization_flag = MARGIN_OLD;
return false;
}
// visualInitialAlign: setBiasGyro setBaisAccelerator setVelocity setGravity setScale
if (!visualInitialAlign()) {
ROS_INFO("Misalign visual structure with IMU");
return false;
}
return true;
}
bool Estimator::solveLocalization()
{
if (window_counter < WINDOW_SIZE)
return false;
triangulatePointMap();
if (!optimization())
return false;
return true;
}
bool Estimator::optimization()
{
TicToc t_op;
ceres::Problem problem;
ceres::LossFunction* loss_function;
loss_function = new ceres::CauchyLoss(1.0);
/*****block*****/
for (unsigned int i = 0; i <= WINDOW_SIZE; ++i) {
ceres::LocalParameterization* local_parameterization = new PoseLocalParameterization();
problem.AddParameterBlock(frames[i]->para_Pose, SIZE_POSE, local_parameterization);
problem.AddParameterBlock(frames[i]->para_SpeedBias, SIZE_SPEEDBIAS);
}
for (unsigned int i = 0; i < NUM_OF_CAM; ++i) {
ceres::LocalParameterization* local_parameterization = new PoseLocalParameterization();
problem.AddParameterBlock(para_Ex_Pose, SIZE_POSE, local_parameterization);
problem.SetParameterBlockConstant(para_Ex_Pose);
}
/*****IMU reidual*****/
for (unsigned int i = 1; i <= WINDOW_SIZE; ++i) {
if (frames[i]->pre_integration->sum_dt > 10.0)
continue;
IMUFactor* imu_factor = new IMUFactor(frames[i]->pre_integration.get());
problem.AddResidualBlock(imu_factor, NULL, frames[i-1]->para_Pose, frames[i-1]->para_SpeedBias,
frames[i]->para_Pose, frames[i]->para_SpeedBias);
}
#ifdef USE_LED_MODE
// tag center blocks
for (auto& tag_m : tags_map) {
AprilTagInstance* tag_instance = tag_m.second;
problem.AddParameterBlock(tag_instance->position_center, 3);
problem.SetParameterBlockConstant(tag_instance->position_center);
}
// tag center residuals
for (auto& tag_m : tags_map) {
AprilTagInstance* tag_instance = tag_m.second;
for (auto& tag_ftr : tag_instance->tag_obs) {
Vector3d center = tag_ftr->ftr_center;
ConstPointFactor* point_factor = new ConstPointFactor(center);
problem.AddResidualBlock(point_factor, loss_function, tag_ftr->frame->para_Pose, para_Ex_Pose, tag_instance->position_center);
}
}
#else
// tag corner blocks
for (auto& tag_m : tags_map) {
AprilTagInstance* tag_instance = tag_m.second;
for (unsigned int i = 0; i < 4; ++i) {//charles
problem.AddParameterBlock(tag_instance->position[i], 3);
problem.SetParameterBlockConstant(tag_instance->position[i]);
}
}
// tag corner residuals
for (auto& tag_m : tags_map) {
AprilTagInstance* tag_instance = tag_m.second;
for (auto& tag_ftr : tag_instance->tag_obs) {
for (unsigned int i = 0; i < 4; ++i) {
Vector3d corner = tag_ftr->tag_fts[i]->pt_c;
ConstPointFactor* point_factor = new ConstPointFactor(corner);
problem.AddResidualBlock(point_factor, loss_function, tag_ftr->frame->para_Pose, para_Ex_Pose, tag_instance->position[i]);
}
}
}
#endif
/*
for (auto& pt_m : pts_map) {
Point* pt = pt_m.second;
if (pt->obs.size() < 3 || pt->type != Point::TYPE_TRIANGULATED)
continue;
problem.AddParameterBlock(pt->position, 3);
// problem.SetParameterBlockConstant(pt->position);
}
for (auto& pt_m : pts_map) {
Point* pt = pt_m.second;
if (pt->obs.size() < 3 || pt->type != Point::TYPE_TRIANGULATED)
continue;
for (auto& ftr : pt->obs) {
PointFactor* point_factor = new PointFactor(ftr->pt_c);
problem.AddResidualBlock(point_factor, loss_function, ftr->frame->para_Pose, para_Ex_Pose, pt->position);
}
} */
ceres::Solver::Options options;
options.linear_solver_type = ceres::DENSE_SCHUR;
options.trust_region_strategy_type = ceres::DOGLEG;
// options.trust_region_strategy_type = ceres::LEVENBERG_MARQUARDT;
// options.max_num_iterations = NUM_ITERATIONS; // This will make system diverges
if (marginalization_flag == MARGIN_OLD)
options.max_solver_time_in_seconds = SOLVER_TIME * 4.0 / 5.0;
else
options.max_solver_time_in_seconds = SOLVER_TIME;
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
if (summary.termination_type == ceres::CONVERGENCE || summary.final_cost < 5e-03)
{
ROS_INFO("Optimization() : Ceres converge!");
}
else
{
ROS_INFO("Optimization() : Ceres does not converge...");
return false;
}
// Frames
for (unsigned int i; i <= WINDOW_SIZE; ++i) {
frames[i]->resetPRVBaBgByPara();
}
// Points
for (auto& pt_m : pts_map) {
Point* pt = pt_m.second;
if (pt->type == Point::TYPE_TRIANGULATED) {
pt->setPositionByPara();
}
}
/*
Vector3d ex_t(para_Ex_Pose[0], para_Ex_Pose[1], para_Ex_Pose[2]);
ROS_INFO_STREAM("Calibrated ex_t " << ex_t.transpose());*/
ROS_INFO("Optimization ceres cost : %f", t_op.toc());
return true;
}
void Estimator::triangulatePointMap()
{
for (auto& tag : tags_map) {
if (tag.second->tag_obs.size() < 2)
continue;
for (unsigned int i = 0; i < 4; ++i) {
Eigen::MatrixXd svd_A(2 * tag.second->tag_obs.size(), 4);
int svd_idx = 0;
for (auto ftr_tag : tag.second->tag_obs) {
Feature* ftr = ftr_tag->tag_fts[i];
int frame_idx = ftr->frame->window_counter;
Eigen::Matrix<double, 3, 4> P;
Eigen::Matrix3d R_w_b = frames[frame_idx]->R_w_b;
Eigen::Vector3d t_w_b = frames[frame_idx]->P_w;
Eigen::Vector3d t_b_w = -R_w_b.transpose() * t_w_b;
Eigen::Vector3d t_c_b = -ric.transpose() * tic;
Eigen::Matrix3d R_c_w = ric.transpose() * R_w_b.transpose();
Eigen::Vector3d t_c_w = ric.transpose() * t_b_w + t_c_b;
P.leftCols<3>() = R_c_w;
P.rightCols<1>() = t_c_w;
//Eigen::Vector3d f = ftr->pt_c.normalized();
Eigen::Vector3d f = ftr->pt_c;
svd_A.row(svd_idx++) = f[0] * P.row(2) - f[2] * P.row(0);
svd_A.row(svd_idx++) = f[1] * P.row(2) - f[2] * P.row(1);
}
ROS_ASSERT(svd_idx == svd_A.rows());
Eigen::Vector4d svd_V = Eigen::JacobiSVD<Eigen::MatrixXd>(svd_A, Eigen::ComputeThinV).matrixV().rightCols<1>();
Vector3d P_w(svd_V[0]/svd_V[3], svd_V[1]/svd_V[3], svd_V[2]/svd_V[3]);
double dep = P_w.z();
// ROS_INFO_STREAM("Tag ID: " << tag.first << " Corner Index: " << i << " Position: " << P_w.transpose());
}
}
for (auto& pt_m : pts_map) {
Point* pt = pt_m.second;
if (pt->obs.size() < 3 || pt->obs.front()->frame->window_counter > WINDOW_SIZE - 3)
continue;
if (pt->type == Point::TYPE_TRIANGULATED)
continue;
Eigen::MatrixXd svd_A(2 * pt->obs.size(), 4);
int svd_idx = 0;
for (auto& ftr : pt->obs) {
int frame_idx = ftr->frame->window_counter;
Eigen::Matrix<double, 3, 4> P;
Eigen::Matrix3d R_w_b = frames[frame_idx]->R_w_b;
Eigen::Vector3d t_w_b = frames[frame_idx]->P_w;
Eigen::Vector3d t_b_w = -R_w_b.transpose() * t_w_b;
Eigen::Vector3d t_c_b = -ric.transpose() * tic;
Eigen::Matrix3d R_c_w = ric.transpose() * R_w_b.transpose();
Eigen::Vector3d t_c_w = ric.transpose() * t_b_w + t_c_b;
P.leftCols<3>() = R_c_w;
P.rightCols<1>() = t_c_w;
// Eigen::Vector3d f = ftr->pt_c.normalized();
Eigen::Vector3d f = ftr->pt_c;
svd_A.row(svd_idx++) = f[0] * P.row(2) - f[2] * P.row(0);
svd_A.row(svd_idx++) = f[1] * P.row(2) - f[2] * P.row(1);
}
ROS_ASSERT(svd_idx == svd_A.rows());
Eigen::Vector4d svd_V = Eigen::JacobiSVD<Eigen::MatrixXd>(svd_A, Eigen::ComputeThinV).matrixV().rightCols<1>();
Vector3d P_w(svd_V[0]/svd_V[3], svd_V[1]/svd_V[3], svd_V[2]/svd_V[3]);
double dep = P_w.z();
/*
bool throwout_flag = false;//charles
for (auto& ftr : pt->obs) {
int frame_n = ftr->frame->window_counter;
Eigen::Matrix3d R_w_b = frames[frame_n]->R_w_b;
Vector3d P_w = frames[frame_n]->P_w;
Vector3d P_c;
if (!projectW2C(R_w_b, P_w, ric, tic, P_w, P_c)) {
throwout_flag = true;
continue;
}
}
if (!throwout_flag)
ROS_INFO("Yahoo!!!");*/
// pt->setPosition(P_w);
// ROS_INFO_STREAM("******New Point: " << pt->id << " Position: " << P_w.transpose());
/*
if (P_w.z() < 200 && P_w.z() > 1.0) {
pt->setPosition(P_w);
ROS_INFO_STREAM("******New Point: " << pt->id << " Position: " << P_w.transpose());
} else {
pt->type = Point::TYPE_INIT;
}*/
}
}
bool Estimator::failureDetection()
{
if (frames[WINDOW_SIZE]->Ba.norm() > 5) {
ROS_INFO(" big IMU acc bias estimation %f", frames[WINDOW_SIZE]->Ba.norm());
return true;
}
if (frames[WINDOW_SIZE]->Bg.norm() > 3.0)
{
ROS_INFO(" big IMU gyr bias estimation %f", frames[WINDOW_SIZE]->Bg.norm());
return true;
}
return false;
}
void Estimator::processImage(const AprilTagMap& _apriltag_map, const FeatureMap& _ftr_map, const std_msgs::Header& _header)
{
//frames[window_counter].reset(new Frame(Frame::frame_counter++, window_counter, _header.stamp.toSec()));
// ROS_INFO("window_counter : %d", window_counter);
FramePtr frame = frames[window_counter];
frame->setFrameId(Frame::frame_counter++);
frame->setWindowCounter(window_counter);
frame->setTimestamp(_header.stamp.toSec());
for (auto& raw_ftr : _ftr_map) {
// Create new feature observation
Feature* ftr = new Feature(frame.get(), raw_ftr.second, _header.stamp.toSec(), FeatureType::POINT);
int id = raw_ftr.first;
auto it = pts_map.find(id);
if (it == pts_map.end()) {
// Create new point
Point* pt = new Point(id);
// Insert new Point into point map
pts_map[id] = pt;
// Add observation into Point and Frame
ftr->setPoint(pt);
pt->addFrameRef(ftr);
frame->addFeature(ftr);
} else {
// Add new observation into Point and Frame
ftr->setPoint(it->second);
it->second->addFrameRef(ftr);
frame->addFeature(ftr);
}
}
int valid_tag_num = 0;
for (auto& raw_tag : _apriltag_map) {
// Create apriltag, generate corresponding point, and add it into frames[window_counter]
int tag_id = raw_tag.first;
vector<Feature*> fts;
for (auto& tag_pt : raw_tag.second) {
Feature* ftr = new Feature(frame.get(), tag_pt, _header.stamp.toSec(), FeatureType::TAG);
fts.push_back(ftr);
}
// Create new AprilTag observation
ROS_ASSERT(fts.size() == 4);
AprilTagFeature* tag_ftr = new AprilTagFeature(frame.get(), fts, _header.stamp.toSec());
auto it = tags_map.find(tag_id);
if (it == tags_map.end()) {
double size_w; Matrix3d R; Vector3d t;
if (!consultDictionary(tag_id, R, t, size_w)) {
ROS_INFO("Detected an unregisterd AprilTag %d!", tag_id);
continue;
}
/******************************************/
// Create new AprilTag
AprilTagInstance* tag_instance = new AprilTagInstance(tag_id, size_w, R, t);
// Insert new AprilTag into tag map
tags_map[tag_id] = tag_instance;
// Add new tag observatio into AprilTagInstance and Frame
tag_ftr->setAprilTag(tag_instance);
tag_instance->addFrameRef(tag_ftr);
frame->addAprilTag(tag_ftr);
valid_tag_num++;
} else {
tag_ftr->setAprilTag(it->second);
it->second->addFrameRef(tag_ftr);
frame->addAprilTag(tag_ftr);
valid_tag_num++;
}
//ROS_INFO("Detected AprilTag %d!", tag_id);
}
ROS_INFO_STREAM(valid_tag_num << " AprilTags detected!");
//TODO Compute Parallex and design which frame to be marginalized out
if (window_counter > 0) {
double parallex = 0.0;
bool result = computeParallex(window_counter-1, window_counter, parallex);
// ROS_INFO("parallex %f in %d window index", parallex, window_counter);
if (result && parallex > MIN_PARALLAX) {// MIN_PARALLAX = 0.0217
marginalization_flag = MARGIN_OLD;
ROS_INFO("MARGIN_OLD");
} else {
marginalization_flag = MARGIN_SECOND_NEW;
ROS_INFO("MARGIN_SECOND_NEW");
}
}
}
void Estimator::processIMU(const double& _dt, const Vector3d& _linear_acceleration, const Vector3d& _angular_velocity)
{
double dt = _dt;
if (first_imu == true) {
first_imu = false;
acc_0 = _linear_acceleration;
gyr_0 = _angular_velocity;
}
FramePtr frame = frames[window_counter];
if (!frame) {
ROS_WARN("frames[ %d ] has not been instantialize", window_counter);
return;
}
// Only happen in initialization stage
if (!frame->pre_integration) {
frame->pre_integration.reset(new IntegrationBase{acc_0, gyr_0, frames[window_counter]->Ba, frames[window_counter]->Bg});
}
if (window_counter != 0) {
frame->pre_integration->push_back(dt, _linear_acceleration, _angular_velocity);
}
acc_0 = _linear_acceleration;
gyr_0 = _angular_velocity;
}
void Estimator::slideWindow()
{
switch (marginalization_flag) {
case MARGIN_OLD:
slideWindowOld();
break;
case MARGIN_SECOND_NEW:
slideWindowNew();
break;
default:
ROS_WARN("Wrong marginalization flag!");
break;
}
// TODO Only points and tags invisible to any frame will be deleted. But actually we can delete it when its observations drop to one.
int n_deleted_point = 0;
int n_deleted_tag = 0;
for (auto it = pts_map.begin(), it_next = pts_map.begin(); it != pts_map.end(); it = it_next) {
it_next++;
if (it->second->type == Point::TYPE_DELETED) {
n_deleted_point++;
pts_map.erase(it);
}
}
for (auto it = tags_map.begin(), it_next = tags_map.begin(); it != tags_map.end(); it = it_next) {
it_next++;
if (it->second->type == AprilTagInstance::TYPE_DELETED) {
n_deleted_tag++;
tags_map.erase(it);
}
}
}
void Estimator::slideWindowOld()
{
for (unsigned int i = 0; i < WINDOW_SIZE; ++i) {
frames[i].swap(frames[i+1]);
frames[i]->setWindowCounter(i);
}
frames[WINDOW_SIZE]->clear();
frames[WINDOW_SIZE].reset(new Frame());
frames[WINDOW_SIZE]->setWindowCounter(WINDOW_SIZE);
frames[WINDOW_SIZE]->setPosition(frames[WINDOW_SIZE-1]->P_w);
frames[WINDOW_SIZE]->setRotation(frames[WINDOW_SIZE-1]->R_w_b);
frames[WINDOW_SIZE]->setVelocity(frames[WINDOW_SIZE-1]->V_w);
frames[WINDOW_SIZE]->setBa(frames[WINDOW_SIZE-1]->Ba);
frames[WINDOW_SIZE]->setBg(frames[WINDOW_SIZE-1]->Bg);
frames[WINDOW_SIZE]->pre_integration.reset(new IntegrationBase{acc_0, gyr_0, frames[WINDOW_SIZE]->Ba, frames[WINDOW_SIZE]->Bg});
}
void Estimator::slideWindowNew()
{
frames[WINDOW_SIZE-1].swap(frames[WINDOW_SIZE]);
frames[WINDOW_SIZE-1]->setWindowCounter(WINDOW_SIZE-1);
frames[WINDOW_SIZE-1]->fusePreintegrationInFront(frames[WINDOW_SIZE]->pre_integration);//charles
frames[WINDOW_SIZE]->clear();
frames[WINDOW_SIZE].reset(new Frame());
frames[WINDOW_SIZE]->setWindowCounter(WINDOW_SIZE);
frames[WINDOW_SIZE]->setPosition(frames[WINDOW_SIZE-1]->P_w);
frames[WINDOW_SIZE]->setRotation(frames[WINDOW_SIZE-1]->R_w_b);
frames[WINDOW_SIZE]->setVelocity(frames[WINDOW_SIZE-1]->V_w);
frames[WINDOW_SIZE]->setBa(frames[WINDOW_SIZE-1]->Ba);
frames[WINDOW_SIZE]->setBg(frames[WINDOW_SIZE-1]->Bg);
frames[WINDOW_SIZE]->pre_integration.reset(new IntegrationBase{acc_0, gyr_0, frames[WINDOW_SIZE]->Ba, frames[WINDOW_SIZE]->Bg});
}
bool Estimator::computeParallex(int i, int j, double& parallex)
{
vector<pair<Feature*, Feature*>> match_points;
getCorrespondingPoints(i, j, match_points);
if (match_points.size() > 20) {
double sum_parallex;
for (auto& m_pt : match_points) {
double parallex;
computeDistanceByImg(m_pt.first->pt_c, m_pt.second->pt_c, parallex);
sum_parallex += parallex;
}
parallex = sum_parallex / match_points.size();
return true;
} else {
ROS_WARN("No enough matched points");
return false;
}
}
void Estimator::computeDistanceByImg(const Vector3d& pt_1, const Vector3d& pt_2, double& parallex)
{
Vector2d dist = pt_1.head<2>() / pt_1.z() - pt_2.head<2>() / pt_2.z();
parallex = dist.norm();
}
void Estimator::getCorrespondingPoints(int i, int j, vector< pair< Feature*, Feature* > >& match_points)
{
vector<pair<Feature*, Feature*>> pt_pairs;
auto it = frames[i]->fts.begin();
auto it_end = frames[i]->fts.end();
for (;it != it_end; ++it) {
Feature* match_ftr = (*it)->point->findFrameRef(frames[j].get());
// return NULL when not found
if (!match_ftr) {
continue;
} else {
pt_pairs.push_back(make_pair(*it, match_ftr));
}
}
match_points = pt_pairs;
}
void Estimator::getCorrespondingTags(int i, int j, vector< std::pair< AprilTagFeature*, AprilTagFeature* > >& match_tags)
{
vector<pair<AprilTagFeature*,AprilTagFeature*>> tag_pair;
auto it = frames[i]->apriltag_fts.begin(); auto it_end = frames[i]->apriltag_fts.end();
for (;it != it_end; ++it) {
AprilTagFeature* match_tag = (*it)->tag_instance->findFrameRef(frames[j].get());
if (!match_tag) {
tag_pair.push_back(make_pair(*it, match_tag));
} else {
continue;
}
}
match_tags = tag_pair;
}
void Estimator::triangulatePointsInTwoFrames(int idx_a, const Eigen::Matrix<double, 3, 4>& Pose_a,
int idx_b, const Eigen::Matrix<double, 3, 4>& Pose_b)
{
ROS_ASSERT(idx_a != idx_b);
vector<pair<Feature*, Feature*>> match_fts;
getCorrespondingPoints(idx_a, idx_b, match_fts);
for (auto& ftr_pair : match_fts) {
if (ftr_pair.first->point->type == Point::TYPE_TRIANGULATED)
continue;
Vector3d pt_w;
Vector2d pt_a = ftr_pair.first->pt_c.head<2>() / ftr_pair.first->pt_c.z();
Vector2d pt_b = ftr_pair.second->pt_c.head<2>() / ftr_pair.second->pt_c.z();
triangulatePoint(Pose_a, Pose_b, pt_a, pt_b, pt_w);
Vector3d pt_c;
if (!(projectW2C(Pose_a.block<3, 3>(0, 0), Pose_a.block<3, 1>(0, 3), pt_w, pt_c) && projectW2C(Pose_b.block<3, 3>(0, 0), Pose_b.block<3, 1>(0, 3), pt_w, pt_c))) {
continue;
}
ftr_pair.first->point->setPosition(pt_w);
}
}
void Estimator::triangulatePoint(const Matrix< double, int(3), int(4) >& _P_a,
const Matrix< double, int(3), int(4) >& _P_b,
const Vector2d& _pt_a, const Vector2d& _pt_b, Vector3d& pt_w)
{
Matrix4d design_matrix = Matrix4d::Zero();
design_matrix.row(0) = _pt_a[0] * _P_a.row(2) - _P_a.row(0);
design_matrix.row(1) = _pt_a[1] * _P_a.row(2) - _P_a.row(1);
design_matrix.row(2) = _pt_b[0] * _P_b.row(2) - _P_b.row(0);
design_matrix.row(3) = _pt_b[1] * _P_b.row(2) - _P_b.row(1);
Vector4d triangulated_point;
triangulated_point = design_matrix.jacobiSvd(Eigen::ComputeFullV).matrixV().rightCols<1>();
pt_w(0) = triangulated_point(0) / triangulated_point(3);
pt_w(1) = triangulated_point(1) / triangulated_point(3);
pt_w(2) = triangulated_point(2) / triangulated_point(3);
}
bool Estimator::solveGlobalRT(int idx, Matrix3d& R, Vector3d& t, int flag, bool use_initial)// R_c_w, t_c
{
int pt_num = frames[idx]->fts.size();
int tag_num = frames[idx]->apriltag_fts.size();
if (flag == 1 && tag_num < 1)
return false;
if (flag == 2 && pt_num < 10)
return false;
if (flag == 0 && tag_num < 1 && pt_num < 10)
return false;
vector<Vector3d> pts;
vector<Vector2d> pxs;
if (flag == 0 || flag == 2) {
for (auto ftr : frames[idx]->fts) {
if (ftr->point->type != Point::TYPE_TRIANGULATED)
continue;
pts.push_back(ftr->point->P_w);
pxs.push_back(ftr->pt_c.head<2>());
}
}
if (flag == 0 || flag == 1) {
for (auto tag : frames[idx]->apriltag_fts) {
vector<Vector2d> tag_pxs;
tag_pxs.clear();
// assert(tag->tag_fts.size() == 4);
for (auto corner : tag->tag_fts) {
tag_pxs.push_back(corner->pt_c.head<2>());
}
pts.insert(pts.end(), tag->tag_instance->pts_w.begin(), tag->tag_instance->pts_w.end());
pxs.insert(pxs.end(), tag_pxs.begin(), tag_pxs.end());
}
}
cv::Matx33d cam = cv::Matx33d::eye(); cv::Vec4d dist(0, 0, 0, 0);
bool result = solveRTByPnP(pts, pxs, R, t, cam, dist, use_initial); // true: use initial values
if (!result)
return false;
return true;
}
bool Estimator::solvePnPByLeds(int idx, Matrix3d& R, Vector3d& t, bool use_initial)// R_c_w, t_c
{
int tag_num = frames[idx]->apriltag_fts.size();
vector<Vector3d> pts;
vector<Vector2d> pxs;
if (tag_num < 4)
return false;
for (auto tag : frames[idx]->apriltag_fts) {
pts.push_back(tag->tag_instance->pt_center);
pxs.push_back(tag->ftr_center.head<2>());
}
cv::Matx33d cam = cv::Matx33d::eye(); cv::Vec4d dist(0, 0, 0, 0);
bool result = solveRTByPnP(pts, pxs, R, t, cam, dist, use_initial); // true: use initial values
if (!result)
return false;
return true;
}
bool Estimator::solveRTByPnP(const vector<Vector3d>& _pts, const vector<Vector2d>& _pxs,
Matrix3d& R, Vector3d& t, cv::Matx33d _cam , cv::Vec4d _dist, bool use_initial)
{
vector<cv::Point3d> pts;
vector<cv::Point2d> pxs;
for (unsigned int i = 0; i < _pts.size(); ++i) {
pts.push_back(cv::Point3d(_pts[i].x(),
_pts[i].y(),
_pts[i].z()));
pxs.push_back(cv::Point2d(_pxs[i].x(), _pxs[i].y()));
}
if (pts.size() < 4)
return false;
cv::Mat rvec, tvec, tmp_r;
// Initial values of rvec and tvec
cv::eigen2cv(R, tmp_r);
cv::Rodrigues(tmp_r, rvec);
cv::eigen2cv(t, tvec);
bool pnp_result = cv::solvePnP(pts, pxs, _cam, _dist, rvec, tvec, use_initial);
if (!pnp_result)
return false;
cv::Matx33d r;
cv::Rodrigues(rvec, r);
R << r(0,0), r(0,1), r(0,2), r(1,0), r(1,1), r(1,2), r(2,0), r(2,1), r(2,2);
t << tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2);
return true;
}
bool Estimator::getTriangulateCandidate(const vector< int >& _tag_index, int& idx)
{
int nearest_idx = _tag_index.back();
for (auto& i : _tag_index) {
if (i == nearest_idx)
break;
double parallex;
bool result = computeParallex(i, nearest_idx, parallex);
if (result && (parallex > MIN_PARALLAX)) {
idx = i;
// ROS_INFO("Find proper initial AprilTag frame...");
return true;
}
}
ROS_WARN("Fail to triangulate AprilTag frame!");
return false;
}
bool Estimator::visualInitialAlign()
{
if(!solveGyroscopeBias()) {
return false;
}
//ROS_INFO_STREAM("******Bas : " << std::endl << frames[window_counter]->Bg.transpose());
if(!linearAlignment())
return false;
return true;
}
bool Estimator::solveGyroscopeBias()
{
Eigen::Matrix3d A;
Vector3d b;
Vector3d delta_bg;
delta_bg.setZero();
A.setZero();
b.setZero();
for (unsigned int i = 0; i < WINDOW_SIZE; ++i) {
Eigen::Matrix3d J_bg;
J_bg.setZero();
J_bg = frames[i]->pre_integration->jacobian.template block<3, 3>(O_R, O_BG);
Vector3d residual;
residual.setZero();
Eigen::Quaterniond q_ij(frames[i]->R_w_b.transpose() * frames[i+1]->R_w_b);
residual = 2 * (frames[i]->pre_integration->delta_q.inverse() * q_ij).vec();
A += J_bg.transpose() * J_bg;
b += J_bg.transpose() * residual;
}
A = A * 1000;
b = b * 1000;
delta_bg = A.ldlt().solve(b);
if (std::isnan(delta_bg(0)) || std::isnan(delta_bg(1)) || std::isnan(delta_bg(2))) {
ROS_WARN("g is nan");
return false;
}
ROS_WARN_STREAM("Gyroscope bias initial calibration: " << delta_bg.transpose());
for (unsigned int i = 0; i <= WINDOW_SIZE; ++i) {
frames[i]->setBa(Vector3d::Zero());
frames[i]->setBg(delta_bg);
frames[i]->pre_integration->repropagate(Vector3d::Zero(), frames[i]->Bg);
}
return true;
}
bool Estimator::linearAlignment()
{
Vector3d estimate_g;
VectorXd x;
x.setZero();
int n_state = (WINDOW_SIZE + 1) * 3 + 3;
Eigen::MatrixXd A(n_state, n_state);
VectorXd b(n_state);
A.setZero();
b.setZero();
for (unsigned int i = 0; i < WINDOW_SIZE; ++i) {
Eigen::MatrixXd H(6, 9);
VectorXd z(6);
H.setZero();
z.setZero();
double dt = frames[i+1]->pre_integration->sum_dt;
H.block<3, 3>(0, 0) = -SCALE_TO_METRIC * dt * Matrix3d::Identity();
H.block<3, 3>(0, 6) = frames[i]->R_w_b.transpose() * dt * dt / 2 * Matrix3d::Identity();
z.block<3, 1>(0, 0) = frames[i+1]->pre_integration->delta_p + frames[i]->R_w_b.transpose() * frames[i+1]->R_w_b * tic - tic - SCALE_TO_METRIC * frames[i]->R_w_b.transpose() * (frames[i+1]->P_w - frames[i]->P_w);
H.block<3, 3>(3, 0) = -SCALE_TO_METRIC * Matrix3d::Identity();
H.block<3, 3>(3, 3) = SCALE_TO_METRIC * frames[i]->R_w_b.transpose() * frames[i+1]->R_w_b;
H.block<3, 3>(3, 6) = frames[i]->R_w_b.transpose() * dt * Matrix3d::Identity();
z.block<3, 1>(3, 0) = frames[i+1]->pre_integration->delta_v;
Matrix<double, 6, 6> cov_inv = Matrix<double, 6, 6>::Zero();
cov_inv.setIdentity();
MatrixXd tmp_A = H.transpose() * cov_inv * H;
VectorXd tmp_b = H.transpose() * cov_inv * z;
A.block<6, 6>(i*3, i*3) += tmp_A.topLeftCorner<6, 6>();
b.segment<6>(i*3) += tmp_b.head<6>();
A.bottomRightCorner<3, 3>() += tmp_A.bottomRightCorner<3, 3>();
b.tail<3>() += tmp_b.tail<3>();
A.block<6, 3>(i*3, n_state - 3) += tmp_A.topRightCorner<6, 3>();
A.block<3, 6>(n_state - 3, i*3) += tmp_A.bottomLeftCorner<3, 6>();
}
A = A * 1000;
b = b * 1000;
x = A.ldlt().solve(b);
estimate_g = x.tail<3>();
if (std::isnan(estimate_g(0)) || std::isnan(estimate_g(1)) || std::isnan(estimate_g(2))) {
ROS_WARN("g is nan");
return false;
}
if(fabs(estimate_g.norm() - G.norm()) > 1.0) {
ROS_WARN("g is wrong");
return false;
}
ROS_WARN_STREAM("Gravity raw " << estimate_g.norm() << " " << estimate_g.transpose());
VectorXd estimate_x;
RefineGravity(estimate_g, estimate_x);
g = estimate_g;
ROS_WARN_STREAM("Gravity refine " << g.norm() << " " << g.transpose());
// Set initial velocity
for (unsigned int i = 0; i <= WINDOW_SIZE; ++i) {
frames[i]->setVelocity( frames[i]->R_w_b * estimate_x.segment<3>(i*3));
}
// Set constant gravity
return true;
}
Eigen::MatrixXd TangentBasis(Vector3d& g0)
{
Vector3d b, c;
Vector3d a = g0.normalized();
Vector3d tmp(0, 0, 1);
if(a == tmp)// if g0 does point to z axis
tmp << 1, 0, 0;
b = (tmp - a * (a.transpose() * tmp)).normalized();
c = a.cross(b);
MatrixXd bc(3, 2);
bc.block<3, 1>(0, 0) = b;
bc.block<3, 1>(0, 1) = c;
return bc;
}
void Estimator::RefineGravity(Vector3d& _g, VectorXd& _x)
{
Vector3d g0 = _g.normalized() * G.norm();
Vector3d lx, ly;
int n_state = (WINDOW_SIZE + 1) * 3 + 2;
Eigen::MatrixXd A(n_state, n_state);
VectorXd b(n_state);
A.setZero();
b.setZero();
for (int k = 0; k < 4; ++k) {
MatrixXd lxly(3, 2);
lxly = TangentBasis(g0);
for (unsigned int i = 0; i < WINDOW_SIZE; ++i) {
Eigen::MatrixXd H(6, 8);
VectorXd z(6);
H.setZero();
z.setZero();
double dt = frames[i+1]->pre_integration->sum_dt;
H.block<3, 3>(0, 0) = -SCALE_TO_METRIC * dt * Matrix3d::Identity();
H.block<3, 2>(0, 6) = frames[i]->R_w_b.transpose() * dt * dt / 2 * Matrix3d::Identity() * lxly;
z.block<3, 1>(0, 0) = frames[i+1]->pre_integration->delta_p + frames[i]->R_w_b.transpose() * frames[i+1]->R_w_b * tic - tic - frames[i]->R_w_b.transpose() * dt * dt / 2 * g0 - SCALE_TO_METRIC * frames[i]->R_w_b.transpose() * (frames[i+1]->P_w - frames[i]->P_w);
H.block<3, 3>(3, 0) = -SCALE_TO_METRIC * Matrix3d::Identity();
H.block<3, 3>(3, 3) = SCALE_TO_METRIC * frames[i]->R_w_b.transpose() * frames[i+1]->R_w_b;
H.block<3, 2>(3, 6) = frames[i]->R_w_b.transpose() * dt * Matrix3d::Identity() * lxly;
z.block<3, 1>(3, 0) = frames[i+1]->pre_integration->delta_v - frames[i]->R_w_b.transpose() * dt * Matrix3d::Identity() * g0;
Matrix<double, 6, 6> cov_inv = Matrix<double, 6, 6>::Zero();
cov_inv.setIdentity();
MatrixXd tmp_A = H.transpose() * cov_inv * H;
VectorXd tmp_b = H.transpose() * cov_inv * z;
A.block<6, 6>(i*3, i*3) += tmp_A.topLeftCorner<6, 6>();
b.segment<6>(i*3) += tmp_b.head<6>();
A.bottomRightCorner<2, 2>() += tmp_A.bottomRightCorner<2, 2>();
b.tail<2>() += tmp_b.tail<2>();
A.block<6, 2>(i*3, n_state - 2) += tmp_A.topRightCorner<6, 2>();
A.block<2, 6>(n_state - 2, i*3) += tmp_A.bottomLeftCorner<2, 6>();
}
A = A * 1000.0;
b = b * 1000.0;
_x = A.ldlt().solve(b);
VectorXd dg = _x.tail<2>();
g0 = (g0 + lxly * dg).normalized() * G.norm();
}
ROS_INFO("D");
_g = g0;
}
bool Estimator::construct(int left_idx, int right_idx)
{
// int n_triang_start = 0;
// for (auto& pt_m : pts_map) {
// if (pt_m.second->type == Point::TYPE_TRIANGULATED)
// n_triang_start++;
// }
//ROS_INFO("Start: %d Points have been triangulated", n_triang_start);
Eigen::Matrix3d R_c[WINDOW_SIZE + 1];
Eigen::Quaterniond Quat_c[WINDOW_SIZE + 1];
Vector3d T_c[WINDOW_SIZE + 1];
Eigen::Matrix<double, 3, 4> Pose[WINDOW_SIZE + 1];
double rotation[WINDOW_SIZE + 1][4];
double translation[WINDOW_SIZE + 1][3];
Matrix3d R_c_w;
Vector3d P_c;
// ROS_INFO("A 1");
if (!solveGlobalRT(left_idx, R_c_w, P_c, 1, false)) // Global position and rotation
return false;
R_c[left_idx] = R_c_w;
Quat_c[left_idx] = R_c_w;
T_c[left_idx] = P_c;
Pose[left_idx].block<3, 3>(0, 0) = R_c[left_idx];
Pose[left_idx].block<3, 1>(0, 3) = T_c[left_idx];
// ROS_INFO("A 1 1");
if(!solveGlobalRT(right_idx, R_c_w, P_c, 1, false))
return false;
R_c[right_idx] = R_c_w;
Quat_c[right_idx] = R_c_w;
T_c[right_idx] = P_c;
Pose[right_idx].block<3, 3>(0, 0) = R_c[right_idx];
Pose[right_idx].block<3, 1>(0, 3) = T_c[right_idx];
// ROS_INFO("A 2");
/*
* 1. Construct: left_idx and right_idx
*/
triangulatePointsInTwoFrames(left_idx, Pose[left_idx], right_idx, Pose[right_idx]);
// ************************************************************************************** 测试solvePnP准不准,结果:准
// frames[left_idx]
// Vector2d pts_2 = frames[left_idx]->apriltag_fts.back()->tag_fts[0]->pt_c.head<2>();
// Vector3d pts_3 = frames[left_idx]->apriltag_fts.back()->tag_instance->pts_w[0];
//
// Vector2d pts_2_hat = (R_c[left_idx] * pts_3 + T_c[left_idx]).head<2>();
//
// for (unsigned int i = 0; i < 4; ++i) {
// Vector2d pts_2 = frames[left_idx]->apriltag_fts.back()->tag_fts[i]->pt_c.head<2>();
// Vector3d pts_3 = frames[left_idx]->apriltag_fts.back()->tag_instance->pts_w[i];
// Vector3d pts_2_s = R_c[left_idx] * pts_3 + T_c[left_idx];
// Vector2d pts_2_hat = pts_2_s.head<2>() / pts_2_s.z();
//
// ROS_INFO_STREAM("Tag " << frames[left_idx]->apriltag_fts.back()->tag_instance->id << "Projection****** TRUE: " << pts_2.transpose() << std::endl <<
// "--------------------------------------------ESTIMATED: " << pts_2_hat.transpose() );
// }
// ************************************************************************************** 测试triangulatePoint准不准, 结果: 准
/*
// triangulatePointMap
for (unsigned int i = 0; i < 4; ++i) {
Eigen::MatrixXd svd_A(2 * 2, 4);
int svd_idx = 0;
Vector3d f = frames[left_idx]->apriltag_fts.back()->tag_fts[i]->pt_c;
Pose[left_idx];
svd_A.row(svd_idx++) = f[0] * Pose[left_idx].row(2) - f[2] * Pose[left_idx].row(0);
svd_A.row(svd_idx++) = f[1] * Pose[left_idx].row(2) - f[2] * Pose[left_idx].row(1);
f = frames[right_idx]->apriltag_fts.back()->tag_fts[i]->pt_c;
Pose[right_idx];
svd_A.row(svd_idx++) = f[0] * Pose[right_idx].row(2) - f[2] * Pose[right_idx].row(0);
svd_A.row(svd_idx++) = f[1] * Pose[right_idx].row(2) - f[2] * Pose[right_idx].row(1);
ROS_ASSERT(svd_idx == svd_A.rows());
Eigen::Vector4d svd_V = Eigen::JacobiSVD<Eigen::MatrixXd>(svd_A, Eigen::ComputeThinV).matrixV().rightCols<1>();
Vector3d P_w(svd_V[0]/svd_V[3], svd_V[1]/svd_V[3], svd_V[2]/svd_V[3]);
ROS_INFO_STREAM("Tag " << frames[left_idx]->apriltag_fts.back()->tag_instance->id << " Pt_w****** TRUE: " << frames[left_idx]->apriltag_fts.back()->tag_instance->pts_w[i].transpose() << std::endl <<
"------------------------------------------------------ESTIMATED: " << P_w.transpose() );
}
*/
// ************************************************************************************** 测试solvePnP准不准,结果:准
/*
for (unsigned int i = 0; i < 4; ++i) {
Vector2d pt_i = frames[left_idx]->apriltag_fts.back()->tag_fts[i]->pt_c.head<2>();
Vector2d pt_j = frames[right_idx]->apriltag_fts.back()->tag_fts[i]->pt_c.head<2>();
Vector3d pt_w;
triangulatePoint(Pose[left_idx], Pose[right_idx], pt_i, pt_j, pt_w);
ROS_INFO_STREAM("Tag " << frames[left_idx]->apriltag_fts.back()->tag_instance->id << " Pt_w****** TRUE: " << frames[left_idx]->apriltag_fts.back()->tag_instance->pts_w[i].transpose() << std::endl <<
"------------------------------------------------------ESTIMATED: " << pt_w.transpose() );
}
*/
// **************************************************************************************
/*
* 2. Construct: idx+1 -> right_idx
*/
for (unsigned int idx = left_idx+1; idx < right_idx; ++idx) {
Matrix3d R_initial = R_c[idx - 1];
Vector3d P_initial = T_c[idx - 1];
if (!solveGlobalRT(idx, R_initial, P_initial, 0, true))
return false;
R_c[idx] = R_initial;
Quat_c[idx] = R_initial;
T_c[idx] = P_initial;
Pose[idx].block<3, 3>(0, 0) = R_c[idx];
Pose[idx].block<3, 1>(0, 3) = T_c[idx];
triangulatePointsInTwoFrames(idx, Pose[idx], right_idx, Pose[right_idx]);
}
// ROS_INFO("A 3");
/*
* 3. Construct: right_idx-1 -> left_idx
*/
for (unsigned int idx = left_idx+1; idx < right_idx; ++idx) {
triangulatePointsInTwoFrames(left_idx, Pose[left_idx], idx, Pose[idx]);
}
/*
* 4. Construct: right_idx+1 -> WINDOW_SIZE+1
*/
for (unsigned int idx = right_idx+1; idx <= WINDOW_SIZE; ++idx) {
Matrix3d R_initial = R_c[idx - 1];
Vector3d P_initial = T_c[idx - 1];
if (!solveGlobalRT(idx, R_initial, P_initial, 0, true))
return false;
R_c[idx] = R_initial;
Quat_c[idx] = R_initial;
T_c[idx] = P_initial;
Pose[idx].block<3, 3>(0, 0) = R_c[idx];
Pose[idx].block<3, 1>(0, 3) = T_c[idx];
triangulatePointsInTwoFrames(right_idx, Pose[right_idx], idx, Pose[idx]);
}
// ROS_INFO("A 4");
/*
* 5. Construct: left_idx-1 -> 0
*/
if (left_idx > 0) {
for (int idx = left_idx-1; idx >= 0; --idx) {
// ROS_INFO("%d idx", idx);
Matrix3d R_initial = R_c[idx + 1];
Vector3d P_initial = T_c[idx + 1];
if (!solveGlobalRT(idx, R_initial, P_initial, 0, true))
return false;
R_c[idx] = R_initial;
Quat_c[idx] = R_initial;
T_c[idx] = P_initial;
Pose[idx].block<3, 3>(0, 0) = R_c[idx];
Pose[idx].block<3, 1>(0, 3) = T_c[idx];
triangulatePointsInTwoFrames(idx, Pose[idx], left_idx, Pose[left_idx]);
}
}
// ROS_INFO("A 5");
// 6. Triangulate all other points
// for (auto& pt_m : pts_map) {
// Point* pt = pt_m.second;
// if (pt->type == Point::TYPE_TRIANGULATED)
// continue;
//
// if (pt->obs.size() < 2)
// continue;
//
// int frame_a = pt->obs.front()->frame->id;
// Vector2d pt_a = pt->obs.front()->pt_c.head<2>();// z = 1
//
// int frame_b = pt->obs.back()->frame->id;
// Vector2d pt_b = pt->obs.back()->pt_c.head<2>();
//
// Vector3d pt_w;
// triangulatePoint(Pose[frame_a], Pose[frame_b], pt_a, pt_b, pt_w);
// pt->setPosition(pt_w);
// }
int n_triang = 0;
for (auto& pt_m : pts_map) {
if (pt_m.second->type == Point::TYPE_TRIANGULATED)
n_triang++;
}
ROS_INFO("%d Points have been triangulated", n_triang);
ceres::Problem problem;
ceres::LocalParameterization* local_parameterization = new ceres::QuaternionParameterization();
for (unsigned int i = 0; i < WINDOW_SIZE+1; ++i) {
translation[i][0] = T_c[i].x();
translation[i][1] = T_c[i].y();
translation[i][2] = T_c[i].z();
rotation[i][0] = Quat_c[i].w();
rotation[i][1] = Quat_c[i].x();
rotation[i][2] = Quat_c[i].y();
rotation[i][3] = Quat_c[i].z();
problem.AddParameterBlock(translation[i], 3);
problem.AddParameterBlock(rotation[i], 4, local_parameterization);
if (i == left_idx || i == right_idx) {
problem.SetParameterBlockConstant(rotation[i]);
problem.SetParameterBlockConstant(translation[i]);
}
}
for (auto& tag_m : tags_map) {
AprilTagInstance* tag_instance = tag_m.second;
for (unsigned int i = 0; i < 4; ++i) {
problem.AddParameterBlock(tag_instance->position[i], 3);
problem.SetParameterBlockConstant(tag_instance->position[i]);
}
}
for (auto& tag_m : tags_map) {
AprilTagInstance* tag_instance = tag_m.second;
ROS_INFO("Number of tag observasion: %d", tag_instance->tag_obs.size());
for (auto& tag_ftr : tag_instance->tag_obs) {
for (unsigned int i = 0; i < 4; ++i) {
int idx = tag_ftr->frame->window_counter;
Vector3d corner = tag_ftr->tag_fts[i]->pt_c;
ceres::CostFunction* cost_function = ReprojectionError3D::Create(corner.x(),
corner.y());
problem.AddResidualBlock(cost_function, NULL, rotation[idx], translation[idx], tag_instance->position[i]);
}
}
}
for (auto it = pts_map.begin(); it != pts_map.end(); ++it) {
Point* pt = (*it).second;
if (pt->type != Point::TYPE_TRIANGULATED)
continue;
auto it_ftr = pt->obs.begin();
auto it_end = pt->obs.end();
for (;it_ftr != it_end; ++it_ftr) {
int idx = (*it_ftr)->frame->window_counter;
ceres::CostFunction* cost_function = ReprojectionError3D::Create((*it_ftr)->pt_c.x(),
(*it_ftr)->pt_c.y());
problem.AddResidualBlock(cost_function, NULL, rotation[idx], translation[idx], pt->position);
}
}
ceres::Solver::Options options;
options.linear_solver_type = ceres::DENSE_SCHUR;
options.max_solver_time_in_seconds = 0.2;
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
if (summary.termination_type == ceres::CONVERGENCE || summary.final_cost < 5e-03)
{
ROS_INFO("Ceres converge!");
}
else
{
ROS_INFO("Ceres does not converge...");
return false;
}
for (unsigned int i = 0; i < WINDOW_SIZE+1; ++i) {
Quat_c[i].w() = rotation[i][0];
Quat_c[i].x() = rotation[i][1];
Quat_c[i].y() = rotation[i][2];
Quat_c[i].z() = rotation[i][3];
Eigen::Quaterniond Quat_w;
Vector3d T_w;
Quat_w = Quat_c[i].normalized().inverse();
T_w = -1 * (Quat_w * Vector3d(translation[i][0], translation[i][1], translation[i][2]));
frames[i]->setRotation(Quat_w.toRotationMatrix() * ric.transpose());
frames[i]->setPosition(T_w);
}
/*
for (auto& pt_m : pts_map) {
Point* pt = pt_m.second;
if (pt->type == Point::TYPE_TRIANGULATED) {
// Points have been triangulated
pt->setPositionByPara();
// pt->type = Point::TYPE_INIT;
}
}*/
/*
n_triang = 0;
for (auto& pt_m : pts_map) {
if (pt_m.second->type == Point::TYPE_TRIANGULATED)
n_triang++;
}
ROS_INFO("%d Points have been triangulated", n_triang); */
// triangulatePointMap();
return true;
}
bool Estimator::consultDictionary(const int& _id, Matrix3d& R, Vector3d& t, double& size)
{
auto it = global_tags_dic.find(_id);//GLOBAL_TAGS_DIC
if (it == global_tags_dic.end()) {
return false;
} else {
t = it->second.second.first;
R = it->second.second.second;
size = it->second.first;
return true;
}
}
void Estimator::loadDictionary()
{
{
vector<Point*> pts;
int tag_id = 0;
double tag_size = TAG_SIZE;
Vector3d eigen_t(0, 0, 0);
Matrix3d eigen_R = Eigen::MatrixXd::Identity(3, 3);
global_tags_dic[tag_id] = make_pair(tag_size, make_pair(eigen_t, eigen_R));
}
{
vector<Point*> pts;
int tag_id = 1;
double tag_size = TAG_SIZE;
Vector3d eigen_t(14.2, 0, 0);
Matrix3d eigen_R = Eigen::MatrixXd::Identity(3, 3);
global_tags_dic[tag_id] = make_pair(tag_size, make_pair(eigen_t, eigen_R));
}
{
vector<Point*> pts;
int tag_id = 2;
double tag_size = TAG_SIZE;
Vector3d eigen_t(14.2, -21.35, 0);
Matrix3d eigen_R = Eigen::MatrixXd::Identity(3, 3);
global_tags_dic[tag_id] = make_pair(tag_size, make_pair(eigen_t, eigen_R));
}
{
vector<Point*> pts;
int tag_id = 3;
double tag_size = TAG_SIZE;
Vector3d eigen_t(0, -21.35, 0);
Matrix3d eigen_R = Eigen::MatrixXd::Identity(3, 3);
global_tags_dic[tag_id] = make_pair(tag_size, make_pair(eigen_t, eigen_R));
}
}
bool Estimator::projectW2C(const Matrix3d& _R_c_w, const Vector3d& _t_c, const Vector3d& _P_w, Vector3d& P_c)
{
Vector3d pt_c = _R_c_w * _P_w + _t_c;
double inv_dep = 1.0 / pt_c.z();
if (inv_dep < 0.02)
return false;
P_c = pt_c * inv_dep;
return true;
}
bool Estimator::projectW2C(const Matrix3d& _R_w_b, const Vector3d& _t_w, const Matrix3d& _r_b_c, const Vector3d& _t_b_c, const Vector3d& _P_w, Vector3d& P_c)
{
Vector3d P_c_s = _r_b_c.transpose() * (_R_w_b.transpose() * (_P_w - _t_w) - _t_b_c);
double inv_dep = 1.0 / P_c_s.z();
if (inv_dep < 0.02)
return false;
P_c = P_c_s * inv_dep;
return true;
}
void Estimator::setParameter()
{
ric = RIC[0];
tic = TIC[0];
para_Ex_Pose[0] = tic.x();
para_Ex_Pose[1] = tic.y();
para_Ex_Pose[2] = tic.z();
Eigen::Quaterniond q{ric};
para_Ex_Pose[3] = q.x();
para_Ex_Pose[4] = q.y();
para_Ex_Pose[5] = q.z();
para_Ex_Pose[6] = q.w();
loadDictionary();
ReprojectionFactor::sqrt_info = FOCAL_LENGTH / 1.5 * Matrix2d::Identity();
ConstPointFactor::const_sqrt_info = 1.5 * Matrix2d::Identity();
PointFactor::sqrt_info = 0.5 * Matrix2d::Identity();
}
bool Estimator::saveData(ofstream* outfile, const int& _index, const Matrix3d& _R, const Vector3d& _t, string _text)
{
if ((*outfile).is_open()) {
Vector3d ypr = Utility::R2ypr(_R);
try {
(*outfile) << _index << " " << _t.transpose() << " " << ypr.transpose() << "\n";
} catch (exception& e) {
ROS_ERROR("saving data fails...");
}
} else {
ROS_ERROR("saving data fails...");
return false;
}
return true;
}
} // end basic
/*
for (auto& pt_m : pts_map) {
Point* pt = pt_m.second;
if (pt->obs.size() < 2 || pt->type != Point::TYPE_TRIANGULATED)
continue;
problem.AddParameterBlock(pt->position, 3);
//problem.SetParameterBlockConstant(pt->position);
}
for (auto& pt_m : pts_map) {
Point* pt = pt_m.second;
if (pt->obs.size() < 2 || pt->type != Point::TYPE_TRIANGULATED)
continue;
for (auto& ftr : pt->obs) {
PointFactor* point_factor = new PointFactor(ftr->pt_c);
problem.AddResidualBlock(point_factor, loss_function, ftr->frame->para_Pose, para_Ex_Pose, pt->position);
}
}
// Points
for (auto& pt_m : pts_map) {
Point* pt = pt_m.second;
if (pt->type == Point::TYPE_TRIANGULATED) {
pt->setPositionByPara();
}
}
*/ | [
"qinchaom4a1@163.com"
] | qinchaom4a1@163.com |
c1538d6cb573fdab76421372cc3a0f5c28c355ca | 4e1791de29f9a74b1ce57c7bce6359c493116534 | /aten/src/ATen/core/boxing/KernelFunction_impl.h | 3459a10d162f0c50cbfd76bf96505aa67519cbf5 | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | play201861/pytorch | af0959bb8bf5c6d937b22ffc566fc7a2ce39ae25 | 916084d933792f7ee619aee7155fedf68d1a8cd1 | refs/heads/master | 2022-09-07T13:20:57.841773 | 2020-05-27T06:19:00 | 2020-05-27T06:21:54 | 267,240,073 | 2 | 0 | NOASSERTION | 2020-05-27T06:34:33 | 2020-05-27T06:34:33 | null | UTF-8 | C++ | false | false | 9,431 | h | #include <ATen/core/boxing/impl/boxing.h>
#include <ATen/core/boxing/impl/make_boxed_from_unboxed_functor.h>
#include <ATen/core/boxing/impl/WrapFunctionIntoFunctor.h>
#include <ATen/core/boxing/impl/WrapFunctionIntoRuntimeFunctor.h>
namespace c10 {
inline KernelFunction::KernelFunction()
: functor_(nullptr)
, boxed_kernel_func_(nullptr)
, unboxed_kernel_func_(nullptr)
{}
inline KernelFunction::KernelFunction(std::unique_ptr<OperatorKernel> functor, InternalBoxedKernelFunction* boxed_kernel_func, void* unboxed_kernel_func)
: functor_(std::move(functor))
, boxed_kernel_func_(boxed_kernel_func)
, unboxed_kernel_func_(unboxed_kernel_func)
{}
template<KernelFunction::BoxedKernelFunction* func>
inline void KernelFunction::make_boxed_function(OperatorKernel*, const OperatorHandle& opHandle, Stack* stack) {
func(opHandle, stack);
}
inline bool KernelFunction::isValid() const {
// TODO We want to introduce the invariant that all kernels must be callable in a boxed way, then this should only check boxed_kernel_func_.
return boxed_kernel_func_ != nullptr || unboxed_kernel_func_ != nullptr;
}
inline bool KernelFunction::isFallthrough() const {
return boxed_kernel_func_ == &fallthrough_kernel;
}
inline void KernelFunction::callBoxed(const OperatorHandle& opHandle, Stack* stack) const {
if (C10_UNLIKELY(boxed_kernel_func_ == nullptr)) {
if (unboxed_kernel_func_ == nullptr) {
TORCH_INTERNAL_ASSERT(false, "Tried to call KernelFunction::callBoxed() on an uninitialized KernelFunction.");
} else {
// TODO We want to introduce the invariant that all kernels must be callable in a boxed way, then this case should be impossible.
TORCH_INTERNAL_ASSERT(false, "Tried to call KernelFunction::callBoxed() on a KernelFunction that can only be called with KernelFunction::call().");
}
}
(*boxed_kernel_func_)(functor_.get(), opHandle, stack);
}
template<class Return, class... Args>
inline Return KernelFunction::call(const OperatorHandle& opHandle, Args... args) const {
// note: Args above is intentionally not Args&&. We don't want perfect
// forwarding, which would require Args to be deduced, but instead we
// want callers to explicitly specify the Args.
if (C10_LIKELY(unboxed_kernel_func_ != nullptr)) {
using ActualSignature = Return (OperatorKernel*, Args...);
ActualSignature* func = reinterpret_cast<ActualSignature*>(unboxed_kernel_func_);
return (*func)(functor_.get(), std::forward<Args>(args)...);
}
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(boxed_kernel_func_ != nullptr, "Tried to call KernelFunction::call() on an uninitialized KernelFunction.");
return impl::boxAndCallBoxedFunc<Return, Args...>(boxed_kernel_func_, functor_.get(), opHandle, std::forward<Args>(args)...);
}
template<KernelFunction::BoxedKernelFunction* func>
inline KernelFunction KernelFunction::makeFromBoxedFunction() {
return KernelFunction(
nullptr, // no functor_ object
&make_boxed_function<func>,
nullptr // no unboxed function pointer
);
}
inline KernelFunction KernelFunction::makeFallthrough() {
return KernelFunction(
nullptr, // no functor_ object
&fallthrough_kernel,
nullptr // no unboxed function pointer
);
}
template<bool AllowLegacyTypes, class KernelFunctor>
inline KernelFunction KernelFunction::makeFromUnboxedFunctor(std::unique_ptr<OperatorKernel> kernelFunctor) {
static_assert(guts::is_functor<KernelFunctor>::value, "Tried to call KernelFunction::makeFromUnboxedFunctor<KernelFunctor> but the argument is not a functor.");
static_assert(std::is_base_of<OperatorKernel, KernelFunctor>::value, "Tried to call KernelFunction::makeFromUnboxedFunctor<KernelFunctor>, but the functor doesn't inherit from c10::OperatorKernel. Please have the functor inherit from it.");
return KernelFunction(
std::move(kernelFunctor),
&impl::make_boxed_from_unboxed_functor<KernelFunctor, AllowLegacyTypes>::call,
reinterpret_cast<void*>(&impl::wrap_kernel_functor_unboxed<KernelFunctor>::call)
);
}
template<class KernelFunctor>
inline KernelFunction KernelFunction::makeFromUnboxedOnlyFunctor(std::unique_ptr<OperatorKernel> kernelFunctor) {
// TODO We want to get rid of kernels that have only an unboxed function pointer.
// All kernels should have a boxed pointer.
static_assert(guts::is_functor<KernelFunctor>::value, "Tried to call KernelFunction::makeFromUnboxedFunctor<KernelFunctor> but the argument is not a functor.");
static_assert(std::is_base_of<OperatorKernel, KernelFunctor>::value, "Tried to call KernelFunction::makeFromUnboxedFunctor<KernelFunctor>, but the functor doesn't inherit from c10::OperatorKernel. Please have the functor inherit from it.");
return KernelFunction(
std::move(kernelFunctor),
nullptr, // Don't create a boxed kernel for this
reinterpret_cast<void*>(&impl::wrap_kernel_functor_unboxed<KernelFunctor>::call)
);
}
template<class FuncType, FuncType* func, bool AllowLegacyTypes>
inline KernelFunction KernelFunction::makeFromUnboxedFunction() {
static_assert(guts::is_function_type<FuncType>::value, "Tried to call KernelFunction::makeFromUnboxedFunction with invalid template parameters. They must be <FuncType, *func_ptr>.");
static_assert(!std::is_same<FuncType, BoxedKernelFunction>::value, "Tried to call KernelFunction::makeFromUnboxedFunction with a boxed function pointer. Please use KernelFunction::makeFromBoxedFunction instead.");
static_assert(func != nullptr, "Kernel function cannot be nullptr");
return makeFromUnboxedFunctor<AllowLegacyTypes, typename impl::WrapFunctionIntoFunctor<FuncType, func>::type>(
guts::make_unique_base<OperatorKernel, typename impl::WrapFunctionIntoFunctor<FuncType, func>::type>()
);
}
template<class FuncType, FuncType* func>
inline KernelFunction KernelFunction::makeFromUnboxedOnlyFunction() {
// TODO We want to get rid of kernels that have only an unboxed function pointer.
// All kernels should have a boxed pointer.
static_assert(guts::is_function_type<FuncType>::value, "Tried to call KernelFunction::makeFromUnboxedOnlyFunction with invalid template parameters. They must be <FuncType, *func_ptr>.");
static_assert(!std::is_same<FuncType, BoxedKernelFunction>::value, "Tried to call KernelFunction::makeFromUnboxedOnlyFunction with a boxed function pointer. Please use KernelFunction::makeFromBoxedFunction instead.");
static_assert(func != nullptr, "Kernel function cannot be nullptr");
return makeFromUnboxedOnlyFunctor<typename impl::WrapFunctionIntoFunctor<FuncType, func>::type> (
guts::make_unique_base<OperatorKernel, typename impl::WrapFunctionIntoFunctor<FuncType, func>::type>()
);
}
template<bool AllowLegacyTypes, class FuncType>
inline KernelFunction KernelFunction::makeFromUnboxedRuntimeFunction(FuncType* func) {
static_assert(guts::is_function_type<FuncType>::value, "Tried to call KernelFunction::makeFromUnboxedRuntimeFunction with a non-function type.");
static_assert(!std::is_same<FuncType, BoxedKernelFunction>::value, "Tried to call KernelFunction::makeFromUnboxedRuntimeFunction with a boxed function pointer. Please use KernelFunction::makeFromBoxedFunction instead.");
TORCH_INTERNAL_ASSERT(func != nullptr, "Kernel function cannot be nullptr");
return makeFromUnboxedFunctor<AllowLegacyTypes, impl::WrapFunctionIntoRuntimeFunctor<std::decay_t<FuncType>>>(
guts::make_unique_base<OperatorKernel, impl::WrapFunctionIntoRuntimeFunctor<std::decay_t<FuncType>>>(func)
);
}
template<class FuncType>
inline KernelFunction KernelFunction::makeFromUnboxedOnlyRuntimeFunction(FuncType* func) {
static_assert(guts::is_function_type<FuncType>::value, "Tried to call KernelFunction::makeFromUnboxedRuntimeFunction with a non-function type.");
static_assert(!std::is_same<FuncType, BoxedKernelFunction>::value, "Tried to call KernelFunction::makeFromUnboxedRuntimeFunction with a boxed function pointer. Please use KernelFunction::makeFromBoxedFunction instead.");
TORCH_INTERNAL_ASSERT(func != nullptr, "Kernel function cannot be nullptr");
return makeFromUnboxedOnlyFunctor<impl::WrapFunctionIntoRuntimeFunctor<std::decay_t<FuncType>>>(
guts::make_unique_base<OperatorKernel, impl::WrapFunctionIntoRuntimeFunctor<std::decay_t<FuncType>>>(func)
);
}
template<bool AllowLegacyTypes, class Lambda>
inline KernelFunction KernelFunction::makeFromUnboxedLambda(Lambda&& lambda) {
static_assert(guts::is_functor<std::decay_t<Lambda>>::value, "Tried to call KernelFunction::makeFromUnboxedLambda with a non-lambda type.");
return makeFromUnboxedFunctor<AllowLegacyTypes, impl::WrapFunctionIntoRuntimeFunctor<std::decay_t<Lambda>>>(
guts::make_unique_base<OperatorKernel, impl::WrapFunctionIntoRuntimeFunctor<std::decay_t<Lambda>>>(std::forward<Lambda>(lambda))
);
}
inline void KernelFunction::setManuallyBoxedKernel_(InternalBoxedKernelFunction* func) {
TORCH_INTERNAL_ASSERT(boxed_kernel_func_ == nullptr, "Tried to set a manually boxed kernel for a kernel that already has a boxed kernel set.");
TORCH_INTERNAL_ASSERT(unboxed_kernel_func_ != nullptr, "Tried to set a manually boxed kernel for an invalid KernelFunction.");
boxed_kernel_func_ = func;
}
}
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
680606c0d6829efcfb917c418cde4979172b518c | 3fa4da4ec11dff76882d85de4cdbff5bd9dff9fa | /[new 4.4]3D_ESSUE/Client/Code/ShockWave.cpp | 248e3eb21bc86ba76c59083f609c96d5ef880111 | [] | no_license | buseog/Direct3D_Solo | 4561259cb8b7d46d0e1e209c5b17a73fa28e0b84 | cb7610976edaa7cc413a32ae60b2382e2ac89d45 | refs/heads/master | 2021-06-20T09:30:21.969667 | 2017-05-11T18:32:47 | 2017-05-11T18:32:47 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 19,327 | cpp | #include "StdAfx.h"
#include "ShockWave.h"
#include "DefaultCamera.h"
#include "BossSword.h"
CShockWave::CShockWave( LPDIRECT3DDEVICE9 pDevice)
: CEffect(pDevice)
{
}
CShockWave::~CShockWave( void )
{
}
HRESULT CShockWave::Initialize( const _uint& iType)
{
m_iType = iType;
if (m_iType < 10)
{
m_pBone = ((Engine::CDynamicMesh*)Engine::Get_Management()->GetLayer(L"Layer_Boss")->GetObject(0)->GetComponent(L"Com_Mesh"))->GetPartsMatrix("ValveBiped_Anim_Attachment_RH");
m_pTarget = ((Engine::CTransform*)Engine::Get_Management()->GetLayer(L"Layer_Boss")->GetObject(0)->GetComponent(L"Com_Transform"))->GetWorldMatrix();
}
else
{
m_pBone = ((Engine::CDynamicMesh*)Engine::Get_Management()->GetLayer(L"Layer_Boss")->GetObject(2)->GetComponent(L"Com_Mesh"))->GetPartsMatrix("ValveBiped_Anim_Attachment_RH");
m_pTarget = ((CBossSword*)Engine::Get_Management()->GetLayer(L"Layer_Boss")->GetObject(2))->GetComputeMatrix();
}
m_vOrigin = *(MyVec3*)&(*m_pBone * *m_pTarget).m[3][0];
DefaultSetting();
if (FAILED(Ready_Component()))
return E_FAIL;
for (_uint i = 0; i < m_iCount; ++i)
AddParticle();
return S_OK;
}
_int CShockWave::Update( const _float& fDelta )
{
if (isDead() == true)
{
m_bDestroy = true;
return 0;
}
m_fDurationAcc += fDelta;
m_fIntervalAcc += fDelta;
if (m_fDurationAcc <= m_fDuration)
{
if (m_fIntervalAcc >= m_fInterval)
{
for (_uint i = 0; i < m_iCount; ++i)
AddParticle();
m_fIntervalAcc = 0.f;
}
}
EFFECTLIST::iterator iter = m_EffectList.begin();
EFFECTLIST::iterator iter_end = m_EffectList.end();
for ( ; iter != iter_end; ++iter)
{
if ((*iter)->bAlive == true)
{
(*iter)->fLifeTime += fDelta;
(*iter)->fFrame += (*iter)->fFrameSpeed * fDelta;
if ((*iter)->fFrame >= 25.f)
(*iter)->fFrame = 0.f;
(*iter)->vPos += (*iter)->vDir * (*iter)->fSpeed * fDelta;
if ((*iter)->fLifeTime >= (*iter)->fMaxLife)
(*iter)->bAlive = false;
}
}
Engine::CGameObject::Update(fDelta);
m_pRendererCom->AddRenderList(Engine::CRenderer::RENDER_ALPHA, this);
return 0;
}
void CShockWave::Render( void )
{
LPD3DXEFFECT pEffect = m_pShaderCom->GetEffect();
if (pEffect == NULL)
return;
SetUpShader(pEffect);
}
void CShockWave::SetUpShader( LPD3DXEFFECT pEffect )
{
pEffect->AddRef();
MyMat matView, matProj;
m_pDevice->GetTransform(D3DTS_VIEW, &matView);
m_pDevice->GetTransform(D3DTS_PROJECTION, &matProj);
pEffect->SetMatrix("g_matView", &matView);
pEffect->SetMatrix("g_matProj", &matProj);
m_pTextureCom->SetUpShader(pEffect, m_iIndex);
pEffect->Begin(NULL, 0);
pEffect->BeginPass(1);
EFFECTLIST::iterator iter = m_EffectList.begin();
EFFECTLIST::iterator iter_end = m_EffectList.end();
MyMat matScale, matRotX, matRotY, matRotZ, matTrans, matWorld;
//MyMat matBill;
//D3DXMatrixIdentity(&matBill);
//matBill._11 = matView._11;
//matBill._13 = matView._13;
//matBill._31 = matView._31;
//matBill._33 = matView._33;
//D3DXMatrixInverse(&matBill, NULL, &matBill);
for ( ; iter != iter_end; ++iter)
{
if ((*iter)->bAlive == true)
{
_float fSizeDelta = GetSizeDelta(*iter);
_float fRollDelta = GetRollDelta(*iter);
_uint iAlphaDelta = GetAlphaDelta(*iter);
MyVec3 ScaleDelta = GetScaleDelta(*iter);
D3DXMatrixScaling(&matScale, (*iter)->vScale.x + fSizeDelta + ScaleDelta.x, (*iter)->vScale.y + fSizeDelta + ScaleDelta.y, (*iter)->vScale.z + ScaleDelta.z);
D3DXMatrixRotationX(&matRotX, D3DXToRadian((*iter)->vAngle.x));
D3DXMatrixRotationY(&matRotY, D3DXToRadian((*iter)->vAngle.y));
D3DXMatrixRotationZ(&matRotZ, D3DXToRadian((*iter)->vAngle.z + fRollDelta));
D3DXMatrixTranslation(&matTrans, (*iter)->vPos.x, (*iter)->vPos.y, (*iter)->vPos.z);
matWorld = matScale * matRotZ * matRotX * matRotY * matTrans;
pEffect->SetMatrix("g_matWorld", &matWorld);
pEffect->SetVector("g_vColor", &MyVec4(D3DXCOLOR(D3DCOLOR_ARGB(255 - iAlphaDelta, (_int)(*iter)->vColor.x, (_int)(*iter)->vColor.y, (_int)(*iter)->vColor.z))));
pEffect->CommitChanges();
m_pBufferCom->Render();
}
}
pEffect->EndPass();
pEffect->End();
Engine::Safe_Release(pEffect);
}
void CShockWave::DefaultSetting( void )
{
switch (m_iType)
{
// shockwave wp
case 0: // 바람01
m_pEffectKey = L"Component_Texture_LightGlow";
m_iCount = 1;
m_iIndex = 3;
m_fInterval = 0.005f;
m_fDuration = 2.2f;
break;
case 1: // 바람01
m_pEffectKey = L"Component_Texture_LightGlow";
m_iCount = 3;
m_iIndex = 3;
m_fInterval = 0.002f;
m_fDuration = 0.3f;
break;
case 2: // 바람02
m_pEffectKey = L"Component_Texture_RingLine";
m_iCount = 5;
m_iIndex = 0;
m_fInterval = 0.04f;
m_fDuration = 0.2f;
break;
case 3: // 바람02
m_pEffectKey = L"Component_Texture_LightRay";
m_iCount = 1;
m_iIndex = 0;
m_fInterval = 0.15f;
m_fDuration = 0.3f;
break;
case 4: // 바람02
m_pEffectKey = L"Component_Texture_ShapeFire";
m_iCount = 1;
m_iIndex = 1;
m_fInterval = 0.02f;
m_fDuration = 0.3f;
break;
case 5: // 바람02
m_pEffectKey = L"Component_Texture_ShapeFire";
m_iCount = 1;
m_iIndex = 3;
m_fInterval = 0.01f;
m_fDuration = 2.2f;
break;
// shockwave front
case 10: // 바람01
m_pEffectKey = L"Component_Texture_LightGlow";
m_iCount = 2;
m_iIndex = 3;
m_fInterval = 0.025f;
m_fDuration = 0.15f;
break;
case 11: // 뾰족먼지2
m_pEffectKey = L"Component_Texture_Blunt";
m_iCount = 4;
m_iIndex = 0;
m_fInterval = 0.01f;
m_fDuration = 0.1f;
break;
case 12: // 뾰족먼지2
m_pEffectKey = L"Component_Texture_Blunt";
m_iCount = 4;
m_iIndex = 0;
m_fInterval = 0.03f;
m_fDuration = 0.1f;
break;
//case 12: // 뾰족먼지2
// m_pEffectKey = L"Component_Texture_CriticalEhen";
// m_iCount = 1;
// m_iIndex = 0;
// m_fInterval = 0.03f;
// m_fDuration = 0.1f;
// break;
case 13: // 뾰족먼지2
m_pEffectKey = L"Component_Texture_ShapeFire";
m_iCount = 4;
m_iIndex = 1;
m_fInterval = 0.02f;
m_fDuration = 0.1f;
break;
case 14: // 바람01
m_pEffectKey = L"Component_Texture_ShapeFire";
m_iCount = 2;
m_iIndex = 3;
m_fInterval = 0.01f;
m_fDuration = 0.15f;
break;
case 15: // 바람01
m_pEffectKey = L"Component_Texture_Ring_Outer_Wind";
m_iCount = 3;
m_iIndex = 2;
m_fInterval = 0.02f;
m_fDuration = 0.25f;
break;
}
}
void CShockWave::AddParticle( void )
{
EFFECT* pEffect= new EFFECT;
ZeroMemory(pEffect, sizeof(EFFECT));
pEffect->vScale = MyVec3(1.f, 1.f, 1.f);
pEffect->bAlive = true;
D3DXVECTOR3 vMin(255.f, 155.f, 115.f);
D3DXVECTOR3 vMax(255.f, 185.f, 155.f);
Engine::GetRandomVector(&pEffect->vColor, &vMin, &vMax);
MyMat matCompute = *m_pBone * *m_pTarget;
MyVec3 vPos = *(MyVec3*)&matCompute.m[3][0];
MyVec3 vLook = *D3DXVec3Normalize(&vLook, (MyVec3*)&m_pTarget->m[2][0]);
_float fSize = 0.f;
switch (m_iType)
{
case 0:
pEffect->vAngle = MyVec3(0.f, 0.f, Engine::GetRandomFloat(-360.f, 360.f));
pEffect->fMaxLife = Engine::GetRandomFloat(0.15f, 0.2f);
pEffect->fSpeed = 1.f;
pEffect->fAngle = 190.f;
pEffect->fRadius = Engine::GetRandomFloat(1.f, 120.f);
pEffect->fRadiusAngle = 0.f;
pEffect->vDir.z = pEffect->fRadius * sinf(pEffect->fAngle) * cosf(pEffect->fRadiusAngle);
pEffect->vDir.x = pEffect->fRadius * sinf(pEffect->fAngle) * sinf(pEffect->fRadiusAngle);
pEffect->vDir.y = pEffect->fRadius * cosf(pEffect->fAngle);
fSize = Engine::GetRandomFloat(7.f, 11.f);
pEffect->vScale = MyVec3(fSize, fSize, 1.f);
pEffect->vPos = vPos;
pEffect->fAlphaDelta = 0.f;
pEffect->fAlphaWayTime = 0.5f;
pEffect->fAlphaWayDelta = 100.f;
pEffect->fRollDelta = 260.f;
break;
case 1:
pEffect->vAngle = MyVec3(0.f, 0.f, Engine::GetRandomFloat(-360.f, 360.f));
pEffect->fMaxLife = Engine::GetRandomFloat(0.5f, 0.7f);
pEffect->fSpeed = Engine::GetRandomFloat(5.f, 25.f);
pEffect->fAngle = 360.f;
pEffect->fRadius = Engine::GetRandomFloat(1.f, 120.f);
pEffect->fRadiusAngle = 0.f;
pEffect->vDir.z = pEffect->fRadius * sinf(pEffect->fAngle) * cosf(pEffect->fRadiusAngle);
pEffect->vDir.x = pEffect->fRadius * sinf(pEffect->fAngle) * sinf(pEffect->fRadiusAngle);
pEffect->vDir.y = pEffect->fRadius * cosf(pEffect->fAngle);
pEffect->vScale = MyVec3(Engine::GetRandomFloat(0.3f, 0.4f), 1.f, 1.f);
pEffect->vPos = vPos;
pEffect->fAlphaDelta = 0.f;
pEffect->fAlphaWayTime = 0.5f;
pEffect->fAlphaWayDelta = 250.f;
break;
case 2:
pEffect->vAngle = MyVec3(0.f, 0.f, Engine::GetRandomFloat(-360.f, 360.f));
pEffect->fMaxLife = Engine::GetRandomFloat(0.2f, 0.3f);
pEffect->fSpeed = 1.f;
pEffect->fAngle = 190.f;
pEffect->fRadius = 1.f;
pEffect->fRadiusAngle = 0.f;
pEffect->vDir.z = pEffect->fRadius * sinf(pEffect->fAngle) * cosf(pEffect->fRadiusAngle);
pEffect->vDir.x = pEffect->fRadius * sinf(pEffect->fAngle) * sinf(pEffect->fRadiusAngle);
pEffect->vDir.y = pEffect->fRadius * cosf(pEffect->fAngle);
fSize = Engine::GetRandomFloat(3.f, 5.f);
pEffect->vScale = MyVec3(fSize, fSize, 1.f);
pEffect->vPos = vPos;
pEffect->fSizeDelta = 13.f;
pEffect->fAlphaDelta = 0.f;
pEffect->fAlphaWayTime = 0.2f;
pEffect->fAlphaWayDelta = 250.f;
break;
case 3:
pEffect->vAngle = MyVec3(0.f, 0.f, Engine::GetRandomFloat(-360.f, 360.f));
pEffect->fMaxLife = Engine::GetRandomFloat(0.2f, 0.4f);
pEffect->fSpeed = 1.f;
pEffect->fAngle = 190.f;
pEffect->fRadius = 1.f;
pEffect->fRadiusAngle = 0.f;
pEffect->vDir.z = pEffect->fRadius * sinf(pEffect->fAngle) * cosf(pEffect->fRadiusAngle);
pEffect->vDir.x = pEffect->fRadius * sinf(pEffect->fAngle) * sinf(pEffect->fRadiusAngle);
pEffect->vDir.y = pEffect->fRadius * cosf(pEffect->fAngle);
fSize = Engine::GetRandomFloat(9.f, 12.f);
pEffect->vScale = MyVec3(fSize, fSize, 1.f);
pEffect->vPos = vPos;
pEffect->fSizeDelta = 13.f;
pEffect->fAlphaDelta = 0.f;
pEffect->fAlphaWayTime = 0.2f;
pEffect->fAlphaWayDelta = 250.f;
break;
case 4:
pEffect->vAngle = MyVec3(0.f, 0.f, Engine::GetRandomFloat(-360.f, 360.f));
pEffect->fMaxLife = Engine::GetRandomFloat(0.2f, 0.4f);
pEffect->fSpeed = 1.f;
pEffect->fAngle = 190.f;
pEffect->fRadius = 1.f;
pEffect->fRadiusAngle = 0.f;
pEffect->vDir.z = pEffect->fRadius * sinf(pEffect->fAngle) * cosf(pEffect->fRadiusAngle);
pEffect->vDir.x = pEffect->fRadius * sinf(pEffect->fAngle) * sinf(pEffect->fRadiusAngle);
pEffect->vDir.y = pEffect->fRadius * cosf(pEffect->fAngle);
fSize = Engine::GetRandomFloat(5.f, 8.f);
pEffect->vScale = MyVec3(fSize, fSize, 1.f);
pEffect->vPos = vPos;
pEffect->fSizeDelta = 6.f;
pEffect->fSizeWayTime = 0.3f;
pEffect->fSizeWayDelta = 4.f;
pEffect->fAlphaDelta = 0.f;
pEffect->fAlphaWayTime = 0.2f;
pEffect->fAlphaWayDelta = 250.f;
break;
case 5:
pEffect->vAngle = MyVec3(0.f, 0.f, Engine::GetRandomFloat(-360.f, 360.f));
pEffect->fMaxLife = Engine::GetRandomFloat(0.35f, 0.45f);
pEffect->fSpeed = 1.f;
pEffect->fAngle = 360.f;
pEffect->fRadius = Engine::GetRandomFloat(1.f, 120.f);
pEffect->fRadiusAngle = 0.f;
pEffect->vDir.z = pEffect->fRadius * sinf(pEffect->fAngle) * cosf(pEffect->fRadiusAngle);
pEffect->vDir.x = pEffect->fRadius * sinf(pEffect->fAngle) * sinf(pEffect->fRadiusAngle);
pEffect->vDir.y = pEffect->fRadius * cosf(pEffect->fAngle);
fSize = Engine::GetRandomFloat(1.f, 3.f);
pEffect->vScale = MyVec3(fSize, fSize, 1.f);
pEffect->vPos = vPos;
pEffect->fSizeDelta = 4.5f;
pEffect->fSizeWayTime = 0.3f;
pEffect->fSizeWayDelta = 3.f;
pEffect->fAlphaDelta = 0.f;
pEffect->fAlphaWayTime = 0.2f;
pEffect->fAlphaWayDelta = 250.f;
break;
case 10:
pEffect->vAngle = MyVec3(30.f, 0.f, Engine::GetRandomFloat(-360.f, 360.f));
pEffect->fMaxLife = 0.6f;
pEffect->fSpeed = 10.f;
pEffect->fAngle = 0.f;
pEffect->fRadius = Engine::GetRandomFloat(10.f, 15.f);
pEffect->fRadiusAngle = 0.f;
pEffect->vDir.z = pEffect->fRadius * sinf(pEffect->fAngle) * cosf(pEffect->fRadiusAngle);
pEffect->vDir.x = pEffect->fRadius * sinf(pEffect->fAngle) * sinf(pEffect->fRadiusAngle);
pEffect->vDir.y = pEffect->fRadius * cosf(pEffect->fAngle);
fSize = Engine::GetRandomFloat(17.f, 21.f);
pEffect->vScale = MyVec3(fSize, fSize, 1.f);
pEffect->vPos = m_vOrigin + MyVec3(0.f, -7.f, 0.f);
pEffect->fSizeDelta = 20.f;
/*pEffect->fSizeWayTime = 0.3f;
pEffect->fSizeWayDelta = 3.f;*/
pEffect->fAlphaDelta = 0.f;
pEffect->fAlphaWayTime = 0.01f;
pEffect->fAlphaWayDelta = 250.f;
pEffect->fRollDelta = 260.f;
break;
case 11:
pEffect->vAngle = MyVec3(Engine::GetRandomFloat(0.f, 70.f), Engine::GetRandomFloat(-360.f, 360.f), 0.f);
pEffect->fMaxLife = Engine::GetRandomFloat(0.25f, 0.3f);
pEffect->fSpeed = Engine::GetRandomFloat(15.f, 30.f);
pEffect->fAngle = 0.f;
pEffect->fRadius = Engine::GetRandomFloat(5.f, 15.f);
pEffect->fRadiusAngle = 40.f;
pEffect->vDir.z = pEffect->fRadius * sinf(pEffect->fAngle) * cosf(pEffect->fRadiusAngle);
pEffect->vDir.x = pEffect->fRadius * sinf(pEffect->fAngle) * sinf(pEffect->fRadiusAngle);
pEffect->vDir.y = pEffect->fRadius * cosf(pEffect->fAngle);
pEffect->vScale = MyVec3(Engine::GetRandomFloat(9.f, 12.f), Engine::GetRandomFloat(35.f, 55.f), 1.f);
pEffect->vPos = m_vOrigin + MyVec3(0.f, -15.f, 0.f);
pEffect->fSizeDelta = -15.f;
pEffect->fSizeWayTime = 0.4f;
pEffect->fSizeWayDelta = 30.f;
pEffect->fAlphaDelta = 0.f;
pEffect->fAlphaWayTime = 0.5f;
pEffect->fAlphaWayDelta = 220.f;
break;
case 12:
pEffect->vAngle = MyVec3(Engine::GetRandomFloat(0.f, 70.f), Engine::GetRandomFloat(-360.f, 360.f), 0.f);
pEffect->fMaxLife = Engine::GetRandomFloat(0.15f, 0.2f);
pEffect->fSpeed = Engine::GetRandomFloat(2.f, 4.f);
pEffect->fAngle = 0.f;
pEffect->fRadius = Engine::GetRandomFloat(5.f, 15.f);
pEffect->fRadiusAngle = 0.f;
pEffect->vDir.z = pEffect->fRadius * sinf(pEffect->fAngle) * cosf(pEffect->fRadiusAngle);
pEffect->vDir.x = pEffect->fRadius * sinf(pEffect->fAngle) * sinf(pEffect->fRadiusAngle);
pEffect->vDir.y = pEffect->fRadius * cosf(pEffect->fAngle);
pEffect->vScale = MyVec3(Engine::GetRandomFloat(5.f, 6.f), Engine::GetRandomFloat(35.f, 55.f), 1.f);
pEffect->vPos = m_vOrigin + MyVec3(0.f, -7.f, 0.f);
pEffect->fSizeDelta = -5.f;
pEffect->fSizeWayTime = 0.2f;
pEffect->fSizeWayDelta = 40.f;
pEffect->fAlphaDelta = 0.f;
pEffect->fAlphaWayTime = 0.7f;
pEffect->fAlphaWayDelta = 220.f;
break;
case 13:
pEffect->vAngle = MyVec3(Engine::GetRandomFloat(70.f, 110.f), 0.f, Engine::GetRandomFloat(-360.f, 360.f));
pEffect->fMaxLife = Engine::GetRandomFloat(0.25f, 0.3f);
pEffect->fSpeed = Engine::GetRandomFloat(1.5f, 3.f);
pEffect->fAngle = Engine::GetRandomFloat(-360.f, 360.f);
pEffect->fRadius = Engine::GetRandomFloat(5.f, 15.f);
pEffect->fRadiusAngle = 20.f;
pEffect->vDir.z = pEffect->fRadius * sinf(pEffect->fAngle) * cosf(pEffect->fRadiusAngle);
pEffect->vDir.x = pEffect->fRadius * sinf(pEffect->fAngle) * sinf(pEffect->fRadiusAngle);
pEffect->vDir.y = pEffect->fRadius * cosf(pEffect->fAngle);
fSize = Engine::GetRandomFloat(8.f, 12.f);
pEffect->vScale = MyVec3(fSize, fSize, 1.f);
pEffect->vPos = m_vOrigin + MyVec3(0.f, -7.f, 0.f);
pEffect->fSizeDelta = 15.f;
pEffect->fSizeWayTime = 0.4f;
pEffect->fSizeWayDelta = 11.f;
pEffect->fAlphaDelta = 0.f;
pEffect->fAlphaWayTime = 0.5f;
pEffect->fAlphaWayDelta = 220.f;
break;
case 14:
pEffect->vAngle = MyVec3(Engine::GetRandomFloat(70.f, 110.f), 0.f, Engine::GetRandomFloat(-360.f, 360.f));
pEffect->fMaxLife = Engine::GetRandomFloat(0.3f, 0.4f);
pEffect->fSpeed = Engine::GetRandomFloat(5.f, 8.f);
pEffect->fAngle = Engine::GetRandomFloat(-360.f, 360.f);
pEffect->fRadius = Engine::GetRandomFloat(10.f, 15.f);
pEffect->fRadiusAngle = 0.f;
pEffect->vDir.z = pEffect->fRadius * sinf(pEffect->fAngle);
pEffect->vDir.x = pEffect->fRadius * cosf(pEffect->fAngle);
pEffect->vDir.y = Engine::GetRandomFloat(0.f, 50.f);;
fSize = Engine::GetRandomFloat(8.f, 12.f);
pEffect->vScale = MyVec3(fSize, fSize, 1.f);
pEffect->vScaleDelta = MyVec3(0.f, -5.f, 0.f);
pEffect->vPos = m_vOrigin + MyVec3(0.f, -7.f, 0.f);
pEffect->fSizeDelta = 15.f;
pEffect->fSizeWayTime = 0.4f;
pEffect->fSizeWayDelta = 11.f;
pEffect->fAlphaDelta = 0.f;
pEffect->fAlphaWayTime = 0.5f;
pEffect->fAlphaWayDelta = 255.f;
break;
case 15:
pEffect->vAngle = MyVec3(Engine::GetRandomFloat(70.f, 110.f), 0.f, Engine::GetRandomFloat(-360.f, 360.f));
pEffect->fMaxLife = Engine::GetRandomFloat(0.4f, 0.6f);
pEffect->fSpeed = Engine::GetRandomFloat(1.f, 2.f);
pEffect->fAngle = 40.f;
pEffect->fRadius = Engine::GetRandomFloat(10.f, 15.f);
pEffect->fRadiusAngle = 0.f;
pEffect->vDir.z = pEffect->fRadius * sinf(pEffect->fAngle);
pEffect->vDir.x = pEffect->fRadius * cosf(pEffect->fAngle);
pEffect->vDir.y = Engine::GetRandomFloat(0.f, 50.f);;
fSize = Engine::GetRandomFloat(10.f, 14.f);
pEffect->vScale = MyVec3(fSize, fSize, 1.f);
pEffect->vPos = m_vOrigin + MyVec3(0.f, -7.f, 0.f);
pEffect->fSizeDelta = 15.f;
pEffect->fSizeWayTime = 0.4f;
pEffect->fSizeWayDelta = 11.f;
pEffect->fAlphaDelta = 0.f;
pEffect->fAlphaWayTime = 0.5f;
pEffect->fAlphaWayDelta = 255.f;
pEffect->fRollDelta = 10.f;
break;
}
D3DXVec3Normalize(&pEffect->vDir, &pEffect->vDir);
pEffect->fAlphaDelta -= 255.f;
m_EffectList.push_back(pEffect);
}
HRESULT CShockWave::Ready_Component( void )
{
m_pRendererCom = (Engine::CRenderer*)Engine::Get_ComponentMgr()->CloneComponent(SCENE_STATIC, L"Component_Renderer");
if (m_pRendererCom == NULL)
return E_FAIL;
if (FAILED(AddComponent(Engine::CGameObject::UPDATE_NONE, L"Com_Renderer", m_pRendererCom)))
return E_FAIL;
m_pTransformCom = (Engine::CTransform*)Engine::Get_ComponentMgr()->CloneComponent(SCENE_STATIC, L"Component_Transform");
if (m_pTransformCom == NULL)
return E_FAIL;
if (FAILED(AddComponent(Engine::CGameObject::UPDATE_DO, L"Com_Transform", m_pTransformCom)))
return E_FAIL;
m_pTextureCom = (Engine::CTexture*)Engine::Get_ComponentMgr()->CloneComponent(SCENE_STAGE, m_pEffectKey);
if (m_pTextureCom == NULL)
return E_FAIL;
if (FAILED(AddComponent(Engine::CGameObject::UPDATE_NONE, L"Com_Texture", m_pTextureCom)))
return E_FAIL;
m_pBufferCom = (Engine::CRcTex*)Engine::Get_ComponentMgr()->CloneComponent(SCENE_STATIC, L"Component_Buffer_RcTex");
if (m_pBufferCom == NULL)
return E_FAIL;
if (FAILED(AddComponent(Engine::CGameObject::UPDATE_NONE, L"Com_Buffer", m_pBufferCom)))
return E_FAIL;
m_pShaderCom = (Engine::CShader*)Engine::Get_ComponentMgr()->CloneComponent(SCENE_STAGE, L"Component_Shader_Particle");
if (m_pShaderCom == NULL)
return E_FAIL;
if (FAILED(AddComponent(Engine::CGameObject::UPDATE_NONE, L"Com_Shader", m_pShaderCom)))
return E_FAIL;
return S_OK;
}
void CShockWave::Free( void )
{
Engine::Safe_Release(m_pRendererCom);
Engine::Safe_Release(m_pTransformCom);
Engine::Safe_Release(m_pTextureCom);
Engine::Safe_Release(m_pBufferCom);
Engine::Safe_Release(m_pShaderCom);
Engine::CGameObject::Free();
}
CShockWave* CShockWave::Create( LPDIRECT3DDEVICE9 pDevice, const _uint& iType)
{
CShockWave* pShockWave = new CShockWave(pDevice);
if (FAILED(pShockWave->Initialize(iType)))
{
MSG_BOX("ShockWave Created Failed");
Engine::Safe_Release(pShockWave);
}
return pShockWave;
}
| [
"buseog1991@naver.com"
] | buseog1991@naver.com |
09df90765aa44fe32409406bedcecf3b3906e6f7 | 654e898008a1cb0ee081233c359c276b8c937a5e | /syscall/mocks/bf_reg_t.hpp | dd8fd1c3421ba30e69b9626528945f55912ec240 | [
"MIT"
] | permissive | shutupandhack-club/hypervisor | a925d287487b6d8231f39b47a7f3a1e91da20a2e | 58418ae1da8364200f2f06225ac801c45bea590a | refs/heads/master | 2023-08-14T01:03:37.208229 | 2021-09-19T01:45:34 | 2021-09-19T01:45:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,776 | hpp | /// @copyright
/// Copyright (C) 2020 Assured Information Security, Inc.
///
/// @copyright
/// 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:
///
/// @copyright
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// @copyright
/// 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 BF_REG_T_HPP
#define BF_REG_T_HPP
#include <bsl/cstdint.hpp>
namespace syscall
{
/// <!-- description -->
/// @brief Defines which register to use for read/write
///
enum class bf_reg_t : bsl::uint64
{
/// @brief defines an unsupported register
bf_reg_t_unsupported = static_cast<bsl::uint64>(0),
/// @brief defines as dummy bf_reg_t
bf_reg_t_dummy = static_cast<bsl::uint64>(1),
/// @brief defines an invalid bf_reg_t
bf_reg_t_invalid = static_cast<bsl::uint64>(42)
};
}
#endif
| [
"rianquinn@gmail.com"
] | rianquinn@gmail.com |
f8267fd40a94cfdff90b18214aa68fea794a5fc7 | 22bd625b1a2ffc102761914469c9673f62cf8e78 | /benchmarks/src/cuda/cutlass-bench/cutlass/gemm/device_gemm_traits.h | 1ff2a11cc90cb034be16f7c6d9d90371fa514cec | [
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | purdue-aalp/gpgpu-sim_simulations | f1c32ac5a88c4120d326d1053c82e598ca2d05fe | 84113a92a4aacfdd1ddbc1beb2f01746060dfb05 | refs/heads/master | 2021-08-05T21:56:58.378115 | 2021-01-28T23:31:26 | 2021-01-28T23:31:26 | 154,350,995 | 6 | 15 | BSD-2-Clause | 2021-05-18T15:28:08 | 2018-10-23T15:18:42 | HTML | UTF-8 | C++ | false | false | 6,790 | h | /***************************************************************************************************
* Copyright (c) 2017-2019, NVIDIA CORPORATION. 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 the NVIDIA CORPORATION 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 NVIDIA CORPORATION 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 TOR (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
#pragma once
#include <assert.h>
#include "cutlass/gemm/device_gemm.h"
#include "cutlass/matrix_traits.h"
#include "cutlass/gemm/gemm_desc.h"
#include "tools/util/type_traits.h"
#include <iostream>
namespace cutlass {
namespace gemm {
template <
/// The Tratis for the first kernel
typename GemmTraits_,
/// The Traits for the second kernel
typename ReductionTraits_
>
struct SplitkPIGemmTraits {
typedef GemmTraits_ GemmTraits;
typedef ReductionTraits_ ReductionTraits;
typedef SplitkPIGemmTraits<GemmTraits_, ReductionTraits_> This_;
typedef typename cutlass::gemm::DeviceGemm<This_> KernelClass;
///
typedef typename GemmTraits::Index Index;
///
typedef typename ReductionTraits::ScalarAlphaBeta Scalar;
///
typedef typename GemmTraits::ScalarA ScalarA;
///
typedef typename GemmTraits::ScalarB ScalarB;
///
typedef typename GemmTraits::ScalarD ScalarAccum;
///
typedef typename ReductionTraits::ScalarC ScalarC;
///
typedef typename ReductionTraits::ScalarD ScalarD;
/// The layout of A. can be deduced from the layout set in batched gemm
static MatrixLayout::Kind const kLayoutA = GemmTraits::kLayoutA;
/// The layout of B. can be deduced from the layout set in batched gemm
static MatrixLayout::Kind const kLayoutB = GemmTraits::kLayoutB;
struct Params {
/// The dimensions of the GEMM in K, N, M order
GemmCoord problem_size;
/// Check if params are init
bool problem_size_initialized;
/// The pointer to workspace memory
ScalarAccum *workspace_ptr;
///
size_t workspace_size;
/// The Params for the first kernel
typename GemmTraits::Params GemmParams;
/// The Params for the second kernel
typename ReductionTraits::Params ReductionParams;
/// ctor
Params() :
workspace_size(0),
problem_size_initialized(false) {}
/// ctor
Params(Index m_,
Index n_,
Index k_
):
problem_size(k_, n_, m_, 1),
workspace_size(0),
problem_size_initialized(true) {
}
/// init problem is needed if using default ctor
void init_problem(Index m_,
Index n_,
Index k_){
problem_size = GemmCoord(k_, n_, m_, 1);
problem_size_initialized = true;
}
int initialize(Scalar alpha_,
ScalarA const* d_a_,
Index lda_,
ScalarB const* d_b_,
Index ldb_,
Scalar beta_,
ScalarC const* d_c_,
Index ldc_,
ScalarD* d_d_,
Index ldd_,
ScalarAccum *workspace_ptr_,
Index partitionK_multiple = 1) {
workspace_ptr = workspace_ptr_;
//call GemmTraits (first kernel) param
//for the first kernel A is A, B is B, C and D are workspace
//alpha is one, beta is zero, partitionK_count is reductionTraits::reductionSize
typename cutlass::gemm::GemmDesc<typename GemmTraits::ScalarA,
typename GemmTraits::ScalarB,
typename GemmTraits::ScalarC,
typename GemmTraits::ScalarD,
typename GemmTraits::Epilogue::Scalar>
desc(
problem_size,
typename cutlass::TypeTraits<typename GemmTraits::Epilogue::Scalar>::host_type(1.0f), /*alpha*/
TensorRef<typename GemmTraits::ScalarA const, 2>(d_a_, lda_),
TensorRef<typename GemmTraits::ScalarB const, 2>(d_b_, ldb_),
typename cutlass::TypeTraits<typename GemmTraits::Epilogue::Scalar>::host_type(0.0f), /*beta*/
TensorRef<typename GemmTraits::ScalarC const, 2>(workspace_ptr, problem_size.m()), /*m = ldc, workspace is not transposed and is packed*/
TensorRef<typename GemmTraits::ScalarD, 2>(workspace_ptr, problem_size.m()) /*m = ldd, workspace is not transposed and is packed*/
);
GemmParams.initialize(desc, ReductionTraits::ReductionSize, partitionK_multiple);
//call batched reduction (second kernel) param
ReductionParams.initialize(problem_size.m(), /*m*/
problem_size.n(), /*n*/
alpha_, /*alpha*/
beta_, /*beta*/
problem_size.n() * problem_size.m() /*reduction_stride*/,
workspace_ptr,
problem_size.m(),
d_c_,
ldc_,
d_d_,
ldd_);
return 0;
}
// workspace will be used to store D (output) from the first gemm kernel (not D of the entire gemm)
// note typedef typename GemmTraits::ScalarD ScalarAccum;
// workspace of size of M * N * Reduction
size_t required_workspace_memory_in_byte(){
assert(problem_size_initialized == true);
workspace_size = static_cast<size_t>(problem_size.n()) *
static_cast<size_t>(problem_size.m()) *
static_cast<size_t>(ReductionTraits::ReductionSize) *
sizeof(ScalarAccum);
return workspace_size;
}
};
};
} // namespace device_gemm
} // namespace cutalss
| [
"k.mkhairy@yahoo.com"
] | k.mkhairy@yahoo.com |
d40028321bb6f90608f0207191ec02f7ef6d3abc | 45b82fe5a86b7d803dd495dda67e13ca231d2754 | /SketchBook/libraries/I2Cdev/I2Cdev.cpp | e9221090b044497a47dfb73a73926773002394d1 | [
"Apache-2.0"
] | permissive | willie68/OpenSeaMapLogger | 4e1dc502976ba7325103e9916e11821f3d3a36b2 | 7a48096f4c1d5aaea8c04a3f61e489774383913d | refs/heads/master | 2020-06-04T17:37:01.000828 | 2018-04-12T08:41:20 | 2018-04-12T08:41:20 | 13,522,905 | 7 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 54,750 | cpp | // I2Cdev library collection - Main I2C device class
// Abstracts bit and byte I2C R/W functions into a convenient class
// 6/9/2012 by Jeff Rowberg <jeff@rowberg.net>
//
// Changelog:
// 2013-05-05 - fix issue with writing bit values to words (Sasquatch/Farzanegan)
// 2012-06-09 - fix major issue with reading > 32 bytes at a time with Arduino Wire
// - add compiler warnings when using outdated or IDE or limited I2Cdev implementation
// 2011-11-01 - fix write*Bits mask calculation (thanks sasquatch @ Arduino forums)
// 2011-10-03 - added automatic Arduino version detection for ease of use
// 2011-10-02 - added Gene Knight's NBWire TwoWire class implementation with small modifications
// 2011-08-31 - added support for Arduino 1.0 Wire library (methods are different from 0.x)
// 2011-08-03 - added optional timeout parameter to read* methods to easily change from default
// 2011-08-02 - added support for 16-bit registers
// - fixed incorrect Doxygen comments on some methods
// - added timeout value for read operations (thanks mem @ Arduino forums)
// 2011-07-30 - changed read/write function structures to return success or byte counts
// - made all methods static for multi-device memory savings
// 2011-07-28 - initial release
/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg
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 "I2Cdev.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#ifdef I2CDEV_IMPLEMENTATION_WARNINGS
#if ARDUINO < 100
#warning Using outdated Arduino IDE with Wire library is functionally limiting.
#warning Arduino IDE v1.0.1+ with I2Cdev Fastwire implementation is recommended.
#warning This I2Cdev implementation does not support:
#warning - Repeated starts conditions
#warning - Timeout detection (some Wire requests block forever)
#elif ARDUINO == 100
#warning Using outdated Arduino IDE with Wire library is functionally limiting.
#warning Arduino IDE v1.0.1+ with I2Cdev Fastwire implementation is recommended.
#warning This I2Cdev implementation does not support:
#warning - Repeated starts conditions
#warning - Timeout detection (some Wire requests block forever)
#elif ARDUINO > 100
/*
#warning Using current Arduino IDE with Wire library is functionally limiting.
#warning Arduino IDE v1.0.1+ with I2CDEV_BUILTIN_FASTWIRE implementation is recommended.
#warning This I2Cdev implementation does not support:
#warning - Timeout detection (some Wire requests block forever)
*/
#endif
#endif
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
#error The I2CDEV_BUILTIN_FASTWIRE implementation is known to be broken right now. Patience, Iago!
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE
#ifdef I2CDEV_IMPLEMENTATION_WARNINGS
#warning Using I2CDEV_BUILTIN_NBWIRE implementation may adversely affect interrupt detection.
#warning This I2Cdev implementation does not support:
#warning - Repeated starts conditions
#endif
// NBWire implementation based heavily on code by Gene Knight <Gene@Telobot.com>
// Originally posted on the Arduino forum at http://arduino.cc/forum/index.php/topic,70705.0.html
// Originally offered to the i2cdevlib project at http://arduino.cc/forum/index.php/topic,68210.30.html
TwoWire Wire;
#elif I2CDEV_IMPLEMENTATION == I2CDEV_I2CMASTER_LIBRARY
#warning Dunno, just don't want it to feel left out ^_^'
#endif
/** Default constructor.
*/
I2Cdev::I2Cdev() {
}
/** Read a single bit from an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to read from
* @param bitNum Bit position to read (0-7)
* @param data Container for single bit value
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Status of read operation (true = success)
*/
int8_t I2Cdev::readBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t *data, uint16_t timeout) {
uint8_t b;
uint8_t count = readByte(devAddr, regAddr, &b, timeout);
*data = b & (1 << bitNum);
return count;
}
/** Read a single bit from a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to read from
* @param bitNum Bit position to read (0-15)
* @param data Container for single bit value
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Status of read operation (true = success)
*/
int8_t I2Cdev::readBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t *data, uint16_t timeout) {
uint16_t b;
uint8_t count = readWord(devAddr, regAddr, &b, timeout);
*data = b & (1 << bitNum);
return count;
}
/** Read multiple bits from an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to read from
* @param bitStart First bit position to read (0-7)
* @param length Number of bits to read (not more than 8)
* @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05)
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Status of read operation (true = success)
*/
int8_t I2Cdev::readBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data, uint16_t timeout) {
// 01101001 read byte
// 76543210 bit numbers
// xxx args: bitStart=4, length=3
// 010 masked
// -> 010 shifted
uint8_t count, b;
if ((count = readByte(devAddr, regAddr, &b, timeout)) != 0) {
uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
b &= mask;
b >>= (bitStart - length + 1);
*data = b;
}
return count;
}
/** Read multiple bits from a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to read from
* @param bitStart First bit position to read (0-15)
* @param length Number of bits to read (not more than 16)
* @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05)
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Status of read operation (1 = success, 0 = failure, -1 = timeout)
*/
int8_t I2Cdev::readBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t *data, uint16_t timeout) {
// 1101011001101001 read byte
// fedcba9876543210 bit numbers
// xxx args: bitStart=12, length=3
// 010 masked
// -> 010 shifted
uint8_t count;
uint16_t w;
if ((count = readWord(devAddr, regAddr, &w, timeout)) != 0) {
uint16_t mask = ((1 << length) - 1) << (bitStart - length + 1);
w &= mask;
w >>= (bitStart - length + 1);
*data = w;
}
return count;
}
/** Read single byte from an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to read from
* @param data Container for byte value read from device
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Status of read operation (true = success)
*/
int8_t I2Cdev::readByte(uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint16_t timeout) {
return readBytes(devAddr, regAddr, 1, data, timeout);
}
/** Read single word from a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to read from
* @param data Container for word value read from device
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Status of read operation (true = success)
*/
int8_t I2Cdev::readWord(uint8_t devAddr, uint8_t regAddr, uint16_t *data, uint16_t timeout) {
return readWords(devAddr, regAddr, 1, data, timeout);
}
/** Read multiple bytes from an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr First register regAddr to read from
* @param length Number of bytes to read
* @param data Buffer to store read data in
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Number of bytes read (-1 indicates failure)
*/
int8_t I2Cdev::readBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data, uint16_t timeout) {
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print("I2C (0x");
Serial.print(devAddr, HEX);
Serial.print(") reading ");
Serial.print(length, DEC);
Serial.print(" bytes from 0x");
Serial.print(regAddr, HEX);
Serial.print("...");
#endif
int8_t count = 0;
uint32_t t1 = millis();
#if (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE)
#if (ARDUINO < 100)
// Arduino v00xx (before v1.0), Wire library
// I2C/TWI subsystem uses internal buffer that breaks with large data requests
// so if user requests more than BUFFER_LENGTH bytes, we have to do it in
// smaller chunks instead of all at once
for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) {
Wire.beginTransmission(devAddr);
Wire.send(regAddr);
Wire.endTransmission();
Wire.beginTransmission(devAddr);
Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));
for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) {
data[count] = Wire.receive();
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[count], HEX);
if (count + 1 < length) Serial.print(" ");
#endif
}
Wire.endTransmission();
}
#elif (ARDUINO == 100)
// Arduino v1.0.0, Wire library
// Adds standardized write() and read() stream methods instead of send() and receive()
// I2C/TWI subsystem uses internal buffer that breaks with large data requests
// so if user requests more than BUFFER_LENGTH bytes, we have to do it in
// smaller chunks instead of all at once
for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) {
Wire.beginTransmission(devAddr);
Wire.write(regAddr);
Wire.endTransmission();
Wire.beginTransmission(devAddr);
Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));
for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) {
data[count] = Wire.read();
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[count], HEX);
if (count + 1 < length) Serial.print(" ");
#endif
}
Wire.endTransmission();
}
#elif (ARDUINO > 100)
// Arduino v1.0.1+, Wire library
// Adds official support for repeated start condition, yay!
// I2C/TWI subsystem uses internal buffer that breaks with large data requests
// so if user requests more than BUFFER_LENGTH bytes, we have to do it in
// smaller chunks instead of all at once
for (uint8_t k = 0; k < length; k += min(length, BUFFER_LENGTH)) {
Wire.beginTransmission(devAddr);
Wire.write(regAddr);
Wire.endTransmission();
Wire.beginTransmission(devAddr);
Wire.requestFrom(devAddr, (uint8_t)min(length - k, BUFFER_LENGTH));
for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) {
data[count] = Wire.read();
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[count], HEX);
if (count + 1 < length) Serial.print(" ");
#endif
}
Wire.endTransmission();
}
#endif
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
// Fastwire library (STILL UNDER DEVELOPMENT, NON-FUNCTIONAL!)
// no loop required for fastwire
uint8_t status = Fastwire::readBuf(devAddr, regAddr, data, length);
if (status == 0) {
count = length; // success
} else {
count = -1; // error
}
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_I2CMASTER_LIBRARY)
uint8_t status = I2c.read(devAddr, regAddr, length, data);
if(status == 0) {
count = length;
} else {
count = -1 * status;
}
#endif
// check for timeout
if (timeout > 0 && millis() - t1 >= timeout && count < length) count = -1; // timeout
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(". Done (");
Serial.print(count, DEC);
Serial.println(" read).");
#endif
return count;
}
/** Read multiple words from a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr First register regAddr to read from
* @param length Number of words to read
* @param data Buffer to store read data in
* @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
* @return Number of words read (0 indicates failure)
*/
int8_t I2Cdev::readWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t *data, uint16_t timeout) {
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print("I2C (0x");
Serial.print(devAddr, HEX);
Serial.print(") reading ");
Serial.print(length, DEC);
Serial.print(" words from 0x");
Serial.print(regAddr, HEX);
Serial.print("...");
#endif
int8_t count = 0;
uint32_t t1 = millis();
#if (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE)
#if (ARDUINO < 100)
// Arduino v00xx (before v1.0), Wire library
// I2C/TWI subsystem uses internal buffer that breaks with large data requests
// so if user requests more than BUFFER_LENGTH bytes, we have to do it in
// smaller chunks instead of all at once
for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
Wire.beginTransmission(devAddr);
Wire.send(regAddr);
Wire.endTransmission();
Wire.beginTransmission(devAddr);
Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes
bool msb = true; // starts with MSB, then LSB
for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) {
if (msb) {
// first byte is bits 15-8 (MSb=15)
data[count] = Wire.receive() << 8;
} else {
// second byte is bits 7-0 (LSb=0)
data[count] |= Wire.receive();
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[count], HEX);
if (count + 1 < length) Serial.print(" ");
#endif
count++;
}
msb = !msb;
}
Wire.endTransmission();
}
#elif (ARDUINO == 100)
// Arduino v1.0.0, Wire library
// Adds standardized write() and read() stream methods instead of send() and receive()
// I2C/TWI subsystem uses internal buffer that breaks with large data requests
// so if user requests more than BUFFER_LENGTH bytes, we have to do it in
// smaller chunks instead of all at once
for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
Wire.beginTransmission(devAddr);
Wire.write(regAddr);
Wire.endTransmission();
Wire.beginTransmission(devAddr);
Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes
bool msb = true; // starts with MSB, then LSB
for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) {
if (msb) {
// first byte is bits 15-8 (MSb=15)
data[count] = Wire.read() << 8;
} else {
// second byte is bits 7-0 (LSb=0)
data[count] |= Wire.read();
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[count], HEX);
if (count + 1 < length) Serial.print(" ");
#endif
count++;
}
msb = !msb;
}
Wire.endTransmission();
}
#elif (ARDUINO > 100)
// Arduino v1.0.1+, Wire library
// Adds official support for repeated start condition, yay!
// I2C/TWI subsystem uses internal buffer that breaks with large data requests
// so if user requests more than BUFFER_LENGTH bytes, we have to do it in
// smaller chunks instead of all at once
for (uint8_t k = 0; k < length * 2; k += min(length * 2, BUFFER_LENGTH)) {
Wire.beginTransmission(devAddr);
Wire.write(regAddr);
Wire.endTransmission();
Wire.beginTransmission(devAddr);
Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes
bool msb = true; // starts with MSB, then LSB
for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) {
if (msb) {
// first byte is bits 15-8 (MSb=15)
data[count] = Wire.read() << 8;
} else {
// second byte is bits 7-0 (LSb=0)
data[count] |= Wire.read();
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[count], HEX);
if (count + 1 < length) Serial.print(" ");
#endif
count++;
}
msb = !msb;
}
Wire.endTransmission();
}
#endif
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
// Fastwire library (STILL UNDER DEVELOPMENT, NON-FUNCTIONAL!)
// no loop required for fastwire
uint16_t intermediate[(uint8_t)length];
uint8_t status = Fastwire::readBuf(devAddr, regAddr, (uint8_t *)intermediate, (uint8_t)(length * 2));
if (status == 0) {
count = length; // success
for (uint8_t i = 0; i < length; i++) {
data[i] = (intermediate[2*i] << 8) | intermediate[2*i + 1];
}
} else {
count = -1; // error
}
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_I2CMASTER_LIBRARY)
uint16_t intermediate[(uint8_t)length];
uint8_t status = I2c.read(devAddr, regAddr, length*2, (uint8_t *)intermediate);
if(status == 0) {
count = length;
for(uint8_t i = 0; i < length; i++) {
data[i] = (intermediate[2*i] << 8) | intermediate[2*i + i];
}
} else {
count = -1 * status;
}
#endif
if (timeout > 0 && millis() - t1 >= timeout && count < length) count = -1; // timeout
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(". Done (");
Serial.print(count, DEC);
Serial.println(" read).");
#endif
return count;
}
/** write a single bit in an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to write to
* @param bitNum Bit position to write (0-7)
* @param value New bit value to write
* @return Status of operation (true = success)
*/
bool I2Cdev::writeBit(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data) {
uint8_t b;
readByte(devAddr, regAddr, &b);
b = (data != 0) ? (b | (1 << bitNum)) : (b & ~(1 << bitNum));
return writeByte(devAddr, regAddr, b);
}
/** write a single bit in a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to write to
* @param bitNum Bit position to write (0-15)
* @param value New bit value to write
* @return Status of operation (true = success)
*/
bool I2Cdev::writeBitW(uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t data) {
uint16_t w;
readWord(devAddr, regAddr, &w);
w = (data != 0) ? (w | (1 << bitNum)) : (w & ~(1 << bitNum));
return writeWord(devAddr, regAddr, w);
}
/** Write multiple bits in an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to write to
* @param bitStart First bit position to write (0-7)
* @param length Number of bits to write (not more than 8)
* @param data Right-aligned value to write
* @return Status of operation (true = success)
*/
bool I2Cdev::writeBits(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data) {
// 010 value to write
// 76543210 bit numbers
// xxx args: bitStart=4, length=3
// 00011100 mask byte
// 10101111 original value (sample)
// 10100011 original & ~mask
// 10101011 masked | value
uint8_t b;
if (readByte(devAddr, regAddr, &b) != 0) {
uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
data <<= (bitStart - length + 1); // shift data into correct position
data &= mask; // zero all non-important bits in data
b &= ~(mask); // zero all important bits in existing byte
b |= data; // combine data with existing byte
return writeByte(devAddr, regAddr, b);
} else {
return false;
}
}
/** Write multiple bits in a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register regAddr to write to
* @param bitStart First bit position to write (0-15)
* @param length Number of bits to write (not more than 16)
* @param data Right-aligned value to write
* @return Status of operation (true = success)
*/
bool I2Cdev::writeBitsW(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t data) {
// 010 value to write
// fedcba9876543210 bit numbers
// xxx args: bitStart=12, length=3
// 0001110000000000 mask word
// 1010111110010110 original value (sample)
// 1010001110010110 original & ~mask
// 1010101110010110 masked | value
uint16_t w;
if (readWord(devAddr, regAddr, &w) != 0) {
uint16_t mask = ((1 << length) - 1) << (bitStart - length + 1);
data <<= (bitStart - length + 1); // shift data into correct position
data &= mask; // zero all non-important bits in data
w &= ~(mask); // zero all important bits in existing word
w |= data; // combine data with existing word
return writeWord(devAddr, regAddr, w);
} else {
return false;
}
}
/** Write single byte to an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register address to write to
* @param data New byte value to write
* @return Status of operation (true = success)
*/
bool I2Cdev::writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t data) {
return writeBytes(devAddr, regAddr, 1, &data);
}
/** Write single word to a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr Register address to write to
* @param data New word value to write
* @return Status of operation (true = success)
*/
bool I2Cdev::writeWord(uint8_t devAddr, uint8_t regAddr, uint16_t data) {
return writeWords(devAddr, regAddr, 1, &data);
}
/** Write multiple bytes to an 8-bit device register.
* @param devAddr I2C slave device address
* @param regAddr First register address to write to
* @param length Number of bytes to write
* @param data Buffer to copy new data from
* @return Status of operation (true = success)
*/
bool I2Cdev::writeBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t* data) {
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print("I2C (0x");
Serial.print(devAddr, HEX);
Serial.print(") writing ");
Serial.print(length, DEC);
Serial.print(" bytes to 0x");
Serial.print(regAddr, HEX);
Serial.print("...");
#endif
uint8_t status = 0;
#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
Wire.beginTransmission(devAddr);
Wire.send((uint8_t) regAddr); // send address
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
Wire.beginTransmission(devAddr);
Wire.write((uint8_t) regAddr); // send address
#endif
for (uint8_t i = 0; i < length; i++) {
#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
Wire.send((uint8_t) data[i]);
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
Wire.write((uint8_t) data[i]);
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
status = Fastwire::write(devAddr, regAddr, data[i]);
Serial.println(status);
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_I2CMASTER_LIBRARY)
status = I2c.write(devAddr, regAddr, data[i]);
#endif
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[i], HEX);
if (i + 1 < length) Serial.print(" ");
#endif
}
#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
Wire.endTransmission();
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
status = Wire.endTransmission();
#endif
#ifdef I2CDEV_SERIAL_DEBUG
Serial.println(". Done.");
#endif
return status == 0;
}
/** Write multiple words to a 16-bit device register.
* @param devAddr I2C slave device address
* @param regAddr First register address to write to
* @param length Number of words to write
* @param data Buffer to copy new data from
* @return Status of operation (true = success)
*/
bool I2Cdev::writeWords(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t* data) {
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print("I2C (0x");
Serial.print(devAddr, HEX);
Serial.print(") writing ");
Serial.print(length, DEC);
Serial.print(" words to 0x");
Serial.print(regAddr, HEX);
Serial.print("...");
#endif
uint8_t status = 0;
#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
Wire.beginTransmission(devAddr);
Wire.send(regAddr); // send address
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
Wire.beginTransmission(devAddr);
Wire.write(regAddr); // send address
#endif
for (uint8_t i = 0; i < length * 2; i++) {
#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
Wire.send((uint8_t)(data[i++] >> 8)); // send MSB
Wire.send((uint8_t)data[i]); // send LSB
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
Wire.write((uint8_t)(data[i++] >> 8)); // send MSB
Wire.write((uint8_t)data[i]); // send LSB
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE)
status = Fastwire::write(devAddr, regAddr, (uint8_t)(data[i++] >> 8));
status = Fastwire::write(devAddr, regAddr + 1, (uint8_t)data[i]);
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_I2CMASTER_LIBRARY)
status = I2c.write((uint8_t)devAddr, (uint8_t)regAddr, (uint8_t)(data[i++] >> 8));
status = I2c.write((uint8_t)devAddr, (uint8_t)regAddr + 1, (uint8_t)data[i]);
#endif
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print(data[i], HEX);
if (i + 1 < length) Serial.print(" ");
#endif
}
#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
Wire.endTransmission();
#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
status = Wire.endTransmission();
#endif
#ifdef I2CDEV_SERIAL_DEBUG
Serial.println(". Done.");
#endif
return status == 0;
}
/** Default timeout value for read operations.
* Set this to 0 to disable timeout detection.
*/
uint16_t I2Cdev::readTimeout = I2CDEV_DEFAULT_READ_TIMEOUT;
#if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
/*
FastWire 0.2
This is a library to help faster programs to read I2C devices.
Copyright(C) 2011 Francesco Ferrara
occhiobello at gmail dot com
*/
boolean Fastwire::waitInt() {
int l = 250;
while (!(TWCR & (1 << TWINT)) && l-- > 0);
return l > 0;
}
void Fastwire::setup(int khz, boolean pullup) {
TWCR = 0;
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega328P__)
// activate internal pull-ups for twi (PORTC bits 4 & 5)
// as per note from atmega8 manual pg167
if (pullup) PORTC |= ((1 << 4) | (1 << 5));
else PORTC &= ~((1 << 4) | (1 << 5));
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
// activate internal pull-ups for twi (PORTC bits 0 & 1)
if (pullup) PORTC |= ((1 << 0) | (1 << 1));
else PORTC &= ~((1 << 0) | (1 << 1));
#else
// activate internal pull-ups for twi (PORTD bits 0 & 1)
// as per note from atmega128 manual pg204
if (pullup) PORTD |= ((1 << 0) | (1 << 1));
else PORTD &= ~((1 << 0) | (1 << 1));
#endif
TWSR = 0; // no prescaler => prescaler = 1
TWBR = ((16000L / khz) - 16) / 2; // change the I2C clock rate
TWCR = 1 << TWEN; // enable twi module, no interrupt
}
byte Fastwire::write(byte device, byte address, byte value) {
byte twst, retry;
retry = 2;
do {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
if (!waitInt()) return 1;
twst = TWSR & 0xF8;
if (twst != TW_START && twst != TW_REP_START) return 2;
TWDR = device & 0xFE; // send device address without read bit (1)
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 3;
twst = TWSR & 0xF8;
} while (twst == TW_MT_SLA_NACK && retry-- > 0);
if (twst != TW_MT_SLA_ACK) return 4;
TWDR = address; // send data to the previously addressed device
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 5;
twst = TWSR & 0xF8;
if (twst != TW_MT_DATA_ACK) return 6;
TWDR = value; // send data to the previously addressed device
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 7;
twst = TWSR & 0xF8;
if (twst != TW_MT_DATA_ACK) return 8;
return 0;
}
byte Fastwire::readBuf(byte device, byte address, byte *data, byte num) {
byte twst, retry;
retry = 2;
do {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
if (!waitInt()) return 16;
twst = TWSR & 0xF8;
if (twst != TW_START && twst != TW_REP_START) return 17;
TWDR = device & 0xfe; // send device address to write
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 18;
twst = TWSR & 0xF8;
} while (twst == TW_MT_SLA_NACK && retry-- > 0);
if (twst != TW_MT_SLA_ACK) return 19;
TWDR = address; // send data to the previously addressed device
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 20;
twst = TWSR & 0xF8;
if (twst != TW_MT_DATA_ACK) return 21;
/***/
retry = 2;
do {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO) | (1 << TWSTA);
if (!waitInt()) return 22;
twst = TWSR & 0xF8;
if (twst != TW_START && twst != TW_REP_START) return 23;
TWDR = device | 0x01; // send device address with the read bit (1)
TWCR = (1 << TWINT) | (1 << TWEN);
if (!waitInt()) return 24;
twst = TWSR & 0xF8;
} while (twst == TW_MR_SLA_NACK && retry-- > 0);
if (twst != TW_MR_SLA_ACK) return 25;
for(uint8_t i = 0; i < num; i++) {
if (i == num - 1)
TWCR = (1 << TWINT) | (1 << TWEN);
else
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
if (!waitInt()) return 26;
twst = TWSR & 0xF8;
if (twst != TW_MR_DATA_ACK && twst != TW_MR_DATA_NACK) return twst;
data[i] = TWDR;
}
return 0;
}
#endif
#if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE
// NBWire implementation based heavily on code by Gene Knight <Gene@Telobot.com>
// Originally posted on the Arduino forum at http://arduino.cc/forum/index.php/topic,70705.0.html
// Originally offered to the i2cdevlib project at http://arduino.cc/forum/index.php/topic,68210.30.html
/*
call this version 1.0
Offhand, the only funky part that I can think of is in nbrequestFrom, where the buffer
length and index are set *before* the data is actually read. The problem is that these
are variables local to the TwoWire object, and by the time we actually have read the
data, and know what the length actually is, we have no simple access to the object's
variables. The actual bytes read *is* given to the callback function, though.
The ISR code for a slave receiver is commented out. I don't have that setup, and can't
verify it at this time. Save it for 2.0!
The handling of the read and write processes here is much like in the demo sketch code:
the process is broken down into sequential functions, where each registers the next as a
callback, essentially.
For example, for the Read process, twi_read00 just returns if TWI is not yet in a
ready state. When there's another interrupt, and the interface *is* ready, then it
sets up the read, starts it, and registers twi_read01 as the function to call after
the *next* interrupt. twi_read01, then, just returns if the interface is still in a
"reading" state. When the reading is done, it copies the information to the buffer,
cleans up, and calls the user-requested callback function with the actual number of
bytes read.
The writing is similar.
Questions, comments and problems can go to Gene@Telobot.com.
Thumbs Up!
Gene Knight
*/
uint8_t TwoWire::rxBuffer[NBWIRE_BUFFER_LENGTH];
uint8_t TwoWire::rxBufferIndex = 0;
uint8_t TwoWire::rxBufferLength = 0;
uint8_t TwoWire::txAddress = 0;
uint8_t TwoWire::txBuffer[NBWIRE_BUFFER_LENGTH];
uint8_t TwoWire::txBufferIndex = 0;
uint8_t TwoWire::txBufferLength = 0;
//uint8_t TwoWire::transmitting = 0;
void (*TwoWire::user_onRequest)(void);
void (*TwoWire::user_onReceive)(int);
static volatile uint8_t twi_transmitting;
static volatile uint8_t twi_state;
static uint8_t twi_slarw;
static volatile uint8_t twi_error;
static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t twi_masterBufferIndex;
static uint8_t twi_masterBufferLength;
static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
static volatile uint8_t twi_rxBufferIndex;
//static volatile uint8_t twi_Interrupt_Continue_Command;
static volatile uint8_t twi_Return_Value;
static volatile uint8_t twi_Done;
void (*twi_cbendTransmissionDone)(int);
void (*twi_cbreadFromDone)(int);
void twi_init() {
// initialize state
twi_state = TWI_READY;
// activate internal pull-ups for twi
// as per note from atmega8 manual pg167
sbi(PORTC, 4);
sbi(PORTC, 5);
// initialize twi prescaler and bit rate
cbi(TWSR, TWPS0); // TWI Status Register - Prescaler bits
cbi(TWSR, TWPS1);
/* twi bit rate formula from atmega128 manual pg 204
SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
note: TWBR should be 10 or higher for master mode
It is 72 for a 16mhz Wiring board with 100kHz TWI */
TWBR = ((CPU_FREQ / TWI_FREQ) - 16) / 2; // bitrate register
// enable twi module, acks, and twi interrupt
TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);
/* TWEN - TWI Enable Bit
TWIE - TWI Interrupt Enable
TWEA - TWI Enable Acknowledge Bit
TWINT - TWI Interrupt Flag
TWSTA - TWI Start Condition
*/
}
typedef struct {
uint8_t address;
uint8_t* data;
uint8_t length;
uint8_t wait;
uint8_t i;
} twi_Write_Vars;
twi_Write_Vars *ptwv = 0;
static void (*fNextInterruptFunction)(void) = 0;
void twi_Finish(byte bRetVal) {
if (ptwv) {
free(ptwv);
ptwv = 0;
}
twi_Done = 0xFF;
twi_Return_Value = bRetVal;
fNextInterruptFunction = 0;
}
uint8_t twii_WaitForDone(uint16_t timeout) {
uint32_t endMillis = millis() + timeout;
while (!twi_Done && (timeout == 0 || millis() < endMillis)) continue;
return twi_Return_Value;
}
void twii_SetState(uint8_t ucState) {
twi_state = ucState;
}
void twii_SetError(uint8_t ucError) {
twi_error = ucError ;
}
void twii_InitBuffer(uint8_t ucPos, uint8_t ucLength) {
twi_masterBufferIndex = 0;
twi_masterBufferLength = ucLength;
}
void twii_CopyToBuf(uint8_t* pData, uint8_t ucLength) {
uint8_t i;
for (i = 0; i < ucLength; ++i) {
twi_masterBuffer[i] = pData[i];
}
}
void twii_CopyFromBuf(uint8_t *pData, uint8_t ucLength) {
uint8_t i;
for (i = 0; i < ucLength; ++i) {
pData[i] = twi_masterBuffer[i];
}
}
void twii_SetSlaRW(uint8_t ucSlaRW) {
twi_slarw = ucSlaRW;
}
void twii_SetStart() {
TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);
}
void twi_write01() {
if (TWI_MTX == twi_state) return; // blocking test
twi_transmitting = 0 ;
if (twi_error == 0xFF)
twi_Finish (0); // success
else if (twi_error == TW_MT_SLA_NACK)
twi_Finish (2); // error: address send, nack received
else if (twi_error == TW_MT_DATA_NACK)
twi_Finish (3); // error: data send, nack received
else
twi_Finish (4); // other twi error
if (twi_cbendTransmissionDone) return twi_cbendTransmissionDone(twi_Return_Value);
return;
}
void twi_write00() {
if (TWI_READY != twi_state) return; // blocking test
if (TWI_BUFFER_LENGTH < ptwv -> length) {
twi_Finish(1); // end write with error 1
return;
}
twi_Done = 0x00; // show as working
twii_SetState(TWI_MTX); // to transmitting
twii_SetError(0xFF); // to No Error
twii_InitBuffer(0, ptwv -> length); // pointer and length
twii_CopyToBuf(ptwv -> data, ptwv -> length); // get the data
twii_SetSlaRW((ptwv -> address << 1) | TW_WRITE); // write command
twii_SetStart(); // start the cycle
fNextInterruptFunction = twi_write01; // next routine
return twi_write01();
}
void twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait) {
uint8_t i;
ptwv = (twi_Write_Vars *)malloc(sizeof(twi_Write_Vars));
ptwv -> address = address;
ptwv -> data = data;
ptwv -> length = length;
ptwv -> wait = wait;
fNextInterruptFunction = twi_write00;
return twi_write00();
}
void twi_read01() {
if (TWI_MRX == twi_state) return; // blocking test
if (twi_masterBufferIndex < ptwv -> length) ptwv -> length = twi_masterBufferIndex;
twii_CopyFromBuf(ptwv -> data, ptwv -> length);
twi_Finish(ptwv -> length);
if (twi_cbreadFromDone) return twi_cbreadFromDone(twi_Return_Value);
return;
}
void twi_read00() {
if (TWI_READY != twi_state) return; // blocking test
if (TWI_BUFFER_LENGTH < ptwv -> length) twi_Finish(0); // error return
twi_Done = 0x00; // show as working
twii_SetState(TWI_MRX); // reading
twii_SetError(0xFF); // reset error
twii_InitBuffer(0, ptwv -> length - 1); // init to one less than length
twii_SetSlaRW((ptwv -> address << 1) | TW_READ); // read command
twii_SetStart(); // start cycle
fNextInterruptFunction = twi_read01;
return twi_read01();
}
void twi_readFrom(uint8_t address, uint8_t* data, uint8_t length) {
uint8_t i;
ptwv = (twi_Write_Vars *)malloc(sizeof(twi_Write_Vars));
ptwv -> address = address;
ptwv -> data = data;
ptwv -> length = length;
fNextInterruptFunction = twi_read00;
return twi_read00();
}
void twi_reply(uint8_t ack) {
// transmit master read ready signal, with or without ack
if (ack){
TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA);
} else {
TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT);
}
}
void twi_stop(void) {
// send stop condition
TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO);
// wait for stop condition to be exectued on bus
// TWINT is not set after a stop condition!
while (TWCR & _BV(TWSTO)) {
continue;
}
// update twi state
twi_state = TWI_READY;
}
void twi_releaseBus(void) {
// release bus
TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT);
// update twi state
twi_state = TWI_READY;
}
SIGNAL(TWI_vect) {
switch (TW_STATUS) {
// All Master
case TW_START: // sent start condition
case TW_REP_START: // sent repeated start condition
// copy device address and r/w bit to output register and ack
TWDR = twi_slarw;
twi_reply(1);
break;
// Master Transmitter
case TW_MT_SLA_ACK: // slave receiver acked address
case TW_MT_DATA_ACK: // slave receiver acked data
// if there is data to send, send it, otherwise stop
if (twi_masterBufferIndex < twi_masterBufferLength) {
// copy data to output register and ack
TWDR = twi_masterBuffer[twi_masterBufferIndex++];
twi_reply(1);
} else {
twi_stop();
}
break;
case TW_MT_SLA_NACK: // address sent, nack received
twi_error = TW_MT_SLA_NACK;
twi_stop();
break;
case TW_MT_DATA_NACK: // data sent, nack received
twi_error = TW_MT_DATA_NACK;
twi_stop();
break;
case TW_MT_ARB_LOST: // lost bus arbitration
twi_error = TW_MT_ARB_LOST;
twi_releaseBus();
break;
// Master Receiver
case TW_MR_DATA_ACK: // data received, ack sent
// put byte into buffer
twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
case TW_MR_SLA_ACK: // address sent, ack received
// ack if more bytes are expected, otherwise nack
if (twi_masterBufferIndex < twi_masterBufferLength) {
twi_reply(1);
} else {
twi_reply(0);
}
break;
case TW_MR_DATA_NACK: // data received, nack sent
// put final byte into buffer
twi_masterBuffer[twi_masterBufferIndex++] = TWDR;
case TW_MR_SLA_NACK: // address sent, nack received
twi_stop();
break;
// TW_MR_ARB_LOST handled by TW_MT_ARB_LOST case
// Slave Receiver (NOT IMPLEMENTED YET)
/*
case TW_SR_SLA_ACK: // addressed, returned ack
case TW_SR_GCALL_ACK: // addressed generally, returned ack
case TW_SR_ARB_LOST_SLA_ACK: // lost arbitration, returned ack
case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack
// enter slave receiver mode
twi_state = TWI_SRX;
// indicate that rx buffer can be overwritten and ack
twi_rxBufferIndex = 0;
twi_reply(1);
break;
case TW_SR_DATA_ACK: // data received, returned ack
case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack
// if there is still room in the rx buffer
if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) {
// put byte in buffer and ack
twi_rxBuffer[twi_rxBufferIndex++] = TWDR;
twi_reply(1);
} else {
// otherwise nack
twi_reply(0);
}
break;
case TW_SR_STOP: // stop or repeated start condition received
// put a null char after data if there's room
if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) {
twi_rxBuffer[twi_rxBufferIndex] = 0;
}
// sends ack and stops interface for clock stretching
twi_stop();
// callback to user defined callback
twi_onSlaveReceive(twi_rxBuffer, twi_rxBufferIndex);
// since we submit rx buffer to "wire" library, we can reset it
twi_rxBufferIndex = 0;
// ack future responses and leave slave receiver state
twi_releaseBus();
break;
case TW_SR_DATA_NACK: // data received, returned nack
case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack
// nack back at master
twi_reply(0);
break;
// Slave Transmitter
case TW_ST_SLA_ACK: // addressed, returned ack
case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
// enter slave transmitter mode
twi_state = TWI_STX;
// ready the tx buffer index for iteration
twi_txBufferIndex = 0;
// set tx buffer length to be zero, to verify if user changes it
twi_txBufferLength = 0;
// request for txBuffer to be filled and length to be set
// note: user must call twi_transmit(bytes, length) to do this
twi_onSlaveTransmit();
// if they didn't change buffer & length, initialize it
if (0 == twi_txBufferLength) {
twi_txBufferLength = 1;
twi_txBuffer[0] = 0x00;
}
// transmit first byte from buffer, fall through
case TW_ST_DATA_ACK: // byte sent, ack returned
// copy data to output register
TWDR = twi_txBuffer[twi_txBufferIndex++];
// if there is more to send, ack, otherwise nack
if (twi_txBufferIndex < twi_txBufferLength) {
twi_reply(1);
} else {
twi_reply(0);
}
break;
case TW_ST_DATA_NACK: // received nack, we are done
case TW_ST_LAST_DATA: // received ack, but we are done already!
// ack future responses
twi_reply(1);
// leave slave receiver state
twi_state = TWI_READY;
break;
*/
// all
case TW_NO_INFO: // no state information
break;
case TW_BUS_ERROR: // bus error, illegal stop/start
twi_error = TW_BUS_ERROR;
twi_stop();
break;
}
if (fNextInterruptFunction) return fNextInterruptFunction();
}
TwoWire::TwoWire() { }
void TwoWire::begin(void) {
rxBufferIndex = 0;
rxBufferLength = 0;
txBufferIndex = 0;
txBufferLength = 0;
twi_init();
}
void TwoWire::beginTransmission(uint8_t address) {
//beginTransmission((uint8_t)address);
// indicate that we are transmitting
twi_transmitting = 1;
// set address of targeted slave
txAddress = address;
// reset tx buffer iterator vars
txBufferIndex = 0;
txBufferLength = 0;
}
uint8_t TwoWire::endTransmission(uint16_t timeout) {
// transmit buffer (blocking)
//int8_t ret =
twi_cbendTransmissionDone = NULL;
twi_writeTo(txAddress, txBuffer, txBufferLength, 1);
int8_t ret = twii_WaitForDone(timeout);
// reset tx buffer iterator vars
txBufferIndex = 0;
txBufferLength = 0;
// indicate that we are done transmitting
// twi_transmitting = 0;
return ret;
}
void TwoWire::nbendTransmission(void (*function)(int)) {
twi_cbendTransmissionDone = function;
twi_writeTo(txAddress, txBuffer, txBufferLength, 1);
return;
}
void TwoWire::send(uint8_t data) {
if (twi_transmitting) {
// in master transmitter mode
// don't bother if buffer is full
if (txBufferLength >= NBWIRE_BUFFER_LENGTH) {
return;
}
// put byte in tx buffer
txBuffer[txBufferIndex] = data;
++txBufferIndex;
// update amount in buffer
txBufferLength = txBufferIndex;
} else {
// in slave send mode
// reply to master
//twi_transmit(&data, 1);
}
}
uint8_t TwoWire::receive(void) {
// default to returning null char
// for people using with char strings
uint8_t value = 0;
// get each successive byte on each call
if (rxBufferIndex < rxBufferLength) {
value = rxBuffer[rxBufferIndex];
++rxBufferIndex;
}
return value;
}
uint8_t TwoWire::requestFrom(uint8_t address, int quantity, uint16_t timeout) {
// clamp to buffer length
if (quantity > NBWIRE_BUFFER_LENGTH) {
quantity = NBWIRE_BUFFER_LENGTH;
}
// perform blocking read into buffer
twi_cbreadFromDone = NULL;
twi_readFrom(address, rxBuffer, quantity);
uint8_t read = twii_WaitForDone(timeout);
// set rx buffer iterator vars
rxBufferIndex = 0;
rxBufferLength = read;
return read;
}
void TwoWire::nbrequestFrom(uint8_t address, int quantity, void (*function)(int)) {
// clamp to buffer length
if (quantity > NBWIRE_BUFFER_LENGTH) {
quantity = NBWIRE_BUFFER_LENGTH;
}
// perform blocking read into buffer
twi_cbreadFromDone = function;
twi_readFrom(address, rxBuffer, quantity);
//uint8_t read = twii_WaitForDone();
// set rx buffer iterator vars
//rxBufferIndex = 0;
//rxBufferLength = read;
rxBufferIndex = 0;
rxBufferLength = quantity; // this is a hack
return; //read;
}
uint8_t TwoWire::available(void) {
return rxBufferLength - rxBufferIndex;
}
#endif
| [
"w.klaas@gmx.de"
] | w.klaas@gmx.de |
e4baeac096e1227cc34c8ca7c4a14c04a033803d | 91e4a4f778b00748bd70e0e7e3d608e6b2060f26 | /Function/cprime 1-n.cpp | 3c91d923a5a8f8109866319003a579f4989e5bab | [] | no_license | Devansh707/DSA-In-CPP | d0d70f52667cfc7052fcc07bd2eb5dabed5aae8e | 28c4eb0e5fc7157785e21679cefbc479aa265cc4 | refs/heads/main | 2023-07-05T01:22:37.436819 | 2021-08-13T05:17:26 | 2021-08-13T05:17:26 | 395,246,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 286 | cpp | #include<iostream>
using namespace std;
int prime(int n)
{
int i;
for(i=2;i<n;i++)
{
if(n%i==0)
{
break;
}
else
{
return (n);
}
}
}
int main()
{
int n;
cout<<"enter n:"<<endl;
cin>>n;
for(int i=1;i<=n;i++)
{
if(prime(i));
{
cout<<i<<endl;
}
}
}
| [
"devanshsrivastava707@gmail.com"
] | devanshsrivastava707@gmail.com |
baa8d3289f4ce6821ccfdf8446ba453c541144a4 | 8d9eed7eb8163ba64c49835c04db140f73821b56 | /eowu-gl/src/shader-builder/Components.cpp | 369a0066fa83c7427bab07ab3247085744a46640 | [] | no_license | nfagan/eowu | 96dba654495e26ab3e39cd20ca489acf55de6a5d | 5116f3306a3f7e813502ba00427fdc418850d28f | refs/heads/master | 2020-03-27T14:18:11.835137 | 2019-01-02T18:08:19 | 2019-01-02T18:08:19 | 146,655,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,414 | cpp | //
// Components.cpp
// eowu-gl
//
// Created by Nick Fagan on 8/29/18.
//
#include "Components.hpp"
std::string eowu::components::declare_variable(const std::string &name, eowu::glsl::Types type) {
return eowu::glsl::get_string_type(type) + " " + name + ";";
}
std::string eowu::components::declare_variable(const std::string &name, eowu::glsl::Types type, const std::string &value) {
return eowu::glsl::get_string_type(type) + " " + name + "=" + value + ";";
}
std::string eowu::components::declare_version(const std::string &version) {
return "#version " + version;
}
std::string eowu::components::declare_attribute(const std::string &loc, const std::string &name, eowu::glsl::Types type) {
return "layout (location = " + loc + ") in " + declare_variable(name, type);
}
std::string eowu::components::declare_uniform(const std::string &name, eowu::glsl::Types type) {
return "uniform " + declare_variable(name, type);
}
std::string eowu::components::to_vec3(const std::string &name, eowu::glsl::Types type) {
switch (type) {
case glsl::sampler2D:
return "texture(" + name + ", tx).rgb";
case glsl::vec3:
return name;
default:
return "vec3(" + name + ")";
}
}
std::string eowu::components::begin_main() {
return "void main() {";
}
std::string eowu::components::open_brace() {
return "{";
}
std::string eowu::components::close_brace() {
return "}";
}
| [
"nick@fagan.org"
] | nick@fagan.org |
4dbf233a0df817fc32d84efd0f5544421f111457 | ce35164b9286114439944ccb2ff0a99d1b74c92a | /code/client_qt/library-manager/mainwindow.cpp | a5265b6ca5c589c86f8c17f47a4c6ef4cbe49db8 | [] | no_license | NorthWardTop/library-procurement-manager | f4f797d6e24f8e3ab16d964689e553eea60a942b | 7fb29fda58aa0720a110c46d4f7cf8f69a7c2907 | refs/heads/master | 2020-04-28T17:47:53.976978 | 2019-05-07T14:33:54 | 2019-05-07T14:33:54 | 175,457,978 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,340 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "database.h"
#include <QSqlQueryModel>
#include <QStandardItemModel>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->demandRefresh_btn, SIGNAL(clicked()), this, SLOT(onDemandRefresh_btn()));
connect(ui->demandSubmit_btn, SIGNAL(clicked()), this, SLOT(onDemandSubmit_btn()));
connect(ui->buyRefresh_btn, SIGNAL(clicked()), this, SLOT(onBuyRefresh_btn()));
connect(ui->delete_btn, SIGNAL(clicked()), this, SLOT(onDelete_btn()));
//设置整行选中
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView_2->setSelectionBehavior(QAbstractItemView::SelectRows);
//构建窗口对象时刷新两个tab
// this->onDemandRefresh_btn();
// this->onBuyRefresh_btn();
}
MainWindow::~MainWindow()
{
delete ui;
}
/**
* @brief MainWindow::onDemandRefresh_btn
* 需求刷新按钮:
* 1.查询需求表状态字段值为待购的条目返回
* 2.更新到list控件
*/
void MainWindow::onDemandRefresh_btn()
{
QString sql="select * from Demand where state='待购';";
//QString sql="select * from Bookseller;";
QSqlQueryModel *model = new QSqlQueryModel;
//QStandardItemModel* model = new QStandardItemModel();
model->setQuery(sql);
qDebug()<<"更新list查询:"<<sql;
model->setHeaderData(0, Qt::Horizontal, tr("bookName"));
model->setHeaderData(1, Qt::Horizontal, tr("publisher"));
model->setHeaderData(2, Qt::Horizontal, tr("ISBN"));
model->setHeaderData(3, Qt::Horizontal, tr("demandNum"));
model->setHeaderData(4, Qt::Horizontal, tr("state"));
ui->tableView->setModel(model);
//delete model;
}
/**
* @brief MainWindow::onDemandSubmit_btn
* 需求提交按钮:
* 修改Demand表中对应SN码的行的状态为已购
*
*/
void MainWindow::onDemandSubmit_btn()
{
//int curRow= ui->tableView->currentIndex().row();//获取选中行号
for(int curRow=0;curRow<ui->tableView->model()->rowCount();++curRow)
{
QAbstractItemModel *modessl = ui->tableView->model();
QModelIndex tmpIndex0 = modessl->index(curRow,2);//第0列(号列)
QString isbn=modessl->data(tmpIndex0).toString();//保存号为string类型将加入sql查询
//QString isbn=ui->tableView->currentIndex().data().toString();
qDebug()<<isbn;
//依照isbn码执行修改操作
QString sql="update Demand set state='已购' where ISBN='"+isbn+"';";
QSqlQuery query;
qDebug()<<sql;
query.prepare(sql);//指定sql语句
query.exec();
}
onDemandRefresh_btn();//刷新列表
onBuyRefresh_btn();//刷新已购列表
}
/**
* @brief MainWindow::onBuyRefresh_btn
* 已购买刷新按钮:
* 1.查询需求表状态字段值为已购的条目返回
* 2.更新到list控件
*/
void MainWindow::onBuyRefresh_btn()
{
QString sql="select * from Demand where state='已购';";
QSqlQueryModel *model = new QSqlQueryModel;
//QStandardItemModel* model = new QStandardItemModel();
model->setQuery(sql);
qDebug()<<"更新list查询:"<<sql;
model->setHeaderData(0, Qt::Horizontal, tr("bookName"));
model->setHeaderData(1, Qt::Horizontal, tr("publisher"));
model->setHeaderData(2, Qt::Horizontal, tr("ISBN"));
model->setHeaderData(3, Qt::Horizontal, tr("demandNum"));
model->setHeaderData(4, Qt::Horizontal, tr("state"));
ui->tableView_2->setModel(model);
}
/**
* @brief MainWindow::onDelete_btn
* 选中一行后点击删除按钮
* 删除数据库对应的行, 参照ISBN码
*/
void MainWindow::onDelete_btn()
{
int curRow= ui->tableView->currentIndex().row();//获取选中行号
QAbstractItemModel *modessl = ui->tableView->model();
QModelIndex tmpIndex0 = modessl->index(curRow,2);//第0列(号列)
QString isbn=modessl->data(tmpIndex0).toString();//保存号为string类型将加入sql查询
//QString isbn=ui->tableView->currentIndex().data().toString();
qDebug()<<isbn;
//依照isbn码执行删除操作
QString sql="delete from Demand where ISBN='"+isbn+"';";
QSqlQuery query;
qDebug()<<sql;
query.prepare(sql);//指定sql语句
query.exec();
onDemandRefresh_btn();//刷新列表
}
| [
"2394783277@qq.com"
] | 2394783277@qq.com |
3b7c57f0235e67c07b5c7dc5218fbf1a758018eb | b0dd7779c225971e71ae12c1093dc75ed9889921 | /libs/wave/samples/cpp_tokens/instantiate_slex_lexer.cpp | 0c94b3fae3506ec9eef819f959c43a28559e8755 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSL-1.0"
] | permissive | blackberry/Boost | 6e653cd91a7806855a162347a5aeebd2a8c055a2 | fc90c3fde129c62565c023f091eddc4a7ed9902b | refs/heads/1_48_0-gnu | 2021-01-15T14:31:33.706351 | 2013-06-25T16:02:41 | 2013-06-25T16:02:41 | 2,599,411 | 244 | 154 | BSL-1.0 | 2018-10-13T18:35:09 | 2011-10-18T14:25:18 | C++ | UTF-8 | C++ | false | false | 1,818 | cpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
Sample: Print out the preprocessed tokens returned by the Wave iterator
Explicit instantiation of the lex_functor generation function
http://www.boost.org/
Copyright (c) 2001-2012 Hartmut Kaiser. Distributed under the Boost
Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include "cpp_tokens.hpp" // config data
#if BOOST_WAVE_SEPARATE_LEXER_INSTANTIATION != 0
#include <string>
#include <boost/wave/token_ids.hpp>
#include "slex_token.hpp"
#include "slex_iterator.hpp"
///////////////////////////////////////////////////////////////////////////////
// The following file needs to be included only once throughout the whole
// program.
#include "slex/cpp_slex_lexer.hpp"
///////////////////////////////////////////////////////////////////////////////
//
// This instantiates the correct 'new_lexer' function, which generates the
// C++ lexer used in this sample.
//
// This is moved into a separate compilation unit to decouple the compilation
// of the C++ lexer from the compilation of the other modules, which helps to
// reduce compilation time.
//
// The template parameter(s) supplied should be identical to the parameters
// supplied while instantiating the context<> template.
//
///////////////////////////////////////////////////////////////////////////////
template struct boost::wave::cpplexer::slex::new_lexer_gen<
std::string::iterator>;
#endif // BOOST_WAVE_SEPARATE_LEXER_INSTANTIATION != 0
| [
"tvaneerd@rim.com"
] | tvaneerd@rim.com |
cc96264529d7311eb2fa32bcee34d073f261436c | edb4fc1fe7f109a1ce651c66e2d4ff0621534fcb | /src/libmv/multiview/structure.cc | 5edaf99b4eae9b85a07a196d6405b0357a87af76 | [
"MIT"
] | permissive | Matthias-Fauconneau/libmv | 88bf38fecbd3ab3e7af0779fc6a2d0de4d9c062e | 531c79bf95fddaaa70707d1abcd4fdafda16bbf0 | refs/heads/master | 2020-12-24T09:09:02.119372 | 2011-08-19T22:00:42 | 2011-08-19T22:00:42 | 1,805,598 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,489 | cc | // Copyright (c) 2010 libmv authors.
//
// 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 "libmv/multiview/structure.h"
namespace libmv {
Structure::Structure() {
}
Structure::~Structure() {
}
PointStructure::PointStructure() {
}
PointStructure::PointStructure(const Vec3 &coords) {
set_coords_affine(coords);
}
PointStructure::PointStructure(const Vec4 &coords) : coords_(coords) {
}
PointStructure::~PointStructure() {
}
} // namespace libmv
| [
"julien.michot.fr@gmail.com"
] | julien.michot.fr@gmail.com |
fc560d7cebc0195f6bbd50a29b40be7e799a06c8 | 7623fa6d1909c968afa8fb3205dde7df2e277990 | /engine/code/primary/system.h | 7485308c10ce6864e6c9bd1779c974b710c5f7f7 | [] | no_license | jm4748/Engine | 3a428039e6f705316627e747f793598790fa068f | d6c010b6e5e76e3a68102bc583dc37e8d458db38 | refs/heads/master | 2023-03-18T21:16:37.025524 | 2021-03-11T09:18:36 | 2021-03-11T09:18:36 | 346,642,648 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 564 | h | #pragma once
#include "core.h"
class State;
class System
{
private:
Core core;
bool running;
State* currentState;
State* nextState;
bool changeState;
private:
System();
void _Run( State* state );
public:
static void Run( State* state );
void ChangeState( State* state );
void Quit();
};
class State
{
public:
System* system;
Core* core;
Input* input;
Graphics* graphics;
public:
virtual void Startup() = 0;
virtual void Cleanup() = 0;
virtual void Update( __int64 timeStep ) = 0;
virtual void Render( float interpolation ) = 0;
}; | [
"josephmeikle@protonmail.com"
] | josephmeikle@protonmail.com |
40e6fa7bb272915136771ace3b6b59f7fac13d9a | 848dc80f92148790d32018e6306787834462d3e2 | /test/test_random.cpp | aa3f2a4e1fd367d1441106b08280e306ed3be8be | [
"MIT"
] | permissive | bloomen/libunittest | 75c216192266249cbd4af7bc4641835a447e435f | b168539c70e5ac8a3c67d295e368d07f3c1854fb | refs/heads/master | 2021-01-13T17:39:42.794919 | 2020-02-23T04:03:42 | 2020-02-23T04:03:42 | 242,443,511 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,664 | cpp | #include <libunittest/all.hpp>
#include <list>
#include <mutex>
using namespace unittest::assertions;
template<typename RandomCont,
typename OrigContainer,
typename T>
void assert_random_container_fixed(RandomCont& random_object,
const OrigContainer& container,
const T& length,
const std::string& spot)
{
for (int i=0; i<100; ++i) {
const auto rand_cont = random_object->get();
assert_equal(length, rand_cont.size(), spot);
for (auto& value : rand_cont)
assert_in_container(value, container, spot);
}
}
template<typename RandomCont,
typename OrigContainer,
typename T>
void assert_random_container_range(RandomCont& random_object,
const OrigContainer& container,
const T& min_length,
const T& max_length,
const std::string& spot)
{
for (int i=0; i<100; ++i) {
const auto rand_cont = random_object->get();
assert_in_range(rand_cont.size(), min_length, max_length, spot);
for (auto& value : rand_cont)
assert_in_container(value, container, spot);
}
}
struct test_random : unittest::testcase<> {
static void run()
{
UNITTEST_CLASS(test_random)
UNITTEST_RUN(test_random_int)
UNITTEST_RUN(test_random_int_throw)
UNITTEST_RUN(test_random_bool)
UNITTEST_RUN(test_random_real)
UNITTEST_RUN(test_random_real_throw)
UNITTEST_RUN(test_random_choice_string)
UNITTEST_RUN(test_random_choice_vector)
UNITTEST_RUN(test_random_choice_list)
UNITTEST_RUN(test_random_container_string)
UNITTEST_RUN(test_random_container_list)
UNITTEST_RUN(test_random_container_vector)
UNITTEST_RUN(test_random_container_throw)
UNITTEST_RUN(test_random_tuple)
UNITTEST_RUN(test_random_pair)
UNITTEST_RUN(test_random_shuffle_vector)
UNITTEST_RUN(test_random_shuffle_list)
UNITTEST_RUN(test_random_shuffle_throw)
UNITTEST_RUN(test_random_combination_vector)
UNITTEST_RUN(test_random_combination_list)
UNITTEST_RUN(test_random_combination_throw)
UNITTEST_RUN(test_random_value_copy_constructor)
UNITTEST_RUN(test_random_value_assignment_operator)
UNITTEST_RUN(test_random_value_clone)
UNITTEST_RUN(test_random_value_thread_safety)
}
void test_random_int()
{
auto randomA = unittest::make_random_value(3);
auto randomB = unittest::make_random_value<long>(2, 4);
auto randomC = unittest::make_random_value<long long>(-9, -2);
for (int i=0; i<100; ++i) {
assert_in_range(randomA->get(), 0, 3, SPOT);
assert_in_range(randomB->get(), 2, 4, SPOT);
assert_in_range(randomC->get(), -9, -2, SPOT);
}
}
void test_random_int_throw()
{
auto functor1 = [](){ unittest::make_random_value(-1); };
assert_throw<std::invalid_argument>(functor1, SPOT);
auto functor2 = [](){ unittest::make_random_value(1, 1); };
assert_throw<std::invalid_argument>(functor2, SPOT);
auto functor3 = [](){ unittest::make_random_value(9, 1); };
assert_throw<std::invalid_argument>(functor3, SPOT);
}
void test_random_bool()
{
auto random = unittest::make_random_bool();
const std::vector<bool> container = {true, false};
for (int i=0; i<100; ++i) {
assert_in_container(random->get(), container, SPOT);
}
}
void test_random_real()
{
auto randomA = unittest::make_random_value(3.);
auto randomB = unittest::make_random_value(1.5, 4.2);
for (int i=0; i<100; ++i) {
assert_in_range(randomA->get(), 0, 3+1e-6, SPOT);
assert_in_range(randomB->get(), 1.5, 4.2+1e-6, SPOT);
}
}
void test_random_real_throw()
{
auto functor1 = [](){ unittest::make_random_value(-1.); };
assert_throw<std::invalid_argument>(functor1, SPOT);
auto functor2 = [](){ unittest::make_random_value(1., 1.); };
assert_throw<std::invalid_argument>(functor2, SPOT);
auto functor3 = [](){ unittest::make_random_value(9., 1.); };
assert_throw<std::invalid_argument>(functor3, SPOT);
}
void test_random_choice_string()
{
const std::string characters("abc");
auto random = unittest::make_random_choice(characters);
for (int i=0; i<100; ++i) {
assert_in_container(random->get(), characters, SPOT);
}
}
void test_random_choice_vector()
{
const std::vector<double> vector = {1, 2, 3};
auto random = unittest::make_random_choice(vector);
for (int i=0; i<100; ++i) {
assert_in_container(random->get(), vector, SPOT);
}
}
void test_random_choice_list()
{
const std::list<int> a_list = {1, 2, 3};
auto random = unittest::make_random_choice(a_list);
for (int i=0; i<100; ++i) {
assert_in_container(random->get(), a_list, SPOT);
}
}
void test_random_container_string()
{
const std::string characters("abc");
auto random = unittest::make_random_choice(characters);
const unsigned length = 5;
const unsigned min_length = 3;
auto random_contA = unittest::make_random_container<std::string>(random, length);
auto random_contB = unittest::make_random_container<std::string>(random, min_length, length);
assert_random_container_fixed(random_contA, characters, length, SPOT);
assert_random_container_range(random_contB, characters, min_length, length, SPOT);
}
void test_random_container_list()
{
auto random = unittest::make_random_value(1, 3);
const unsigned length = 5;
const unsigned min_length = 3;
auto random_contA = unittest::make_random_container<std::list<int>>(random, length);
auto random_contB = unittest::make_random_container<std::list<int>>(random, min_length, length);
const std::list<int> a_list = {1, 2, 3};
assert_random_container_fixed(random_contA, a_list, length, SPOT);
assert_random_container_range(random_contB, a_list, min_length, length, SPOT);
}
void test_random_container_vector()
{
auto random = unittest::make_random_value(1, 3);
const unsigned length = 5;
const unsigned min_length = 3;
auto random_contA = unittest::make_random_vector(random, length);
auto random_contB = unittest::make_random_vector(random, min_length, length);
const std::vector<int> vector = {1, 2, 3};
assert_random_container_fixed(random_contA, vector, length, SPOT);
assert_random_container_range(random_contB, vector, min_length, length, SPOT);
}
void test_random_container_throw()
{
auto random = unittest::make_random_value(1, 3);
auto functor1 = [&](){ unittest::make_random_container<std::list<int>>(random, 1, 1); };
assert_throw<std::invalid_argument>(functor1, SPOT);
auto functor2 = [&](){ unittest::make_random_container<std::list<int>>(random, 3, 1); };
assert_throw<std::invalid_argument>(functor2, SPOT);
}
void test_random_tuple()
{
auto rand_float = unittest::make_random_value<double>(2.0, 3.0);
auto rand_int = unittest::make_random_value<int>(4, 8);
auto rand_bool = unittest::make_random_value<bool>();
auto random = unittest::make_random_tuple(rand_float, rand_int, rand_bool);
const std::vector<bool> container = {true, false};
for (int i=0; i<100; ++i) {
const auto rand_tuple = random->get();
assert_equal<unsigned>(3, std::tuple_size<std::tuple<float, int, bool>>::value, SPOT);
assert_in_range(std::get<0>(rand_tuple), 2.0, 3.0, SPOT);
assert_in_range(std::get<1>(rand_tuple), 4, 8, SPOT);
assert_in_container(std::get<2>(rand_tuple), container, SPOT);
}
}
void test_random_pair()
{
auto rand_float = unittest::make_random_value<double>(2.0, 3.0);
auto rand_int = unittest::make_random_value<int>(4, 8);
auto random = unittest::make_random_pair(rand_float, rand_int);
for (int i=0; i<100; ++i) {
const auto rand_pair = random->get();
assert_in_range(rand_pair.first, 2.0, 3.0, SPOT);
assert_in_range(rand_pair.second, 4, 8, SPOT);
}
}
void test_random_shuffle_vector()
{
const std::vector<int> vector = {1, 2, 3};
auto random = unittest::make_random_shuffle(vector);
for (int i=0; i<100; ++i) {
const auto perm_vector = random->get();
assert_in_container(perm_vector[0], vector, SPOT);
assert_in_container(perm_vector[1], vector, SPOT);
assert_in_container(perm_vector[2], vector, SPOT);
assert_equal(6, perm_vector[0] + perm_vector[1] + perm_vector[2], SPOT);
}
}
void test_random_shuffle_list()
{
const std::list<double> a_list = {1, 2, 3};
auto random = unittest::make_random_shuffle(a_list, 2);
for (int i=0; i<100; ++i) {
const auto perm_list = random->get();
auto first = std::begin(perm_list);
auto sum = *first;
assert_in_container(*first, a_list, SPOT);
++first;
sum += *first;
assert_in_container(*first, a_list, SPOT);
assert_in_range(sum, 3, 5, SPOT);
}
}
void test_random_shuffle_throw()
{
const std::list<int> a_list = {1, 2, 3};
auto functor1 = [&](){ unittest::make_random_shuffle(a_list, 0); };
assert_throw<std::invalid_argument>(functor1, SPOT);
auto functor2 = [&](){ unittest::make_random_shuffle(a_list, 4); };
assert_throw<std::invalid_argument>(functor2, SPOT);
}
void test_random_combination_vector()
{
const std::vector<int> vector1 = {1, 2, 3};
const std::vector<double> vector2 = {5, 6};
auto rand_combo = unittest::make_random_combination(vector1, vector2, 4);
for (int i=0; i<100; ++i) {
const auto combo = rand_combo->get();
assert_equal<unsigned>(4, combo.size(), SPOT);
for (auto& value : combo) {
assert_in_container(value.first, vector1, SPOT);
assert_in_container(value.second, vector2, SPOT);
}
}
}
void test_random_combination_list()
{
const std::list<int> list1 = {1, 2, 3};
const std::list<double> list2 = {5, 6};
auto rand_combo = unittest::make_random_combination(list1, list2, 3);
for (int i=0; i<100; ++i) {
const auto combo = rand_combo->get();
assert_equal<unsigned>(3, combo.size(), SPOT);
for (auto& value : combo) {
assert_in_container(value.first, list1, SPOT);
assert_in_container(value.second, list2, SPOT);
}
}
}
void test_random_combination_throw()
{
const std::list<int> list1 = {1, 2, 3};
const std::list<double> list2 = {5, 6};
auto functor1 = [&]() { unittest::make_random_combination(list1, list2, 0); };
assert_throw<std::invalid_argument>(functor1, SPOT);
auto functor2 = [&]() { unittest::make_random_combination(list1, list2, 7); };
assert_throw<std::invalid_argument>(functor2, SPOT);
}
void test_random_value_copy_constructor()
{
unittest::random_value<double> random1;
random1.get();
unittest::random_value<double> random2(random1);
assert_equal(random1.get(), random2.get(), SPOT);
}
void test_random_value_assignment_operator()
{
unittest::random_value<double> random1;
random1.get();
random1.get();
unittest::random_value<double> random2 = random1;
assert_equal(random1.get(), random2.get(), SPOT);
}
void test_random_value_clone()
{
auto random1 = unittest::make_random_value<double>();
random1->get();
auto random2 = random1->clone();
assert_equal(random1->get(), random2->get(), SPOT);
}
void test_random_value_thread_safety()
{
auto random1 = unittest::make_random_value<double>();
auto random2 = unittest::make_random_value<int>(0, 1000);
std::vector<std::function<void()>> functions(100);
std::exception_ptr ptr;
std::mutex except_mutex;
for (auto& function : functions)
function = std::move([&]() {
try {
auto seed = random2->get();
assert_in_range(seed, 0, 1000, SPOT);
random1->seed(seed);
assert_in_range(random1->get(), 0, 1, SPOT);
auto random3 = random1->clone();
assert_in_range(random3->get(), 0, 1, SPOT);
auto random4 = random2->clone();
assert_in_range(random4->get(), 0, 1000, SPOT);
} catch (...) {
std::lock_guard<std::mutex> lock(except_mutex);
ptr = std::current_exception();
}
});
unittest::core::call_functions(functions, 100);
if (ptr)
std::rethrow_exception(ptr);
}
};
REGISTER(test_random)
| [
"chr.blume@gmail.com"
] | chr.blume@gmail.com |
f5f7a1a6b193fdcd8d5000d48421bb0385e9ac70 | ce3c874edfdc4697626bed8e7e8d68a880eaa8e2 | /src/uBase/Object.h | aae9a2299b13183e6b1e4c1dcab0ef504eee44e0 | [
"MIT"
] | permissive | fuse-open/legacy-cpp-framework | f620db7e2c6becb53a2d66c781a8ced2042d4e71 | aff4d462158bb595b62be2fec18e5b33a6f02f43 | refs/heads/master | 2022-10-16T12:21:10.092515 | 2022-10-08T18:31:50 | 2022-10-08T18:31:50 | 131,840,555 | 2 | 0 | MIT | 2022-10-08T18:31:51 | 2018-05-02T11:23:11 | C++ | UTF-8 | C++ | false | false | 469 | h | #pragma once
#include <uBase/Config.h>
namespace uBase
{
class String;
/** \ingroup uObject */
class U_DLLEXPORT Object
{
int _refCount;
Object(const Object& copy);
Object& operator =(const Object& copy);
public:
Object();
virtual ~Object();
int GetRefCount() const;
void Retain();
void Release();
virtual void Delete();
virtual String ToString() const;
};
}
| [
"erik@fusetools.com"
] | erik@fusetools.com |
e8759825c81fd1296c661c5d2262cab34a2a80f3 | 3b0aff95c6f51226f5257315315de5d32e81ed52 | /src/BinderThread.cpp | 8d83c532621655423823a11955913e6b8c747dd2 | [
"BSD-3-Clause"
] | permissive | AprilAndFriends/sakit | c92b702ad6d1c08459148612e5217d228fac41c6 | cc0db11c312b9d2436427114bf04664879663bfc | refs/heads/master | 2021-01-25T15:04:44.977830 | 2019-10-21T14:53:25 | 2019-10-21T14:53:25 | 38,994,786 | 7 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 1,132 | cpp | /// @file
/// @version 1.2
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause
#include <hltypes/hstream.h>
#include <hltypes/hthread.h>
#include "PlatformSocket.h"
#include "sakit.h"
#include "Socket.h"
#include "SocketDelegate.h"
#include "BinderThread.h"
#include "TcpSocket.h"
namespace sakit
{
BinderThread::BinderThread(PlatformSocket* socket) :
WorkerThread(socket)
{
}
void BinderThread::_updateBinding()
{
bool result = this->socket->bind(this->host, this->port);
hmutex::ScopeLock lock(&this->resultMutex);
this->result = (result ? State::Finished : State::Failed);
}
void BinderThread::_updateUnbinding()
{
bool result = this->socket->disconnect();
hmutex::ScopeLock lock(&this->resultMutex);
this->result = (result ? State::Finished : State::Failed);
}
void BinderThread::_updateProcess()
{
if (this->state == State::Binding)
{
this->_updateBinding();
}
else if (this->state == State::Unbinding)
{
this->_updateUnbinding();
}
}
}
| [
"boris.blizzard@gmail.com"
] | boris.blizzard@gmail.com |
a60ecf14e8a9dbc030fc895f2ef5ad54264da32e | 634120df190b6262fccf699ac02538360fd9012d | /Develop/Server/AppServer/main/PNetServer.cpp | 5eda2d7d4db12c7ac375980fc938c0f3e657fb58 | [] | no_license | ktj007/Raiderz_Public | c906830cca5c644be384e68da205ee8abeb31369 | a71421614ef5711740d154c961cbb3ba2a03f266 | refs/heads/master | 2021-06-08T03:37:10.065320 | 2016-11-28T07:50:57 | 2016-11-28T07:50:57 | 74,959,309 | 6 | 4 | null | 2016-11-28T09:53:49 | 2016-11-28T09:53:49 | null | UTF-8 | C++ | false | false | 1,410 | cpp | #include "stdafx.h"
#include "PNetServer.h"
#include "PCommandTable.h"
#include "PCommandCenter.h"
#include "PCmdHandlerGroup.h"
PNetServer::PNetServer(const MNetServerDesc& desc) :MNetServer(desc)
, m_nLastCheckTime(0)
, m_nRecvCPS(0)
, m_nSendCPS(0)
, m_nLocalCPS(0)
{
m_pCmdHandlerGroup = new PCmdHandlerGroup(this);
}
PNetServer::~PNetServer()
{
SAFE_DELETE(m_pCmdHandlerGroup);
}
void PNetServer::OnPrepareCommand( MCommand* pCommand )
{
minet::MNetServer::OnPrepareCommand(pCommand);
LogCommand(pCommand);
}
void PNetServer::UpdateCmdCount(MCommand* pCommand)
{
if (pCommand->m_pCommandDesc->IsFlag(MCDT_LOCAL))
{
m_nLocalTotalCmdCount++;m_nLocalCmdCnt++;
}
else if (pCommand->m_Receiver==m_This)
{
m_nRecvTotalCmdCount++;
m_nRecvCmdCnt++;
}
else
{
m_nSendTotalCmdCount++;
m_nSendCmdCnt += pCommand->GetReceiverCount();
}
unsigned int nNowTime = timeGetTime();
if (nNowTime - m_nLastCheckTime >= 1000)
{
m_nLocalCPS = m_nLocalCmdCnt;
m_nRecvCPS = m_nRecvCmdCnt;
m_nSendCPS = m_nSendCmdCnt;
m_nLocalCmdCnt = m_nRecvCmdCnt = m_nSendCmdCnt = 0;
m_nLastCheckTime = nNowTime;
}
}
void PNetServer::SendCommand( minet::MCommand* pCommand )
{
MNetServer::SendCommand(pCommand);
LogCommand(pCommand);
}
void PNetServer::LogCommand( minet::MCommand* pCommand )
{
//if (gsys.pCommandCenter) gsys.pCommandCenter->LogCommand(pCommand);
//UpdateCmdCount(pCommand);
}
| [
"espause0703@gmail.com"
] | espause0703@gmail.com |
a0656253f1de5b823289ce6118bb786309198d06 | a6a964e70f3775d7f2c1401dc55193d2ebf8a89c | /DanganHooker/MemoryAddresses.cpp | b4d62c5f8db28f6f0413c846e631d03098120c89 | [
"MIT"
] | permissive | Keightiie/DanganHooker | 6422720a8d3a110eae0a4f63ba0c75206de3f9a8 | 7d7ba7d4d826db4610183e875001c415deed46cf | refs/heads/master | 2023-02-24T13:52:42.965522 | 2023-02-18T20:03:29 | 2023-02-18T20:03:29 | 220,554,562 | 1 | 0 | null | 2023-02-18T20:03:30 | 2019-11-08T22:02:26 | C++ | UTF-8 | C++ | false | false | 113 | cpp | #include "MemoryAddresses.h"
DWORD CommonAddresses::ReturnGetOpFunc = 0;
DWORD CommonAddresses::BaseAddress = 0; | [
"undermybrella@abimon.org"
] | undermybrella@abimon.org |
8327d95c70c683127330d1bfa5f5af8a0d21ac9b | 474ca3fbc2b3513d92ed9531a9a99a2248ec7f63 | /ThirdParty/boost_1_63_0/libs/thread/example/ba_externallly_locked.cpp | 1cf4f6926b94cb7543955499a1812c6243a457e2 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | LazyPlanet/MX-Architecture | 17b7b2e6c730409b22b7f38633e7b1f16359d250 | 732a867a5db3ba0c716752bffaeb675ebdc13a60 | refs/heads/master | 2020-12-30T15:41:18.664826 | 2018-03-02T00:59:12 | 2018-03-02T00:59:12 | 91,156,170 | 4 | 0 | null | 2018-02-04T03:29:46 | 2017-05-13T07:05:52 | C++ | UTF-8 | C++ | false | false | 2,947 | cpp | // Copyright (C) 2012 Vicente Botet
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#define BOOST_THREAD_VERSION 4
#include <boost/thread/mutex.hpp>
#include <boost/thread/lockable_adapter.hpp>
#include <boost/thread/externally_locked.hpp>
#include <boost/thread/strict_lock.hpp>
#include <boost/thread/lock_types.hpp>
#include <iostream>
using namespace boost;
class BankAccount
{
int balance_;
public:
void Deposit(int amount)
{
balance_ += amount;
}
void Withdraw(int amount)
{
balance_ -= amount;
}
int GetBalance()
{
return balance_;
}
};
//[AccountManager
class AccountManager: public basic_lockable_adapter<mutex>
{
public:
typedef basic_lockable_adapter<mutex> lockable_base_type;
AccountManager() :
lockable_base_type(), checkingAcct_(*this), savingsAcct_(*this)
{
}
inline void Checking2Savings(int amount);
inline void AMoreComplicatedChecking2Savings(int amount);
private:
/*<-*/
bool some_condition()
{
return true;
} /*->*/
externally_locked<BankAccount, AccountManager > checkingAcct_;
externally_locked<BankAccount, AccountManager > savingsAcct_;
};
//]
//[Checking2Savings
void AccountManager::Checking2Savings(int amount)
{
strict_lock<AccountManager> guard(*this);
checkingAcct_.get(guard).Withdraw(amount);
savingsAcct_.get(guard).Deposit(amount);
}
//]
//#if DO_NOT_COMPILE
////[AMoreComplicatedChecking2Savings_DO_NOT_COMPILE
//void AccountManager::AMoreComplicatedChecking2Savings(int amount) {
// unique_lock<AccountManager> guard(*this);
// if (some_condition()) {
// guard.lock();
// }
// checkingAcct_.get(guard).Withdraw(amount);
// savingsAcct_.get(guard).Deposit(amount);
// guard1.unlock();
//}
////]
//#elif DO_NOT_COMPILE_2
////[AMoreComplicatedChecking2Savings_DO_NOT_COMPILE2
//void AccountManager::AMoreComplicatedChecking2Savings(int amount) {
// unique_lock<AccountManager> guard1(*this);
// if (some_condition()) {
// guard1.lock();
// }
// {
// strict_lock<AccountManager> guard(guard1);
// checkingAcct_.get(guard).Withdraw(amount);
// savingsAcct_.get(guard).Deposit(amount);
// }
// guard1.unlock();
//}
////]
//#else
////[AMoreComplicatedChecking2Savings
void AccountManager::AMoreComplicatedChecking2Savings(int amount) {
unique_lock<AccountManager> guard1(*this);
if (some_condition()) {
guard1.lock();
}
{
nested_strict_lock<unique_lock<AccountManager> > guard(guard1);
checkingAcct_.get(guard).Withdraw(amount);
savingsAcct_.get(guard).Deposit(amount);
}
guard1.unlock();
}
////]
//#endif
int main()
{
AccountManager mgr;
mgr.Checking2Savings(100);
return 0;
}
| [
"1211618464@qq.com"
] | 1211618464@qq.com |
61a6e4285e4db91a573ba3c103518a34c521c38f | f83ef53177180ebfeb5a3e230aa29794f52ce1fc | /ACE/ACE_wrappers/TAO/orbsvcs/orbsvcs/LoadBalancing/LB_LoadMinimum.inl | 4d8296efa9240d544fb43f5dd0d653d44f5abda4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-sun-iiop",
"Apache-2.0"
] | permissive | msrLi/portingSources | fe7528b3fd08eed4a1b41383c88ee5c09c2294ef | 57d561730ab27804a3172b33807f2bffbc9e52ae | refs/heads/master | 2021-07-08T01:22:29.604203 | 2019-07-10T13:07:06 | 2019-07-10T13:07:06 | 196,183,165 | 2 | 1 | Apache-2.0 | 2020-10-13T14:30:53 | 2019-07-10T10:16:46 | null | UTF-8 | C++ | false | false | 617 | inl | // -*- C++ -*-
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_INLINE CORBA::Float
TAO_LB_LoadMinimum::effective_load (CORBA::Float previous_load,
CORBA::Float new_load)
{
// Apply per-balance load. (Recompute raw load)
previous_load += this->per_balance_load_;
// Apply dampening. (Recompute new raw load)
CORBA::Float result =
this->dampening_ * previous_load + (1 - this->dampening_) * new_load;
ACE_ASSERT (!ACE::is_equal (this->tolerance_, 0.0f));
// Compute the effective load.
result /= this->tolerance_;
return result;
}
TAO_END_VERSIONED_NAMESPACE_DECL
| [
"lihuibin705@163.com"
] | lihuibin705@163.com |
b5849f7f56a9072a52638b4a315e17a6e4a2835a | 8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a | /3rdParty/boost/1.78.0/libs/proto/example/external_transforms.cpp | 3667ebbd69f1d2c93c3813632a05aec6bd0cf313 | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode... | permissive | arangodb/arangodb | 0980625e76c56a2449d90dcb8d8f2c485e28a83b | 43c40535cee37fc7349a21793dc33b1833735af5 | refs/heads/devel | 2023-08-31T09:34:47.451950 | 2023-08-31T07:25:02 | 2023-08-31T07:25:02 | 2,649,214 | 13,385 | 982 | Apache-2.0 | 2023-09-14T17:02:16 | 2011-10-26T06:42:00 | C++ | UTF-8 | C++ | false | false | 3,839 | cpp | //[ CheckedCalc
// Copyright 2011 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// This is an example of how to specify a transform externally so
// that a single grammar can be used to drive multiple differnt
// calculations. In particular, it defines a calculator grammar
// that computes the result of an expression with either checked
// or non-checked division.
#include <iostream>
#include <boost/assert.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/next.hpp>
#include <boost/mpl/min_max.hpp>
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/container/generation/make_vector.hpp>
#include <boost/proto/proto.hpp>
namespace mpl = boost::mpl;
namespace proto = boost::proto;
namespace fusion = boost::fusion;
// The argument placeholder type
template<typename I> struct placeholder : I {};
// Give each rule in the grammar a "name". This is so that we
// can easily dispatch on it later.
struct calc_grammar;
struct divides_rule : proto::divides<calc_grammar, calc_grammar> {};
// Use external transforms in calc_gramar
struct calc_grammar
: proto::or_<
proto::when<
proto::terminal<placeholder<proto::_> >
, proto::functional::at(proto::_state, proto::_value)
>
, proto::when<
proto::terminal<proto::convertible_to<double> >
, proto::_value
>
, proto::when<
proto::plus<calc_grammar, calc_grammar>
, proto::_default<calc_grammar>
>
, proto::when<
proto::minus<calc_grammar, calc_grammar>
, proto::_default<calc_grammar>
>
, proto::when<
proto::multiplies<calc_grammar, calc_grammar>
, proto::_default<calc_grammar>
>
// Note that we don't specify how division nodes are
// handled here. Proto::external_transform is a placeholder
// for an actual transform.
, proto::when<
divides_rule
, proto::external_transform
>
>
{};
template<typename E> struct calc_expr;
struct calc_domain : proto::domain<proto::generator<calc_expr> > {};
template<typename E>
struct calc_expr
: proto::extends<E, calc_expr<E>, calc_domain>
{
calc_expr(E const &e = E()) : calc_expr::proto_extends(e) {}
};
calc_expr<proto::terminal<placeholder<mpl::int_<0> > >::type> _1;
calc_expr<proto::terminal<placeholder<mpl::int_<1> > >::type> _2;
// Use proto::external_transforms to map from named grammar rules to
// transforms.
struct non_checked_division
: proto::external_transforms<
proto::when< divides_rule, proto::_default<calc_grammar> >
>
{};
struct division_by_zero : std::exception {};
struct do_checked_divide
: proto::callable
{
typedef int result_type;
int operator()(int left, int right) const
{
if (right == 0) throw division_by_zero();
return left / right;
}
};
// Use proto::external_transforms again, this time to map the divides_rule
// to a transforms that performs checked division.
struct checked_division
: proto::external_transforms<
proto::when<
divides_rule
, do_checked_divide(calc_grammar(proto::_left), calc_grammar(proto::_right))
>
>
{};
int main()
{
non_checked_division non_checked;
int result2 = calc_grammar()(_1 / _2, fusion::make_vector(6, 2), non_checked);
BOOST_ASSERT(result2 == 3);
try
{
checked_division checked;
// This should throw
int result3 = calc_grammar()(_1 / _2, fusion::make_vector(6, 0), checked);
BOOST_ASSERT(false); // shouldn't get here!
}
catch(division_by_zero)
{
std::cout << "caught division by zero!\n";
}
}
//]
| [
"frank@arangodb.com"
] | frank@arangodb.com |
60cb90dcbbb2a3fff45893236b4e84d820caac72 | 058ba23d6d1c6a3b68883d10ff71fc9ebf94cf0e | /DAY7/Palindrome Linked List.cpp | ebb7ea4cc0cb4490b8e06ee1544abf1ab83960de | [] | no_license | Narayana3057/CP1_CIPHERSCHOOLS | 0e00534f7099f549d8d46d12c61a7c5cddebc2d1 | f3f4202e7b2c2831b6eaeae1cb3a7f805ea39d8b | refs/heads/master | 2022-12-09T13:24:02.215951 | 2020-08-30T11:23:24 | 2020-08-30T11:23:24 | 288,426,163 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 779 | cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
stack<int> s;
ListNode *next=head;
while(next!=nullptr){
s.push(next->val);
next = next->next;
}
next=head;
while(!s.empty()){
int val=s.top();
s.pop();
if(val!=next->val){
return false;
}
next=next->next;
}
return true;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
5fcc5cfc186b11ae282de580c8c419971fc22f7f | 0bedbcd5d9821abaad01e1d32949007a1a3f756b | /12890 - Easy Peasy.cpp | bfba0320c80ebb808e8e30a99c2e8f9a24dddd89 | [] | no_license | ahqmrf/desktopUva | 02a17c20f114cd305883ad1c809d6f135a12f816 | 33a6579e0c8bb25f5893d05d9a95de88db5ccc80 | refs/heads/master | 2021-01-23T12:16:25.145257 | 2015-03-19T07:02:55 | 2015-03-19T07:02:55 | 32,505,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 364 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int cases;
scanf("%d", &cases);
while(cases--)
{
int n, x, low = 0;
long long ret = 0;
map <int, int> R;
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
scanf("%d", &x);
int &y = R[x];
if(y > low) low = y;
y = i;
ret += i - low;
}
printf("%lld\n", ret);
}
return 0;
} | [
"bsse0621@iit.du.ac.bd"
] | bsse0621@iit.du.ac.bd |
55fc779c74a7ccd7c8273d8c8b0ae925c13e90a5 | 8a4a69e5b39212b955eb52cc005311a440189c9b | /src/emu/ioport.h | 20a40ebcf4d455d5c50de19d90ed1ff0bbd91c30 | [] | no_license | Ced2911/mame-lx | 7d503b63eb5ae52f1e49763fc156dffa18517ec9 | e58a80fefc46bdb879790c6bcfe882a9aff6f3ae | refs/heads/master | 2021-01-01T17:37:22.723553 | 2012-02-04T10:05:52 | 2012-02-04T10:05:52 | 3,058,666 | 1 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 47,900 | h | /***************************************************************************
ioport.h
Input/output port handling.
Copyright Nicola Salmoria and the MAME Team.
Visit http://mamedev.org for licensing and usage restrictions.
***************************************************************************/
#pragma once
#ifndef __EMU_H__
#error Dont include this file directly; include emu.h instead.
#endif
#ifndef __INPTPORT_H__
#define __INPTPORT_H__
#include <time.h>
#ifdef INP_CAPTION
#include "render.h"
#endif /* INP_CAPTION */
/***************************************************************************
CONSTANTS
***************************************************************************/
#define MAX_PLAYERS 8
#ifdef USE_AUTOFIRE
#define AUTOFIRE_ON 1 /* Autofire enable bit */
#define AUTOFIRE_TOGGLE 2 /* Autofire toggle enable bit */
#endif /* USE_AUTOFIRE */
#ifdef USE_CUSTOM_BUTTON
#define MAX_CUSTOM_BUTTONS 4
#endif /* USE_CUSTOM_BUTTON */
#define MAX_NORMAL_BUTTONS 10
#define IP_ACTIVE_HIGH 0x00000000
#define IP_ACTIVE_LOW 0xffffffff
/* flags for input_field_configs */
#define FIELD_FLAG_UNUSED 0x01 /* set if this field is unused but relevant to other games on the same hw */
#define FIELD_FLAG_COCKTAIL 0x02 /* set if this field is relevant only for cocktail cabinets */
#define FIELD_FLAG_TOGGLE 0x04 /* set if this field should behave as a toggle */
#define FIELD_FLAG_ROTATED 0x08 /* set if this field represents a rotated control */
#define ANALOG_FLAG_REVERSE 0x10 /* analog only: reverse the sense of the axis */
#define ANALOG_FLAG_RESET 0x20 /* analog only: always preload in->default for relative axes, returning only deltas */
#define ANALOG_FLAG_WRAPS 0x40 /* analog only: positional count wraps around */
#define ANALOG_FLAG_INVERT 0x80 /* analog only: bitwise invert bits */
/* INP file information */
#define INP_HEADER_SIZE 64
#define INP_HEADER_MAJVERSION 3
#define INP_HEADER_MINVERSION 0
/* sequence types for input_port_seq() call */
enum _input_seq_type
{
SEQ_TYPE_STANDARD = 0,
SEQ_TYPE_INCREMENT,
SEQ_TYPE_DECREMENT,
SEQ_TYPE_TOTAL
};
typedef enum _input_seq_type input_seq_type;
DECLARE_ENUM_OPERATORS(input_seq_type)
/* conditions for DIP switches */
enum
{
PORTCOND_ALWAYS = 0,
PORTCOND_EQUALS,
PORTCOND_NOTEQUALS,
PORTCOND_GREATERTHAN,
PORTCOND_NOTGREATERTHAN,
PORTCOND_LESSTHAN,
PORTCOND_NOTLESSTHAN
};
/* crosshair types */
enum
{
CROSSHAIR_AXIS_NONE = 0,
CROSSHAIR_AXIS_X,
CROSSHAIR_AXIS_Y
};
/* groups for input ports */
enum ioport_group
{
IPG_UI = 0,
IPG_PLAYER1,
IPG_PLAYER2,
IPG_PLAYER3,
IPG_PLAYER4,
IPG_PLAYER5,
IPG_PLAYER6,
IPG_PLAYER7,
IPG_PLAYER8,
IPG_OTHER,
IPG_TOTAL_GROUPS,
IPG_INVALID
};
/* various input port types */
enum
{
/* pseudo-port types */
IPT_INVALID = 0,
IPT_UNUSED,
IPT_END,
IPT_UNKNOWN,
IPT_PORT,
IPT_DIPSWITCH,
IPT_VBLANK,
IPT_CONFIG,
/* start buttons */
IPT_START1,
IPT_START2,
IPT_START3,
IPT_START4,
IPT_START5,
IPT_START6,
IPT_START7,
IPT_START8,
/* coin slots */
IPT_COIN1,
IPT_COIN2,
IPT_COIN3,
IPT_COIN4,
IPT_COIN5,
IPT_COIN6,
IPT_COIN7,
IPT_COIN8,
IPT_COIN9,
IPT_COIN10,
IPT_COIN11,
IPT_COIN12,
IPT_BILL1,
/* service coin */
IPT_SERVICE1,
IPT_SERVICE2,
IPT_SERVICE3,
IPT_SERVICE4,
/* tilt inputs */
IPT_TILT1,
IPT_TILT2,
IPT_TILT3,
IPT_TILT4,
/* misc other digital inputs */
IPT_SERVICE,
IPT_TILT,
IPT_INTERLOCK,
IPT_VOLUME_UP,
IPT_VOLUME_DOWN,
IPT_START, /* MESS only */
IPT_SELECT, /* MESS only */
IPT_KEYPAD, /* MESS only */
IPT_KEYBOARD, /* MESS only */
#define __ipt_digital_joystick_start IPT_JOYSTICK_UP
/* use IPT_JOYSTICK for panels where the player has one single joystick */
IPT_JOYSTICK_UP,
IPT_JOYSTICK_DOWN,
IPT_JOYSTICK_LEFT,
IPT_JOYSTICK_RIGHT,
/* use IPT_JOYSTICKLEFT and IPT_JOYSTICKRIGHT for dual joystick panels */
IPT_JOYSTICKRIGHT_UP,
IPT_JOYSTICKRIGHT_DOWN,
IPT_JOYSTICKRIGHT_LEFT,
IPT_JOYSTICKRIGHT_RIGHT,
IPT_JOYSTICKLEFT_UP,
IPT_JOYSTICKLEFT_DOWN,
IPT_JOYSTICKLEFT_LEFT,
IPT_JOYSTICKLEFT_RIGHT,
#define __ipt_digital_joystick_end IPT_JOYSTICKLEFT_RIGHT
/* action buttons */
IPT_BUTTON1,
IPT_BUTTON2,
IPT_BUTTON3,
IPT_BUTTON4,
IPT_BUTTON5,
IPT_BUTTON6,
IPT_BUTTON7,
IPT_BUTTON8,
IPT_BUTTON9,
IPT_BUTTON10,
IPT_BUTTON11,
IPT_BUTTON12,
IPT_BUTTON13,
IPT_BUTTON14,
IPT_BUTTON15,
IPT_BUTTON16,
#ifdef USE_AUTOFIRE
/* autofire control buttons */
IPT_TOGGLE_AUTOFIRE,
#endif /* USE_AUTOFIRE */
#ifdef USE_CUSTOM_BUTTON
/* custom action buttons */
IPT_CUSTOM1,
IPT_CUSTOM2,
IPT_CUSTOM3,
IPT_CUSTOM4,
#endif /* USE_CUSTOM_BUTTON */
/* mahjong inputs */
#define __ipt_mahjong_start IPT_MAHJONG_A
IPT_MAHJONG_A,
IPT_MAHJONG_B,
IPT_MAHJONG_C,
IPT_MAHJONG_D,
IPT_MAHJONG_E,
IPT_MAHJONG_F,
IPT_MAHJONG_G,
IPT_MAHJONG_H,
IPT_MAHJONG_I,
IPT_MAHJONG_J,
IPT_MAHJONG_K,
IPT_MAHJONG_L,
IPT_MAHJONG_M,
IPT_MAHJONG_N,
IPT_MAHJONG_O,
IPT_MAHJONG_P,
IPT_MAHJONG_Q,
IPT_MAHJONG_KAN,
IPT_MAHJONG_PON,
IPT_MAHJONG_CHI,
IPT_MAHJONG_REACH, //IPT_MAHJONG_RIICHI, // REACH is Japanglish
IPT_MAHJONG_RON,
IPT_MAHJONG_BET,
IPT_MAHJONG_LAST_CHANCE,
IPT_MAHJONG_SCORE,
IPT_MAHJONG_DOUBLE_UP,
IPT_MAHJONG_FLIP_FLOP,
IPT_MAHJONG_BIG,
IPT_MAHJONG_SMALL,
#define __ipt_mahjong_end IPT_MAHJONG_SMALL
/* hanafuda inputs */
#define __ipt_hanafuda_start IPT_HANAFUDA_A
IPT_HANAFUDA_A,
IPT_HANAFUDA_B,
IPT_HANAFUDA_C,
IPT_HANAFUDA_D,
IPT_HANAFUDA_E,
IPT_HANAFUDA_F,
IPT_HANAFUDA_G,
IPT_HANAFUDA_H,
IPT_HANAFUDA_YES,
IPT_HANAFUDA_NO,
#define __ipt_hanafuda_end IPT_HANAFUDA_NO
#define __ipt_gambling_start IPT_GAMBLE_KEYIN
/* gambling inputs */
IPT_GAMBLE_KEYIN, // attendant
IPT_GAMBLE_KEYOUT, // attendant
IPT_GAMBLE_SERVICE, // attendant
IPT_GAMBLE_BOOK, // attendant
IPT_GAMBLE_DOOR, // attendant
// IPT_GAMBLE_DOOR2, // many gambling games have several doors.
// IPT_GAMBLE_DOOR3,
// IPT_GAMBLE_DOOR4,
// IPT_GAMBLE_DOOR5,
IPT_GAMBLE_HIGH, // player
IPT_GAMBLE_LOW, // player
IPT_GAMBLE_HALF, // player
IPT_GAMBLE_DEAL, // player
IPT_GAMBLE_D_UP, // player
IPT_GAMBLE_TAKE, // player
IPT_GAMBLE_STAND, // player
IPT_GAMBLE_BET, // player
IPT_GAMBLE_PAYOUT, // player
// IPT_GAMBLE_BUTTON1, // player
// IPT_GAMBLE_BUTTON2, // many many gambling games have multi-games and/or multi-function-buttons
// IPT_GAMBLE_BUTTON3, // I suggest to eliminate specific names
// IPT_GAMBLE_BUTTON4,
// IPT_GAMBLE_BUTTON5,
// IPT_GAMBLE_BUTTON6,
// IPT_GAMBLE_BUTTON7,
// IPT_GAMBLE_BUTTON8,
// IPT_GAMBLE_BUTTON9,
// IPT_GAMBLE_BUTTON10,
// IPT_GAMBLE_BUTTON11,
// IPT_GAMBLE_BUTTON12,
// IPT_GAMBLE_BUTTON13,
// IPT_GAMBLE_BUTTON14,
// IPT_GAMBLE_BUTTON15,
// IPT_GAMBLE_BUTTON16,
/* poker-specific inputs */
IPT_POKER_HOLD1,
IPT_POKER_HOLD2,
IPT_POKER_HOLD3,
IPT_POKER_HOLD4,
IPT_POKER_HOLD5,
IPT_POKER_CANCEL,
IPT_POKER_BET,
/* slot-specific inputs */
IPT_SLOT_STOP1,
IPT_SLOT_STOP2,
IPT_SLOT_STOP3,
IPT_SLOT_STOP4,
IPT_SLOT_STOP_ALL,
#define __ipt_gambling_end IPT_SLOT_STOP_ALL
/* analog inputs */
#define __ipt_analog_start IPT_AD_STICK_X
#define __ipt_analog_absolute_start IPT_AD_STICK_X
IPT_AD_STICK_X, // absolute // autocenter
IPT_AD_STICK_Y, // absolute // autocenter
IPT_AD_STICK_Z, // absolute // autocenter
IPT_PADDLE, // absolute // autocenter
IPT_PADDLE_V, // absolute // autocenter
IPT_PEDAL, // absolute // autocenter
IPT_PEDAL2, // absolute // autocenter
IPT_PEDAL3, // absolute // autocenter
IPT_LIGHTGUN_X, // absolute
IPT_LIGHTGUN_Y, // absolute
IPT_POSITIONAL, // absolute // autocenter if not wraps
IPT_POSITIONAL_V, // absolute // autocenter if not wraps
#define __ipt_analog_absolute_end IPT_POSITIONAL_V
IPT_DIAL, // relative
IPT_DIAL_V, // relative
IPT_TRACKBALL_X, // relative
IPT_TRACKBALL_Y, // relative
IPT_MOUSE_X, // relative
IPT_MOUSE_Y, // relative
#define __ipt_analog_end IPT_MOUSE_Y
/* analog adjuster support */
IPT_ADJUSTER,
/* the following are special codes for user interface handling - not to be used by drivers! */
#define __ipt_ui_start IPT_UI_CONFIGURE
IPT_UI_CONFIGURE,
IPT_UI_ON_SCREEN_DISPLAY,
IPT_UI_DEBUG_BREAK,
IPT_UI_PAUSE,
IPT_UI_RESET_MACHINE,
IPT_UI_SOFT_RESET,
IPT_UI_SHOW_GFX,
IPT_UI_FRAMESKIP_DEC,
IPT_UI_FRAMESKIP_INC,
IPT_UI_THROTTLE,
IPT_UI_FAST_FORWARD,
IPT_UI_SHOW_FPS,
IPT_UI_SNAPSHOT,
IPT_UI_RECORD_MOVIE,
IPT_UI_TOGGLE_CHEAT,
#ifdef USE_SHOW_TIME
IPT_UI_TIME,
#endif /* USE_SHOW_TIME */
#ifdef USE_SHOW_INPUT_LOG
IPT_UI_SHOW_INPUT_LOG,
#endif /* USE_SHOW_INPUT_LOG */
IPT_UI_UP,
IPT_UI_DOWN,
IPT_UI_LEFT,
IPT_UI_RIGHT,
IPT_UI_HOME,
IPT_UI_END,
IPT_UI_PAGE_UP,
IPT_UI_PAGE_DOWN,
IPT_UI_SELECT,
IPT_UI_CANCEL,
IPT_UI_DISPLAY_COMMENT,
IPT_UI_CLEAR,
IPT_UI_ZOOM_IN,
IPT_UI_ZOOM_OUT,
IPT_UI_PREV_GROUP,
IPT_UI_NEXT_GROUP,
IPT_UI_ROTATE,
IPT_UI_SHOW_PROFILER,
IPT_UI_TOGGLE_UI,
IPT_UI_TOGGLE_DEBUG,
IPT_UI_PASTE,
IPT_UI_SAVE_STATE,
IPT_UI_LOAD_STATE,
/* additional OSD-specified UI port types (up to 16) */
IPT_OSD_1,
IPT_OSD_2,
IPT_OSD_3,
IPT_OSD_4,
IPT_OSD_5,
IPT_OSD_6,
IPT_OSD_7,
IPT_OSD_8,
IPT_OSD_9,
IPT_OSD_10,
IPT_OSD_11,
IPT_OSD_12,
IPT_OSD_13,
IPT_OSD_14,
IPT_OSD_15,
IPT_OSD_16,
#define __ipt_ui_end IPT_OSD_16
/* other meaning not mapped to standard defaults */
IPT_OTHER,
/* special meaning handled by custom code */
IPT_SPECIAL,
IPT_OUTPUT,
__ipt_max
};
/* default strings used in port definitions */
enum
{
INPUT_STRING_Off = 1,
INPUT_STRING_On,
INPUT_STRING_No,
INPUT_STRING_Yes,
INPUT_STRING_Lives,
INPUT_STRING_Bonus_Life,
INPUT_STRING_Difficulty,
INPUT_STRING_Demo_Sounds,
INPUT_STRING_Coinage,
INPUT_STRING_Coin_A,
INPUT_STRING_Coin_B,
// INPUT_STRING_20C_1C, // 0.050000
// INPUT_STRING_15C_1C, // 0.066667
// INPUT_STRING_10C_1C, // 0.100000
#define __input_string_coinage_start INPUT_STRING_9C_1C
INPUT_STRING_9C_1C, // 0.111111
INPUT_STRING_8C_1C, // 0.125000
INPUT_STRING_7C_1C, // 0.142857
INPUT_STRING_6C_1C, // 0.166667
// INPUT_STRING_10C_2C, // 0.200000
INPUT_STRING_5C_1C, // 0.200000
// INPUT_STRING_9C_2C, // 0.222222
// INPUT_STRING_8C_2C, // 0.250000
INPUT_STRING_4C_1C, // 0.250000
// INPUT_STRING_7C_2C, // 0.285714
// INPUT_STRING_10C_3C, // 0.300000
// INPUT_STRING_9C_3C, // 0.333333
// INPUT_STRING_6C_2C, // 0.333333
INPUT_STRING_3C_1C, // 0.333333
INPUT_STRING_8C_3C, // 0.375000
// INPUT_STRING_10C_4C, // 0.400000
// INPUT_STRING_5C_2C, // 0.400000
// INPUT_STRING_7C_3C, // 0.428571
// INPUT_STRING_9C_4C, // 0.444444
// INPUT_STRING_10C_5C, // 0.500000
// INPUT_STRING_8C_4C, // 0.500000
// INPUT_STRING_6C_3C, // 0.500000
INPUT_STRING_4C_2C, // 0.500000
INPUT_STRING_2C_1C, // 0.500000
// INPUT_STRING_9C_5C, // 0.555556
// INPUT_STRING_7C_4C, // 0.571429
// INPUT_STRING_10C_6C, // 0.600000
INPUT_STRING_5C_3C, // 0.600000
// INPUT_STRING_8C_5C, // 0.625000
// INPUT_STRING_9C_6C, // 0.666667
// INPUT_STRING_6C_4C, // 0.666667
INPUT_STRING_3C_2C, // 0.666667
// INPUT_STRING_10C_7C, // 0.700000
// INPUT_STRING_7C_5C, // 0.714286
// INPUT_STRING_8C_6C, // 0.750000
INPUT_STRING_4C_3C, // 0.750000
// INPUT_STRING_9C_7C, // 0.777778
// INPUT_STRING_10C_8C, // 0.800000
// INPUT_STRING_5C_4C, // 0.800000
// INPUT_STRING_6C_5C, // 0.833333
// INPUT_STRING_7C_6C, // 0.857143
// INPUT_STRING_8C_7C, // 0.875000
// INPUT_STRING_9C_8C, // 0.888889
// INPUT_STRING_10C_9C, // 0.900000
// INPUT_STRING_10C_10C, // 1.000000
// INPUT_STRING_9C_9C, // 1.000000
// INPUT_STRING_8C_8C, // 1.000000
// INPUT_STRING_7C_7C, // 1.000000
// INPUT_STRING_6C_6C, // 1.000000
// INPUT_STRING_5C_5C, // 1.000000
INPUT_STRING_4C_4C, // 1.000000
INPUT_STRING_3C_3C, // 1.000000
INPUT_STRING_2C_2C, // 1.000000
INPUT_STRING_1C_1C, // 1.000000
// INPUT_STRING_9C_10C, // 1.111111
// INPUT_STRING_8C_9C, // 1.125000
// INPUT_STRING_7C_8C, // 1.142857
// INPUT_STRING_6C_7C, // 1.166667
// INPUT_STRING_5C_6C, // 1.200000
// INPUT_STRING_8C_10C, // 1.250000
INPUT_STRING_4C_5C, // 1.250000
// INPUT_STRING_7C_9C, // 1.285714
// INPUT_STRING_6C_8C, // 1.333333
INPUT_STRING_3C_4C, // 1.333333
// INPUT_STRING_5C_7C, // 1.400000
// INPUT_STRING_7C_10C, // 1.428571
// INPUT_STRING_6C_9C, // 1.500000
// INPUT_STRING_4C_6C, // 1.500000
INPUT_STRING_2C_3C, // 1.500000
// INPUT_STRING_5C_8C, // 1.600000
// INPUT_STRING_6C_10C, // 1.666667
// INPUT_STRING_3C_5C, // 1.666667
INPUT_STRING_4C_7C, // 1.750000
// INPUT_STRING_5C_9C, // 1.800000
// INPUT_STRING_5C_10C, // 2.000000
// INPUT_STRING_4C_8C, // 2.000000
// INPUT_STRING_3C_6C, // 2.000000
INPUT_STRING_2C_4C, // 2.000000
INPUT_STRING_1C_2C, // 2.000000
// INPUT_STRING_4C_9C, // 2.250000
// INPUT_STRING_3C_7C, // 2.333333
// INPUT_STRING_4C_10C, // 2.500000
INPUT_STRING_2C_5C, // 2.500000
// INPUT_STRING_3C_8C, // 2.666667
// INPUT_STRING_3C_9C, // 3.000000
INPUT_STRING_2C_6C, // 3.000000
INPUT_STRING_1C_3C, // 3.000000
// INPUT_STRING_3C_10C, // 3.333333
INPUT_STRING_2C_7C, // 3.500000
INPUT_STRING_2C_8C, // 4.000000
INPUT_STRING_1C_4C, // 4.000000
// INPUT_STRING_2C_9C, // 4.500000
// INPUT_STRING_2C_10C, // 5.000000
INPUT_STRING_1C_5C, // 5.000000
INPUT_STRING_1C_6C, // 6.000000
INPUT_STRING_1C_7C, // 7.000000
INPUT_STRING_1C_8C, // 8.000000
INPUT_STRING_1C_9C, // 9.000000
#define __input_string_coinage_end INPUT_STRING_1C_9C
// INPUT_STRING_1C_10C, // 10.000000
// INPUT_STRING_1C_11C, // 11.000000
// INPUT_STRING_1C_12C, // 12.000000
// INPUT_STRING_1C_13C, // 13.000000
// INPUT_STRING_1C_14C, // 14.000000
// INPUT_STRING_1C_15C, // 15.000000
// INPUT_STRING_1C_20C, // 20.000000
// INPUT_STRING_1C_25C, // 25.000000
// INPUT_STRING_1C_30C, // 30.000000
// INPUT_STRING_1C_40C, // 40.000000
// INPUT_STRING_1C_50C, // 50.000000
// INPUT_STRING_1C_99C, // 99.000000
// INPUT_STRING_1C_100C, // 100.000000
// INPUT_STRING_1C_120C, // 120.000000
// INPUT_STRING_1C_125C, // 125.000000
// INPUT_STRING_1C_150C, // 150.000000
// INPUT_STRING_1C_200C, // 200.000000
// INPUT_STRING_1C_250C, // 250.000000
// INPUT_STRING_1C_500C, // 500.000000
// INPUT_STRING_1C_1000C, // 1000.000000
INPUT_STRING_Free_Play,
INPUT_STRING_Cabinet,
INPUT_STRING_Upright,
INPUT_STRING_Cocktail,
INPUT_STRING_Flip_Screen,
INPUT_STRING_Service_Mode,
INPUT_STRING_Pause,
INPUT_STRING_Test,
INPUT_STRING_Tilt,
INPUT_STRING_Version,
INPUT_STRING_Region,
INPUT_STRING_International,
INPUT_STRING_Japan,
INPUT_STRING_USA,
INPUT_STRING_Europe,
INPUT_STRING_Asia,
INPUT_STRING_China,
INPUT_STRING_Hong_Kong,
INPUT_STRING_Korea,
INPUT_STRING_Southeast_Asia,
INPUT_STRING_Taiwan,
INPUT_STRING_World,
INPUT_STRING_Language,
INPUT_STRING_English,
INPUT_STRING_Japanese,
INPUT_STRING_Chinese,
INPUT_STRING_French,
INPUT_STRING_German,
INPUT_STRING_Italian,
INPUT_STRING_Korean,
INPUT_STRING_Spanish,
INPUT_STRING_Very_Easy,
INPUT_STRING_Easiest,
INPUT_STRING_Easier,
INPUT_STRING_Easy,
INPUT_STRING_Medium_Easy,
INPUT_STRING_Normal,
INPUT_STRING_Medium,
INPUT_STRING_Medium_Hard,
INPUT_STRING_Hard,
INPUT_STRING_Harder,
INPUT_STRING_Hardest,
INPUT_STRING_Very_Hard,
INPUT_STRING_Medium_Difficult,
INPUT_STRING_Difficult,
INPUT_STRING_Very_Difficult,
INPUT_STRING_Very_Low,
INPUT_STRING_Low,
INPUT_STRING_High,
INPUT_STRING_Higher,
INPUT_STRING_Highest,
INPUT_STRING_Very_High,
INPUT_STRING_Players,
INPUT_STRING_Controls,
INPUT_STRING_Dual,
INPUT_STRING_Single,
INPUT_STRING_Game_Time,
INPUT_STRING_Continue_Price,
INPUT_STRING_Controller,
INPUT_STRING_Light_Gun,
INPUT_STRING_Joystick,
INPUT_STRING_Trackball,
INPUT_STRING_Continues,
INPUT_STRING_Allow_Continue,
INPUT_STRING_Level_Select,
// INPUT_STRING_Allow,
// INPUT_STRING_Forbid,
// INPUT_STRING_Enable,
// INPUT_STRING_Disable,
INPUT_STRING_Infinite,
// INPUT_STRING_Invincibility,
// INPUT_STRING_Invulnerability,
INPUT_STRING_Stereo,
INPUT_STRING_Mono,
INPUT_STRING_Unused,
INPUT_STRING_Unknown,
// INPUT_STRING_Undefined,
INPUT_STRING_Standard,
INPUT_STRING_Reverse,
INPUT_STRING_Alternate,
// INPUT_STRING_Reserve,
// INPUT_STRING_Spare,
// INPUT_STRING_Invalid,
INPUT_STRING_None,
INPUT_STRING_COUNT
};
/* input classes */
enum
{
INPUT_CLASS_INTERNAL,
INPUT_CLASS_KEYBOARD,
INPUT_CLASS_CONTROLLER,
INPUT_CLASS_CONFIG,
INPUT_CLASS_DIPSWITCH,
INPUT_CLASS_MISC
};
#define UCHAR_PRIVATE (0x100000)
#define UCHAR_SHIFT_1 (UCHAR_PRIVATE + 0)
#define UCHAR_SHIFT_2 (UCHAR_PRIVATE + 1)
#define UCHAR_MAMEKEY_BEGIN (UCHAR_PRIVATE + 2)
#define UCHAR_MAMEKEY(code) (UCHAR_MAMEKEY_BEGIN + ITEM_ID_##code)
#define UCHAR_SHIFT_BEGIN (UCHAR_SHIFT_1)
#define UCHAR_SHIFT_END (UCHAR_SHIFT_2)
/***************************************************************************
TYPE DEFINITIONS
***************************************************************************/
/* input ports support up to 32 bits each */
typedef UINT32 input_port_value;
/* opaque types pointing to live state */
typedef struct _input_port_state input_port_state;
typedef struct _input_field_state input_field_state;
/* forward declarations */
class input_port_config;
class input_field_config;
/* template specializations */
typedef tagged_list<input_port_config> ioport_list;
/* read input port callback function */
typedef delegate<UINT32 (const input_field_config &, void *)> input_field_read_delegate;
/* input port write callback function */
typedef delegate<void (const input_field_config &, void *, input_port_value, input_port_value)> input_field_write_delegate;
/* crosshair mapping function */
typedef delegate<float (const input_field_config &, float)> input_field_crossmap_delegate;
/* encapsulates a condition on a port field or setting */
typedef struct _input_condition input_condition;
struct _input_condition
{
const char * tag; /* tag of port whose condition is to be tested */
input_port_value mask; /* mask to apply to the port */
input_port_value value; /* value to compare against */
UINT8 condition; /* condition to use */
};
/* a single setting for a configuration or DIP switch */
class input_setting_config
{
DISABLE_COPYING(input_setting_config);
friend class simple_list<input_setting_config>;
public:
input_setting_config(input_field_config &field, input_port_value value, const char *name);
input_setting_config *next() const { return m_next; }
input_port_value value; /* value of the bits in this setting */
input_condition condition; /* condition under which this setting is valid */
const char * name; /* user-friendly name to display */
private:
input_field_config & m_field; /* pointer back to the field that owns us */
input_setting_config * m_next; /* pointer to next setting in sequence */
};
/* a mapping from a bit to a physical DIP switch description */
class input_field_diplocation
{
DISABLE_COPYING(input_field_diplocation);
friend class simple_list<input_field_diplocation>;
public:
input_field_diplocation(const char *string, UINT8 swnum, bool invert);
input_field_diplocation *next() const { return m_next; }
astring swname; /* name of the physical DIP switch */
UINT8 swnum; /* physical switch number */
bool invert; /* is this an active-high DIP? */
private:
input_field_diplocation * m_next; /* pointer to the next bit */
};
/* a single bitfield within an input port */
class input_field_config
{
DISABLE_COPYING(input_field_config);
friend class simple_list<input_field_config>;
public:
input_field_config(input_port_config &port, int type, input_port_value defvalue, input_port_value maskbits, const char *name = NULL);
input_field_config *next() const { return m_next; }
input_port_config &port() const { return m_port; }
running_machine &machine() const;
simple_list<input_setting_config> &settinglist() { return m_settinglist; }
const simple_list<input_setting_config> &settinglist() const { return m_settinglist; }
simple_list<input_field_diplocation> &diploclist() { return m_diploclist; }
int modcount() const { return m_modcount; }
/* generally-applicable data */
input_port_value mask; /* mask of bits belonging to the field */
input_port_value defvalue; /* default value of these bits */
input_condition condition; /* condition under which this field is relevant */
UINT32 type; /* IPT_* type for this port */
UINT8 player; /* player number (0-based) */
UINT32 flags; /* combination of FIELD_FLAG_* and ANALOG_FLAG_* above */
UINT8 impulse; /* number of frames before reverting to defvalue */
const char * name; /* user-friendly name to display */
input_seq seq[SEQ_TYPE_TOTAL];/* sequences of all types */
input_field_read_delegate read; /* read callback routine */
void * read_param; /* parameter for read callback routine */
const char * read_device; /* parameter for read callback routine */
input_field_write_delegate write; /* write callback routine */
void * write_param; /* parameter for write callback routine */
const char * write_device; /* parameter for write callback routine */
/* data relevant to analog control types */
INT32 min; /* minimum value for absolute axes */
INT32 max; /* maximum value for absolute axes */
INT32 sensitivity; /* sensitivity (100=normal) */
INT32 delta; /* delta to apply each frame a digital inc/dec key is pressed */
INT32 centerdelta; /* delta to apply each frame no digital inputs are pressed */
UINT8 crossaxis; /* crosshair axis */
double crossscale; /* crosshair scale */
double crossoffset; /* crosshair offset */
double crossaltaxis; /* crosshair alternate axis value */
input_field_crossmap_delegate crossmapper; /* crosshair mapping function */
const char * crossmapper_device; /* parameter for write callback routine */
UINT16 full_turn_count;/* number of optical counts for 1 full turn of the original control */
const input_port_value * remap_table; /* pointer to an array that remaps the port value */
/* data relevant to other specific types */
UINT8 way; /* digital joystick 2/4/8-way descriptions */
unicode_char chars[3]; /* (MESS-specific) unicode key data */
/* this field is only valid if the device is live */
input_field_state * state; /* live state of field (NULL if not live) */
private:
input_field_config * m_next; /* pointer to next field in sequence */
input_port_config & m_port; /* pointer back to the port that owns us */
int m_modcount;
simple_list<input_setting_config> m_settinglist; /* list of input_setting_configs */
simple_list<input_field_diplocation> m_diploclist; /* list of locations for various bits */
};
/* user-controllable settings for a field */
typedef struct _input_field_user_settings input_field_user_settings;
struct _input_field_user_settings
{
input_port_value value; /* for DIP switches */
#ifdef USE_AUTOFIRE
int autofire; /* autofire */
#endif /* USE_AUTOFIRE */
input_seq seq[SEQ_TYPE_TOTAL];/* sequences of all types */
INT32 sensitivity; /* for analog controls */
INT32 delta; /* for analog controls */
INT32 centerdelta; /* for analog controls */
UINT8 reverse; /* for analog controls */
};
/* device defined default input settings */
typedef struct _input_device_default input_device_default;
struct _input_device_default
{
const char * tag; /* tag of port to update */
input_port_value mask; /* mask to apply to the port */
input_port_value defvalue; /* new default value */
};
/* a single input port configuration */
class input_port_config
{
DISABLE_COPYING(input_port_config);
friend class simple_list<input_port_config>;
public:
// construction/destruction
input_port_config(device_t &owner, const char *tag);
// getters
input_port_config *next() const { return m_next; }
device_t &owner() const { return m_owner; }
running_machine &machine() const;
input_field_config *first_field() const { return m_fieldlist.first(); }
simple_list<input_field_config> &fieldlist() { return m_fieldlist; }
const char *tag() const { return m_tag; }
int modcount() const { return m_modcount; }
void bump_modcount() { m_modcount++; }
void collapse_fields(astring &errorbuf);
/* these fields are only valid if the port is live */
input_port_state * state; /* live state of port (NULL if not live) */
input_port_value active; /* mask of active bits in the port */
private:
input_port_config * m_next; /* pointer to next port */
device_t & m_owner; /* associated device, when appropriate */
simple_list<input_field_config> m_fieldlist; /* list of input_field_configs */
astring m_tag; /* pointer to this port's tag */
int m_modcount;
};
/* describes a fundamental input type, including default input sequences */
class input_type_entry
{
friend class simple_list<input_type_entry>;
public:
input_type_entry(UINT32 type, ioport_group group, int player, const char *token, const char *name, input_seq standard);
input_type_entry(UINT32 type, ioport_group group, int player, const char *token, const char *name, input_seq standard, input_seq decrement, input_seq increment);
input_type_entry *next() const { return m_next; }
UINT32 type; /* IPT_* for this entry */
ioport_group group; /* which group the port belongs to */
UINT8 player; /* player number (0 is player 1) */
const char * token; /* token used to store settings */
const char * name; /* user-friendly name */
input_seq defseq[SEQ_TYPE_TOTAL];/* default input sequence */
input_seq seq[SEQ_TYPE_TOTAL];/* currently configured sequences */
private:
input_type_entry * m_next; /* next description in the list */
};
/* header at the front of INP files */
typedef struct _inp_header inp_header;
struct _inp_header
{
char header[8]; /* +00: 8 byte header - must be "MAMEINP\0" */
UINT64 basetime; /* +08: base time of recording */
UINT8 majversion; /* +10: major INP version */
UINT8 minversion; /* +11: minor INP version */
UINT8 reserved[2]; /* +12: must be zero */
char gamename[12]; /* +14: game name string, NULL-terminated */
char version[32]; /* +20: system version string, NULL-terminated */
};
/***************************************************************************
MACROS
***************************************************************************/
/* macro for a read callback function (PORT_CUSTOM) */
#define CUSTOM_INPUT(name) input_port_value name(device_t &device, const input_field_config &field, void *param)
#define CUSTOM_INPUT_MEMBER(name) input_port_value name(const input_field_config &field, void *param)
#define DECLARE_CUSTOM_INPUT_MEMBER(name) input_port_value name(const input_field_config &field, void *param)
/* macro for port write callback functions (PORT_CHANGED) */
#define INPUT_CHANGED(name) void name(device_t &device, const input_field_config &field, void *param, input_port_value oldval, input_port_value newval)
#define INPUT_CHANGED_MEMBER(name) void name(const input_field_config &field, void *param, input_port_value oldval, input_port_value newval)
#define DECLARE_INPUT_CHANGED_MEMBER(name) void name(const input_field_config &field, void *param, input_port_value oldval, input_port_value newval)
/* macro for port changed callback functions (PORT_CROSSHAIR_MAPPER) */
#define CROSSHAIR_MAPPER(name) float name(device_t &device, const input_field_config &field, float linear_value)
#define CROSSHAIR_MAPPER_MEMBER(name) float name(const input_field_config &field, float linear_value)
#define DECLARE_CROSSHAIR_MAPPER_MEMBER(name) float name(const input_field_config &field, float linear_value)
/* macro for wrapping a default string */
#define DEF_STR(str_num) ((const char *)INPUT_STRING_##str_num)
template<int (*_FunctionPointer)(device_t *)>
input_port_value ioport_read_line_wrapper(device_t &device, const input_field_config &field, void *param)
{
return (*_FunctionPointer)(&device);
}
template<class _FunctionClass, int (_FunctionClass::*_FunctionPointer)()>
input_port_value ioport_read_line_wrapper(_FunctionClass &device, const input_field_config &field, void *param)
{
return (device.*_FunctionPointer)();
}
template<void (*_FunctionPointer)(device_t *, int)>
void ioport_write_line_wrapper(device_t &device, const input_field_config &field, void *param, input_port_value oldval, input_port_value newval)
{
return (*_FunctionPointer)(&device, newval);
}
template<class _FunctionClass, void (_FunctionClass::*_FunctionPointer)(int)>
void ioport_write_line_wrapper(_FunctionClass &device, const input_field_config &field, void *param, input_port_value oldval, input_port_value newval)
{
return (device.*_FunctionPointer)(newval);
}
/***************************************************************************
MACROS FOR BUILDING INPUT PORTS
***************************************************************************/
typedef void (*ioport_constructor)(device_t &owner, ioport_list &portlist, astring &errorbuf);
/* so that "0" can be used for unneeded input ports */
#define construct_ioport_0 NULL
/* name of table */
#define INPUT_PORTS_NAME(_name) construct_ioport_##_name
/* start of table */
#define INPUT_PORTS_START(_name) \
ATTR_COLD void INPUT_PORTS_NAME(_name)(device_t &owner, ioport_list &portlist, astring &errorbuf) \
{ \
astring fulltag; \
input_setting_config *cursetting = NULL; \
input_field_config *curfield = NULL; \
input_port_config *curport = NULL; \
input_port_value maskbits = 0; \
(void)cursetting; (void)curfield; (void)curport; (void)maskbits; \
/* end of table */
#define INPUT_PORTS_END \
}
/* aliasing */
#define INPUT_PORTS_EXTERN(_name) \
extern void INPUT_PORTS_NAME(_name)(device_t &owner, ioport_list &portlist, astring &errorbuf)
/* including */
#define PORT_INCLUDE(_name) \
INPUT_PORTS_NAME(_name)(owner, portlist, errorbuf); \
/* start of a new input port (with included tag) */
#define PORT_START(_tag) \
curport = ioconfig_alloc_port(portlist, owner, _tag); \
curfield = NULL; \
cursetting = NULL; \
maskbits = 0; \
/* modify an existing port */
#define PORT_MODIFY(_tag) \
curport = ioconfig_modify_port(portlist, owner, _tag); \
curfield = NULL; \
cursetting = NULL; \
maskbits = 0; \
/* input bit definition */
#define PORT_BIT(_mask, _default, _type) \
curfield = ioconfig_alloc_field(*curport, (_type), (_default), (_mask)); \
cursetting = NULL;
#define PORT_SPECIAL_ONOFF(_mask, _default, _strindex) PORT_SPECIAL_ONOFF_DIPLOC(_mask, _default, _strindex, NULL)
#define PORT_SPECIAL_ONOFF_DIPLOC(_mask, _default, _strindex, _diploc) \
curfield = ioconfig_alloc_onoff(*curport, DEF_STR(_strindex), _default, _mask, _diploc, errorbuf); \
cursetting = NULL;
/* append a code */
#define PORT_CODE(_code) \
ioconfig_add_code(*curfield, SEQ_TYPE_STANDARD, _code);
#define PORT_CODE_DEC(_code) \
ioconfig_add_code(*curfield, SEQ_TYPE_DECREMENT, _code);
#define PORT_CODE_INC(_code) \
ioconfig_add_code(*curfield, SEQ_TYPE_INCREMENT, _code);
/* joystick flags */
#define PORT_2WAY \
curfield->way = 2;
#define PORT_4WAY \
curfield->way = 4;
#define PORT_8WAY \
curfield->way = 8;
#define PORT_16WAY \
curfield->way = 16;
#define PORT_ROTATED \
curfield->flags |= FIELD_FLAG_ROTATED
/* general flags */
#define PORT_NAME(_name) \
curfield->name = input_port_string_from_token(_name);
#define PORT_PLAYER(_player) \
curfield->player = (_player) - 1;
#define PORT_COCKTAIL \
curfield->flags |= FIELD_FLAG_COCKTAIL; \
curfield->player = 1;
#define PORT_TOGGLE \
curfield->flags |= FIELD_FLAG_TOGGLE;
#define PORT_IMPULSE(_duration) \
curfield->impulse = _duration;
#define PORT_REVERSE \
curfield->flags |= ANALOG_FLAG_REVERSE;
#define PORT_RESET \
curfield->flags |= ANALOG_FLAG_RESET;
#define PORT_UNUSED \
curfield->flags |= FIELD_FLAG_UNUSED;
/* analog settings */
/* if this macro is not used, the minimum defaluts to 0 and maximum defaults to the mask value */
#define PORT_MINMAX(_min, _max) \
curfield->min = _min; \
curfield->max = _max;
#define PORT_SENSITIVITY(_sensitivity) \
curfield->sensitivity = _sensitivity;
#define PORT_KEYDELTA(_delta) \
curfield->delta = curfield->centerdelta = _delta;
/* note that PORT_CENTERDELTA must appear after PORT_KEYDELTA */
#define PORT_CENTERDELTA(_delta) \
curfield->centerdelta = _delta;
#define PORT_CROSSHAIR(axis, scale, offset, altaxis) \
curfield->crossaxis = CROSSHAIR_AXIS_##axis; \
curfield->crossaltaxis = altaxis; \
curfield->crossscale = scale; \
curfield->crossoffset = offset;
#define PORT_CROSSHAIR_MAPPER(_callback) \
curfield->crossmapper = input_field_crossmap_delegate(_callback, #_callback, (device_t *)NULL); \
curfield->crossmapper_device = DEVICE_SELF;
#define PORT_CROSSHAIR_MAPPER_MEMBER(_device, _class, _member) \
curfield->crossmapper = input_field_crossmap_delegate(&_class::_member, #_class "::" #_member, (_class *)NULL); \
curfield->crossmapper_device = _device;
/* how many optical counts for 1 full turn of the control */
#define PORT_FULL_TURN_COUNT(_count) \
curfield->full_turn_count = _count;
/* positional controls can be binary or 1 of X */
/* 1 of X not completed yet */
/* if it is specified as PORT_REMAP_TABLE then it is binary, but remapped */
/* otherwise it is binary */
#define PORT_POSITIONS(_positions) \
curfield->max = _positions;
/* positional control wraps at min/max */
#define PORT_WRAPS \
curfield->flags |= ANALOG_FLAG_WRAPS;
/* positional control uses this remap table */
#define PORT_REMAP_TABLE(_table) \
curfield->remap_table = _table;
/* positional control bits are active low */
#define PORT_INVERT \
curfield->flags |= ANALOG_FLAG_INVERT;
/* read callbacks */
#define PORT_CUSTOM(_callback, _param) \
curfield->read = input_field_read_delegate(_callback, #_callback, (device_t *)NULL); \
curfield->read_param = (void *)(_param); \
curfield->read_device = DEVICE_SELF;
#define PORT_CUSTOM_MEMBER(_device, _class, _member, _param) \
curfield->read = input_field_read_delegate(&_class::_member, #_class "::" #_member, (_class *)NULL); \
curfield->read_param = (void *)(_param); \
curfield->read_device = (_device);
/* write callbacks */
#define PORT_CHANGED(_callback, _param) \
curfield->write = input_field_write_delegate(_callback, #_callback, (device_t *)NULL); \
curfield->write_param = (void *)(_param); \
curfield->write_device = DEVICE_SELF;
#define PORT_CHANGED_MEMBER(_device, _class, _member, _param) \
curfield->write = input_field_write_delegate(&_class::_member, #_class "::" #_member, (_class *)NULL); \
curfield->write_param = (void *)(_param); \
curfield->write_device = (_device);
/* input device handler */
#define PORT_READ_LINE_DEVICE(_device, _read_line_device) \
curfield->read = input_field_read_delegate(&ioport_read_line_wrapper<_read_line_device>, #_read_line_device, (device_t *)NULL); \
curfield->read_param = NULL; \
curfield->read_device = _device;
#define PORT_READ_LINE_DEVICE_MEMBER(_device, _class, _member) \
curfield->read = input_field_read_delegate(&ioport_read_line_wrapper<_class, &_class::_member>, #_class "::" #_member, (_class *)NULL); \
curfield->read_param = NULL; \
curfield->read_device = _device;
/* output device handler */
#define PORT_WRITE_LINE_DEVICE(_device, _write_line_device) \
curfield->write = input_field_write_delegate(&ioport_write_line_wrapper<_write_line_device>, #_write_line_device, (device_t *)NULL); \
curfield->write_param = NULL; \
curfield->write_device = _device;
#define PORT_WRITE_LINE_DEVICE_MEMBER(_device, _class, _member) \
curfield->write = input_field_write_delegate(&ioport_write_line_wrapper<_class, &_class::_member>, #_class "::" #_member, (_class *)NULL); \
curfield->write_param = NULL; \
curfield->write_device = _device;
/* dip switch definition */
#define PORT_DIPNAME(_mask, _default, _name) \
curfield = ioconfig_alloc_field(*curport, IPT_DIPSWITCH, (_default), (_mask), (_name)); \
cursetting = NULL;
#define PORT_DIPSETTING(_default, _name) \
cursetting = ioconfig_alloc_setting(*curfield, (_default) & curfield->mask, (_name));
/* physical location, of the form: name:[!]sw,[name:][!]sw,... */
/* note that these are specified LSB-first */
#define PORT_DIPLOCATION(_location) \
diplocation_list_alloc(*curfield, _location, errorbuf);
/* conditionals for dip switch settings */
#define PORT_CONDITION(_tag, _mask, _condition, _value) \
{ \
input_condition &condition = (cursetting != NULL) ? cursetting->condition : curfield->condition; \
condition.tag = (_tag); \
condition.mask = (_mask); \
condition.condition = (_condition); \
condition.value = (_value); \
}
/* analog adjuster definition */
#define PORT_ADJUSTER(_default, _name) \
curfield = ioconfig_alloc_field(*curport, IPT_ADJUSTER, (_default), 0xff, (_name)); \
cursetting = NULL; \
/* config definition */
#define PORT_CONFNAME(_mask, _default, _name) \
curfield = ioconfig_alloc_field(*curport, IPT_CONFIG, (_default), (_mask), (_name)); \
cursetting = NULL; \
#define PORT_CONFSETTING(_default, _name) \
cursetting = ioconfig_alloc_setting(*curfield, (_default) & curfield->mask, (_name));
/* keyboard chars */
#define PORT_CHAR(_ch) \
ioconfig_field_add_char(*curfield, _ch, errorbuf);
/* name of table */
#define DEVICE_INPUT_DEFAULTS_NAME(_name) device_iptdef_##_name
#define device_iptdef_0 NULL
#define device_iptdef___null NULL
/* start of table */
#define DEVICE_INPUT_DEFAULTS_START(_name) \
const input_device_default DEVICE_INPUT_DEFAULTS_NAME(_name)[] = {
/* end of table */
#define DEVICE_INPUT_DEFAULTS(_tag,_mask,_defval) \
{ _tag ,_mask, _defval }, \
/* end of table */
#define DEVICE_INPUT_DEFAULTS_END \
{NULL,0,0} };
/***************************************************************************
HELPER MACROS
***************************************************************************/
#define PORT_DIPUNUSED_DIPLOC(_mask, _default, _diploc) \
PORT_SPECIAL_ONOFF_DIPLOC(_mask, _default, Unused, _diploc)
#define PORT_DIPUNUSED(_mask, _default) \
PORT_SPECIAL_ONOFF(_mask, _default, Unused)
#define PORT_DIPUNKNOWN_DIPLOC(_mask, _default, _diploc) \
PORT_SPECIAL_ONOFF_DIPLOC(_mask, _default, Unknown, _diploc)
#define PORT_DIPUNKNOWN(_mask, _default) \
PORT_SPECIAL_ONOFF(_mask, _default, Unknown)
#define PORT_SERVICE_DIPLOC(_mask, _default, _diploc) \
PORT_SPECIAL_ONOFF_DIPLOC(_mask, _default, Service_Mode, _diploc)
#define PORT_SERVICE(_mask, _default) \
PORT_SPECIAL_ONOFF(_mask, _default, Service_Mode)
#define PORT_SERVICE_NO_TOGGLE(_mask, _default) \
PORT_BIT( _mask, _mask & _default, IPT_SERVICE ) PORT_NAME( DEF_STR( Service_Mode ))
#ifdef USE_CUSTOM_BUTTON
extern UINT16 custom_button[MAX_PLAYERS][MAX_CUSTOM_BUTTONS];
extern int custom_buttons;
#endif /* USE_CUSTOM_BUTTON */
#ifdef USE_SHOW_INPUT_LOG
typedef struct _input_log input_log;
struct _input_log
{
unicode_char code;
double time;
};
extern input_log command_buffer[];
extern int show_input_log;
#endif /* USE_SHOW_INPUT_LOG */
#ifdef INP_CAPTION
void draw_caption(running_machine &machine, render_container *container);
#endif /* INP_CAPTION */
/***************************************************************************
FUNCTION PROTOTYPES
***************************************************************************/
/* ----- core system management ----- */
/* initialize the input ports, processing the given token list */
time_t input_port_init(running_machine &machine);
/* ----- port configurations ----- */
/* initialize an input port list structure and allocate ports according to the given tokens */
void input_port_list_init(device_t &device, ioport_list &portlist, astring &errorbuf);
/* return the field that matches the given tag and mask */
const input_field_config *input_field_by_tag_and_mask(const ioport_list &portlist, const char *tag, input_port_value mask);
/* ----- accessors for input types ----- */
/* return TRUE if the given type represents an analog control */
int input_type_is_analog(int type);
/* return the name for the given type/player */
const char *input_type_name(running_machine &machine, int type, int player);
/* return the group for the given type/player */
int input_type_group(running_machine &machine, int type, int player);
/* return the global input mapping sequence for the given type/player */
const input_seq &input_type_seq(running_machine &machine, int type, int player, input_seq_type seqtype);
/* change the global input sequence for the given type/player */
void input_type_set_seq(running_machine &machine, int type, int player, input_seq_type seqtype, const input_seq *newseq);
/* return TRUE if the sequence for the given input type/player is pressed */
int input_type_pressed(running_machine &machine, int type, int player);
/* return the list of default mappings */
const simple_list<input_type_entry> &input_type_list(running_machine &machine);
/* ----- accessors for input fields ----- */
/* return the expanded string name of the field */
const char *input_field_name(const input_field_config *field);
/* return the input sequence for the given input field */
const input_seq &input_field_seq(const input_field_config *field, input_seq_type seqtype);
/* return the current settings for the given input field */
void input_field_get_user_settings(const input_field_config *field, input_field_user_settings *settings);
/* modify the current settings for the given input field */
void input_field_set_user_settings(const input_field_config *field, const input_field_user_settings *settings);
/* return the expanded setting name for a field */
const char *input_field_setting_name(const input_field_config *field);
/* return TRUE if the given field has a "previous" setting */
int input_field_has_previous_setting(const input_field_config *field);
/* select the previous item for a DIP switch or configuration field */
void input_field_select_previous_setting(const input_field_config *field);
/* return TRUE if the given field has a "next" setting */
int input_field_has_next_setting(const input_field_config *field);
/* select the next item for a DIP switch or configuration field */
void input_field_select_next_setting(const input_field_config *field);
/* has_record_file */
int has_record_file(running_machine &machine);
/* has_playback_file */
int has_playback_file(running_machine &machine);
#ifdef USE_AUTOFIRE
int get_autofiredelay(int player);
void set_autofiredelay(int player, int delay);
#endif /* USE_AUTOFIRE */
/* ----- port checking ----- */
/* return whether an input port exists */
bool input_port_exists(running_machine &machine, const char *tag);
/* return a bitmask of which bits of an input port are active (i.e. not unused or unknown) */
input_port_value input_port_active(running_machine &machine, const char *tag);
/* return a bitmask of which bits of an input port are active (i.e. not unused or unknown), or a default value if the port does not exist */
input_port_value input_port_active_safe(running_machine &machine, const char *tag, input_port_value defvalue);
/* ----- port reading ----- */
/* return the value of an input port */
input_port_value input_port_read_direct(const input_port_config *port);
/* return the value of an input port specified by tag */
input_port_value input_port_read(running_machine &machine, const char *tag);
/* return the value of a device input port specified by tag */
input_port_value input_port_read(device_t *device, const char *tag);
/* return the value of an input port specified by tag, or a default value if the port does not exist */
input_port_value input_port_read_safe(running_machine &machine, const char *tag, input_port_value defvalue);
/* return the extracted crosshair values for the given player */
int input_port_get_crosshair_position(running_machine &machine, int player, float *x, float *y);
/* force an update to the input port values based on current conditions */
void input_port_update_defaults(running_machine &machine);
/* ----- port writing ----- */
/* write a value to a port */
void input_port_write_direct(const input_port_config *port, input_port_value value, input_port_value mask);
/* write a value to a port specified by tag */
void input_port_write(running_machine &machine, const char *tag, input_port_value value, input_port_value mask);
/* write a value to a port, ignore if the port does not exist */
void input_port_write_safe(running_machine &machine, const char *tag, input_port_value value, input_port_value mask);
/* ----- misc helper functions ----- */
/* return the TRUE if the given condition attached is true */
int input_condition_true(running_machine &machine, const input_condition *condition,device_t &owner);
/* convert an input_port_token to a default string */
const char *input_port_string_from_token(const char *token);
/* return TRUE if machine use full keyboard emulation */
int input_machine_has_keyboard(running_machine &machine);
/* these are called by the core; they should not be called from FEs */
void inputx_init(running_machine &machine);
/* called by drivers to setup natural keyboard support */
void inputx_setup_natural_keyboard(running_machine &machine,
int (*queue_chars)(running_machine &machine, const unicode_char *text, size_t text_len),
int (*accept_char)(running_machine &machine, unicode_char ch),
int (*charqueue_empty)(running_machine &machine));
/* validity checks */
int validate_natural_keyboard_statics(void);
/* these can be called from FEs */
int inputx_can_post(running_machine &machine);
/* various posting functions; can be called from FEs */
void inputx_postc(running_machine &machine, unicode_char ch);
void inputx_post_utf8(running_machine &machine, const char *text);
void inputx_post_utf8_rate(running_machine &machine, const char *text, attotime rate);
int inputx_is_posting(running_machine &machine);
/* miscellaneous functions */
int input_classify_port(const input_field_config *field);
int input_has_input_class(running_machine &machine, int inputclass);
int input_player_number(const input_field_config *field);
int input_count_players(running_machine &machine);
inline running_machine &input_field_config::machine() const
{
return m_port.machine();
}
// temporary construction helpers
void field_config_insert(input_field_config &newfield, input_port_value &disallowedbits, astring &errorbuf);
void diplocation_list_alloc(input_field_config &field, const char *location, astring &errorbuf);
input_port_config *ioconfig_alloc_port(ioport_list &portlist, device_t &device, const char *tag);
input_port_config *ioconfig_modify_port(ioport_list &portlist, device_t &device, const char *tag);
input_field_config *ioconfig_alloc_field(input_port_config &port, int type, input_port_value defval, input_port_value mask, const char *name = NULL);
input_field_config *ioconfig_alloc_onoff(input_port_config &port, const char *name, input_port_value defval, input_port_value mask, const char *diplocation, astring &errorbuf);
input_setting_config *ioconfig_alloc_setting(input_field_config &field, input_port_value value, const char *name);
void ioconfig_field_add_char(input_field_config &field, unicode_char ch, astring &errorbuf);
void ioconfig_add_code(input_field_config &field, int which, input_code code);
#endif /* __INPTPORT_H__ */
| [
"cc2911@facebook.com"
] | cc2911@facebook.com |
44a97b4486477ed7471d1581e06347edbfba118e | bb9ea8638b4d5826c030f31a9dd54f90fd4de7f9 | /build/moc_qvalidatedlineedit.cpp | e3414fbd28bf57f249e74e41ab9fdda06436fea2 | [
"MIT"
] | permissive | mdtspain/MWC | 25a410801574b9f615dea2992119e8d9fed6e92e | 5805ddd7eaf0ab23e560277f7930e24011642e81 | refs/heads/master | 2020-05-29T14:41:14.875322 | 2016-06-13T18:54:30 | 2016-06-13T18:54:30 | 61,061,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,038 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'qvalidatedlineedit.h'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/qt/qvalidatedlineedit.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'qvalidatedlineedit.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_QValidatedLineEdit[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
19, 34, 40, 40, 0x0a,
41, 40, 40, 40, 0x08,
0 // eod
};
static const char qt_meta_stringdata_QValidatedLineEdit[] = {
"QValidatedLineEdit\0setValid(bool)\0"
"valid\0\0markValid()\0"
};
void QValidatedLineEdit::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
QValidatedLineEdit *_t = static_cast<QValidatedLineEdit *>(_o);
switch (_id) {
case 0: _t->setValid((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 1: _t->markValid(); break;
default: ;
}
}
}
const QMetaObjectExtraData QValidatedLineEdit::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject QValidatedLineEdit::staticMetaObject = {
{ &QLineEdit::staticMetaObject, qt_meta_stringdata_QValidatedLineEdit,
qt_meta_data_QValidatedLineEdit, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &QValidatedLineEdit::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *QValidatedLineEdit::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *QValidatedLineEdit::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QValidatedLineEdit))
return static_cast<void*>(const_cast< QValidatedLineEdit*>(this));
return QLineEdit::qt_metacast(_clname);
}
int QValidatedLineEdit::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QLineEdit::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"michaeltammerijn@Michael-Tammerijns-iMac.local"
] | michaeltammerijn@Michael-Tammerijns-iMac.local |
9f516d75be7a42010555a6b2805dbecc0c7e9fec | aa66f8ecb4bc4b7a80792e403d42351a090e1517 | /kmp.cpp | 6680c217121c4845c1698e308a940dd538410871 | [] | no_license | burg1ar/code | 4452c792641b002ff8deb904bd562e0630157346 | cd065e893c048c7ef275388142cbb48f03416ce5 | refs/heads/master | 2021-01-01T18:43:31.911630 | 2017-12-01T12:37:35 | 2017-12-01T12:37:35 | 98,412,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,940 | cpp | #include<iostream>
#include<string>
using namespace std;
int naive_matcher_v1(string text,string pattern){
int n=text.size();
int m=pattern.size();
int s,i;
for(s=0;s<n-m+1;++s){
for(i=0;i<m;++i){
if(text[s+i]!=pattern[i]) break;
}
if(i==m) return s;
}
return -1;
}
int naive_matcher_v2(string text,string pattern){
int n=text.size();
int m=pattern.size();
int i=0,j=0;
while(i<n && j<m){
if(text[i]==pattern[j]){
++i;++j;
}else{
i=i-j+1;j=0; //shift=i-j,increase shift by 1
}
}
if(j==m) return i-j;
else return -1;
}
int* prefix_function(string pattern){
int n=pattern.size();
int* next=new int[n]; //next[i]=0 for all i=0,1,...,n-1
int i=1,j=0;
while(i<n){
if(pattern[i]==pattern[j]){
next[i]=j+1;
++i;++j;
}else{
if(j>0){
j=next[j-1];
}else{
next[i]=0;
++i;
}
}
}
return next;
}
int kmp(string text,string pattern){
int* next=prefix_function(pattern);
int i=0,j=0;
while(i<text.size() && j<pattern.size()){
if(text[i]==pattern[j]){
++i;++j;
}else{
if(j>0){
j=next[j-1];
}else{
++i;
}
}
}
if(j==pattern.size()){
return i-j;
}else{
return -1;
}
}
void display(int arr[],int n){
for(int i=0;i<n;++i){
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main(){
string pattern="aaab";
int n=pattern.size();
int* next=new int[n];
next=prefix_function(pattern);
display(next,n);
string text="acacbbcaaabaabccabacacdb";
cout<<kmp(text,pattern)<<endl;
cout<<naive_matcher_v1(text,pattern)<<endl;
cout<<naive_matcher_v2(text,pattern)<<endl;
return 0;
}
| [
"921752421@qq.com"
] | 921752421@qq.com |
c94d0b3735c9d891051dc5a15bc37b1f6b8bc521 | dd16dbde81e611d7c8994c453b76595c0f9963f1 | /src/snd_wav.cpp | b36c70625ea5a94814421eb285e1c703438291a6 | [] | no_license | dreameatergames/Rizzo_Dreamplaces | f4e739d7e6a9bd6e262b00bbea0b33e78d323e57 | ba85ba171ea7da90d9baac1272478af2ee027951 | refs/heads/master | 2021-09-06T22:42:44.877874 | 2018-02-12T20:24:43 | 2018-02-12T20:24:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,850 | cpp | /*
Copyright (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to:
Free Software Foundation, Inc.
59 Temple Place - Suite 330
Boston, MA 02111-1307, USA
*/
#ifndef NO_SOUND
#include "quakedef.h"
#include "snd_main.h"
#include "snd_wav.h"
typedef struct wavinfo_s
{
int rate;
int width;
int channels;
int loopstart;
int samples;
int dataofs; // chunk starts this many bytes from file start
} wavinfo_t;
static unsigned char *data_p;
static unsigned char *iff_end;
static unsigned char *last_chunk;
static unsigned char *iff_data;
static int iff_chunk_len;
static short GetLittleShort(void)
{
short val;
val = BuffLittleShort (data_p);
data_p += 2;
return val;
}
static int GetLittleLong(void)
{
int val = 0;
val = BuffLittleLong (data_p);
data_p += 4;
return val;
}
static void FindNextChunk(char *name)
{
while (1)
{
data_p=last_chunk;
if (data_p >= iff_end)
{ // didn't find the chunk
data_p = NULL;
return;
}
data_p += 4;
iff_chunk_len = GetLittleLong();
if (iff_chunk_len < 0)
{
data_p = NULL;
return;
}
data_p -= 8;
last_chunk = data_p + 8 + ( (iff_chunk_len + 1) & ~1 );
if (!strncmp((const char *)data_p, name, 4))
return;
}
}
static void FindChunk(char *name)
{
last_chunk = iff_data;
FindNextChunk (name);
}
/*
static void DumpChunks(void)
{
char str[5];
str[4] = 0;
data_p=iff_data;
do
{
memcpy (str, data_p, 4);
data_p += 4;
iff_chunk_len = GetLittleLong();
Con_Printf("0x%x : %s (%d)\n", (int)(data_p - 4), str, iff_chunk_len);
data_p += (iff_chunk_len + 1) & ~1;
} while (data_p < iff_end);
}
*/
/*
============
GetWavinfo
============
*/
static wavinfo_t GetWavinfo (char *name, unsigned char *wav, int wavlength)
{
wavinfo_t info;
int i;
int format;
int samples;
memset (&info, 0, sizeof(info));
if (!wav)
return info;
iff_data = wav;
iff_end = wav + wavlength;
// find "RIFF" chunk
FindChunk("RIFF");
if (!(data_p && !strncmp((const char *)data_p+8, "WAVE", 4)))
{
Con_Print("Missing RIFF/WAVE chunks\n");
return info;
}
// get "fmt " chunk
iff_data = data_p + 12;
//DumpChunks ();
FindChunk("fmt ");
if (!data_p)
{
Con_Print("Missing fmt chunk\n");
return info;
}
data_p += 8;
format = GetLittleShort();
if (format != 1)
{
Con_Print("Microsoft PCM format only\n");
return info;
}
info.channels = GetLittleShort();
info.rate = GetLittleLong();
data_p += 4+2;
info.width = GetLittleShort() / 8;
// get cue chunk
FindChunk("cue ");
if (data_p)
{
data_p += 32;
info.loopstart = GetLittleLong();
// if the next chunk is a LIST chunk, look for a cue length marker
FindNextChunk ("LIST");
if (data_p)
{
if (!strncmp ((const char *)data_p + 28, "mark", 4))
{ // this is not a proper parse, but it works with cooledit...
data_p += 24;
i = GetLittleLong (); // samples in loop
info.samples = info.loopstart + i;
}
}
}
else
info.loopstart = -1;
// find data chunk
FindChunk("data");
if (!data_p)
{
Con_Print("Missing data chunk\n");
return info;
}
data_p += 4;
samples = GetLittleLong () / info.width / info.channels;
if (info.samples)
{
if (samples < info.samples)
{
Con_Printf ("Sound %s has a bad loop length\n", name);
info.samples = samples;
}
}
else
info.samples = samples;
info.dataofs = data_p - wav;
return info;
}
/*
====================
WAV_FetchSound
====================
*/
static const snd_buffer_t* WAV_FetchSound (channel_t* ch, unsigned int *start, unsigned int nbsampleframes)
{
*start = 0;
return (snd_buffer_t *)ch->sfx->fetcher_data;
}
/*
====================
WAV_FreeSfx
====================
*/
static void WAV_FreeSfx (sfx_t* sfx)
{
snd_buffer_t* sb = (snd_buffer_t *)sfx->fetcher_data;
// Free the sound buffer
sfx->memsize -= (sb->maxframes * sb->format.channels * sb->format.width) + sizeof (*sb) - sizeof (sb->samples);
Mem_Free(sb);
sfx->fetcher_data = NULL;
sfx->fetcher = NULL;
}
/*
====================
WAV_GetFormat
====================
*/
static const snd_format_t* WAV_GetFormat (sfx_t* sfx)
{
snd_buffer_t* sb = (snd_buffer_t *)sfx->fetcher_data;
return &sb->format;
}
const snd_fetcher_t wav_fetcher = { WAV_FetchSound, NULL, WAV_FreeSfx, WAV_GetFormat };
/*
==============
S_LoadWavFile
==============
*/
qboolean S_LoadWavFile (const char *filename, sfx_t *sfx)
{
fs_offset_t filesize;
unsigned char *data;
wavinfo_t info;
snd_format_t wav_format;
snd_buffer_t* sb;
// Already loaded?
if (sfx->fetcher != NULL)
return true;
// Load the file
data = FS_LoadFile(filename, snd_mempool, false, &filesize);
if (!data)
return false;
// Don't try to load it if it's not a WAV file
if (memcmp (data, "RIFF", 4) || memcmp (data + 8, "WAVE", 4))
{
Mem_Free(data);
return false;
}
Con_DPrintf ("Loading WAV file \"%s\"\n", filename);
info = GetWavinfo (sfx->name, data, (int)filesize);
if (info.channels < 1 || info.channels > 2) // Stereo sounds are allowed (intended for music)
{
Con_Printf("%s has an unsupported number of channels (%i)\n",sfx->name, info.channels);
Mem_Free(data);
return false;
}
//if (info.channels == 2)
// Log_Printf("stereosounds.log", "%s\n", sfx->name);
#if BYTE_ORDER != LITTLE_ENDIAN
// We must convert the WAV data from little endian
// to the machine endianess before resampling it
if (info.width == 2)
{
unsigned int len, i;
short* ptr;
len = info.samples * info.channels;
ptr = (short*)(data + info.dataofs);
for (i = 0; i < len; i++)
ptr[i] = LittleShort (ptr[i]);
}
#endif
wav_format.speed = info.rate;
wav_format.width = info.width;
wav_format.channels = info.channels;
sb = Snd_CreateSndBuffer (data + info.dataofs, info.samples, &wav_format, snd_renderbuffer->format.speed);
if (sb == NULL)
{
Mem_Free(data);
return false;
}
sfx->fetcher = &wav_fetcher;
sfx->fetcher_data = sb;
sfx->total_length = sb->nbframes;
sfx->memsize += sb->maxframes * sb->format.channels * sb->format.width + sizeof (*sb) - sizeof (sb->samples);
if (info.loopstart < 0)
sfx->loopstart = -1;
else
sfx->loopstart = (double)info.loopstart * (double)snd_renderbuffer->format.speed / (double)sb->format.speed;
sfx->flags &= ~SFXFLAG_STREAMED;
Mem_Free (data);
return true;
}
#endif
| [
"rizzoislandgame@gmail.com"
] | rizzoislandgame@gmail.com |
22466aadc7f2f12ec2ac96c86972d818941be2b6 | bf4614b62c44cbb7cb4630bcf0838b3723a359be | /src/globals.cpp | 0afc8838db64025a1f690d6345745e6c6764745d | [] | no_license | prickle/GameBloke | 4c9ca8910affc2b3ce27ce7b8ea9f9a45667d7f5 | e9f512f5f1753f27705b79a62eabfadc2c612678 | refs/heads/master | 2021-07-22T02:15:38.991893 | 2017-10-29T06:26:39 | 2017-10-29T06:26:39 | 108,696,158 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 486 | cpp | #include "globals.h"
FileManager *g_filemanager = NULL;
Cpu *g_cpu = NULL;
VM *g_vm = NULL;
PhysicalDisplay *g_display = NULL;
PhysicalKeyboard *g_keyboard = NULL;
PhysicalSpeaker *g_speaker = NULL;
PhysicalPrinter *g_printer = NULL;
uint16_t g_battery = 0;
uint16_t g_charge = 0;
int16_t g_volume = 15;
int8_t g_displayType = 3; // FIXME m_perfectcolor
uint8_t g_joyTrimX = 127;
uint8_t g_joyTrimY = 127;
uint8_t g_joySpeed = 5;
uint8_t g_screenSync = true;
bool biosRequest = false;
| [
"valves@alphalink.com.au"
] | valves@alphalink.com.au |
f3943ea1163843941dde24074d633a9aa21c5bc4 | 1af49694004c6fbc31deada5618dae37255ce978 | /components/exo/test/run_all_unittests.cc | a844f5a688b2c3594057bb0c06317032dda8adc7 | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | C++ | false | false | 842 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/test/launcher/unit_test_launcher.h"
#include "build/chromeos_buildflags.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "ash/test/ash_test_suite.h"
#else
#include "components/exo/test/exo_test_suite_aura.h"
#endif
#if !defined(OS_IOS)
#include "mojo/core/embedder/embedder.h"
#endif
int main(int argc, char** argv) {
#if BUILDFLAG(IS_CHROMEOS_ASH)
ash::AshTestSuite test_suite(argc, argv);
#else
exo::test::ExoTestSuiteAura test_suite(argc, argv);
#endif
#if !defined(OS_IOS)
mojo::core::Init();
#endif
return base::LaunchUnitTests(
argc, argv,
base::BindOnce(&base::TestSuite::Run, base::Unretained(&test_suite)));
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
222d4b5773b546d4c18204b059e439a712241cc4 | 00ed3f287739d07968a22d6c5eaedf3c9b9eedb6 | /base/include/multimedia/mmparam.h | 75f0ab08bf9c107bce434eff3442bd4a4ab4f476 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | halleyzhao/cow-mmf | afeffda4e43273e2f64b3323ae821ba785447e24 | 5aada0bd06533ee8100ed4385448856be8d5ac97 | refs/heads/master | 2021-05-08T20:51:38.875878 | 2018-01-31T03:02:09 | 2018-01-31T03:02:09 | 119,620,752 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,428 | h | /**
* Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __mmparam_H
#define __mmparam_H
#include <vector>
#include <string>
#include <multimedia/mm_types.h>
#include <multimedia/mm_errors.h>
#include <multimedia/mm_cpp_utils.h>
#include <multimedia/mm_refbase.h>
namespace YUNOS_MM {
class MMParam {
public:
MMParam();
MMParam(const MMParam & another);
MMParam(const MMParam * another);
~MMParam();
public:
mm_status_t writeInt32(int32_t val);
mm_status_t writeInt64(int64_t val);
mm_status_t writeFloat(float val);
mm_status_t writeDouble(double val);
mm_status_t writeCString(const char * val);
mm_status_t writePointer(const MMRefBaseSP & pointer);
mm_status_t writeRawPointer(uint8_t *pointer);
mm_status_t readInt32(int32_t * val) const;
mm_status_t readInt64(int64_t * val) const;
mm_status_t readFloat(float * val) const;
mm_status_t readDouble(double * val) const;
const char * readCString() const;
MMRefBaseSP readPointer() const;
mm_status_t readRawPointer(uint8_t **val) const;
int32_t readInt32() const;
int64_t readInt64() const;
float readFloat() const;
double readDouble() const;
uint8_t* readRawPointer() const;
public:
const MMParam & operator=(const MMParam & another);
private:
template<class T>
mm_status_t writeFixed(T val);
template<class T>
mm_status_t readFixed(T * val) const;
void copy(const MMParam * another);
private:
uint8_t * mData;
size_t mDataSize;
mutable size_t mDataWritePos;
mutable size_t mDataReadPos;
std::vector<std::string> mStrings;
mutable size_t mStringReadPos;
std::vector<MMRefBaseSP> mPointers;
mutable size_t mPointersReadPos;
DECLARE_LOGTAG()
};
typedef MMSharedPtr<MMParam> MMParamSP;
}
#endif // __mmparam_H
| [
"aihua.zah@alibaba-inc.com"
] | aihua.zah@alibaba-inc.com |
b56bd926e8415f28968bf80a925c8f1c559fc70f | 44d0fa41a7682480b3f7c13801db83c7da360655 | /Gunz_The_MMORPG/RNavigationNode.cpp | ddee99cf9198113eac85715960b5f7c5129c2be7 | [] | no_license | TheChayo/gunz-the-tps-mmorpg | e74de0f2084ade5de7b77b083521bfa57567d398 | b5880e60891dd7aa3063541865463de186227616 | refs/heads/master | 2016-08-12T11:17:59.523436 | 2012-11-10T03:09:05 | 2012-11-10T03:09:05 | 55,033,954 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 6,678 | cpp | #include "stdafx.h"
#include "RNavigationNode.h"
#include "RTypes.h"
#include <crtdbg.h>
RNavigationNode::RNavigationNode() : RAStarNode(), bSelected(false), m_iArrivalLink(0), m_iID(-1)
{
}
RNavigationNode::~RNavigationNode()
{
}
void RNavigationNode::Init(int nID, const rvector& v1, const rvector& v2, const rvector& v3)
{
m_iID = nID;
m_Vertex[0] = v1;
m_Vertex[1] = v2;
m_Vertex[2] = v3;
m_Links[0] = 0;
m_Links[1] = 0;
m_Links[2] = 0;
ComputeNodeData();
}
void RNavigationNode::ComputeNodeData()
{
// create 2D versions of our verticies
rvector2 Point1(m_Vertex[VERT_A].x,m_Vertex[VERT_A].y);
rvector2 Point2(m_Vertex[VERT_B].x,m_Vertex[VERT_B].y);
rvector2 Point3(m_Vertex[VERT_C].x,m_Vertex[VERT_C].y);
// innitialize our sides
m_Side[SIDE_AB].SetLine(Point1,Point2); // line AB
m_Side[SIDE_BC].SetLine(Point2,Point3); // line BC
m_Side[SIDE_CA].SetLine(Point3,Point1); // line CA
D3DXPlaneFromPoints(&m_Plane, &m_Vertex[VERT_A], &m_Vertex[VERT_B], &m_Vertex[VERT_C]);
// compute midpoint as centroid of polygon
m_CenterPos.x=((m_Vertex[VERT_A].x + m_Vertex[VERT_B].x + m_Vertex[VERT_C].x)/3);
m_CenterPos.y=((m_Vertex[VERT_A].y + m_Vertex[VERT_B].y + m_Vertex[VERT_C].y)/3);
m_CenterPos.z=((m_Vertex[VERT_A].z + m_Vertex[VERT_B].z + m_Vertex[VERT_C].z)/3);
// compute the midpoint of each cell wall
m_WallMidpoint[0].x = (m_Vertex[VERT_A].x + m_Vertex[VERT_B].x)/2.0f;
m_WallMidpoint[0].y = (m_Vertex[VERT_A].y + m_Vertex[VERT_B].y)/2.0f;
m_WallMidpoint[0].z = (m_Vertex[VERT_A].z + m_Vertex[VERT_B].z)/2.0f;
m_WallMidpoint[1].x = (m_Vertex[VERT_B].x + m_Vertex[VERT_C].x)/2.0f;
m_WallMidpoint[1].y = (m_Vertex[VERT_B].y + m_Vertex[VERT_C].y)/2.0f;
m_WallMidpoint[1].z = (m_Vertex[VERT_B].z + m_Vertex[VERT_C].z)/2.0f;
m_WallMidpoint[2].x = (m_Vertex[VERT_C].x + m_Vertex[VERT_A].x)/2.0f;
m_WallMidpoint[2].y = (m_Vertex[VERT_C].y + m_Vertex[VERT_A].y)/2.0f;
m_WallMidpoint[2].z = (m_Vertex[VERT_C].z + m_Vertex[VERT_A].z)/2.0f;
// compute the distances between the wall midpoints
m_WallDistance[0] = _REALSPACE2::Magnitude(m_WallMidpoint[0] - m_WallMidpoint[1]);
m_WallDistance[1] = _REALSPACE2::Magnitude(m_WallMidpoint[1] - m_WallMidpoint[2]);
m_WallDistance[2] = _REALSPACE2::Magnitude(m_WallMidpoint[2] - m_WallMidpoint[0]);
}
bool RNavigationNode::RequestLink(const rvector& PointA, const rvector& PointB, RNavigationNode* pCaller)
{
if (m_Vertex[VERT_A] == PointA)
{
if (m_Vertex[VERT_B] == PointB)
{
m_Links[SIDE_AB] = pCaller;
return true;
}
else if (m_Vertex[VERT_C] == PointB)
{
m_Links[SIDE_CA] = pCaller;
return true;
}
}
else if (m_Vertex[VERT_B] == PointA)
{
if (m_Vertex[VERT_A] == PointB)
{
m_Links[SIDE_AB] = pCaller;
return true;
}
else if (m_Vertex[VERT_C] == PointB)
{
m_Links[SIDE_BC] = pCaller;
return true;
}
}
else if (m_Vertex[VERT_C] == PointA)
{
if (m_Vertex[VERT_A] == PointB)
{
m_Links[SIDE_CA] = pCaller;
return true;
}
else if (m_Vertex[VERT_B] == PointB)
{
m_Links[SIDE_BC] = pCaller;
return true;
}
}
return false;
}
bool RNavigationNode::IsPointInNodeColumn(const rvector& TestPoint) const
{
rvector2 pos = rvector2(TestPoint.x,TestPoint.y);
return (IsPointInNodeColumn(pos));
}
bool RNavigationNode::IsPointInNodeColumn(const rvector2& TestPoint) const
{
int InteriorCount = 0;
for (int i=0;i<3;i++)
{
rline2d::POINT_CLASSIFICATION SideResult = m_Side[i].ClassifyPoint(TestPoint);
// 선위의 점도 삼각형 안에 있는걸로 간주한다.
if (SideResult != rline2d::RIGHT_SIDE)
{
InteriorCount++;
}
}
return (InteriorCount == 3);
return false;
}
bool RNavigationNode::ForcePointToNodeColumn(rvector2& TestPoint) const
{
bool PointAltered = false;
// create a motion path from the center of the cell to our point
rline2d TestPath(rvector2(m_CenterPos.x, m_CenterPos.y), TestPoint);
rvector2 PointOfIntersection;
NODE_SIDE Side;
RNavigationNode* pNextNode;
PATH_RESULT result = ClassifyPathToNode(TestPath, &pNextNode, Side, &PointOfIntersection);
// compare this path to the cell.
if (result == EXITING_NODE)
{
rvector2 PathDirection(PointOfIntersection.x - m_CenterPos.x, PointOfIntersection.y - m_CenterPos.y);
PathDirection *= 0.9f;
TestPoint.x = m_CenterPos.x + PathDirection.x;
TestPoint.y = m_CenterPos.y + PathDirection.y;
return (true);
}
else if (result == NO_RELATIONSHIP)
{
TestPoint.x = m_CenterPos.x;
TestPoint.y = m_CenterPos.y;
return (true);
}
return (false);
}
bool RNavigationNode::ForcePointToNodeColumn(rvector& TestPoint)const
{
rvector2 TestPoint2D(TestPoint.x,TestPoint.y);
bool PointAltered = ForcePointToNodeColumn(TestPoint2D);
if (PointAltered)
{
TestPoint.x=TestPoint2D.x;
TestPoint.y=TestPoint2D.y;
}
return (PointAltered);
}
void RNavigationNode::MapVectorHeightToNode(rvector& MotionPoint) const
{
// ax + by + cz + d = 0
// cz = -(ax+by+d)
// z = -(ax+by+d)/b
if (m_Plane.c)
{
MotionPoint.z = ( -(m_Plane.a*MotionPoint.x + m_Plane.b*MotionPoint.y+m_Plane.d)/m_Plane.c);
}
else
{
MotionPoint.z = 0.0f;
}
}
RNavigationNode::PATH_RESULT RNavigationNode::ClassifyPathToNode(const rline2d& MotionPath, RNavigationNode** ppNextNode,
NODE_SIDE& side, rvector2* pPointOfIntersection) const
{
int nInteriorCount = 0;
for (int i=0; i<3; ++i)
{
if (m_Side[i].ClassifyPoint(MotionPath.end) != rline2d::LEFT_SIDE)
{
if (m_Side[i].ClassifyPoint(MotionPath.start) != rline2d::RIGHT_SIDE)
{
rline2d::LINE_CLASSIFICATION IntersectResult = MotionPath.Intersection(m_Side[i], pPointOfIntersection);
if (IntersectResult == rline2d::SEGMENTS_INTERSECT || IntersectResult == rline2d::A_BISECTS_B)
{
*ppNextNode = m_Links[i];
side = (NODE_SIDE)i;
return (EXITING_NODE);
}
}
}
else
{
nInteriorCount++;
}
}
if (nInteriorCount == 3)
{
return (ENDING_NODE);
}
return (NO_RELATIONSHIP);
}
float RNavigationNode::GetSuccessorCost(RAStarNode* pSuccessor)
{
_ASSERT(pSuccessor != NULL);
float fWeight = (m_fWeight + pSuccessor->GetWeight()) / 2.0f;
rvector d = m_CenterPos - ((RNavigationNode*)pSuccessor)->m_CenterPos;
return (D3DXVec3LengthSq(&d) * fWeight);
}
float RNavigationNode::GetHeuristicCost(RAStarNode* pGoal)
{
_ASSERT(pGoal != NULL);
rvector d = m_CenterPos - ((RNavigationNode*)pGoal)->m_CenterPos;
return D3DXVec3LengthSq(&d);
} | [
"Celestialkey@fbef6bb8-bedc-06fa-898d-b3a7711f07bf"
] | Celestialkey@fbef6bb8-bedc-06fa-898d-b3a7711f07bf |
b93d3bdd6c5287a8af1da141068513e2010e82b9 | cbaeed5cb57c4a7e047f3350da380bb7ae80f399 | /7. Greedy Algorithm/OnlineBookStore.cpp | adcc9b8dcd1a66f2086a85ca8c6f4dc6d3b171c8 | [] | no_license | seungmin97/algorithmm | 861f0c240c63c1ccf2a5740ed7b7336289c300f8 | 92cd133861aa306a337ac2d84065768fdd2f091e | refs/heads/master | 2020-05-02T17:19:37.808415 | 2019-05-28T01:37:02 | 2019-05-28T01:37:02 | 178,094,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,070 | cpp | //
// Created by 이승민 on 2019-05-03.
//
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#define MAX INT_MAX
using namespace std;
class Book {
private:
int price;
int remain;
public:
vector <pair<int, int>> vec;
Book(){
this->price = 0;
this->remain = 0;
}
int calculate_price();
};
int Book::calculate_price() {
for (int i = 0; i < vec.size(); ++i) {
if(i == 0){
price += vec[i].first;
}
else {
if (vec[i - 1].second <= vec[i].first) {
int temp = 0;
temp = vec[i].first - vec[i-1].second;
if(remain != 0){
if(temp > remain){
price += temp - remain;
remain = 0;
}
else{
remain -= temp;
}
}
else{
price += temp;
}
}
else{
remain += vec[i-1].second - vec[i].first;
}
}
}
return price;
}
bool cmp(const pair<int, int> &a, const pair<int, int> &b)
{
return a.second > b.second;
}
int main() {
int num;
cin >> num;
int min;
for (int k = 0; k < num; k++) {
int store, book;
cin >> book >> store;
// min = MAX;
vector <Book> v(store);
for (int i = 0; i < book; i++) {
for (int j = 0; j < store; j++) {
int temp1, temp2;
cin >> temp1 >> temp2;
v[j].vec.push_back(make_pair(temp1, temp2));
}
}
for (int i = 0; i < store; ++i) {
sort(v[i].vec.begin(), v[i].vec.end(), cmp);
int result = v[i].calculate_price();
if(i == 0){
min = result;
}
else if (min > result) {
min = result;
}
}
cout << min << endl;
}
return 0;
} | [
"lsm0341@naver.com"
] | lsm0341@naver.com |
2b4b74059d3e74b630495b606851665b9e233281 | 9b8ee7a681cf875fdc4322f568f7400fa67fc14c | /standard_lidar4_ws/devel/include/ltme_node/QueryHardwareVersionRequest.h | 678f1f5a9e4a9a1a7e1039574e518f2c161974f0 | [] | no_license | jie104/learngit | 8442ddd9f460710ad0d504749e83647faae085b7 | b5aed9eef4d548939d28c5fb11cf30cd18350d42 | refs/heads/master | 2023-04-28T20:37:43.518840 | 2023-04-16T14:54:53 | 2023-04-16T14:54:53 | 329,828,443 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,477 | h | // Generated by gencpp from file ltme_node/QueryHardwareVersionRequest.msg
// DO NOT EDIT!
#ifndef LTME_NODE_MESSAGE_QUERYHARDWAREVERSIONREQUEST_H
#define LTME_NODE_MESSAGE_QUERYHARDWAREVERSIONREQUEST_H
#include <string>
#include <vector>
#include <memory>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace ltme_node
{
template <class ContainerAllocator>
struct QueryHardwareVersionRequest_
{
typedef QueryHardwareVersionRequest_<ContainerAllocator> Type;
QueryHardwareVersionRequest_()
{
}
QueryHardwareVersionRequest_(const ContainerAllocator& _alloc)
{
(void)_alloc;
}
typedef boost::shared_ptr< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> const> ConstPtr;
}; // struct QueryHardwareVersionRequest_
typedef ::ltme_node::QueryHardwareVersionRequest_<std::allocator<void> > QueryHardwareVersionRequest;
typedef boost::shared_ptr< ::ltme_node::QueryHardwareVersionRequest > QueryHardwareVersionRequestPtr;
typedef boost::shared_ptr< ::ltme_node::QueryHardwareVersionRequest const> QueryHardwareVersionRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace ltme_node
namespace ros
{
namespace message_traits
{
template <class ContainerAllocator>
struct IsMessage< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> >
{
static const char* value()
{
return "d41d8cd98f00b204e9800998ecf8427e";
}
static const char* value(const ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xd41d8cd98f00b204ULL;
static const uint64_t static_value2 = 0xe9800998ecf8427eULL;
};
template<class ContainerAllocator>
struct DataType< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> >
{
static const char* value()
{
return "ltme_node/QueryHardwareVersionRequest";
}
static const char* value(const ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> >
{
static const char* value()
{
return "\n"
;
}
static const char* value(const ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream&, T)
{}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct QueryHardwareVersionRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream&, const std::string&, const ::ltme_node::QueryHardwareVersionRequest_<ContainerAllocator>&)
{}
};
} // namespace message_operations
} // namespace ros
#endif // LTME_NODE_MESSAGE_QUERYHARDWAREVERSIONREQUEST_H
| [
"1430974500@qq.com"
] | 1430974500@qq.com |
c3d86ac417a691bbfb58847655a86028922172bd | bdffc5173555cf6fbaf40bee6f3e868884d584ab | /Sources/VertexFormat.cpp | 094098e2025cd1ef9a5c8f898ccae9a544dbf91d | [] | no_license | Mantharis/Vulkan | 38d2da1d15ec79f874de20c345173d41184c867f | a4647eb1c8d71d28e4b3b95967d91689440b7bfa | refs/heads/master | 2020-08-22T13:40:01.988000 | 2020-01-04T11:21:50 | 2020-01-04T11:21:50 | 216,407,049 | 0 | 0 | null | 2019-11-10T22:17:06 | 2019-10-20T18:21:19 | C++ | UTF-8 | C++ | false | false | 1,824 | cpp |
#include "VertexFormat.h"
VkVertexInputBindingDescription Vertex::getBindingDescription()
{
VkVertexInputBindingDescription bindingDescription = {};
bindingDescription.binding = 0;
bindingDescription.stride = sizeof(Vertex);
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return bindingDescription;
}
array<VkVertexInputAttributeDescription, 6> Vertex::getAttributeDescriptions()
{
array<VkVertexInputAttributeDescription, 6> attributeDescriptions = {};
attributeDescriptions[0].binding = 0;
attributeDescriptions[0].location = 0;
attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[0].offset = offsetof(Vertex, pos);
attributeDescriptions[1].binding = 0;
attributeDescriptions[1].location = 1;
attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[1].offset = offsetof(Vertex, color);
attributeDescriptions[2].binding = 0;
attributeDescriptions[2].location = 2;
attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescriptions[2].offset = offsetof(Vertex, texCoord);
attributeDescriptions[3].binding = 0;
attributeDescriptions[3].location = 3;
attributeDescriptions[3].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[3].offset = offsetof(Vertex, normal);
attributeDescriptions[4].binding = 0;
attributeDescriptions[4].location = 4;
attributeDescriptions[4].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[4].offset = offsetof(Vertex, tangent);
attributeDescriptions[5].binding = 0;
attributeDescriptions[5].location = 5;
attributeDescriptions[5].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[5].offset = offsetof(Vertex, bitangent);
return attributeDescriptions;
}
| [
"noreply@github.com"
] | noreply@github.com |
2626cc77231dd6ee3fe5f24a9812f7b65b8d5207 | 01a8d4f2dd5de176287699b5e659b646011427a2 | /FELICITY/Code_Generation/Interpolation/Unit_Test/Dim_2/Hdiv/Interpolation_Code_AutoGen/Coef_Functions/Data_Type_v_restricted_to_Gamma.cc | 34fca45930ab619347e929bbc66c1c7d3b4586b2 | [
"BSD-3-Clause",
"MIT"
] | permissive | brianchowlab/BcLOV4-FEM | 2bd2286011f5d09d01a9973c59023031612b63b2 | 27432974422d42b4fe3c8cc79bcdd5cb14a800a7 | refs/heads/main | 2023-04-16T08:27:57.927561 | 2022-05-27T15:26:46 | 2022-05-27T15:26:46 | 318,320,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,948 | cc | /*
============================================================================================
This class points to outside MATLAB data which contains info about a given FE function.
NOTE: portions of this code are automatically generated!
Copyright (c) 01-18-2018, Shawn W. Walker
============================================================================================
*/
/*------------ BEGIN: Auto Generate ------------*/
// define the name of the FEM function (should be the same as the filename of this file)
#define SpecificNAME "v"
#define SpecificFUNC Data_Type_v_restricted_to_Gamma
#define SpecificFUNC_str "Data_Type_v_restricted_to_Gamma"
// set the type of function space
#define SPACE_type "CG - brezzi_douglas_marini_deg1_dim2"
// set the number of cartesian tuple components (m*n) = 1 * 1
#define NC 1
// NOTE: the (i,j) tuple component is accessed by the linear index k = i + (j-1)*m
// set the number of quad points
#define NQ 1
// set the number of basis functions
#define NB 6
/*------------ END: Auto Generate ------------*/
/*------------ BEGIN: Auto Generate ------------*/
/***************************************************************************************/
/* C++ (Specific) FEM Function class definition */
class SpecificFUNC
{
public:
// pointer to basis function that drives this coefficient function
const Data_Type_BDM1_phi_restricted_to_Gamma* basis_func;
double* Node_Value[NC]; // node values
char* Name; // specifies the name of the finite element function itself
char* CPP_Routine; // specifies the name of the C++ routine itself (only needed for debugging)
char* Type; // specifies the name of function space (only needed for debugging)
int Num_Nodes; // number of nodes (number of global DoFs)
int Num_Comp; // number of (scalar) components (i.e. is it a vector or scalar?)
int Num_QP; // number of quadrature points used
// data structure containing information on the function evaluations.
// Note: this data is evaluated at several quadrature points!
// coefficient function evaluated at a quadrature point in reference element
VEC_2x1 Func_vv_Value[NC][NQ];
// constructor
SpecificFUNC ();
~SpecificFUNC (); // destructor
void Setup_Function_Space(const mxArray*, const Data_Type_BDM1_phi_restricted_to_Gamma*);
void Compute_Func();
private:
};
/*------------ END: Auto Generate ------------*/
/*------------ BEGIN: Auto Generate ------------*/
/***************************************************************************************/
/* constructor */
SpecificFUNC::SpecificFUNC ()
{
Name = (char*) SpecificNAME;
CPP_Routine = (char*) SpecificFUNC_str;
Type = (char*) SPACE_type;
Num_Nodes = 0;
Num_Comp = NC;
Num_QP = NQ;
// init pointers
basis_func = NULL;
for (int nc_i = 0; (nc_i < Num_Comp); nc_i++)
Node_Value[nc_i] = NULL;
// init everything to zero
for (int qp_i = 0; (qp_i < Num_QP); qp_i++)
for (int nc_i = 0; (nc_i < Num_Comp); nc_i++)
Func_vv_Value[nc_i][qp_i].Set_To_Zero();
}
/***************************************************************************************/
/*------------ END: Auto Generate ------------*/
/***************************************************************************************/
/* DE-structor */
SpecificFUNC::~SpecificFUNC ()
{
}
/***************************************************************************************/
/*------------ BEGIN: Auto Generate ------------*/
/***************************************************************************************/
/* put incoming function data from MATLAB into a nice struct */
void SpecificFUNC::Setup_Function_Space(const mxArray* Values, // inputs
const Data_Type_BDM1_phi_restricted_to_Gamma* basis_func_input) // inputs
{
basis_func = basis_func_input;
/*------------ END: Auto Generate ------------*/
// get the number of columns (components)
int CHK_Num_Comp = (int) mxGetN(Values);
// get the number of vertices
int Temp_Num_Nodes = (int) mxGetM(Values);
/* BEGIN: Error Checking */
if (CHK_Num_Comp != Num_Comp)
{
mexPrintf("ERROR: Function Nodal Value List for %s has %d columns; expected %d columns.\n", Name, CHK_Num_Comp, Num_Comp);
mexPrintf("ERROR: You should check the function: Name = %s, Type = %s!\n",Name,Type);
mexErrMsgTxt("ERROR: number of function components must match!");
}
if (Temp_Num_Nodes < basis_func->Num_Nodes)
{
mexPrintf("ERROR: Function Nodal Value List for %s has %d rows; expected at least %d rows.\n", Name, Temp_Num_Nodes, basis_func->Num_Nodes);
mexPrintf("ERROR: You should check the function: Name = %s, Type = %s, \n",Name,Type);
mexPrintf("ERROR: and make sure you are using the correct DoFmap.\n");
mexErrMsgTxt("ERROR: number of given function values must >= what the DoFmap references!");
}
if (basis_func->Num_Basis != NB)
{
mexPrintf("ERROR: Coefficient Function %s has %d basis functions,\n", Name, NB);
mexPrintf("ERROR: but reference function space has %d basis functions,\n", basis_func->Num_Basis);
mexPrintf("ERROR: You should check the function: Name = %s, Type = %s, \n",Name,Type);
mexPrintf("ERROR: and make sure you are using the correct DoFmap.\n");
mexErrMsgTxt("ERROR: number of basis functions describing function must match!");
}
/* END: Error Checking */
// if we make it here, then update the number of DoFs
Num_Nodes = Temp_Num_Nodes;
// split up the columns of the node data
Node_Value[0] = mxGetPr(Values);
for (int nc_i = 1; (nc_i < Num_Comp); nc_i++)
Node_Value[nc_i] = Node_Value[nc_i-1] + Num_Nodes;
}
/***************************************************************************************/
/*------------ BEGIN: Auto Generate ------------*/
/***************************************************************************************/
/* compute the local transformation from the standard reference element
to an element in the Domain */
void SpecificFUNC::Compute_Func()
{
// get current FE space element index
const int elem_index = basis_func->Mesh->Domain->Sub_Cell_Index;
int kc[NB]; // for indexing through the function's DoFmap
basis_func->Get_Local_to_Global_DoFmap(elem_index, kc);
/*------------ BEGIN: Auto Generate ------------*/
/*** compute coefficient function quantities ***/
// get coefficient function values
// loop through quad points
for (int qp_i = 0; (qp_i < Num_QP); qp_i++)
{
// loop through all components (indexing is in the C style)
for (int nc_i = 0; (nc_i < Num_Comp); nc_i++)
{
SCALAR NodeV;
NodeV.a = Node_Value[nc_i][kc[0]];
Scalar_Mult_Vector(basis_func->Func_vv_Value[0][qp_i], NodeV, Func_vv_Value[nc_i][qp_i]); // first basis function
// sum over basis functions
for (int basis_i = 1; (basis_i < NB); basis_i++)
{
NodeV.a = Node_Value[nc_i][kc[basis_i]];
VEC_2x1 temp_vec;
Scalar_Mult_Vector(basis_func->Func_vv_Value[basis_i][qp_i], NodeV, temp_vec);
Add_Vector_Self(temp_vec, Func_vv_Value[nc_i][qp_i]);
}
}
}
/*------------ END: Auto Generate ------------*/
}
/***************************************************************************************/
/*------------ END: Auto Generate ------------*/
// remove those macros!
#undef SpecificNAME
#undef SpecificFUNC
#undef SpecificFUNC_str
#undef SPACE_type
#undef NC
#undef NQ
#undef NB
/***/
| [
"ikuznet1@users.noreply.github.com"
] | ikuznet1@users.noreply.github.com |
6c932480b7dea563a5ce1448df2171f5501a0cf9 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /base/third_party/double_conversion/double-conversion/bignum.cc | d858c16ca00049d8a1516ae757b9930ef0e42c7b | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 24,714 | cc | // Copyright 2010 the V8 project authors. 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 Google 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.
#include <algorithm>
#include <cstring>
#include "bignum.h"
#include "utils.h"
namespace double_conversion {
Bignum::Chunk& Bignum::RawBigit(const int index) {
DOUBLE_CONVERSION_ASSERT(static_cast<unsigned>(index) < kBigitCapacity);
return bigits_buffer_[index];
}
const Bignum::Chunk& Bignum::RawBigit(const int index) const {
DOUBLE_CONVERSION_ASSERT(static_cast<unsigned>(index) < kBigitCapacity);
return bigits_buffer_[index];
}
template<typename S>
static int BitSize(const S value) {
(void) value; // Mark variable as used.
return 8 * sizeof(value);
}
// Guaranteed to lie in one Bigit.
void Bignum::AssignUInt16(const uint16_t value) {
DOUBLE_CONVERSION_ASSERT(kBigitSize >= BitSize(value));
Zero();
if (value > 0) {
RawBigit(0) = value;
used_bigits_ = 1;
}
}
void Bignum::AssignUInt64(uint64_t value) {
Zero();
for(int i = 0; value > 0; ++i) {
RawBigit(i) = value & kBigitMask;
value >>= kBigitSize;
++used_bigits_;
}
}
void Bignum::AssignBignum(const Bignum& other) {
exponent_ = other.exponent_;
for (int i = 0; i < other.used_bigits_; ++i) {
RawBigit(i) = other.RawBigit(i);
}
used_bigits_ = other.used_bigits_;
}
static uint64_t ReadUInt64(const Vector<const char> buffer,
const int from,
const int digits_to_read) {
uint64_t result = 0;
for (int i = from; i < from + digits_to_read; ++i) {
const int digit = buffer[i] - '0';
DOUBLE_CONVERSION_ASSERT(0 <= digit && digit <= 9);
result = result * 10 + digit;
}
return result;
}
void Bignum::AssignDecimalString(const Vector<const char> value) {
// 2^64 = 18446744073709551616 > 10^19
static const int kMaxUint64DecimalDigits = 19;
Zero();
int length = value.length();
unsigned pos = 0;
// Let's just say that each digit needs 4 bits.
while (length >= kMaxUint64DecimalDigits) {
const uint64_t digits = ReadUInt64(value, pos, kMaxUint64DecimalDigits);
pos += kMaxUint64DecimalDigits;
length -= kMaxUint64DecimalDigits;
MultiplyByPowerOfTen(kMaxUint64DecimalDigits);
AddUInt64(digits);
}
const uint64_t digits = ReadUInt64(value, pos, length);
MultiplyByPowerOfTen(length);
AddUInt64(digits);
Clamp();
}
static uint64_t HexCharValue(const int c) {
if ('0' <= c && c <= '9') {
return c - '0';
}
if ('a' <= c && c <= 'f') {
return 10 + c - 'a';
}
DOUBLE_CONVERSION_ASSERT('A' <= c && c <= 'F');
return 10 + c - 'A';
}
// Unlike AssignDecimalString(), this function is "only" used
// for unit-tests and therefore not performance critical.
void Bignum::AssignHexString(Vector<const char> value) {
Zero();
// Required capacity could be reduced by ignoring leading zeros.
EnsureCapacity(((value.length() * 4) + kBigitSize - 1) / kBigitSize);
DOUBLE_CONVERSION_ASSERT(sizeof(uint64_t) * 8 >= kBigitSize + 4); // TODO: static_assert
// Accumulates converted hex digits until at least kBigitSize bits.
// Works with non-factor-of-four kBigitSizes.
uint64_t tmp = 0; // Accumulates converted hex digits until at least
for (int cnt = 0; !value.is_empty(); value.pop_back()) {
tmp |= (HexCharValue(value.last()) << cnt);
if ((cnt += 4) >= kBigitSize) {
RawBigit(used_bigits_++) = (tmp & kBigitMask);
cnt -= kBigitSize;
tmp >>= kBigitSize;
}
}
if (tmp > 0) {
RawBigit(used_bigits_++) = tmp;
}
Clamp();
}
void Bignum::AddUInt64(const uint64_t operand) {
if (operand == 0) {
return;
}
Bignum other;
other.AssignUInt64(operand);
AddBignum(other);
}
void Bignum::AddBignum(const Bignum& other) {
DOUBLE_CONVERSION_ASSERT(IsClamped());
DOUBLE_CONVERSION_ASSERT(other.IsClamped());
// If this has a greater exponent than other append zero-bigits to this.
// After this call exponent_ <= other.exponent_.
Align(other);
// There are two possibilities:
// aaaaaaaaaaa 0000 (where the 0s represent a's exponent)
// bbbbb 00000000
// ----------------
// ccccccccccc 0000
// or
// aaaaaaaaaa 0000
// bbbbbbbbb 0000000
// -----------------
// cccccccccccc 0000
// In both cases we might need a carry bigit.
EnsureCapacity(1 + (std::max)(BigitLength(), other.BigitLength()) - exponent_);
Chunk carry = 0;
int bigit_pos = other.exponent_ - exponent_;
DOUBLE_CONVERSION_ASSERT(bigit_pos >= 0);
for (int i = used_bigits_; i < bigit_pos; ++i) {
RawBigit(i) = 0;
}
for (int i = 0; i < other.used_bigits_; ++i) {
const Chunk my = (bigit_pos < used_bigits_) ? RawBigit(bigit_pos) : 0;
const Chunk sum = my + other.RawBigit(i) + carry;
RawBigit(bigit_pos) = sum & kBigitMask;
carry = sum >> kBigitSize;
++bigit_pos;
}
while (carry != 0) {
const Chunk my = (bigit_pos < used_bigits_) ? RawBigit(bigit_pos) : 0;
const Chunk sum = my + carry;
RawBigit(bigit_pos) = sum & kBigitMask;
carry = sum >> kBigitSize;
++bigit_pos;
}
used_bigits_ = (std::max)(bigit_pos, static_cast<int>(used_bigits_));
DOUBLE_CONVERSION_ASSERT(IsClamped());
}
void Bignum::SubtractBignum(const Bignum& other) {
DOUBLE_CONVERSION_ASSERT(IsClamped());
DOUBLE_CONVERSION_ASSERT(other.IsClamped());
// We require this to be bigger than other.
DOUBLE_CONVERSION_ASSERT(LessEqual(other, *this));
Align(other);
const int offset = other.exponent_ - exponent_;
Chunk borrow = 0;
int i;
for (i = 0; i < other.used_bigits_; ++i) {
DOUBLE_CONVERSION_ASSERT((borrow == 0) || (borrow == 1));
const Chunk difference = RawBigit(i + offset) - other.RawBigit(i) - borrow;
RawBigit(i + offset) = difference & kBigitMask;
borrow = difference >> (kChunkSize - 1);
}
while (borrow != 0) {
const Chunk difference = RawBigit(i + offset) - borrow;
RawBigit(i + offset) = difference & kBigitMask;
borrow = difference >> (kChunkSize - 1);
++i;
}
Clamp();
}
void Bignum::ShiftLeft(const int shift_amount) {
if (used_bigits_ == 0) {
return;
}
exponent_ += (shift_amount / kBigitSize);
const int local_shift = shift_amount % kBigitSize;
EnsureCapacity(used_bigits_ + 1);
BigitsShiftLeft(local_shift);
}
void Bignum::MultiplyByUInt32(const uint32_t factor) {
if (factor == 1) {
return;
}
if (factor == 0) {
Zero();
return;
}
if (used_bigits_ == 0) {
return;
}
// The product of a bigit with the factor is of size kBigitSize + 32.
// Assert that this number + 1 (for the carry) fits into double chunk.
DOUBLE_CONVERSION_ASSERT(kDoubleChunkSize >= kBigitSize + 32 + 1);
DoubleChunk carry = 0;
for (int i = 0; i < used_bigits_; ++i) {
const DoubleChunk product = static_cast<DoubleChunk>(factor) * RawBigit(i) + carry;
RawBigit(i) = static_cast<Chunk>(product & kBigitMask);
carry = (product >> kBigitSize);
}
while (carry != 0) {
EnsureCapacity(used_bigits_ + 1);
RawBigit(used_bigits_) = carry & kBigitMask;
used_bigits_++;
carry >>= kBigitSize;
}
}
void Bignum::MultiplyByUInt64(const uint64_t factor) {
if (factor == 1) {
return;
}
if (factor == 0) {
Zero();
return;
}
if (used_bigits_ == 0) {
return;
}
DOUBLE_CONVERSION_ASSERT(kBigitSize < 32);
uint64_t carry = 0;
const uint64_t low = factor & 0xFFFFFFFF;
const uint64_t high = factor >> 32;
for (int i = 0; i < used_bigits_; ++i) {
const uint64_t product_low = low * RawBigit(i);
const uint64_t product_high = high * RawBigit(i);
const uint64_t tmp = (carry & kBigitMask) + product_low;
RawBigit(i) = tmp & kBigitMask;
carry = (carry >> kBigitSize) + (tmp >> kBigitSize) +
(product_high << (32 - kBigitSize));
}
while (carry != 0) {
EnsureCapacity(used_bigits_ + 1);
RawBigit(used_bigits_) = carry & kBigitMask;
used_bigits_++;
carry >>= kBigitSize;
}
}
void Bignum::MultiplyByPowerOfTen(const int exponent) {
static const uint64_t kFive27 = DOUBLE_CONVERSION_UINT64_2PART_C(0x6765c793, fa10079d);
static const uint16_t kFive1 = 5;
static const uint16_t kFive2 = kFive1 * 5;
static const uint16_t kFive3 = kFive2 * 5;
static const uint16_t kFive4 = kFive3 * 5;
static const uint16_t kFive5 = kFive4 * 5;
static const uint16_t kFive6 = kFive5 * 5;
static const uint32_t kFive7 = kFive6 * 5;
static const uint32_t kFive8 = kFive7 * 5;
static const uint32_t kFive9 = kFive8 * 5;
static const uint32_t kFive10 = kFive9 * 5;
static const uint32_t kFive11 = kFive10 * 5;
static const uint32_t kFive12 = kFive11 * 5;
static const uint32_t kFive13 = kFive12 * 5;
static const uint32_t kFive1_to_12[] =
{ kFive1, kFive2, kFive3, kFive4, kFive5, kFive6,
kFive7, kFive8, kFive9, kFive10, kFive11, kFive12 };
DOUBLE_CONVERSION_ASSERT(exponent >= 0);
if (exponent == 0) {
return;
}
if (used_bigits_ == 0) {
return;
}
// We shift by exponent at the end just before returning.
int remaining_exponent = exponent;
while (remaining_exponent >= 27) {
MultiplyByUInt64(kFive27);
remaining_exponent -= 27;
}
while (remaining_exponent >= 13) {
MultiplyByUInt32(kFive13);
remaining_exponent -= 13;
}
if (remaining_exponent > 0) {
MultiplyByUInt32(kFive1_to_12[remaining_exponent - 1]);
}
ShiftLeft(exponent);
}
void Bignum::Square() {
DOUBLE_CONVERSION_ASSERT(IsClamped());
const int product_length = 2 * used_bigits_;
EnsureCapacity(product_length);
// Comba multiplication: compute each column separately.
// Example: r = a2a1a0 * b2b1b0.
// r = 1 * a0b0 +
// 10 * (a1b0 + a0b1) +
// 100 * (a2b0 + a1b1 + a0b2) +
// 1000 * (a2b1 + a1b2) +
// 10000 * a2b2
//
// In the worst case we have to accumulate nb-digits products of digit*digit.
//
// Assert that the additional number of bits in a DoubleChunk are enough to
// sum up used_digits of Bigit*Bigit.
if ((1 << (2 * (kChunkSize - kBigitSize))) <= used_bigits_) {
DOUBLE_CONVERSION_UNIMPLEMENTED();
}
DoubleChunk accumulator = 0;
// First shift the digits so we don't overwrite them.
const int copy_offset = used_bigits_;
for (int i = 0; i < used_bigits_; ++i) {
RawBigit(copy_offset + i) = RawBigit(i);
}
// We have two loops to avoid some 'if's in the loop.
for (int i = 0; i < used_bigits_; ++i) {
// Process temporary digit i with power i.
// The sum of the two indices must be equal to i.
int bigit_index1 = i;
int bigit_index2 = 0;
// Sum all of the sub-products.
while (bigit_index1 >= 0) {
const Chunk chunk1 = RawBigit(copy_offset + bigit_index1);
const Chunk chunk2 = RawBigit(copy_offset + bigit_index2);
accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
bigit_index1--;
bigit_index2++;
}
RawBigit(i) = static_cast<Chunk>(accumulator) & kBigitMask;
accumulator >>= kBigitSize;
}
for (int i = used_bigits_; i < product_length; ++i) {
int bigit_index1 = used_bigits_ - 1;
int bigit_index2 = i - bigit_index1;
// Invariant: sum of both indices is again equal to i.
// Inner loop runs 0 times on last iteration, emptying accumulator.
while (bigit_index2 < used_bigits_) {
const Chunk chunk1 = RawBigit(copy_offset + bigit_index1);
const Chunk chunk2 = RawBigit(copy_offset + bigit_index2);
accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
bigit_index1--;
bigit_index2++;
}
// The overwritten RawBigit(i) will never be read in further loop iterations,
// because bigit_index1 and bigit_index2 are always greater
// than i - used_bigits_.
RawBigit(i) = static_cast<Chunk>(accumulator) & kBigitMask;
accumulator >>= kBigitSize;
}
// Since the result was guaranteed to lie inside the number the
// accumulator must be 0 now.
DOUBLE_CONVERSION_ASSERT(accumulator == 0);
// Don't forget to update the used_digits and the exponent.
used_bigits_ = product_length;
exponent_ *= 2;
Clamp();
}
void Bignum::AssignPowerUInt16(uint16_t base, const int power_exponent) {
DOUBLE_CONVERSION_ASSERT(base != 0);
DOUBLE_CONVERSION_ASSERT(power_exponent >= 0);
if (power_exponent == 0) {
AssignUInt16(1);
return;
}
Zero();
int shifts = 0;
// We expect base to be in range 2-32, and most often to be 10.
// It does not make much sense to implement different algorithms for counting
// the bits.
while ((base & 1) == 0) {
base >>= 1;
shifts++;
}
int bit_size = 0;
int tmp_base = base;
while (tmp_base != 0) {
tmp_base >>= 1;
bit_size++;
}
const int final_size = bit_size * power_exponent;
// 1 extra bigit for the shifting, and one for rounded final_size.
EnsureCapacity(final_size / kBigitSize + 2);
// Left to Right exponentiation.
int mask = 1;
while (power_exponent >= mask) mask <<= 1;
// The mask is now pointing to the bit above the most significant 1-bit of
// power_exponent.
// Get rid of first 1-bit;
mask >>= 2;
uint64_t this_value = base;
bool delayed_multiplication = false;
const uint64_t max_32bits = 0xFFFFFFFF;
while (mask != 0 && this_value <= max_32bits) {
this_value = this_value * this_value;
// Verify that there is enough space in this_value to perform the
// multiplication. The first bit_size bits must be 0.
if ((power_exponent & mask) != 0) {
DOUBLE_CONVERSION_ASSERT(bit_size > 0);
const uint64_t base_bits_mask =
~((static_cast<uint64_t>(1) << (64 - bit_size)) - 1);
const bool high_bits_zero = (this_value & base_bits_mask) == 0;
if (high_bits_zero) {
this_value *= base;
} else {
delayed_multiplication = true;
}
}
mask >>= 1;
}
AssignUInt64(this_value);
if (delayed_multiplication) {
MultiplyByUInt32(base);
}
// Now do the same thing as a bignum.
while (mask != 0) {
Square();
if ((power_exponent & mask) != 0) {
MultiplyByUInt32(base);
}
mask >>= 1;
}
// And finally add the saved shifts.
ShiftLeft(shifts * power_exponent);
}
// Precondition: this/other < 16bit.
uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) {
DOUBLE_CONVERSION_ASSERT(IsClamped());
DOUBLE_CONVERSION_ASSERT(other.IsClamped());
DOUBLE_CONVERSION_ASSERT(other.used_bigits_ > 0);
// Easy case: if we have less digits than the divisor than the result is 0.
// Note: this handles the case where this == 0, too.
if (BigitLength() < other.BigitLength()) {
return 0;
}
Align(other);
uint16_t result = 0;
// Start by removing multiples of 'other' until both numbers have the same
// number of digits.
while (BigitLength() > other.BigitLength()) {
// This naive approach is extremely inefficient if `this` divided by other
// is big. This function is implemented for doubleToString where
// the result should be small (less than 10).
DOUBLE_CONVERSION_ASSERT(other.RawBigit(other.used_bigits_ - 1) >= ((1 << kBigitSize) / 16));
DOUBLE_CONVERSION_ASSERT(RawBigit(used_bigits_ - 1) < 0x10000);
// Remove the multiples of the first digit.
// Example this = 23 and other equals 9. -> Remove 2 multiples.
result += static_cast<uint16_t>(RawBigit(used_bigits_ - 1));
SubtractTimes(other, RawBigit(used_bigits_ - 1));
}
DOUBLE_CONVERSION_ASSERT(BigitLength() == other.BigitLength());
// Both bignums are at the same length now.
// Since other has more than 0 digits we know that the access to
// RawBigit(used_bigits_ - 1) is safe.
const Chunk this_bigit = RawBigit(used_bigits_ - 1);
const Chunk other_bigit = other.RawBigit(other.used_bigits_ - 1);
if (other.used_bigits_ == 1) {
// Shortcut for easy (and common) case.
int quotient = this_bigit / other_bigit;
RawBigit(used_bigits_ - 1) = this_bigit - other_bigit * quotient;
DOUBLE_CONVERSION_ASSERT(quotient < 0x10000);
result += static_cast<uint16_t>(quotient);
Clamp();
return result;
}
const int division_estimate = this_bigit / (other_bigit + 1);
DOUBLE_CONVERSION_ASSERT(division_estimate < 0x10000);
result += static_cast<uint16_t>(division_estimate);
SubtractTimes(other, division_estimate);
if (other_bigit * (division_estimate + 1) > this_bigit) {
// No need to even try to subtract. Even if other's remaining digits were 0
// another subtraction would be too much.
return result;
}
while (LessEqual(other, *this)) {
SubtractBignum(other);
result++;
}
return result;
}
template<typename S>
static int SizeInHexChars(S number) {
DOUBLE_CONVERSION_ASSERT(number > 0);
int result = 0;
while (number != 0) {
number >>= 4;
result++;
}
return result;
}
static char HexCharOfValue(const int value) {
DOUBLE_CONVERSION_ASSERT(0 <= value && value <= 16);
if (value < 10) {
return static_cast<char>(value + '0');
}
return static_cast<char>(value - 10 + 'A');
}
bool Bignum::ToHexString(char* buffer, const int buffer_size) const {
DOUBLE_CONVERSION_ASSERT(IsClamped());
// Each bigit must be printable as separate hex-character.
DOUBLE_CONVERSION_ASSERT(kBigitSize % 4 == 0);
static const int kHexCharsPerBigit = kBigitSize / 4;
if (used_bigits_ == 0) {
if (buffer_size < 2) {
return false;
}
buffer[0] = '0';
buffer[1] = '\0';
return true;
}
// We add 1 for the terminating '\0' character.
const int needed_chars = (BigitLength() - 1) * kHexCharsPerBigit +
SizeInHexChars(RawBigit(used_bigits_ - 1)) + 1;
if (needed_chars > buffer_size) {
return false;
}
int string_index = needed_chars - 1;
buffer[string_index--] = '\0';
for (int i = 0; i < exponent_; ++i) {
for (int j = 0; j < kHexCharsPerBigit; ++j) {
buffer[string_index--] = '0';
}
}
for (int i = 0; i < used_bigits_ - 1; ++i) {
Chunk current_bigit = RawBigit(i);
for (int j = 0; j < kHexCharsPerBigit; ++j) {
buffer[string_index--] = HexCharOfValue(current_bigit & 0xF);
current_bigit >>= 4;
}
}
// And finally the last bigit.
Chunk most_significant_bigit = RawBigit(used_bigits_ - 1);
while (most_significant_bigit != 0) {
buffer[string_index--] = HexCharOfValue(most_significant_bigit & 0xF);
most_significant_bigit >>= 4;
}
return true;
}
Bignum::Chunk Bignum::BigitOrZero(const int index) const {
if (index >= BigitLength()) {
return 0;
}
if (index < exponent_) {
return 0;
}
return RawBigit(index - exponent_);
}
int Bignum::Compare(const Bignum& a, const Bignum& b) {
DOUBLE_CONVERSION_ASSERT(a.IsClamped());
DOUBLE_CONVERSION_ASSERT(b.IsClamped());
const int bigit_length_a = a.BigitLength();
const int bigit_length_b = b.BigitLength();
if (bigit_length_a < bigit_length_b) {
return -1;
}
if (bigit_length_a > bigit_length_b) {
return +1;
}
for (int i = bigit_length_a - 1; i >= (std::min)(a.exponent_, b.exponent_); --i) {
const Chunk bigit_a = a.BigitOrZero(i);
const Chunk bigit_b = b.BigitOrZero(i);
if (bigit_a < bigit_b) {
return -1;
}
if (bigit_a > bigit_b) {
return +1;
}
// Otherwise they are equal up to this digit. Try the next digit.
}
return 0;
}
int Bignum::PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c) {
DOUBLE_CONVERSION_ASSERT(a.IsClamped());
DOUBLE_CONVERSION_ASSERT(b.IsClamped());
DOUBLE_CONVERSION_ASSERT(c.IsClamped());
if (a.BigitLength() < b.BigitLength()) {
return PlusCompare(b, a, c);
}
if (a.BigitLength() + 1 < c.BigitLength()) {
return -1;
}
if (a.BigitLength() > c.BigitLength()) {
return +1;
}
// The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
// 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
// of 'a'.
if (a.exponent_ >= b.BigitLength() && a.BigitLength() < c.BigitLength()) {
return -1;
}
Chunk borrow = 0;
// Starting at min_exponent all digits are == 0. So no need to compare them.
const int min_exponent = (std::min)((std::min)(a.exponent_, b.exponent_), c.exponent_);
for (int i = c.BigitLength() - 1; i >= min_exponent; --i) {
const Chunk chunk_a = a.BigitOrZero(i);
const Chunk chunk_b = b.BigitOrZero(i);
const Chunk chunk_c = c.BigitOrZero(i);
const Chunk sum = chunk_a + chunk_b;
if (sum > chunk_c + borrow) {
return +1;
} else {
borrow = chunk_c + borrow - sum;
if (borrow > 1) {
return -1;
}
borrow <<= kBigitSize;
}
}
if (borrow == 0) {
return 0;
}
return -1;
}
void Bignum::Clamp() {
while (used_bigits_ > 0 && RawBigit(used_bigits_ - 1) == 0) {
used_bigits_--;
}
if (used_bigits_ == 0) {
// Zero.
exponent_ = 0;
}
}
void Bignum::Align(const Bignum& other) {
if (exponent_ > other.exponent_) {
// If "X" represents a "hidden" bigit (by the exponent) then we are in the
// following case (a == this, b == other):
// a: aaaaaaXXXX or a: aaaaaXXX
// b: bbbbbbX b: bbbbbbbbXX
// We replace some of the hidden digits (X) of a with 0 digits.
// a: aaaaaa000X or a: aaaaa0XX
const int zero_bigits = exponent_ - other.exponent_;
EnsureCapacity(used_bigits_ + zero_bigits);
for (int i = used_bigits_ - 1; i >= 0; --i) {
RawBigit(i + zero_bigits) = RawBigit(i);
}
for (int i = 0; i < zero_bigits; ++i) {
RawBigit(i) = 0;
}
used_bigits_ += zero_bigits;
exponent_ -= zero_bigits;
DOUBLE_CONVERSION_ASSERT(used_bigits_ >= 0);
DOUBLE_CONVERSION_ASSERT(exponent_ >= 0);
}
}
void Bignum::BigitsShiftLeft(const int shift_amount) {
DOUBLE_CONVERSION_ASSERT(shift_amount < kBigitSize);
DOUBLE_CONVERSION_ASSERT(shift_amount >= 0);
Chunk carry = 0;
for (int i = 0; i < used_bigits_; ++i) {
const Chunk new_carry = RawBigit(i) >> (kBigitSize - shift_amount);
RawBigit(i) = ((RawBigit(i) << shift_amount) + carry) & kBigitMask;
carry = new_carry;
}
if (carry != 0) {
RawBigit(used_bigits_) = carry;
used_bigits_++;
}
}
void Bignum::SubtractTimes(const Bignum& other, const int factor) {
DOUBLE_CONVERSION_ASSERT(exponent_ <= other.exponent_);
if (factor < 3) {
for (int i = 0; i < factor; ++i) {
SubtractBignum(other);
}
return;
}
Chunk borrow = 0;
const int exponent_diff = other.exponent_ - exponent_;
for (int i = 0; i < other.used_bigits_; ++i) {
const DoubleChunk product = static_cast<DoubleChunk>(factor) * other.RawBigit(i);
const DoubleChunk remove = borrow + product;
const Chunk difference = RawBigit(i + exponent_diff) - (remove & kBigitMask);
RawBigit(i + exponent_diff) = difference & kBigitMask;
borrow = static_cast<Chunk>((difference >> (kChunkSize - 1)) +
(remove >> kBigitSize));
}
for (int i = other.used_bigits_ + exponent_diff; i < used_bigits_; ++i) {
if (borrow == 0) {
return;
}
const Chunk difference = RawBigit(i) - borrow;
RawBigit(i) = difference & kBigitMask;
borrow = difference >> (kChunkSize - 1);
}
Clamp();
}
} // namespace double_conversion
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
93e6372cf903aee1d7fd140c6e6141696d964ea0 | b4c2427ece02bc1bc1f5e6279539ac884efcb323 | /Codeforces/codeforces1076A.cpp | f52771b71ba32cc4ae4416278bf5cfdd7d902923 | [] | no_license | sohag16030/ACM-Programming | eb7210be3685c3f7e5ea855c1598f5e7f3044463 | 39943162ed7b08d34b2b07b1a866b039c6ec2cc7 | refs/heads/master | 2023-01-31T11:08:46.389769 | 2020-12-14T08:57:24 | 2020-12-14T08:57:24 | 218,221,513 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,525 | cpp | /**************************************************
* BISMILLAHIR RAHMANIR RAHIM
* Author Name : SHOHAG (ICT'13)
* University : ICT, MBSTU
***************************************************/
#include<bits/stdc++.h>
#define sf(n) scanf("%lld", &n)
#define sff(n,m) scanf("%lld%lld", &n, &m)
#define pf(n) printf("%lld", n)
#define pff(n,m) printf("%lld%lld", n, m)
#define pi acos(-1.0)
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define all(x) x.begin(),x.end()
#define Mod(x, m) ((((x) % (m)) + (m)) % (m))
#define Max3(a, b, c) max(a, max(b, c))
#define Min3(a, b, c) min(a, min(b, c))
#define MAX 100005
#define MIN -1
#define INF 1000000000
#define debug cout<<"Executed"<<endl;
#define SET(array_name,value) memset(array_name,value,sizeof(array_name))
#define __FastIO ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
ll n,i,j,L,m,k,sum,cnt,d,rem,mod,v,r,l,row,extra,mx=-1;
string s;
map<char,ll>Mp;
map<ll,char>_mp;
map<char,ll>::iterator it;
vector<ll>v1,v2,v3;
vector<ll>v4[51];
/************************************ Code Start Here ******************************************************/
int main()
{
cin>>n>>s;
bool flag=false;
for(i=0; i<n-1; i++)
{
if(s[i]>s[i+1])
{
s.erase(i,1);
flag=true;
break;
}
}
if(flag==false)
s.erase(n-1,1);
cout<<s;
return 0;
}
| [
"shohag.mbstu.it16030@gmail.com"
] | shohag.mbstu.it16030@gmail.com |
6853c9bec8005560597fa4173310200fb1041987 | 9369318cdbde33f5910c6de3736f1d07400cf276 | /363c.cpp | 9a4c8fcf8996363d76e884b7adc63087c739628f | [] | no_license | cwza/codeforces | cc58c646383a201e10422ec80567b52bef4a0da9 | e193f5d766e8ddda6cdc8a43b9f1826eeecfc870 | refs/heads/master | 2023-04-11T12:22:04.555974 | 2021-04-22T04:45:20 | 2021-04-22T04:45:20 | 352,477,628 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 752 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
string s;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
cin >> s;
int n = s.size();
string ans;
bool prev = false;
int i = 0, j = 0;
while(i < n) {
while(j < n && s[i]==s[j]) j++;
int l = j - i;
if(l==1) {
ans += s[i];
prev = false;
}
else {
if(prev) {
ans += s[i];
prev = false;
} else {
ans += s[i];
ans += s[i];
prev = true;
}
}
i = j;
}
cout << ans;
} | [
"cwz0205a@gmail.com"
] | cwz0205a@gmail.com |
287ecffe054ea033fdfa82ea922e2d4cac377445 | ee023caabf3abe209a3e01e52f93d922e73805cc | /okos1/interface.h~ | 1e39ebf22dd764192dd72b04f9ddbc8ec57c0401 | [] | no_license | okos/okos1 | 630f9f72f55763a6e89319d9c8f9c45e52bc26c3 | 49012dec43728204a605ffc430cd142291929045 | refs/heads/master | 2021-03-12T20:07:49.483950 | 2014-05-26T18:09:56 | 2014-05-26T18:09:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,741 | /*
* interface.h
*
* Created: 3/27/2014 10:57:13 AM
* Author: vicky
*/
#ifndef INTERFACE_H_
#define INTERFACE_H_
class Interface
{
Account *account;
Meter *meter;
Communication *comm;
Time *system_time;
char buffer[120];
Packet pkt;
int32_t temp_val;
uint8_t temp_val1;
public:
Interface(Account*, Meter*, Communication*, Time*);
uint8_t check_packet(Packet*);
void make_packet(Packet *packet, uint32_t destination_address, uint8_t pkt_type, char *data);
void update();
};
Interface::Interface(Account *acc, Meter *mtr, Communication *cmm, Time *syt)
{
pkt = Packet();
account = acc;
meter = mtr;
comm = cmm;
system_time = syt;
}
inline uint8_t Interface::check_packet(Packet *packet)
{
if (packet->destination_address == account->get_ip_address() || packet->destination_address == 0 || packet->destination_address == 255)
return 1;
return 0;
}
void Interface::make_packet(Packet *packet, uint32_t destination_address, uint8_t pkt_type, char *data)
{
uint8_t i;
packet->source_address = account->get_ip_address();
packet->destination_address = destination_address;
packet->type = pkt_type;
for (i=0;data[i]!='\0';i++)
packet->data[i] = data[i];
packet->data[i] = '\0';
packet->length = 12 + i;
}
void Interface::update()
{
uint32_t val;
if (!comm->receive(&pkt))
return;
if (!check_packet(&pkt))
return;
if (pkt.type == NORMAL_PACKET)
{
uint8_t reconized = 0;
//sscanf(pkt.data, "%s", buffer);
strcpy(buffer, pkt.data);
val = 0;
if (sscanf(buffer, "set address %lu", &val) == 1)
{
account->set_ip_address(val);
/*buffer[0] = '\0';
sprintf(buffer, "Address is now %lu", val);*/
reconized = 1;
}
else if (sscanf(buffer, "set rate %lu", &val) == 1)
{
account->set_rate(val);
/*buffer[0] = '\0';
sprintf(buffer, "Rate is now %lu", val);*/
reconized = 1;
}
else if (sscanf(buffer, "set power limit %lu", &val) == 1)
{
account->set_power_limit((uint16_t)val);
/*buffer[0] = '\0';
sprintf(buffer, "Power limit is now %lu", val);*/
reconized = 1;
}
else if (sscanf(buffer, "set time %lu", &val) == 1)
{
system_time->set(val);
reconized = 1;
}
else if (sscanf(buffer, "set hw version %lu", &val) == 1)
{
account->set_hw_version((uint8_t)val);
reconized = 1;
}
else if (sscanf(buffer, "set sw version %lu", &val) == 1)
{
account->set_hw_version((uint8_t)val);
reconized = 1;
}
else if (sscanf(buffer, "set installation date %lu", &val) == 1)
{
account->set_installation_date(val);
reconized = 1;
}
else if (strcmp(buffer, "reset energy") == 0)
{
account->set_energy_remaining(0);
reconized = 1;
}
else if (sscanf(buffer, "cal v %lu", &val) == 1)
{
meter->meter_coff.calculate_parameters(1, 0, 0, (int32_t)val, meter->voltage_val_unscaled());
meter->meter_coff.store_parameters();
reconized = 1;
}
else if (strcmp(buffer, "cal i ofs") == 0)
{
temp_val = meter->current_val_unscaled();
reconized = 1;
}
else if (sscanf(buffer, "cal i %lu", &val) == 1)
{
meter->meter_coff.calculate_parameters(0, 0, temp_val, (int32_t)val, meter->current_val_unscaled());
meter->meter_coff.store_parameters();
reconized = 1;
}
else if (strcmp(buffer, "turn relay off") == 0)
{
account->set_state(account->get_state()|RELAY_OFF);
reconized = 1;
}
else if (strcmp(buffer, "turn relay on") == 0)
{
account->set_state(account->get_state()&(~RELAY_OFF));
reconized = 1;
}
else if (strcmp(buffer, "cal") == 0)
{
temp_val1 = account->get_state();
account->set_state(CAL_MODE);
reconized = 1;
}
else if (strcmp(buffer, "normal") == 0)
{
account->set_state(temp_val1);
reconized = 1;
}
if (reconized)
{
buffer[0] = '\0';
sprintf(buffer,"Done(%lu)",val);
make_packet(&pkt, pkt.destination_address, NORMAL_PACKET, buffer);
account->write_to_rom(1);
}
else
make_packet(&pkt, pkt.destination_address, NORMAL_PACKET, "Invalid command");
comm->send(&pkt);
}
else if (pkt.type == DATA_PACKET)
{
buffer[0] = '\0';
char tmp_buffer[15];
sprintf(tmp_buffer, "%lu,\0", system_time->get());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%lu,\0", account->get_ip_address());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%ld,\0", meter->voltage());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%ld,\0", meter->current());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%ld,\0", meter->power_apparent_val());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%lu,\0", account->get_energy_used());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%d,\0", account->get_balance());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%hu,\0", account->get_state());
strcat(buffer, tmp_buffer);
make_packet(&pkt, pkt.source_address, DATA_PACKET, buffer);
comm->send(&pkt);
}
else if (pkt.type == METER_DETAILS_PACKET)
{
buffer[0] = '\0';
char tmp_buffer[15];
sprintf(tmp_buffer, "%lu,\0", system_time->get());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%ld,\0", meter->voltage());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%ld,\0", meter->voltage_val_unscaled());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%ld,\0", meter->voltage_val_raw());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%ld,\0", meter->current());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%ld,\0", meter->current_val_unscaled());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%ld,\0", meter->current_val_raw());
strcat(buffer, tmp_buffer);
make_packet(&pkt, pkt.source_address, METER_DETAILS_PACKET, buffer);
comm->send(&pkt);
}
else if (pkt.type == CALIBRATION_DETAILS_PACKET)
{
buffer[0] = '\0';
char tmp_buffer[15];
sprintf(tmp_buffer, "%ld,\0", meter->meter_coff.get_voltage_scale());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%ld,\0", meter->meter_coff.get_voltage_offset());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%ld,\0", meter->meter_coff.get_current_scale());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%ld,\0", meter->meter_coff.get_current_offset());
strcat(buffer, tmp_buffer);
make_packet(&pkt, pkt.source_address, CALIBRATION_DETAILS_PACKET, buffer);
comm->send(&pkt);
}
else if (pkt.type == RECHARGE_PACKET)
{
uint8_t result;
int recharge_amount;
uint32_t recharge_validity, carry_forward_energy_units;
sscanf(pkt.data, "%d,%lu,%lu,", &recharge_amount, &recharge_validity, &carry_forward_energy_units);
result = account->recharge(recharge_amount, recharge_validity, carry_forward_energy_units);
buffer[0] = '\0';
sprintf(buffer, "%d,%lu,%lu,%hu\0", recharge_amount, recharge_validity, carry_forward_energy_units, result);
make_packet(&pkt, pkt.source_address, NORMAL_PACKET, buffer);
account->write_to_rom();
comm->send(&pkt);
}
else if (pkt.type == ACCOUNT_DETAILS_PACKET)
{
buffer[0] = '\0';
char tmp_buffer[15];
sprintf(tmp_buffer, "%d,\0", account->get_balance());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%lu,\0", account->get_validity());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%lu,\0", account->get_carry_forward_units());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%lu,\0", account->get_energy_remaining());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%lu,\0", account->get_energy_used());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%lu,\0", account->get_last_recharge_time());
strcat(buffer, tmp_buffer);
make_packet(&pkt, pkt.source_address, ACCOUNT_DETAILS_PACKET, buffer);
comm->send(&pkt);
}
else if (pkt.type == DEVICE_DETAILS_PACKET)
{
buffer[0] = '\0';
char tmp_buffer[15];
sprintf(tmp_buffer, "%lu,\0", account->get_ip_address());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%hu,\0", account->get_hw_version());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%hu,\0", account->get_sw_version());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%lu,\0", account->get_installation_date());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%lu,\0", account->get_rate());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%u,\0", account->get_power_limit());
strcat(buffer, tmp_buffer);
sprintf(tmp_buffer, "%hu,\0", account->get_state());
strcat(buffer, tmp_buffer);
make_packet(&pkt, pkt.source_address, ACCOUNT_DETAILS_PACKET, buffer);
comm->send(&pkt);
}
}
#endif /* INTERFACE_H_ */
| [
"vikas13jun@gmail.com"
] | vikas13jun@gmail.com | |
3d0a70ba491fb319669b59aab85aca7a3b5fb273 | c31778ebfb45cfa963d7b568208498a9b19913ba | /determinant/determinant.cpp | 0571ee7193ea96d6c2eea964e5382c20882c9e23 | [] | no_license | djjkobe/Parallel-Programming- | 7d3ada6e501cea19167ca44bbf56e6c71821adbb | e2d3f4e5879f8982f38db2a0ebb1b1db2541464f | refs/heads/master | 2020-12-30T09:26:15.837563 | 2015-04-23T14:57:23 | 2015-04-23T14:57:23 | 29,807,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,118 | cpp | /**
* University of Pittsburgh
* Department of Computer Science
* CS1645: Introduction to HPC Systems
* Instructor: Esteban Meneses, PhD (emeneses@pitt.edu)
* OpenMP parallel determinant computation.
*/
#include <math.h>
#include <set>
#include <iostream>
using namespace std;
int determinant_minor(int **A, int N, int i, set<int> cols);
// Determinant function
int determinant(int **A, int N){
int result = 0, sign;
#pragma omp parallel for private(sign) reduction(+:result)
for(int j=0; j<N; j++) {
sign = (int) pow(-1,j);
set<int> cols;
cols.insert(j);
result += sign * A[0][j] * determinant_minor(A,N,1,cols);
}
return result;
}
// Computes determinant of minor(i,j) of matrix A using Laplace expansion.
int determinant_minor(int **A, int N, int row, set<int> cols){
int result = 0, sign, index = 0;
for(int j=0; j<N; j++) {
if(cols.find(j) == cols.end()){
if(row == N-1) return A[row][j];
sign = (int) pow(-1,index++);
set<int> next_cols(cols);
next_cols.insert(j);
result += sign * A[row][j] * determinant_minor(A,N,row+1,next_cols);
}
}
return result;
}
| [
"djjkobe@gmail.com"
] | djjkobe@gmail.com |
78e66c93f69eec9082f9faeeff061c5cb1c08e4f | e6589fdcb0ba4f148c5a662934dbfb10a62873ab | /Arduino/libraries/BasicSerial/examples/SerialTX_BlinkLED/SerialTX_BlinkLED.ino | 630dd51e42f505b27849ddb7328c5ec7f4117e03 | [] | no_license | macalencar/attiny13-utils | 6c7084f14f8a6a53812eb2c9f2e5d8af0e2505bf | 48c8cedc8bb663159021b56f0f57aa74f5a624c4 | refs/heads/master | 2020-03-08T17:41:47.121490 | 2018-04-06T01:01:03 | 2018-04-06T01:01:03 | 128,275,625 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 728 | ino | /* @author: Ralph Doncaster
* @updatedby: Márcio Alencar
*
* Attiny13A @ 1MHz -> Baudrate 9600 : Delay(1000) = 1 s
* Attiny13A @ 1.2 MHz -> Baudrate 2400 ~ 34800 : Delay(1000) = 1.2s
* Default Baudrate @ 1.0Mhz: 9600
* Default Baudrate @ 1.2Mhz: 2400
*
*/
#include <BasicSerial.h>
//#define BAUD_RATE 34800 //set clock @ 1.2 Mhz
#define LEDPIN 2 //PINB2
void setup(){
pinMode(LEDPIN,OUTPUT); //DDRB |= (1<<LEDPIN);
}
void serOut(const char* str) { while (*str) TxByte (*str++); }
void loop(){
serOut("Turning on LED\n");
//PORTB |= (1<<LEDPIN); // turn on LED
digitalWrite(LEDPIN,HIGH);
delay(1000);
//PORTB &= ~(1<<LEDPIN); // turn off LED
digitalWrite(LEDPIN,LOW);
delay(1000);
} | [
"noreply@github.com"
] | noreply@github.com |
72a08de2c3aa646bb3d3f0fed7ad057309b64b51 | 235c46852fc2d26512331ab29e8822af337e1b4a | /tsps.cpp | aa4a2a2b7b82791db73776ec4ca119df6eb96b22 | [] | no_license | Clone0/abc | 40d7ffbb6e715d46e4cc49f75f86ea9c2f35a251 | 201b3cb6dd14acf12fd4ee217d2bfee599e2470e | refs/heads/master | 2021-05-04T05:58:02.764372 | 2016-10-17T03:02:18 | 2016-10-17T03:02:18 | 70,993,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,188 | cpp | #include <iostream>
#include<omp.h>
using namespace std;
class dynamic
{
private:
int c[5][5],n,d[24],p[24][6],list[5],r;
public:
dynamic();
void getdata();
void display();
int fact(int num);
int min(int list[]);
void perm(int list[], int k, int m);
void sol();
};
dynamic::dynamic()
{
r=0;
}
void dynamic::getdata()
{ int i,j;
cout<<"Enter no. of cities:";
cin>>n;
cout<<endl;
for (i=0;i<n;i++)
for (j=0;j<n;j++)
c[i][j]=0;
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
if (i!=j)
{
if (c[i][j]==0)
{
cout<<"Enter cost from "<<i<<" to "<<j<<" :";
cin>>c[i][j];
c[j][i]=c[i][j];
}
}
}
}
for (i=0;i<n-1;i++)
list[i]=i+1;
}
int dynamic::fact(int num)
{
int f=1;
if (num!=0)
for (int i=1;i<=num;i++)
f=f*i;
return f;
}
void dynamic::perm(int list[], int k, int m)
{
int i,temp;
if (k==m)
{
for (i=0;i<=m;i++)
{
p[r][i+1]=list[i];
}
r++;
}
else
for (i=k;i<=m;i++)
{
temp=list[k]; list[k]=list[i]; list[i]=temp;
perm(list,k+1,m);
temp=list[k]; list[k]=list[i]; list[i]=temp;
}
}
void dynamic::sol()
{
int i;
#pragma openmp parallel
perm(list,0,n-2);
for (i=0;i<fact(n-1);i++)
{
p[i][0]=0;
p[i][n]=0;
}
for (i=0;i<fact(n-1);i++)
{
d[i]=0;
for (int j=0;j<n;j++)
{
d[i]=d[i]+c[p[i][j]][p[i][j+1]];
}
}
}
int dynamic::min(int list[])
{
int minimum=list[0];
for (int i=0;i<fact(n-1);i++)
{
if (list[i]<minimum)
minimum=list[i];
}
return minimum;
}
void dynamic::display()
{
int i,j;
cout<<endl<<"The cost Matrix:"<<endl;
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
cout<<c[i][j]<<"\t";
cout<<endl;
}
cout<<endl<<"The Possible paths and their corresponding cost:"<<endl;
for (i=0;i<fact(n-1);i++)
{
for (j=0;j<n+1;j++)
cout<<p[i][j]<<"\t";
cout<<"--> "<<d[i]<<endl;
}
cout<<endl<<"The shortest path :"<<endl;
for (i=0;i<fact(n-1);i++)
{
if (d[i]==min(d))
break;
}
for (j=0;j<=n;j++)
{
cout<<p[i][j]<<" ";
}
cout<<endl<<"\nThe cost of this path is "<<d[i]<<endl;
}
int main()
{
dynamic ts;
ts.getdata();
ts.sol();
ts.display();
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
5888d2b7c49dc46530bb8ad3b6ae3bd5468978bc | 80ab557dfa38bffd770dd0d6b39e04b00cd8e134 | /test/test_pp.cc | 64c8468005993b383200921088c234fe22cda547 | [] | no_license | EhevuTov/tcp2snmp | 02970e911e3956302f66b60143ebb0d417144ec8 | fc82b0394bd3e5465d0b400fa22425d95a7a912b | refs/heads/master | 2021-01-10T20:50:15.525312 | 2013-01-14T19:20:39 | 2013-01-14T19:20:39 | 6,496,705 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 400 | cc | #include <iostream>
#define ENTERPRISE(s) 1,3,6,1,3,1,36872
//#define NUMBER3 #NUMBER1 ## #NUMBER2
#define NUMBER3(TRAP) TRAP ## 4
#define NUMBER4() 123 ## 4
#define NUMBER5 NUMBER3(123)
//#define TRAP(OID) ENTERPRISE ## OID
int main(void) {
std::cout << NUMBER3(123) << std::endl;
std::cout << NUMBER4() << std::endl;
std::cout << NUMBER5 << std::endl;
std::cout << TRAP << std::endl;
};
| [
"jamesgosnell@gmail.com"
] | jamesgosnell@gmail.com |
f9112c24928fdc0dadfd48687f8ed907e20d1766 | 349fe789ab1e4e46aae6812cf60ada9423c0b632 | /Program/FIBPlus/DBServ20/SprFirm/UOleDMSprFirm.h | af03039e6c46e351d72622bdc2cb4facedf06028 | [] | no_license | presscad/ERP | a6acdaeb97b3a53f776677c3a585ca860d4de980 | 18ecc6c8664ed7fc3f01397d587cce91fc3ac78b | refs/heads/master | 2020-08-22T05:24:15.449666 | 2019-07-12T12:59:13 | 2019-07-12T12:59:13 | 216,326,440 | 1 | 0 | null | 2019-10-20T07:52:26 | 2019-10-20T07:52:26 | null | WINDOWS-1251 | C++ | false | false | 2,706 | h | // 1.1
// Unit1.h : Declaration of the TOleDMSprFirmImpl
#ifndef UOleDMSprFirmH
#define UOleDMSprFirmH
#define _ATL_APARTMENT_THREADED
#include "DBServ20_TLB.h"
#include "UDMSprFirm.h"
#include "UDM.h"
/////////////////////////////////////////////////////////////////////////////
// TOleDMSprFirmImpl Implements IOleDMSprFirm, default interface of OleDMSprFirm
// ThreadingModel : tmApartment
// Dual Interface : TRUE
// Event Support : FALSE
// Default ProgID : DBServ20.OleDMSprFirm
// Description :
/////////////////////////////////////////////////////////////////////////////
class ATL_NO_VTABLE TOleDMSprFirmImpl :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<TOleDMSprFirmImpl, &CLSID_OleDMSprFirm>,
public IDispatchImpl<IOleDMSprFirm, &IID_IOleDMSprFirm, &LIBID_DBServ20>
{
public:
TOleDMSprFirmImpl()
{
DMSprFirm=new TDMSprFirm(Application);
CodeError=0;
TextError="Ошибок нет";
}
~TOleDMSprFirmImpl()
{
delete DMSprFirm;
}
// Data used when registering Object
//
DECLARE_THREADING_MODEL(otApartment);
DECLARE_PROGID("DBServ20.OleDMSprFirm");
DECLARE_DESCRIPTION("");
// Function invoked to (un)register object
//
static HRESULT WINAPI UpdateRegistry(BOOL bRegister)
{
TTypedComServerRegistrarT<TOleDMSprFirmImpl>
regObj(GetObjectCLSID(), GetProgID(), GetDescription());
return regObj.UpdateRegistry(bRegister);
}
DECLARE_GET_CONTROLLING_UNKNOWN()
BEGIN_COM_MAP(TOleDMSprFirmImpl)
COM_INTERFACE_ENTRY(IOleDMSprFirm)
COM_INTERFACE_ENTRY2(IDispatch, IOleDMSprFirm)
END_COM_MAP()
// IOleDMSprFirm
public:
TDMSprFirm *DMSprFirm;
int CodeError;
AnsiString TextError;
STDMETHOD(get_CodeError(int* Value));
STDMETHOD(get_TextError(BSTR* Value));
STDMETHOD(OpenTable());
STDMETHOD(OpenElement(BSTR id, int* result));
STDMETHOD(NewElement());
STDMETHOD(SaveElement(int* result));
STDMETHOD(DeleteElement(BSTR id));
STDMETHOD(GetGidElement(BSTR id, BSTR* gid));
STDMETHOD(GetIdElement(BSTR gid, BSTR* id));
STDMETHOD(get_TableIDFIRM(BSTR* Value));
STDMETHOD(get_TableINNFIRM(BSTR* Value));
STDMETHOD(get_TableNAMEFIRM(BSTR* Value));
STDMETHOD(get_ElementIDFIRM(BSTR* Value));
STDMETHOD(get_ElementINNFIRM(BSTR* Value));
STDMETHOD(get_ElementNAMEFIRM(BSTR* Value));
STDMETHOD(get_TableEof(int* Value));
STDMETHOD(set_ElementIDFIRM(BSTR Value));
STDMETHOD(set_ElementINNFIRM(BSTR Value));
STDMETHOD(set_ElementNAMEFIRM(BSTR Value));
STDMETHOD(TableFirst());
STDMETHOD(TableNext());
STDMETHOD(get_ElementGID_SFIRM(BSTR* Value));
STDMETHOD(get_TableGID_SFIRM(BSTR* Value));
STDMETHOD(set_ElementGID_SFIRM(BSTR Value));
};
#endif //Unit1H
| [
"sasha@kaserv.ru"
] | sasha@kaserv.ru |
8cb40a1a6703e4697dd00d46e6610c1d1170aa64 | 14ce01a6f9199d39e28d036e066d99cfb3e3f211 | /Cpp/SDK/BP_JetSki_Bounty_Shotgun_functions.cpp | 95ece7447c03be447cd4f16dd035707697afaa22 | [] | no_license | zH4x-SDK/zManEater-SDK | 73f14dd8f758bb7eac649f0c66ce29f9974189b7 | d040c05a93c0935d8052dd3827c2ef91c128bce7 | refs/heads/main | 2023-07-19T04:54:51.672951 | 2021-08-27T13:47:27 | 2021-08-27T13:47:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,398 | cpp | // Name: ManEater, Version: 1.0.0
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BP_JetSki_Bounty_Shotgun.BP_JetSki_Bounty_Shotgun_C.WallHit
// (Event, Protected, BlueprintEvent)
// Parameters:
// class UPrimitiveComponent* MyComp (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// class UPrimitiveComponent* OtherComp (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// struct FVector HitLocation (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void ABP_JetSki_Bounty_Shotgun_C::WallHit(class UPrimitiveComponent* MyComp, class UPrimitiveComponent* OtherComp, const struct FVector& HitLocation)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_JetSki_Bounty_Shotgun.BP_JetSki_Bounty_Shotgun_C.WallHit");
ABP_JetSki_Bounty_Shotgun_C_WallHit_Params params;
params.MyComp = MyComp;
params.OtherComp = OtherComp;
params.HitLocation = HitLocation;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_JetSki_Bounty_Shotgun.BP_JetSki_Bounty_Shotgun_C.ExecuteUbergraph_BP_JetSki_Bounty_Shotgun
// (Final)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void ABP_JetSki_Bounty_Shotgun_C::ExecuteUbergraph_BP_JetSki_Bounty_Shotgun(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_JetSki_Bounty_Shotgun.BP_JetSki_Bounty_Shotgun_C.ExecuteUbergraph_BP_JetSki_Bounty_Shotgun");
ABP_JetSki_Bounty_Shotgun_C_ExecuteUbergraph_BP_JetSki_Bounty_Shotgun_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
300e076264865a31f6b7da35c654a6c78032b66a | 3165ab1f92f8f57d4dc2f012ea4d5b2d0ed562d5 | /FiniteStateMachine.h | b8455683845fffb7a6a86f876d6d8aa71d334478 | [] | no_license | gpdeal/finite-state-machine | 1047acf7fc70e7d42636a62b589896c42f3425ac | 7bed00c5c15bf5971b122852e0cf400a8a59783b | refs/heads/master | 2020-05-04T22:21:10.279176 | 2015-02-20T20:42:42 | 2015-02-20T20:42:42 | 31,083,972 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 216 | h | #pragma once
#include <set>
#include <list>
#include "Transition.h"
using namespace std;
struct FiniteStateMachine {
set<int> nodes;
int startNode;
set<int> goalNodes;
list<Transition> transitions;
};
| [
"gpdeal@gmail.com"
] | gpdeal@gmail.com |
78a618f46271de79cc4bfd0f91a1273ce2abbcb0 | 9be77717c32c8798ecaae37f09597e9fcaf31c20 | /src/Case.hpp | b0cfd1b49462cef110dc2ec0f6cb4b9a157b6937 | [] | no_license | metalcolic/Game-01 | dcb7b3eb3ba984101afd5a4e61b0716a8fc6b1af | 876e8c7d3a4243902f99f27ad095e57ebe05d72c | refs/heads/master | 2021-01-19T07:38:59.107665 | 2012-08-24T13:10:17 | 2012-08-24T13:10:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 603 | hpp | #ifndef CASE_HPP_INCLUDED
#define CASE_HPP_INCLUDED
#include "Structures.hpp"
class Case
{
public:
Case(sf::RenderWindow* _app);
bool setTuile(Couche, sf::Texture&);
void setPosition(int x, int y);
Position& getMapPosition();
Position& getPosition();
void setBloquante(bool Block);
bool isBloquante();
bool draw();
Case& getCase();
private:
sf::RenderWindow* _app;
Position _pos;
Position _mapPos;
bool _bloquante;
sf::Sprite _devant, _derriere;
};
#endif // CASE_HPP_INCLUDED
| [
"manganim@live.fr"
] | manganim@live.fr |
f5ec1781fb7c35b835b38fc5a6d14e1913e7e3cc | 2108fc8a2be2d2bc79efc5aca5c9e89a9676e333 | /distributed_file_system_mp3/member.cpp | 608e48e86e7a12d21cf988e775949033da896a24 | [
"Apache-2.0"
] | permissive | frank0098/distributedsystem | 7060de13aa33af41933c35a5ae913f273bf9a15c | 72373208d0ba00af443c43a68350bb62ded7a0b5 | refs/heads/master | 2021-03-27T09:31:04.143325 | 2018-08-06T04:53:44 | 2018-08-06T04:53:44 | 90,808,370 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,162 | cpp | #include "member.h"
std::string coordinator;
std::string machine_ip;
int machine_id=-1;
int highest_id=-1;
std::map<std::string,int> ip_mapping;
std::string failure_process;
bool alive_member::add(std::string ip){
// static int id_cnt=0;
if(ip.empty()) return false;
std::lock_guard<std::mutex> guard(mutex);
highest_id=std::max(ip_mapping[ip],highest_id);
if(ip_mapping[ip]==highest_id) coordinator=ip;
for(auto x:_am){
if(x.ip==ip) return false;
}
if(ip==machine_ip) machine_id=ip_mapping[ip];
_am.push_back(machine_info(ip,ip_mapping[ip]));
return true;
}
void alive_member::remove(std::string ip){
std::lock_guard<std::mutex> guard(mutex);
// auto it = std::find(_am.begin(), _am.end(), ip);
for(auto it=_am.begin();it!=_am.end();++it){
if((*it).ip==ip){
if((*it).id==highest_id){
int second_highest_id=-1;
for(auto itt=_am.begin();itt!=_am.end();++itt){
int curid=(*itt).id;
if(curid>=second_highest_id && curid!=highest_id){
second_highest_id=curid;
}
}
highest_id=second_highest_id;
}
_am.erase(it);
break;
}
}
}
bool alive_member::exists(std::string ip){
std::lock_guard<std::mutex> guard(mutex);
for(auto x:_am){
if(x.ip==ip) return true;
}
return false;
}
std::vector<std::string> alive_member::get_alive_member(){
std::lock_guard<std::mutex> guard(mutex);
std::vector<std::string> ret;
for(auto x:_am){
ret.push_back(x.ip);
}
return ret;
}
std::vector<std::string> alive_member::random_select_K(size_t K,std::vector<std::string> v){
if(K>=v.size()) return v;
std::vector<std::string> reservoir(K);
srand(time(NULL));
size_t i=0;
for (size_t i = 0; i < K; i++)
reservoir[i] = v[i];
i=0;
for(auto x:v){
size_t j=rand()%(i+1);
if(j<K){
reservoir[j]=v[i];
}
i++;
}
return reservoir;
}
std::string alive_member::get_alive_member_list(){
std::lock_guard<std::mutex> guard(mutex);
std::string ret;
for(auto x:_am){
ret+=x.ip;
ret+=":";
ret+=std::to_string(x.id);
ret+=" ";
}
return ret;
}
std::vector<machine_info> alive_member::get_alive_member_with_id(){
std::lock_guard<std::mutex> guard(mutex);
return _am;
} | [
"ysong71@illinois.edu"
] | ysong71@illinois.edu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.