hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ecc90a195b2c23533e38ab29f2058fc49afa0c10
| 14,279
|
cpp
|
C++
|
MongoDB/samples/SQLToMongo/src/SQLToMongo.cpp
|
abyss7/poco
|
a651a78c76eebd414b37745f7dd8539460154cab
|
[
"BSL-1.0"
] | null | null | null |
MongoDB/samples/SQLToMongo/src/SQLToMongo.cpp
|
abyss7/poco
|
a651a78c76eebd414b37745f7dd8539460154cab
|
[
"BSL-1.0"
] | 3
|
2021-06-02T02:59:06.000Z
|
2021-09-16T04:35:06.000Z
|
MongoDB/samples/SQLToMongo/src/SQLToMongo.cpp
|
abyss7/poco
|
a651a78c76eebd414b37745f7dd8539460154cab
|
[
"BSL-1.0"
] | 6
|
2021-06-02T02:39:34.000Z
|
2022-03-29T05:51:57.000Z
|
//
// main.cpp
//
// $Id$
//
// This sample shows SQL to mongo Shell to C++ examples.
//
// Copyright (c) 2013, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/MongoDB/MongoDB.h"
#include "Poco/MongoDB/Connection.h"
#include "Poco/MongoDB/Database.h"
#include "Poco/MongoDB/Cursor.h"
#include "Poco/MongoDB/Array.h"
// INSERT INTO players
// VALUES( "Messi", "Lionel", 1987)
void sample1(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 1 ***" << std::endl;
Poco::MongoDB::Database db("sample");
Poco::SharedPtr<Poco::MongoDB::InsertRequest> insertPlayerRequest = db.createInsertRequest("players");
// With one insert request, we can add multiple documents
insertPlayerRequest->addNewDocument()
.add("lastname", "Valdes")
.add("firstname", "Victor")
.add("birthyear", 1982);
insertPlayerRequest->addNewDocument()
.add("lastname", "Alves")
.add("firstname", "Daniel")
.add("birthyear", 1983);
insertPlayerRequest->addNewDocument()
.add("lastname", "Bartra")
.add("firstname", "Marc")
.add("birthyear", 1991);
insertPlayerRequest->addNewDocument()
.add("lastname", "Alba")
.add("firstname", "Jordi")
.add("birthyear", 1989);
insertPlayerRequest->addNewDocument()
.add("lastname", "Montoya")
.add("firstname", "Martin")
.add("birthyear", 1991);
insertPlayerRequest->addNewDocument()
.add("lastname", "Abidal")
.add("firstname", "Eric")
.add("birthyear", 1979);
insertPlayerRequest->addNewDocument()
.add("lastname", "Fontas")
.add("firstname", "Andreu")
.add("birthyear", 1989);
insertPlayerRequest->addNewDocument()
.add("lastname", "Messi")
.add("firstname", "Lionel")
.add("birthyear", 1987);
insertPlayerRequest->addNewDocument()
.add("lastname", "Puyol")
.add("firstname", "Carles")
.add("birthyear", 1978);
insertPlayerRequest->addNewDocument()
.add("lastname", "Piqué")
.add("firstname", "Gerard")
.add("birthyear", 1987);
insertPlayerRequest->addNewDocument()
.add("lastname", "Muniesa")
.add("firstname", "Marc")
.add("birthyear", 1992);
insertPlayerRequest->addNewDocument()
.add("lastname", "Fabrégas")
.add("firstname", "Cesc")
.add("birthyear", 1987);
insertPlayerRequest->addNewDocument()
.add("lastname", "Hernandez")
.add("firstname", "Xavi")
.add("birthyear", 1980);
insertPlayerRequest->addNewDocument()
.add("lastname", "Iniesta")
.add("firstname", "Andres")
.add("birthyear", 1984);
insertPlayerRequest->addNewDocument()
.add("lastname", "Alcantara")
.add("firstname", "Thiago")
.add("birthyear", 1991);
insertPlayerRequest->addNewDocument()
.add("lastname", "Dos Santos")
.add("firstname", "Jonathan")
.add("birthyear", 1990);
insertPlayerRequest->addNewDocument()
.add("lastname", "Mascherano")
.add("firstname", "Javier")
.add("birthyear", 1984);
insertPlayerRequest->addNewDocument()
.add("lastname", "Busquets")
.add("firstname", "Sergio")
.add("birthyear", 1988);
insertPlayerRequest->addNewDocument()
.add("lastname", "Adriano")
.add("firstname", "")
.add("birthyear", 1984);
insertPlayerRequest->addNewDocument()
.add("lastname", "Song")
.add("firstname", "Alex")
.add("birthyear", 1987);
insertPlayerRequest->addNewDocument()
.add("lastname", "Villa")
.add("firstname", "David")
.add("birthyear", 1981);
insertPlayerRequest->addNewDocument()
.add("lastname", "Sanchez")
.add("firstname", "Alexis")
.add("birthyear", 1988);
insertPlayerRequest->addNewDocument()
.add("lastname", "Pedro")
.add("firstname", "")
.add("birthyear", 1987);
insertPlayerRequest->addNewDocument()
.add("lastname", "Cuenca")
.add("firstname", "Isaac")
.add("birthyear", 1991);
insertPlayerRequest->addNewDocument()
.add("lastname", "Tello")
.add("firstname", "Cristian")
.add("birthyear", 1991);
std::cout << insertPlayerRequest->documents().size() << std::endl;
connection.sendRequest(*insertPlayerRequest);
std::string lastError = db.getLastError(connection);
if (!lastError.empty())
{
std::cout << "Last Error: " << db.getLastError(connection) << std::endl;
}
}
// SELECT lastname, birthyear FROM players
void sample2(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 2 ***" << std::endl;
Poco::MongoDB::Cursor cursor("sample", "players");
// Selecting fields is done by adding them to the returnFieldSelector
// Use 1 as value of the element.
cursor.query().returnFieldSelector().add("lastname", 1);
cursor.query().returnFieldSelector().add("birthyear", 1);
Poco::MongoDB::ResponseMessage& response = cursor.next(connection);
for (;;)
{
for (Poco::MongoDB::Document::Vector::const_iterator it = response.documents().begin(); it != response.documents().end(); ++it)
{
std::cout << (*it)->get<std::string>("lastname") << " (" << (*it)->get<int>("birthyear") << ')' << std::endl;
}
// When the cursorID is 0, there are no documents left, so break out ...
if (response.cursorID() == 0)
{
break;
}
// Get the next bunch of documents
response = cursor.next(connection);
}
}
// SELECT * FROM players
void sample3(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 3 ***" << std::endl;
Poco::MongoDB::Cursor cursor("sample", "players");
Poco::MongoDB::ResponseMessage& response = cursor.next(connection);
for (;;)
{
for (Poco::MongoDB::Document::Vector::const_iterator it = response.documents().begin(); it != response.documents().end(); ++it)
{
std::cout << (*it)->get<std::string>("lastname") << ' ' << (*it)->get<std::string>("firstname") << " (" << (*it)->get<int>("birthyear") << ')' << std::endl;
}
// When the cursorID is 0, there are no documents left, so break out ...
if (response.cursorID() == 0)
{
break;
}
// Get the next bunch of documents
response = cursor.next(connection);
};
}
// SELECT * FROM players WHERE birthyear = 1978
void sample4(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 4 ***" << std::endl;
Poco::MongoDB::Cursor cursor("sample", "players");
cursor.query().selector().add("birthyear", 1978);
Poco::MongoDB::ResponseMessage& response = cursor.next(connection);
for (;;)
{
for (Poco::MongoDB::Document::Vector::const_iterator it = response.documents().begin(); it != response.documents().end(); ++it)
{
std::cout << (*it)->get<std::string>("lastname") << ' ' << (*it)->get<std::string>("firstname") << " (" << (*it)->get<int>("birthyear") << ')' << std::endl;
}
// When the cursorID is 0, there are no documents left, so break out ...
if (response.cursorID() == 0)
{
break;
}
// Get the next bunch of documents
response = cursor.next(connection);
};
}
// SELECT * FROM players WHERE birthyear = 1987 ORDER BY name
void sample5(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 5 ***" << std::endl;
Poco::MongoDB::Cursor cursor("sample", "players");
// When orderby is needed, use 2 separate documents in the query selector
cursor.query().selector().addNewDocument("$query").add("birthyear", 1987);
cursor.query().selector().addNewDocument("$orderby").add("lastname", 1);
Poco::MongoDB::ResponseMessage& response = cursor.next(connection);
for (;;)
{
for (Poco::MongoDB::Document::Vector::const_iterator it = response.documents().begin(); it != response.documents().end(); ++it)
{
std::cout << (*it)->get<std::string>("lastname") << ' ' << (*it)->get<std::string>("firstname") << " (" << (*it)->get<int>("birthyear") << ')' << std::endl;
}
// When the cursorID is 0, there are no documents left, so break out ...
if (response.cursorID() == 0)
{
break;
}
// Get the next bunch of documents
response = cursor.next(connection);
};
}
// SELECT * FROM players WHERE birthyear > 1969 and birthyear <= 1980
void sample6(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 6 ***" << std::endl;
Poco::MongoDB::Cursor cursor("sample", "players");
cursor.query().selector().addNewDocument("birthyear")
.add("$gt", 1969)
.add("$lte", 1980);
Poco::MongoDB::ResponseMessage& response = cursor.next(connection);
for (;;)
{
for (Poco::MongoDB::Document::Vector::const_iterator it = response.documents().begin(); it != response.documents().end(); ++it)
{
std::cout << (*it)->get<std::string>("lastname") << ' ' << (*it)->get<std::string>("firstname") << " (" << (*it)->get<int>("birthyear") << ')' << std::endl;
}
// When the cursorID is 0, there are no documents left, so break out ...
if (response.cursorID() == 0)
{
break;
}
// Get the next bunch of documents
response = cursor.next(connection);
};
}
// CREATE INDEX playername
// ON players(lastname)
void sample7(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 7 ***" << std::endl;
Poco::MongoDB::Database db("sample");
Poco::MongoDB::Document::Ptr keys = new Poco::MongoDB::Document();
keys->add("lastname", 1);
Poco::MongoDB::Document::Ptr errorDoc = db.ensureIndex(connection, "players", "lastname", keys);
/* Sample above is the same as the following code:
Poco::MongoDB::Document::Ptr index = new Poco::MongoDB::Document();
index->add("ns", "sample.players");
index->add("name", "lastname");
index->addNewDocument("key").add("lastname", 1);
Poco::SharedPtr<Poco::MongoDB::InsertRequest> insertRequest = db.createInsertRequest("system.indexes");
insertRequest->documents().push_back(index);
connection.sendRequest(*insertRequest);
Poco::MongoDB::Document::Ptr errorDoc = db.getLastErrorDoc(connection);
*/
std::cout << errorDoc->toString(2);
}
// SELECT * FROM players LIMIT 10 SKIP 20
void sample8(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 8 ***" << std::endl;
Poco::MongoDB::Cursor cursor("sample", "players");
cursor.query().setNumberToReturn(10);
cursor.query().setNumberToSkip(20);
Poco::MongoDB::ResponseMessage& response = cursor.next(connection);
for (;;)
{
for (Poco::MongoDB::Document::Vector::const_iterator it = response.documents().begin(); it != response.documents().end(); ++it)
{
std::cout << (*it)->get<std::string>("lastname") << ' ' << (*it)->get<std::string>("firstname") << " (" << (*it)->get<int>("birthyear") << ')' << std::endl;
}
// When the cursorID is 0, there are no documents left, so break out ...
if (response.cursorID() == 0)
{
break;
}
// Get the next bunch of documents
response = cursor.next(connection);
};
}
// SELECT * FROM players LIMIT 1
void sample9(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 9 ***" << std::endl;
// QueryRequest can be used directly
Poco::MongoDB::QueryRequest query("sample.players");
query.setNumberToReturn(1);
Poco::MongoDB::ResponseMessage response;
connection.sendRequest(query, response);
if (response.hasDocuments())
{
std::cout << response.documents()[0]->toString(2) << std::endl;
}
// QueryRequest can be created using the Database class
Poco::MongoDB::Database db("sample");
Poco::SharedPtr<Poco::MongoDB::QueryRequest> queryPtr = db.createQueryRequest("players");
queryPtr->setNumberToReturn(1);
connection.sendRequest(*queryPtr, response);
if (response.hasDocuments())
{
std::cout << response.documents()[0]->toString(2) << std::endl;
}
}
// SELECT DISTINCT birthyear FROM players WHERE birthyear > 1980
void sample10(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 10 ***" << std::endl;
Poco::MongoDB::Database db("sample");
Poco::SharedPtr<Poco::MongoDB::QueryRequest> command = db.createCommand();
command->selector()
.add("distinct", "players")
.add("key", "birthyear")
.addNewDocument("query")
.addNewDocument("birthyear")
.add("$gt", 1980);
Poco::MongoDB::ResponseMessage response;
connection.sendRequest(*command, response);
if (response.hasDocuments())
{
Poco::MongoDB::Array::Ptr values = response.documents()[0]->get<Poco::MongoDB::Array::Ptr>("values");
for (int i = 0; i < values->size(); ++i )
{
std::cout << values->get<int>(i) << std::endl;
}
}
}
// SELECT COUNT(*) FROM players WHERE birthyear > 1980
void sample11(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 11 ***" << std::endl;
Poco::MongoDB::Database db("sample");
Poco::SharedPtr<Poco::MongoDB::QueryRequest> count = db.createCountRequest("players");
count->selector().addNewDocument("query")
.addNewDocument("birthyear")
.add("$gt", 1980);
Poco::MongoDB::ResponseMessage response;
connection.sendRequest(*count, response);
if (response.hasDocuments())
{
std::cout << "Count: " << response.documents()[0]->getInteger("n") << std::endl;
}
}
//UPDATE players SET birthyear = birthyear + 1 WHERE firstname = 'Victor'
void sample12(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 12 ***" << std::endl;
Poco::MongoDB::Database db("sample");
Poco::SharedPtr<Poco::MongoDB::UpdateRequest> request = db.createUpdateRequest("players");
request->selector().add("firstname", "Victor");
request->update().addNewDocument("$inc").add("birthyear", 1);
connection.sendRequest(*request);
Poco::MongoDB::Document::Ptr lastError = db.getLastErrorDoc(connection);
std::cout << "LastError: " << lastError->toString(2) << std::endl;
}
//DELETE players WHERE firstname = 'Victor'
void sample13(Poco::MongoDB::Connection& connection)
{
std::cout << "*** SAMPLE 13 ***" << std::endl;
Poco::MongoDB::Database db("sample");
Poco::SharedPtr<Poco::MongoDB::DeleteRequest> request = db.createDeleteRequest("players");
request->selector().add("firstname", "Victor");
connection.sendRequest(*request);
Poco::MongoDB::Document::Ptr lastError = db.getLastErrorDoc(connection);
std::cout << "LastError: " << lastError->toString(2) << std::endl;
}
int main(int argc, char** argv)
{
Poco::MongoDB::Connection connection("localhost", 27017);
try
{
sample1(connection);
sample2(connection);
sample3(connection);
sample4(connection);
sample5(connection);
sample6(connection);
sample7(connection);
sample8(connection);
sample9(connection);
sample10(connection);
sample11(connection);
sample12(connection);
sample13(connection);
}
catch (Poco::Exception& exc)
{
std::cerr << exc.displayText() << std::endl;
}
return 0;
}
| 29.810021
| 159
| 0.663702
|
abyss7
|
ecca2c85028fc214c245c0c32dc1e89412bb87c1
| 594
|
cc
|
C++
|
test/asan/TestCases/use-after-poison.cc
|
crystax/android-toolchain-compiler-rt-3-7
|
6b848d1e7d55df3227b212aa229f8b60b16bdd5d
|
[
"MIT"
] | 21
|
2015-04-19T20:47:50.000Z
|
2019-03-08T18:39:41.000Z
|
test/asan/TestCases/use-after-poison.cc
|
crystax/android-toolchain-compiler-rt-3-7
|
6b848d1e7d55df3227b212aa229f8b60b16bdd5d
|
[
"MIT"
] | 1
|
2016-02-10T15:40:03.000Z
|
2016-02-10T15:40:03.000Z
|
test/asan/TestCases/use-after-poison.cc
|
crystax/android-toolchain-compiler-rt-3-7
|
6b848d1e7d55df3227b212aa229f8b60b16bdd5d
|
[
"MIT"
] | 12
|
2019-06-21T03:33:51.000Z
|
2021-12-13T09:08:31.000Z
|
// Check that __asan_poison_memory_region works.
// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s
//
// Check that we can disable it
// RUN: env ASAN_OPTIONS=$ASAN_OPTIONS:allow_user_poisoning=0 %run %t
#include <stdlib.h>
extern "C" void __asan_poison_memory_region(void *, size_t);
int main(int argc, char **argv) {
char *x = new char[16];
x[10] = 0;
__asan_poison_memory_region(x, 16);
int res = x[argc * 10]; // BOOOM
// CHECK: ERROR: AddressSanitizer: use-after-poison
// CHECK: main{{.*}}use-after-poison.cc:[[@LINE-2]]
delete [] x;
return res;
}
| 28.285714
| 69
| 0.6633
|
crystax
|
ecd362a4100bf815d2c2b50f074575bd8f6cff07
| 4,365
|
cpp
|
C++
|
source/Reeval/MMASib_experiments.cpp
|
fq00/noisyLandscapes
|
5866a6f523e4e99f9b1ab68b08b2443821ec10dd
|
[
"MIT"
] | null | null | null |
source/Reeval/MMASib_experiments.cpp
|
fq00/noisyLandscapes
|
5866a6f523e4e99f9b1ab68b08b2443821ec10dd
|
[
"MIT"
] | null | null | null |
source/Reeval/MMASib_experiments.cpp
|
fq00/noisyLandscapes
|
5866a6f523e4e99f9b1ab68b08b2443821ec10dd
|
[
"MIT"
] | null | null | null |
//
// rAnalysis.cpp
// Reeval
//
// Created by Francesco Quinzan on 26.11.15.
// Copyright © 2015 Francesco Quinzan. All rights reserved.
//
#include "MMASib_experiments.hpp"
void MMASib_experiments::parameter_calibration(string dir, int seed){
randomEngine::set_seed(seed);
int sample_size = 100;
typedef std::numeric_limits< double > dbl;
/* variables */
int dimension = 100;
double sigma = ::sqrt(10);
int r = 1;
/* output file */
ofstream MMASib_results;
MMASib_results.precision(dbl::max_digits10);
MMASib_results.open(dir + "/MMASib_parameter_calibration.txt");
header::make_header(&MMASib_results, "MMASib", seed);
MMASib_experiments::make_legend(&MMASib_results);
for (int n_ants = 2; n_ants < 15; n_ants++){
for (double evaporation = 0.03; evaporation < 0.06; evaporation = evaporation + 0.002){
ACO ACO(dimension, n_ants, evaporation);
ACO.posteriorNoise(sigma, r);
/* run for given number of steps */
for (int k = 0; k < sample_size; k++){
MMASib_results << dimension << " ";
MMASib_results << n_ants << " ";
MMASib_results << evaporation << " ";
MMASib_results << sigma << " ";
MMASib_results << r << " ";
MMASib_results << ACO.run()*n_ants*r << endl;
}
}
}
MMASib_results.close();
return;
};
void MMASib_experiments::r_analysis(string dir, int seed){
randomEngine::set_seed(seed);
int sample_size = 100;
/* variables */
int dimension = 100;
double evaporation = 0.045;
int n_ants = 5;
double sigma = ::sqrt(100);
int results = 0;
/* output file */
ofstream MMASib_results;
MMASib_results.open(dir + "/MMASib_r_analysis.txt");
header::make_header(&MMASib_results, "MMASib", seed);
MMASib_experiments::make_legend(&MMASib_results);
for (int r = 1; r < 100; r++){
ACO ACO(dimension, n_ants, evaporation);
ACO.posteriorNoise(sigma, r);
/* run for given number of steps */
for (int k = 0; k < sample_size; k++){
results = ACO.run();
results = results*n_ants*r;
cout << results << endl;
MMASib_results << dimension << " ";
MMASib_results << n_ants << " ";
MMASib_results << evaporation << " ";
MMASib_results << sigma << " ";
MMASib_results << r << " ";
MMASib_results << results << endl;
}
}
MMASib_results.close();
return;
};
void MMASib_experiments::variance_analysis(string dir, int seed){
randomEngine::set_seed(seed);
int sample_size = 100;
/* variables */
int dimension = 100;
double evaporation = 0.045;
int n_ants = 5;
int r = 5;
int results = 0;
/* output file */
ofstream MMASib_results;
MMASib_results.open(dir + "/MMASib_variance_analysis.txt");
header::make_header(&MMASib_results, "MMASib", seed);
MMASib_experiments::make_legend(&MMASib_results);
for (double sigma = ::sqrt(0); sigma < ::sqrt(10)*14; sigma = sigma + ::sqrt(10)/2){
ACO ACO(dimension, n_ants, evaporation);
ACO.posteriorNoise(sigma, r);
/* run for given number of steps */
for (int k = 10; k < sample_size; k++){
results = ACO.run()*n_ants*r;
cout << results << endl;
MMASib_results << dimension << " ";
MMASib_results << n_ants << " ";
MMASib_results << evaporation << " ";
MMASib_results << sigma << " ";
MMASib_results << r << " ";
MMASib_results << results << endl;
}
}
MMASib_results.close();
return;
};
void MMASib_experiments::make_legend(ofstream* file){
*file << "DIMENSION" << " ";
*file << "N_ANTS" << " ";
*file << "EVAPORATION" << " ";
*file << "SIGMA" << " ";
*file << "N_RE_EVALUATIONS" << " ";
*file << "N_FITNESS_EVALUATIONS" << endl;
};
| 26.779141
| 95
| 0.529439
|
fq00
|
ecd3aae26ea04430c1ff48dcc3b931f294fa0f57
| 915
|
cpp
|
C++
|
Backends/System/Windows/Sources/Kore/Input/Mouse.cpp
|
psmtec/Kore
|
3665641e1c411bfafbf55aa946dc8636eb379a12
|
[
"Zlib"
] | null | null | null |
Backends/System/Windows/Sources/Kore/Input/Mouse.cpp
|
psmtec/Kore
|
3665641e1c411bfafbf55aa946dc8636eb379a12
|
[
"Zlib"
] | null | null | null |
Backends/System/Windows/Sources/Kore/Input/Mouse.cpp
|
psmtec/Kore
|
3665641e1c411bfafbf55aa946dc8636eb379a12
|
[
"Zlib"
] | null | null | null |
#include "../pch.h"
#include <Kore/Input/Mouse.h>
#include <Kore/System.h>
#include <Kore/Window.h>
#include <Windows.h>
using namespace Kore;
void Mouse::_lock(int windowId, bool truth) {
show(!truth);
if (truth) {
HWND handle = Kore::Window::get(windowId)->_data.handle;
SetCapture(handle);
RECT rect;
GetWindowRect(handle, &rect);
ClipCursor(&rect);
}
else {
ReleaseCapture();
ClipCursor(nullptr);
}
}
bool Mouse::canLock(int windowId) {
return true;
}
void Mouse::show(bool truth) {
ShowCursor(truth);
}
void Mouse::setPosition(int windowId, int x, int y) {
POINT point;
point.x = x;
point.y = y;
ClientToScreen(Window::get(windowId)->_data.handle, &point);
SetCursorPos(point.x, point.y);
}
void Mouse::getPosition(int windowId, int& x, int& y) {
POINT point;
GetCursorPos(&point);
ScreenToClient(Window::get(windowId)->_data.handle, &point);
x = point.x;
y = point.y;
}
| 18.673469
| 61
| 0.68306
|
psmtec
|
ecd6361fb7eb8012b86da23f244376a3df282638
| 3,958
|
cpp
|
C++
|
engine/utils/grabfont.cpp
|
jpmorris33/ire
|
d6a0a9468c1f98010c5959be301b717f02336895
|
[
"BSD-3-Clause"
] | null | null | null |
engine/utils/grabfont.cpp
|
jpmorris33/ire
|
d6a0a9468c1f98010c5959be301b717f02336895
|
[
"BSD-3-Clause"
] | 8
|
2020-03-29T21:03:23.000Z
|
2020-04-11T23:28:14.000Z
|
engine/utils/grabfont.cpp
|
jpmorris33/ire
|
d6a0a9468c1f98010c5959be301b717f02336895
|
[
"BSD-3-Clause"
] | 1
|
2020-06-11T16:54:37.000Z
|
2020-06-11T16:54:37.000Z
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define IRE_FNT1 0x31544e46
#define IRE_FNT2 0x32544e46
int Getpixel(int x, int y);
int FindNextRow(int start, int *height);
int FindNextCharacter(int x, int y, int *width);
int W,H;
int nullcolour=0;
unsigned char buffer[131072];
int main(int argc, char *argv[])
{
FILE *fpo,*fpi;
char filename[256];
int ctr;
unsigned char Pal[768];
int val,w,h,mw,mh,x,y;
int GotPal=0;
int colour=0;
mw=mh=0;
memset(Pal,0,768);
if(argc < 3 || (argv[1][0] == '-'))
{
printf("Usage: grabfont <input.cel> <output.fnt> [-colour]\n");
printf(" Attempts to extract a font from a single large .CEL grid\n");
exit(1);
}
// Colour or monochrome?
if(argc > 3)
if(strcmp(argv[3],"-colour") == 0 || strcmp(argv[3],"-color") == 0)
colour=1;
fpi=fopen(argv[1],"rb");
if(!fpi)
{
printf("Error opening input file '%s'\n",argv[1]);
exit(1);
}
val=0;
fread(&val,1,2,fpi);
if(val != 0x9119)
{
printf("Error: File is not a valid Animator 1 CEL file\n");
exit(1);
}
w=0;
fread(&w,1,2,fpi);
h=0;
fread(&h,1,2,fpi);
// Global size
W=w;
H=h;
val=w*h;
if(val > 131071)
{
printf("Error: %s is %d bytes long, exceeds 128k!\n",filename,val);
exit(1);
}
fseek(fpi,32L,SEEK_SET); // Skip to the raw data
fread(Pal,1,768,fpi);
fread(buffer,1,val,fpi);
fclose(fpi);
// Read in the CEL file, now try and create an output file
fpo=fopen(argv[2],"wb");
if(!fpo)
{
printf("Error: Could not create file '%s'\n",argv[2]);
exit(1);
}
// Write header
if(colour)
val=IRE_FNT2;
else
val=IRE_FNT1;
fwrite(&val,1,4,fpo);
// Write blank characters up to SPACE
val=0; // W&H = 0 for a null entry
for(ctr=0;ctr<32;ctr++)
fwrite(&val,1,4,fpo); // W&H
nullcolour=buffer[0]; // This is the invalid colour
ctr=32; // start from SPACE
y=0;
do
{
if(ctr>255)
break; // Too many characters
y=FindNextRow(y,&h);
if(y == -1 || h < 1)
break;
// printf("Row start at %d for %d pixels\n",y,h);
x=0;
do
{
if(ctr>255)
break; // Too many characters
x=FindNextCharacter(x,y,&w);
if(x == -1 || w < 1)
break;
// printf("Col start at %d for %d pixels\n",x,w);
// Okay, we have a character
if(w>mw)
mw=w;
if(h>mh)
mh=h;
fwrite(&w,1,2,fpo); // Width
fwrite(&h,1,2,fpo); // Height
for(int vy=0;vy<h;vy++)
for(int vx=0;vx<w;vx++)
fputc(Getpixel(vx+x,vy+y),fpo);
printf("Added %d (%c)\n",ctr,ctr);
ctr++; // Another character written
x+=w;
} while(x < W);
y+=h;
} while(y < H);
// Okay, now write the remaining entries, starting from whatever ctr is at the moment
val=0; // W&H = 0 for a null entry
for(;ctr<256;ctr++)
fwrite(&val,1,4,fpo); // W&H
// Palette conversion
for(ctr=0;ctr<768;ctr++)
Pal[ctr]=Pal[ctr]<<2;
if(colour)
fwrite(Pal,1,768,fpo);
fclose(fpo);
printf("Wrote %s font file %s\n",colour?"colour":"monochrome",argv[1]);
printf("Largest character was %dx%d pixels\n",mw,mh);
}
int Getpixel(int x, int y)
{
if(x<0 || x>=W)
return -1;
if(y<0 || y>=H)
return -1;
return buffer[(y*W)+x];
}
//
// Find a row of characters
//
int FindNextRow(int start, int *height)
{
int x,y;
int startrow=-1;
int endrow=-1;
int found;
*height=0;
found=0;
for(y=start;y<H;y++)
{
for(x=0;x<W;x++)
if(Getpixel(x,y) != nullcolour)
{
found=1;
break;
}
if(found)
{
startrow=y;
break;
}
}
if(startrow == -1)
return -1;
// Find end of row
for(y=startrow;y<H;y++)
{
found=0;
for(x=0;x<W;x++)
if(Getpixel(x,y) != nullcolour)
found=1;
if(!found)
{
endrow=y;
break;
}
}
if(endrow == -1)
return -1;
*height=endrow-startrow;
return startrow;
}
int FindNextCharacter(int x, int y, int *width)
{
int ctr;
int st=-1;
int nd=-1;
*width=0;
for(ctr=x;ctr<W;ctr++)
if(Getpixel(ctr,y) != nullcolour)
{
st=ctr;
break;
}
if(st == -1)
return -1;
for(ctr=st;ctr<W;ctr++)
if(Getpixel(ctr,y) == nullcolour)
{
nd=ctr;
break;
}
if(nd == -1)
return -1;
*width=nd-st;
return st;
}
| 15.281853
| 85
| 0.602072
|
jpmorris33
|
ecd9dde3446b314caf24c7374a0cbd70cf1a7f97
| 1,366
|
cpp
|
C++
|
soil.cpp
|
ZacharyWesterman/pico-sandbox
|
4ab83b7a52242a6a684bf5aef3cd39fb1b4d9c30
|
[
"Unlicense"
] | null | null | null |
soil.cpp
|
ZacharyWesterman/pico-sandbox
|
4ab83b7a52242a6a684bf5aef3cd39fb1b4d9c30
|
[
"Unlicense"
] | null | null | null |
soil.cpp
|
ZacharyWesterman/pico-sandbox
|
4ab83b7a52242a6a684bf5aef3cd39fb1b4d9c30
|
[
"Unlicense"
] | null | null | null |
#include "soil.hpp"
#include "pico/stdlib.h"
soil::soil(i2c_inst_t* i2c_instance, uint i2c_address) noexcept
{
i2c = i2c_instance;
address = i2c_address;
}
float soil::temperature(char degrees) const noexcept
{
//Request temperature
const uint8_t txdata[2] = { 0x00, 0x04 };
i2c_write_blocking(i2c, address, txdata, 2, false);
sleep_ms(1);//wait a little bit for response.
//Read temperature
uint8_t rxdata[4];
i2c_read_blocking(i2c, address, rxdata, 4, false);
//Convert to Celcius
int32_t tempdata = ((int32_t)rxdata[0] << 24) | ((int32_t)rxdata[1] << 16) | ((int32_t)rxdata[2] << 8) | (int32_t)rxdata[3];
float temp = (1.0f / (1UL << 16)) * tempdata;
//Convert to chosen scale.
//Note "efficiency" doesn't really matter here,
//since we're already waiting 1ms above.
if (degrees == 'C') return temp; //Celcius
if (degrees == 'F') return (temp * 1.8) + 32; //Fahrenheit
if (degrees == 'R') return temp * 1.8; //Rankine
return temp + 273; //Default to Kelvin.
}
uint16_t soil::moisture() const noexcept
{
//Request moisture measurement
const uint8_t txdata[2] = { 0x0F, 0x10 };
i2c_write_blocking(i2c, address, txdata, 2, false);
sleep_ms(10); //delay to allow sampling
//Read moisture measurement
uint8_t rxdata[2];
i2c_read_blocking(i2c, address, rxdata, 2, false);
return ((uint16_t)rxdata[0] << 8) | (uint16_t)rxdata[1];
}
| 27.32
| 125
| 0.688141
|
ZacharyWesterman
|
ecdbd986f8b950e695d4919071ecaa7cd73a1e7c
| 1,919
|
hpp
|
C++
|
include/elemental/matrices/Identity.hpp
|
ahmadia/Elemental-1
|
f9a82c76a06728e9e04a4316e41803efbadb5a19
|
[
"BSD-3-Clause"
] | null | null | null |
include/elemental/matrices/Identity.hpp
|
ahmadia/Elemental-1
|
f9a82c76a06728e9e04a4316e41803efbadb5a19
|
[
"BSD-3-Clause"
] | null | null | null |
include/elemental/matrices/Identity.hpp
|
ahmadia/Elemental-1
|
f9a82c76a06728e9e04a4316e41803efbadb5a19
|
[
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef MATRICES_IDENTITY_HPP
#define MATRICES_IDENTITY_HPP
#include "elemental/blas-like/level1/Zero.hpp"
namespace elem {
template<typename T>
inline void
Identity( Matrix<T>& I, int m, int n )
{
#ifndef RELEASE
CallStackEntry entry("Identity");
#endif
I.ResizeTo( m, n );
MakeIdentity( I );
}
template<typename T,Distribution U,Distribution V>
inline void
Identity( DistMatrix<T,U,V>& I, int m, int n )
{
#ifndef RELEASE
CallStackEntry entry("Identity");
#endif
I.ResizeTo( m, n );
MakeIdentity( I );
}
template<typename T>
inline void
MakeIdentity( Matrix<T>& I )
{
#ifndef RELEASE
CallStackEntry entry("MakeIdentity");
#endif
Zero( I );
const int m = I.Height();
const int n = I.Width();
for( int j=0; j<std::min(m,n); ++j )
I.Set( j, j, T(1) );
}
template<typename T,Distribution U,Distribution V>
inline void
MakeIdentity( DistMatrix<T,U,V>& I )
{
#ifndef RELEASE
CallStackEntry entry("MakeIdentity");
#endif
Zero( I.Matrix() );
const int localHeight = I.LocalHeight();
const int localWidth = I.LocalWidth();
const int colShift = I.ColShift();
const int rowShift = I.RowShift();
const int colStride = I.ColStride();
const int rowStride = I.RowStride();
for( int jLocal=0; jLocal<localWidth; ++jLocal )
{
const int j = rowShift + jLocal*rowStride;
for( int iLocal=0; iLocal<localHeight; ++iLocal )
{
const int i = colShift + iLocal*colStride;
if( i == j )
I.SetLocal( iLocal, jLocal, T(1) );
}
}
}
} // namespace elem
#endif // ifndef MATRICES_IDENTITY_HPP
| 23.120482
| 73
| 0.647733
|
ahmadia
|
ecdcd7a2bf47ea5e9081e0e6b305cd7101aeb747
| 1,603
|
hpp
|
C++
|
third_party/boost/simd/constant/signmask.hpp
|
SylvainCorlay/pythran
|
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
|
[
"BSD-3-Clause"
] | 6
|
2018-02-25T22:23:33.000Z
|
2021-01-15T15:13:12.000Z
|
third_party/boost/simd/constant/signmask.hpp
|
SylvainCorlay/pythran
|
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
|
[
"BSD-3-Clause"
] | null | null | null |
third_party/boost/simd/constant/signmask.hpp
|
SylvainCorlay/pythran
|
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
|
[
"BSD-3-Clause"
] | 7
|
2017-12-12T12:36:31.000Z
|
2020-02-10T14:27:07.000Z
|
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_CONSTANT_SIGNMASK_HPP_INCLUDED
#define BOOST_SIMD_CONSTANT_SIGNMASK_HPP_INCLUDED
/*!
@ingroup group-constant
@defgroup constant-Signmask Signmask (function template)
Generates a constant able to mask the sign bit of any value.
@headerref{<boost/simd/constant/signmask.hpp>}
@par Description
1. @code
template<typename T> T Signmask();
@endcode
2. @code
template<typename T> T Signmask( boost::simd::as_<T> const& target );
@endcode
Generates a value of type @c T that evaluates to a value where the most significant bit is set
to 1 (includign for unsigned type).
@par Parameters
| Name | Description |
|--------------------:|:--------------------------------------------------------------------|
| **target** | a [placeholder](@ref type-as) value encapsulating the constant type |
@par Return Value
A value of type @c T that evaluates to `bitwise_cast<T>(1 << sizeof(scalar_of_t<T>)*8-1)`
@par Requirements
- **T** models Value
**/
#include <boost/simd/constant/scalar/signmask.hpp>
#include <boost/simd/constant/simd/signmask.hpp>
#endif
| 30.826923
| 100
| 0.547723
|
SylvainCorlay
|
ecde0c61eed21d8e946bb7adf80b461bab2844d0
| 935
|
hpp
|
C++
|
src/Enums.hpp
|
jason-markham/pinchot-c-api
|
6b28f2b021a249e02b0a9ac87abad4e289cfbd9e
|
[
"BSD-3-Clause"
] | null | null | null |
src/Enums.hpp
|
jason-markham/pinchot-c-api
|
6b28f2b021a249e02b0a9ac87abad4e289cfbd9e
|
[
"BSD-3-Clause"
] | null | null | null |
src/Enums.hpp
|
jason-markham/pinchot-c-api
|
6b28f2b021a249e02b0a9ac87abad4e289cfbd9e
|
[
"BSD-3-Clause"
] | 2
|
2020-11-24T00:56:02.000Z
|
2021-12-07T04:12:53.000Z
|
/**
* Copyright (c) JoeScan Inc. All Rights Reserved.
*
* Licensed under the BSD 3 Clause License. See LICENSE.txt in the project
* root for license information.
*/
#ifndef JOESCAN_ENUMS_H
#define JOESCAN_ENUMS_H
#include "enum.h"
namespace joescan {
// This enum has to agree with the `ConnectionType` enum in the C# API
BETTER_ENUM(ConnectionType, uint8_t, Normal = 0, Mappler = 1)
BETTER_ENUM(ServerConnectionStatus, uint8_t, Disconnected = 0, Connected = 1,
Scanning = 2)
BETTER_ENUM(
UdpPacketType, uint8_t, Invalid = 0,
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// This field is deprecated and kept for historical purposes. Do not use.
Connect = 1,
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
StartScanning = 2, Status = 3, SetWindow = 4, GetMappleTable = 5,
Disconnect = 6, BroadcastConnect = 7)
} // namespace joescan
#endif
| 30.16129
| 77
| 0.59893
|
jason-markham
|
ecde30044bc1faec52caa12086edf74dc8236e7f
| 2,683
|
cpp
|
C++
|
tests/Waves/SignerTests.cpp
|
Khaos-Labs/khaos-wallet-core
|
2c06d49fddf978e0815b208dddef50ee2011c551
|
[
"MIT"
] | 2
|
2020-11-16T08:06:30.000Z
|
2021-06-18T03:21:44.000Z
|
tests/Waves/SignerTests.cpp
|
Khaos-Labs/khaos-wallet-core
|
2c06d49fddf978e0815b208dddef50ee2011c551
|
[
"MIT"
] | null | null | null |
tests/Waves/SignerTests.cpp
|
Khaos-Labs/khaos-wallet-core
|
2c06d49fddf978e0815b208dddef50ee2011c551
|
[
"MIT"
] | null | null | null |
// Copyright © 2017-2020 Khaos Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "HexCoding.h"
#include "PublicKey.h"
#include "Waves/Signer.h"
#include "Waves/Transaction.h"
#include <TrezorCrypto/sodium/keypair.h>
#include <gtest/gtest.h>
using namespace TW;
using namespace TW::Waves;
TEST(WavesSigner, SignTransaction) {
const auto privateKey =
PrivateKey(parse_hex("9864a747e1b97f131fabb6b447296c9b6f0201e79fb3c5356e6c77e89b6a806a"));
const auto publicKeyCurve25519 = privateKey.getPublicKey(TWPublicKeyTypeCURVE25519);
ASSERT_EQ(hex(Data(publicKeyCurve25519.bytes.begin(), publicKeyCurve25519.bytes.end())),
"559a50cb45a9a8e8d4f83295c354725990164d10bb505275d1a3086c08fb935d");
// 3P2uzAzX9XTu1t32GkWw68YFFLwtapWvDds
const auto address = Address(publicKeyCurve25519);
auto input = Proto::SigningInput();
input.set_timestamp(int64_t(1526641218066));
input.set_private_key(privateKey.bytes.data(), privateKey.bytes.size());
auto &message = *input.mutable_transfer_message();
message.set_amount(int64_t(100000000));
message.set_asset(Transaction::WAVES);
message.set_fee(int64_t(100000000));
message.set_fee_asset(Transaction::WAVES);
message.set_to(address.string());
message.set_attachment("falafel");
auto tx1 = Transaction(
input,
/* pub_key */
parse_hex("559a50cb45a9a8e8d4f83295c354725990164d10bb505275d1a3086c08fb935d"));
auto signature = Signer::sign(privateKey, tx1);
EXPECT_EQ(hex(tx1.serializeToSign()),
"0402559a50cb45a9a8e8d4f83295c354725990164d10bb505275d1a3086c08fb935d00000000016372e8"
"52120000000005f5e1000000000005f5e10001570acc4110b78a6d38b34d879b5bba38806202ecf1732f"
"8542000766616c6166656c");
EXPECT_EQ(hex(signature), "af7989256f496e103ce95096b3f52196dd9132e044905fe486da3b829b5e403bcba9"
"5ab7e650a4a33948c2d05cfca2dce4d4df747e26402974490fb4c49fbe8f");
ASSERT_TRUE(publicKeyCurve25519.verify(signature, tx1.serializeToSign()));
}
TEST(WavesSigner, curve25519_pk_to_ed25519) {
const auto publicKeyCurve25519 =
parse_hex("559a50cb45a9a8e8d4f83295c354725990164d10bb505275d1a3086c08fb935d");
auto r = Data();
r.resize(32);
curve25519_pk_to_ed25519(r.data(), publicKeyCurve25519.data());
EXPECT_EQ(hex(r), "ff84c4bfc095df25b01e48807715856d95af93d88c5b57f30cb0ce567ca4ce56");
}
| 43.274194
| 106
| 0.740962
|
Khaos-Labs
|
ecde5f4777f94c406c33ef92760ed81620808356
| 5,497
|
cpp
|
C++
|
FKCore/FKServerConnectionManager.cpp
|
FajraKatviro/FKFramework2
|
0b55b402c255b50fe07ee568bbf46acd6617a6e4
|
[
"MIT"
] | 2
|
2015-10-01T07:25:36.000Z
|
2015-11-02T23:14:10.000Z
|
FKCore/FKServerConnectionManager.cpp
|
FajraKatviro/FKFramework2
|
0b55b402c255b50fe07ee568bbf46acd6617a6e4
|
[
"MIT"
] | 13
|
2015-11-02T22:15:14.000Z
|
2015-11-03T21:08:51.000Z
|
FKCore/FKServerConnectionManager.cpp
|
FajraKatviro/FKFramework2
|
0b55b402c255b50fe07ee568bbf46acd6617a6e4
|
[
"MIT"
] | null | null | null |
#include "FKServerConnectionManager.h"
#include "FKServerInfrastructure.h"
#include "FKClientInfrastructureReferent.h"
#include "FKMessage.h"
#include "FKBasicEvent.h"
#include "FKEventObject.h"
#include "FKLogger.h"
#include "FKBasicEventSubjects.h"
/*!
\class FKServerConnectionManager
\brief This class used to process guest connectors at server-side
*/
/*!
* \brief Create manager for \i connector at \i server with \i parent
*/
FKServerConnectionManager::FKServerConnectionManager(FKServerInfrastructure *server, FKConnector *connector, QObject *parent):
FKConnectionManager(connector,parent),_server(server){
FK_CBEGIN
FK_CEND
}
/*!
* \brief Deletes manager
*/
FKServerConnectionManager::~FKServerConnectionManager(){
FK_DBEGIN
FK_DEND
}
void FKServerConnectionManager::processMessage(FKMessage* msg){
FK_MLOGV("Unexpected message from guest to server",msg->subject())
msg->deleteLater();
}
void FKServerConnectionManager::processGuestEvent(FKBasicEvent* ev){
const QString subject=ev->subject();
const QVariant value=ev->value();
ev->deleteLater();
if(subject==FKBasicEventSubject::login){
_server->syncRequest(this,value);
}else{
FK_MLOGV("Unexpected guest event subject from guest to server",subject)
_server->stopGuestConnection(this);
}
}
void FKServerConnectionManager::processBasicEvent(FKBasicEvent* ev){
FK_MLOGV("Unexpected basic event from guest to server",ev->subject())
ev->deleteLater();
}
void FKServerConnectionManager::processEvent(FKEventObject* ev){
FK_MLOGV("Unexpected event from guest to server",ev->subject())
ev->deleteLater();
}
void FKServerConnectionManager::incomeMessageError(const QString& msgType, const QString& reason){
FK_MLOGV(QString("Income message error from guest to server: ")+reason,msgType)
}
/*!
\class FKServerConnectionManagerR
\brief This class used to process realm connector at server-side
*/
/*!
* \brief Create manager for \i connector at \i server with \i parent
*/
FKServerConnectionManagerR::FKServerConnectionManagerR(FKServerInfrastructure *server, FKConnector *connector, QObject *parent):
FKConnectionManager(connector,parent),_server(server){
FK_CBEGIN
FK_CEND
}
/*!
* \brief Deletes manager
*/
FKServerConnectionManagerR::~FKServerConnectionManagerR(){
FK_DBEGIN
FK_DEND
}
void FKServerConnectionManagerR::processMessage(FKMessage* msg){
_server->messageFromRealm(msg->subject());
msg->deleteLater();
}
void FKServerConnectionManagerR::processGuestEvent(FKBasicEvent* ev){
FK_MLOGV("Unexpected guest event from realm to server",ev->subject())
ev->deleteLater();
}
void FKServerConnectionManagerR::processBasicEvent(FKBasicEvent* ev){
const QString subject=ev->subject();
const QVariant value=ev->value();
ev->deleteLater();
if(subject==FKBasicEventSubject::login){
_server->submitLoginRealm(value);
}else if(subject==FKBasicEventSubject::registerRoomType){
_server->registerRoomTypeRespond(value);
}else if(subject==FKBasicEventSubject::removeRoomType){
_server->removeRoomTypeRespond(value);
}else if(subject==FKBasicEventSubject::createRoom){
_server->createRoomRequested(value);
}else if(subject==FKBasicEventSubject::joinRoom){
_server->clientInvited(value);
}else if(subject==FKBasicEventSubject::roomTypeList){
_server->roomTypesNotification(value);
}else{
FK_MLOGV("Unexpected basic event subject from realm to server",subject)
}
}
void FKServerConnectionManagerR::processEvent(FKEventObject* ev){
FK_MLOGV("Unexpected event from realm to server",ev->subject())
ev->deleteLater();
}
void FKServerConnectionManagerR::incomeMessageError(const QString& msgType, const QString& reason){
FK_MLOGV(QString("Income message error from realm to server: ")+reason,msgType)
}
/*!
\class FKServerConnectionManagerU
\brief This class used to process connectors from users at server-side
*/
/*!
* \brief Create manager for \i connector at \i userSlot with \i parent
*/
FKServerConnectionManagerU::FKServerConnectionManagerU(FKClientInfrastructureReferent* referent, FKConnector *connector, QObject *parent):
FKConnectionManager(connector,parent),_referent(referent){
FK_CBEGIN
FK_CEND
}
/*!
* \brief Deletes manager
*/
FKServerConnectionManagerU::~FKServerConnectionManagerU(){
FK_DBEGIN
FK_DEND
}
void FKServerConnectionManagerU::processMessage(FKMessage* msg){
FK_MLOGV("Unexpected message from user to client referent",msg->subject())
msg->deleteLater();
}
void FKServerConnectionManagerU::processGuestEvent(FKBasicEvent* ev){
FK_MLOGV("Unexpected guest event from user to client referent",ev->subject())
ev->deleteLater();
}
void FKServerConnectionManagerU::processBasicEvent(FKBasicEvent* ev){
const QString subject=ev->subject();
const QVariant value=ev->value();
ev->deleteLater();
if(false/*subject==FKBasicEventSubject::_____*/){
todo;// reconnect event, quit event
}else{
FK_MLOGV("Unexpected basic event subject from user to client referent",subject)
}
}
void FKServerConnectionManagerU::processEvent(FKEventObject* ev){
//_referent->incomeAction(ev);
}
void FKServerConnectionManagerU::incomeMessageError(const QString& msgType, const QString& reason){
FK_MLOGV(QString("Income message error from user to client referent: ")+reason,msgType)
}
| 30.038251
| 138
| 0.744588
|
FajraKatviro
|
ecde884684663576fef3f92ae1d4f7a5c2ffc33e
| 4,811
|
hpp
|
C++
|
core/lgraphbase.hpp
|
MikeAnj/LiveHD_clone
|
d725a3bebc04457be7eb356f27e3b93969ee8d60
|
[
"BSD-3-Clause"
] | 1
|
2022-01-30T03:06:22.000Z
|
2022-01-30T03:06:22.000Z
|
core/lgraphbase.hpp
|
MikeAnj/LiveHD_clone
|
d725a3bebc04457be7eb356f27e3b93969ee8d60
|
[
"BSD-3-Clause"
] | null | null | null |
core/lgraphbase.hpp
|
MikeAnj/LiveHD_clone
|
d725a3bebc04457be7eb356f27e3b93969ee8d60
|
[
"BSD-3-Clause"
] | null | null | null |
// This file is distributed under the BSD 3-Clause License. See LICENSE for details.
#pragma once
#include <iostream>
#include <map>
#include <type_traits>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "iassert.hpp"
#include "lgedge.hpp"
#include "lgraph_base_core.hpp"
#include "mmap_vector.hpp"
class Fwd_edge_iterator;
class Bwd_edge_iterator;
class Fast_edge_iterator;
class Graph_library;
class LGraph_Base : public Lgraph_base_core {
private:
protected:
mmap_lib::vector<Node_internal> node_internal;
static inline constexpr std::string_view unknown_io = "unknown";
Graph_library * library;
absl::flat_hash_map<uint32_t, uint32_t> idx_insert_cache;
Index_ID create_node_space(const Index_ID idx, const Port_ID dst_pid, const Index_ID master_nid, const Index_ID root_nid);
Index_ID get_space_output_pin(const Index_ID idx, const Port_ID dst_pid, Index_ID &root_nid);
Index_ID get_space_output_pin(const Index_ID master_nid, const Index_ID idx, const Port_ID dst_pid, const Index_ID root_nid);
// Index_ID get_space_input_pin(const Index_ID master_nid, const Index_ID idx, bool large = false);
Index_ID create_node_int();
Index_ID add_edge_int(Index_ID dst_nid, Port_ID dst_pid, Index_ID src_nid, Port_ID inp_pid);
Port_ID recompute_io_ports(const Index_ID track_nid);
Index_ID find_idx_from_pid_int(const Index_ID nid, const Port_ID pid) const;
Index_ID find_idx_from_pid(const Index_ID nid, const Port_ID pid) const {
if (likely(node_internal[nid].get_dst_pid() == pid)) { // Common case
return nid;
}
return find_idx_from_pid_int(nid, pid);
}
Index_ID setup_idx_from_pid(const Index_ID nid, const Port_ID pid);
Index_ID get_master_nid(Index_ID idx) const { return node_internal[idx].get_master_root_nid(); }
uint32_t get_bits(Index_ID idx) const {
I(idx < node_internal.size());
I(node_internal[idx].is_root());
return node_internal[idx].get_bits();
}
void set_bits(Index_ID idx, uint32_t bits) {
I(idx < node_internal.size());
I(node_internal[idx].is_root());
node_internal.ref(idx)->set_bits(bits);
}
public:
LGraph_Base() = delete;
LGraph_Base(const LGraph_Base &) = delete;
explicit LGraph_Base(std::string_view _path, std::string_view _name, Lg_type_id lgid) noexcept;
virtual ~LGraph_Base();
virtual void clear();
virtual void sync();
void emplace_back();
#if 1
// WARNING: deprecated: Use get/set_bits(const Node_pin)
void set_bits_pid(Index_ID nid, Port_ID pid, uint32_t bits);
uint32_t get_bits_pid(Index_ID nid, Port_ID pid) const;
uint32_t get_bits_pid(Index_ID nid, Port_ID pid);
#endif
void add_edge(const Index_ID dst_idx, const Index_ID src_idx) {
I(src_idx < node_internal.size());
I(node_internal[src_idx].is_root());
I(dst_idx < node_internal.size());
I(node_internal[dst_idx].is_root());
I(src_idx != dst_idx);
add_edge_int(dst_idx, node_internal[dst_idx].get_dst_pid(), src_idx, node_internal[src_idx].get_dst_pid());
}
void print_stats() const;
const Node_internal &get_node_int(Index_ID idx) const {
I(static_cast<Index_ID>(node_internal.size()) > idx);
return node_internal[idx];
}
/*
Node_internal &get_node_int(Index_ID idx) {
I(static_cast<Index_ID>(node_internal.size()) > idx);
return node_internal[idx];
}
*/
bool is_valid_node(Index_ID nid) const {
if (nid >= node_internal.size())
return false;
return node_internal[nid].is_valid() && node_internal[nid].is_master_root();
}
bool is_valid_node_pin(Index_ID idx) const {
if (idx >= node_internal.size())
return false;
return node_internal[idx].is_valid() && node_internal[idx].is_root();
}
Port_ID get_dst_pid(Index_ID idx) const {
I(static_cast<Index_ID>(node_internal.size()) > idx);
I(node_internal[idx].is_root());
return node_internal[idx].get_dst_pid();
}
bool is_root(Index_ID idx) const {
I(static_cast<Index_ID>(node_internal.size()) > idx);
return node_internal[idx].is_root();
}
static size_t max_size() { return (((size_t)1) << Index_bits) - 1; }
size_t size() const { return node_internal.size(); }
class _init {
public:
_init();
} _static_initializer;
const Graph_library &get_library() const { return *library; }
Graph_library * ref_library() const { return library; }
static void error_int(std::string_view text);
static void warn_int(std::string_view text);
template <typename S, typename... Args>
static void error(const S& format, Args&&... args) {
error_int(fmt::format(format, args...));
}
template <typename S, typename... Args>
static void warn(const S& format, Args&&... args) {
warn_int(fmt::format(format, args...));
}
};
| 31.03871
| 127
| 0.717314
|
MikeAnj
|
ece1eff65c6bb09da113047b761b6e7f13020cf3
| 13,135
|
cpp
|
C++
|
src/dedicated/console/TextConsoleWin32.cpp
|
DeadZoneLuna/csso-src
|
6c978ea304ee2df3796bc9c0d2916bac550050d5
|
[
"Unlicense"
] | 4
|
2021-10-03T05:16:55.000Z
|
2021-12-28T16:49:27.000Z
|
src/dedicated/console/TextConsoleWin32.cpp
|
cafeed28/what
|
08e51d077f0eae50afe3b592543ffa07538126f5
|
[
"Unlicense"
] | null | null | null |
src/dedicated/console/TextConsoleWin32.cpp
|
cafeed28/what
|
08e51d077f0eae50afe3b592543ffa07538126f5
|
[
"Unlicense"
] | 3
|
2022-02-02T18:09:58.000Z
|
2022-03-06T18:54:39.000Z
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// CTextConsoleWin32.cpp: Win32 implementation of the TextConsole class.
//
//////////////////////////////////////////////////////////////////////
#include "TextConsoleWin32.h"
#include "tier0/dbg.h"
#include "utlvector.h"
// Could possibly switch all this code over to using readline. This:
// http://mingweditline.sourceforge.net/?Description
// readline() / add_history(char *)
#ifdef _WIN32
BOOL WINAPI ConsoleHandlerRoutine( DWORD CtrlType )
{
NOTE_UNUSED( CtrlType );
/* TODO ?
if ( CtrlType != CTRL_C_EVENT && CtrlType != CTRL_BREAK_EVENT )
m_System->Stop(); // don't quit on break or ctrl+c
*/
return TRUE;
}
// GetConsoleHwnd() helper function from MSDN Knowledge Base Article Q124103
// needed, because HWND GetConsoleWindow(VOID) is not avaliable under Win95/98/ME
HWND GetConsoleHwnd(void)
{
typedef HWND (WINAPI *PFNGETCONSOLEWINDOW)( VOID );
static PFNGETCONSOLEWINDOW s_pfnGetConsoleWindow = (PFNGETCONSOLEWINDOW) GetProcAddress( GetModuleHandle("kernel32"), "GetConsoleWindow" );
if ( s_pfnGetConsoleWindow )
return s_pfnGetConsoleWindow();
HWND hwndFound; // This is what is returned to the caller.
char pszNewWindowTitle[1024]; // Contains fabricated WindowTitle
char pszOldWindowTitle[1024]; // Contains original WindowTitle
// Fetch current window title.
GetConsoleTitle( pszOldWindowTitle, 1024 );
// Format a "unique" NewWindowTitle.
wsprintf( pszNewWindowTitle,"%d/%d", GetTickCount(), GetCurrentProcessId() );
// Change current window title.
SetConsoleTitle(pszNewWindowTitle);
// Ensure window title has been updated.
Sleep(40);
// Look for NewWindowTitle.
hwndFound = FindWindow( NULL, pszNewWindowTitle );
// Restore original window title.
SetConsoleTitle( pszOldWindowTitle );
return hwndFound;
}
CTextConsoleWin32::CTextConsoleWin32()
{
hinput = NULL;
houtput = NULL;
Attrib = 0;
statusline[0] = '\0';
}
bool CTextConsoleWin32::Init()
{
(void) AllocConsole();
SetTitle( "SOURCE DEDICATED SERVER" );
hinput = GetStdHandle ( STD_INPUT_HANDLE );
houtput = GetStdHandle ( STD_OUTPUT_HANDLE );
if ( !SetConsoleCtrlHandler( &ConsoleHandlerRoutine, TRUE) )
{
Print( "WARNING! TextConsole::Init: Could not attach console hook.\n" );
}
Attrib = FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY ;
SetWindowPos( GetConsoleHwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW );
memset( m_szConsoleText, 0, sizeof( m_szConsoleText ) );
m_nConsoleTextLen = 0;
m_nCursorPosition = 0;
memset( m_szSavedConsoleText, 0, sizeof( m_szSavedConsoleText ) );
m_nSavedConsoleTextLen = 0;
memset( m_aszLineBuffer, 0, sizeof( m_aszLineBuffer ) );
m_nTotalLines = 0;
m_nInputLine = 0;
m_nBrowseLine = 0;
// these are log messages, not related to console
Msg( "\n" );
Msg( "Console initialized.\n" );
return CTextConsole::Init();
}
void CTextConsoleWin32::ShutDown( void )
{
FreeConsole();
}
void CTextConsoleWin32::SetVisible( bool visible )
{
ShowWindow ( GetConsoleHwnd(), visible ? SW_SHOW : SW_HIDE );
m_ConsoleVisible = visible;
}
char * CTextConsoleWin32::GetLine( int index, char *buf, int buflen )
{
while ( 1 )
{
INPUT_RECORD recs[ 1024 ];
unsigned long numread;
unsigned long numevents;
if ( !GetNumberOfConsoleInputEvents( hinput, &numevents ) )
{
Error("CTextConsoleWin32::GetLine: !GetNumberOfConsoleInputEvents");
return NULL;
}
if ( numevents <= 0 )
break;
if ( !ReadConsoleInput( hinput, recs, ARRAYSIZE( recs ), &numread ) )
{
Error("CTextConsoleWin32::GetLine: !ReadConsoleInput");
return NULL;
}
if ( numread == 0 )
return NULL;
for ( int i=0; i < (int)numread; i++ )
{
INPUT_RECORD *pRec = &recs[i];
if ( pRec->EventType != KEY_EVENT )
continue;
if ( pRec->Event.KeyEvent.bKeyDown )
{
// check for cursor keys
if ( pRec->Event.KeyEvent.wVirtualKeyCode == VK_UP )
{
ReceiveUpArrow();
}
else if ( pRec->Event.KeyEvent.wVirtualKeyCode == VK_DOWN )
{
ReceiveDownArrow();
}
else if ( pRec->Event.KeyEvent.wVirtualKeyCode == VK_LEFT )
{
ReceiveLeftArrow();
}
else if ( pRec->Event.KeyEvent.wVirtualKeyCode == VK_RIGHT )
{
ReceiveRightArrow();
}
else
{
char ch;
int nLen;
ch = pRec->Event.KeyEvent.uChar.AsciiChar;
switch ( ch )
{
case '\r': // Enter
nLen = ReceiveNewline();
if ( nLen )
{
strncpy( buf, m_szConsoleText, buflen );
buf[ buflen - 1 ] = 0;
return buf;
}
break;
case '\b': // Backspace
ReceiveBackspace();
break;
case '\t': // TAB
ReceiveTab();
break;
default:
if ( ( ch >= ' ') && ( ch <= '~' ) ) // dont' accept nonprintable chars
{
ReceiveStandardChar( ch );
}
break;
}
}
}
}
}
return NULL;
}
void CTextConsoleWin32::Print( char * pszMsg )
{
if ( m_nConsoleTextLen )
{
int nLen;
nLen = m_nConsoleTextLen;
while ( nLen-- )
{
PrintRaw( "\b \b" );
}
}
PrintRaw( pszMsg );
if ( m_nConsoleTextLen )
{
PrintRaw( m_szConsoleText, m_nConsoleTextLen );
}
UpdateStatus();
}
void CTextConsoleWin32::PrintRaw( const char * pszMsg, int nChars )
{
unsigned long dummy;
if ( houtput == NULL )
{
houtput = GetStdHandle ( STD_OUTPUT_HANDLE );
if ( houtput == NULL )
return;
}
if ( nChars <= 0 )
{
nChars = strlen( pszMsg );
if ( nChars <= 0 )
return;
}
// filter out ASCII BEL characters because windows actually plays a
// bell sound, which can be used to lag the server in a DOS attack.
char * pTempBuf = NULL;
for ( int i = 0; i < nChars; ++i )
{
if ( pszMsg[i] == 0x07 /*BEL*/ )
{
if ( !pTempBuf )
{
pTempBuf = ( char * ) malloc( nChars );
memcpy( pTempBuf, pszMsg, nChars );
}
pTempBuf[i] = '.';
}
}
WriteFile( houtput, pTempBuf ? pTempBuf : pszMsg, nChars, &dummy, NULL );
free( pTempBuf ); // usually NULL
}
int CTextConsoleWin32::GetWidth( void )
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
int nWidth;
nWidth = 0;
if ( GetConsoleScreenBufferInfo( houtput, &csbi ) )
{
nWidth = csbi.dwSize.X;
}
if ( nWidth <= 1 )
nWidth = 80;
return nWidth;
}
void CTextConsoleWin32::SetStatusLine( char * pszStatus )
{
strncpy( statusline, pszStatus, 80 );
statusline[ 79 ] = '\0';
UpdateStatus();
}
void CTextConsoleWin32::UpdateStatus( void )
{
COORD coord;
DWORD dwWritten = 0;
WORD wAttrib[ 80 ];
for ( int i = 0; i < 80; i++ )
{
wAttrib[i] = Attrib; //FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY ;
}
coord.X = coord.Y = 0;
WriteConsoleOutputAttribute( houtput, wAttrib, 80, coord, &dwWritten );
WriteConsoleOutputCharacter( houtput, statusline, 80, coord, &dwWritten );
}
void CTextConsoleWin32::SetTitle( char * pszTitle )
{
SetConsoleTitle( pszTitle );
}
void CTextConsoleWin32::SetColor(WORD attrib)
{
Attrib = attrib;
}
int CTextConsoleWin32::ReceiveNewline( void )
{
int nLen = 0;
PrintRaw( "\n" );
if ( m_nConsoleTextLen )
{
nLen = m_nConsoleTextLen;
m_szConsoleText[ m_nConsoleTextLen ] = 0;
m_nConsoleTextLen = 0;
m_nCursorPosition = 0;
// cache line in buffer, but only if it's not a duplicate of the previous line
if ( ( m_nInputLine == 0 ) || ( strcmp( m_aszLineBuffer[ m_nInputLine - 1 ], m_szConsoleText ) ) )
{
strncpy( m_aszLineBuffer[ m_nInputLine ], m_szConsoleText, MAX_CONSOLE_TEXTLEN );
m_nInputLine++;
if ( m_nInputLine > m_nTotalLines )
m_nTotalLines = m_nInputLine;
if ( m_nInputLine >= MAX_BUFFER_LINES )
m_nInputLine = 0;
}
m_nBrowseLine = m_nInputLine;
}
return nLen;
}
void CTextConsoleWin32::ReceiveBackspace( void )
{
int nCount;
if ( m_nCursorPosition == 0 )
{
return;
}
m_nConsoleTextLen--;
m_nCursorPosition--;
PrintRaw( "\b" );
for ( nCount = m_nCursorPosition; nCount < m_nConsoleTextLen; nCount++ )
{
m_szConsoleText[ nCount ] = m_szConsoleText[ nCount + 1 ];
PrintRaw( m_szConsoleText + nCount, 1 );
}
PrintRaw( " " );
nCount = m_nConsoleTextLen;
while ( nCount >= m_nCursorPosition )
{
PrintRaw( "\b" );
nCount--;
}
m_nBrowseLine = m_nInputLine;
}
void CTextConsoleWin32::ReceiveTab( void )
{
CUtlVector<char *> matches;
m_szConsoleText[ m_nConsoleTextLen ] = 0;
if ( matches.Count() == 0 )
{
return;
}
if ( matches.Count() == 1 )
{
char * pszCmdName;
char * pszRest;
pszCmdName = matches[0];
pszRest = pszCmdName + strlen( m_szConsoleText );
if ( pszRest )
{
PrintRaw( pszRest );
strcat( m_szConsoleText, pszRest );
m_nConsoleTextLen += strlen( pszRest );
PrintRaw( " " );
strcat( m_szConsoleText, " " );
m_nConsoleTextLen++;
}
}
else
{
int nLongestCmd;
int nTotalColumns;
int nCurrentColumn;
char * pszCurrentCmd;
int i = 0;
nLongestCmd = 0;
pszCurrentCmd = matches[0];
while ( pszCurrentCmd )
{
if ( (int)strlen( pszCurrentCmd) > nLongestCmd )
{
nLongestCmd = strlen( pszCurrentCmd);
}
i++;
pszCurrentCmd = (char *)matches[i];
}
nTotalColumns = ( GetWidth() - 1 ) / ( nLongestCmd + 1 );
nCurrentColumn = 0;
PrintRaw( "\n" );
// Would be nice if these were sorted, but not that big a deal
pszCurrentCmd = matches[0];
i = 0;
while ( pszCurrentCmd )
{
char szFormatCmd[ 256 ];
nCurrentColumn++;
if ( nCurrentColumn > nTotalColumns )
{
PrintRaw( "\n" );
nCurrentColumn = 1;
}
Q_snprintf( szFormatCmd, sizeof(szFormatCmd), "%-*s ", nLongestCmd, pszCurrentCmd );
PrintRaw( szFormatCmd );
i++;
pszCurrentCmd = matches[i];
}
PrintRaw( "\n" );
PrintRaw( m_szConsoleText );
// TODO: Tack on 'common' chars in all the matches, i.e. if I typed 'con' and all the
// matches begin with 'connect_' then print the matches but also complete the
// command up to that point at least.
}
m_nCursorPosition = m_nConsoleTextLen;
m_nBrowseLine = m_nInputLine;
}
void CTextConsoleWin32::ReceiveStandardChar( const char ch )
{
int nCount;
// If the line buffer is maxed out, ignore this char
if ( m_nConsoleTextLen >= ( sizeof( m_szConsoleText ) - 2 ) )
{
return;
}
nCount = m_nConsoleTextLen;
while ( nCount > m_nCursorPosition )
{
m_szConsoleText[ nCount ] = m_szConsoleText[ nCount - 1 ];
nCount--;
}
m_szConsoleText[ m_nCursorPosition ] = ch;
PrintRaw( m_szConsoleText + m_nCursorPosition, m_nConsoleTextLen - m_nCursorPosition + 1 );
m_nConsoleTextLen++;
m_nCursorPosition++;
nCount = m_nConsoleTextLen;
while ( nCount > m_nCursorPosition )
{
PrintRaw( "\b" );
nCount--;
}
m_nBrowseLine = m_nInputLine;
}
void CTextConsoleWin32::ReceiveUpArrow( void )
{
int nLastCommandInHistory;
nLastCommandInHistory = m_nInputLine + 1;
if ( nLastCommandInHistory > m_nTotalLines )
{
nLastCommandInHistory = 0;
}
if ( m_nBrowseLine == nLastCommandInHistory )
{
return;
}
if ( m_nBrowseLine == m_nInputLine )
{
if ( m_nConsoleTextLen > 0 )
{
// Save off current text
strncpy( m_szSavedConsoleText, m_szConsoleText, m_nConsoleTextLen );
// No terminator, it's a raw buffer we always know the length of
}
m_nSavedConsoleTextLen = m_nConsoleTextLen;
}
m_nBrowseLine--;
if ( m_nBrowseLine < 0 )
{
m_nBrowseLine = m_nTotalLines - 1;
}
while ( m_nConsoleTextLen-- ) // delete old line
{
PrintRaw( "\b \b" );
}
// copy buffered line
PrintRaw( m_aszLineBuffer[ m_nBrowseLine ] );
strncpy( m_szConsoleText, m_aszLineBuffer[ m_nBrowseLine ], MAX_CONSOLE_TEXTLEN );
m_nConsoleTextLen = strlen( m_aszLineBuffer[ m_nBrowseLine ] );
m_nCursorPosition = m_nConsoleTextLen;
}
void CTextConsoleWin32::ReceiveDownArrow( void )
{
if ( m_nBrowseLine == m_nInputLine )
{
return;
}
m_nBrowseLine++;
if ( m_nBrowseLine > m_nTotalLines )
{
m_nBrowseLine = 0;
}
while ( m_nConsoleTextLen-- ) // delete old line
{
PrintRaw( "\b \b" );
}
if ( m_nBrowseLine == m_nInputLine )
{
if ( m_nSavedConsoleTextLen > 0 )
{
// Restore current text
strncpy( m_szConsoleText, m_szSavedConsoleText, m_nSavedConsoleTextLen );
// No terminator, it's a raw buffer we always know the length of
PrintRaw( m_szConsoleText, m_nSavedConsoleTextLen );
}
m_nConsoleTextLen = m_nSavedConsoleTextLen;
}
else
{
// copy buffered line
PrintRaw( m_aszLineBuffer[ m_nBrowseLine ] );
strncpy( m_szConsoleText, m_aszLineBuffer[ m_nBrowseLine ], MAX_CONSOLE_TEXTLEN );
m_nConsoleTextLen = strlen( m_aszLineBuffer[ m_nBrowseLine ] );
}
m_nCursorPosition = m_nConsoleTextLen;
}
void CTextConsoleWin32::ReceiveLeftArrow( void )
{
if ( m_nCursorPosition == 0 )
{
return;
}
PrintRaw( "\b" );
m_nCursorPosition--;
}
void CTextConsoleWin32::ReceiveRightArrow( void )
{
if ( m_nCursorPosition == m_nConsoleTextLen )
{
return;
}
PrintRaw( m_szConsoleText + m_nCursorPosition, 1 );
m_nCursorPosition++;
}
#endif // _WIN32
| 20.364341
| 140
| 0.659536
|
DeadZoneLuna
|
ece3bc32ec565796b3f4da56d7fe87f6c8c112bd
| 974
|
cpp
|
C++
|
src/engine/EngineInterface.cpp
|
Arkshine/PrototypeEngine
|
6833b931ca02934dd5f68377fc8c486f01103841
|
[
"Unlicense"
] | 2
|
2018-10-09T14:42:39.000Z
|
2021-02-07T21:41:00.000Z
|
src/engine/EngineInterface.cpp
|
Arkshine/PrototypeEngine
|
6833b931ca02934dd5f68377fc8c486f01103841
|
[
"Unlicense"
] | null | null | null |
src/engine/EngineInterface.cpp
|
Arkshine/PrototypeEngine
|
6833b931ca02934dd5f68377fc8c486f01103841
|
[
"Unlicense"
] | 1
|
2018-10-09T14:42:41.000Z
|
2018-10-09T14:42:41.000Z
|
#include "Platform.h"
#include "Engine.h"
#include "FilePaths.h"
#include "EngineInterface.h"
#ifdef WIN32
//See post VS 2015 update 3 delayimp.h for the reason why this has to be defined. - Solokiller
#define DELAYIMP_INSECURE_WRITABLE_HOOKS
#include <delayimp.h>
FARPROC WINAPI DelayHook(
unsigned dliNotify,
PDelayLoadInfo pdli
)
{
if( dliNotify == dliNotePreLoadLibrary )
{
if( strcmp( pdli->szDll, "Tier1.dll" ) == 0 )
{
char szPath[ MAX_PATH ];
if( !( *g_Engine.GetMyGameDir() ) )
return nullptr;
const int iResult = snprintf( szPath, sizeof( szPath ), "%s/%s/%s", g_Engine.GetMyGameDir(), filepaths::BIN_DIR, pdli->szDll );
if( iResult < 0 || static_cast<size_t>( iResult ) >= sizeof( szPath ) )
return nullptr;
HMODULE hLib = LoadLibraryA( szPath );
return ( FARPROC ) hLib;
}
}
return nullptr;
}
ExternC PfnDliHook __pfnDliNotifyHook2 = DelayHook;
ExternC PfnDliHook __pfnDliFailureHook2 = nullptr;
#endif
| 22.136364
| 130
| 0.693018
|
Arkshine
|
ece5c5993b62ac96455e64e2039b2e4f929ea31d
| 6,340
|
hpp
|
C++
|
esp/logging/logginglib/logconfigptree.hpp
|
asselitx/HPCC-Platform
|
b13c1a368d132f0282323667313afd647ede63c9
|
[
"Apache-2.0"
] | null | null | null |
esp/logging/logginglib/logconfigptree.hpp
|
asselitx/HPCC-Platform
|
b13c1a368d132f0282323667313afd647ede63c9
|
[
"Apache-2.0"
] | null | null | null |
esp/logging/logginglib/logconfigptree.hpp
|
asselitx/HPCC-Platform
|
b13c1a368d132f0282323667313afd647ede63c9
|
[
"Apache-2.0"
] | null | null | null |
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2021 HPCC Systems®.
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 _LOGCONFIGPTREE_HPP_
#define _LOGCONFIGPTREE_HPP_
#include "jptree.hpp"
#include "jstring.hpp"
#include "tokenserialization.hpp"
namespace LogConfigPTree
{
/**
* When relying upon a default value, check and report if the default value is not compatibile
* with the requested value type. Most mismatches are errors. Some may be recorded as warnings
* if a reasonable use case, e.g., defaulting an unsigned value to -1, exists to justify it.
* In all cases, recorded findings should be addressed by either changing the default value or
* casting the intended value correctly.
*/
template <typename value_t, typename default_t>
value_t applyDefault(const default_t& defaultValue, const char* xpath)
{
auto report = [&](bool isError)
{
StringBuffer msg;
msg << "unexpected default value '" << defaultValue << "'";
if (!isEmptyString(xpath))
msg << " for configuration XPath '" << xpath << "'";
if (isError)
IERRLOG("%s", msg.str());
else
IWARNLOG("%s", msg.str());
};
if (std::is_integral<value_t>() == std::is_integral<default_t>())
{
if (std::is_signed<value_t>() == std::is_signed<default_t>())
{
if (defaultValue < std::numeric_limits<value_t>::min())
report(true);
else if (defaultValue > std::numeric_limits<value_t>::max())
report(true);
}
else if (std::is_signed<value_t>())
{
if (defaultValue > std::numeric_limits<value_t>::max())
report(true);
}
else
{
if (defaultValue < 0 || defaultValue > std::numeric_limits<value_t>::max())
report(false);
}
}
else if (std::is_floating_point<value_t>() == std::is_floating_point<default_t>())
{
if (defaultValue < -std::numeric_limits<value_t>::max())
report(true);
else if (defaultValue > std::numeric_limits<value_t>::max())
report(true);
}
else
{
report(false);
}
return value_t(defaultValue);
}
/**
* Access a configuration property value, supporting legacy configurations that use element
* content and newer configurations relying on attributes.
*
* Preferring new configurations instead of legacy, consider a request for an attribute to be
* just that and a request for element content to be a request for either an attribute or an
* element. A request for "A/@B" will be viewed as only a request for attribute B in element A,
* while a request for "A/B" will be viewed first as a request for "A/@B" and as a request for
* "A/B" only if "A/@B" is not found.
*/
inline const char* queryConfigValue(const IPTree& node, const char* xpath)
{
const char* value = nullptr;
if (!isEmptyString(xpath))
{
const char* delim = strrchr(xpath, '/');
size_t attrIndex = (delim ? delim - xpath + 1 : 0);
if (xpath[attrIndex] != '@')
{
StringBuffer altXPath(xpath);
altXPath.insert(attrIndex, '@');
value = node.queryProp(altXPath);
if (value)
return value;
}
value = node.queryProp(xpath);
}
return value;
}
inline const char* queryConfigValue(const IPTree* node, const char* xpath)
{
if (node)
return queryConfigValue(*node, xpath);
return nullptr;
}
inline bool getConfigValue(const IPTree& node, const char* xpath, StringBuffer& value)
{
const char* raw = queryConfigValue(node, value);
if (raw)
{
value.set(raw);
return true;
}
return false;
}
inline bool getConfigValue(const IPTree* node, const char* xpath, StringBuffer& value)
{
if (node)
return getConfigValue(*node, xpath, value);
return false;
}
template <typename value_t, typename default_t>
value_t getConfigValue(const IPTree& node, const char* xpath, const default_t& defaultValue)
{
const char* raw = queryConfigValue(node, xpath);
if (raw)
{
static TokenDeserializer deserializer;
value_t value;
if (deserializer(raw, value) == Deserialization_SUCCESS)
return value;
}
return applyDefault<value_t>(defaultValue, xpath);
}
template <typename value_t>
value_t getConfigValue(const IPTree& node, const char* xpath)
{
value_t defaultValue = value_t(0);
return getConfigValue<value_t>(node, xpath, defaultValue);
}
template <typename value_t, typename default_t>
value_t getConfigValue(const IPTree* node, const char* xpath, const default_t& defaultValue)
{
if (node)
return getConfigValue<value_t>(*node, xpath, defaultValue);
return applyDefault<value_t>(defaultValue, xpath);
}
template <typename value_t>
value_t getConfigValue(const IPTree* node, const char* xpath)
{
if (node)
return getConfigValue<value_t>(*node, xpath);
return value_t(0);
}
} // namespace LogConfigPTree
#endif // _LOGCONFIGPTREE_HPP_
| 35.617978
| 99
| 0.579653
|
asselitx
|
ece61a786b25557969da5a4009fa858ce8754175
| 5,197
|
cpp
|
C++
|
src/config/TOMLConfigBuilder.cpp
|
smangano/theoria
|
216c3edb5973cee60d3381881071e0a32428fee5
|
[
"Apache-2.0"
] | null | null | null |
src/config/TOMLConfigBuilder.cpp
|
smangano/theoria
|
216c3edb5973cee60d3381881071e0a32428fee5
|
[
"Apache-2.0"
] | 1
|
2016-10-09T15:40:16.000Z
|
2016-10-20T03:11:38.000Z
|
src/config/TOMLConfigBuilder.cpp
|
smangano/theoria
|
216c3edb5973cee60d3381881071e0a32428fee5
|
[
"Apache-2.0"
] | null | null | null |
#include <theoria/config/TOMLConfigBuilder.h>
#include <theoria/config/Config.h>
#include <theoria/except/except.h>
#include <utility>
#include <cpptoml.h>
#include <iostream>
using namespace theoria ;
using namespace config ;
TOMLConfigBuilder::~TOMLConfigBuilder()
{
}
std::unique_ptr<const Config> TOMLConfigBuilder::parse(std::istream& stream)
{
try {
cpptoml::parser parser_(stream) ;
auto config = parser_.parse();
auto application = config->get_as<std::string>("application").value_or("") ;
auto appdesc = config->get_as<std::string>("desc").value_or("") ;
pushConfig(application, appdesc) ;
_recursive_build(*config) ;
}
catch(const cpptoml::parse_exception& parseEx) {
throw RUNTIME_ERROR("Could not parse TOML config: %s", parseEx.what()) ;
}
return std::unique_ptr<const Config>(releaseAll()) ;
}
std::unique_ptr<const Config> TOMLConfigBuilder::parse_file(const std::string& filename)
{
try {
auto config = cpptoml::parse_file(filename);
if (!config)
throw RUNTIME_ERROR("Could not parse TOML config: %s", filename.c_str()) ;
auto application = config->get_as<std::string>("application").value_or(filename) ;
auto appdesc = config->get_as<std::string>("desc").value_or("") ;
pushConfig(application, appdesc) ;
_recursive_build(*config) ;
}
catch(const cpptoml::parse_exception& parseEx) {
throw RUNTIME_ERROR("Could not parse TOML config: %s: %s", filename.c_str(), parseEx.what()) ;
}
return std::unique_ptr<const Config>(releaseAll()) ;
}
void TOMLConfigBuilder::_recursive_build(cpptoml::table& table)
{
for (auto iter = table.begin(), end = table.end(); iter != end; ++iter)
{
if (iter->second->is_value())
{
if (iter->first == "desc")
setDesc(*table.get_as<std::string>(iter->first)) ;
else {
//attributes
auto val_type = _getValueAndTypeAsString(table, iter->first) ;
auto value = val_type.first ;
auto type = val_type.second ;
_addAttr(iter->first, value, type) ;
}
}
if (iter->second->is_array())
{
throw RUNTIME_ERROR("TOML array support not implemented yet") ;
}
else
if (iter->second->is_table_array())
{
pushConfigArray(iter->first + "_Array") ;
auto tarr = table.get_table_array(iter->first);
for (const auto& tableElem : *tarr) {
pushConfig(iter->first, iter->first) ;
_recursive_build(*tableElem) ;
popAsChild(true) ;
}
popAsChild() ;
}
else
if (iter->second->is_table())
{
pushConfig(iter->first, iter->first) ;
_recursive_build(*(iter->second->as_table())) ;
popAsChild() ;
}
else
{
}
}
}
void TOMLConfigBuilder::_addAttr(const std::string& name, const std::string& value, const std::string& type)
{
addAttr(name, value, type) ;
}
void TOMLConfigBuilder::_addAttrWithResolve(
const std::string& name,
const std::string& value,
const std::string& type)
{
//TODO
}
std::pair<std::string, std::string> TOMLConfigBuilder::_getValueAndTypeAsString(const cpptoml::table& owner,const std::string& name)
{
std::ostringstream oss ;
auto strVal = owner.get_as<std::string>(name) ;
if (strVal) {
return std::make_pair(*strVal, std::string("string")) ;
}
auto intVal = owner.get_as<int64_t>(name) ;
if (intVal) {
oss << *intVal ;
return std::make_pair(oss.str(), std::string("int")) ;
}
auto doubleVal = owner.get_as<double>(name) ;
if (doubleVal) {
oss << *doubleVal ;
return std::make_pair(oss.str(), std::string("double")) ;
}
auto boolVal = owner.get_as<bool>(name) ;
if (boolVal) {
oss << *boolVal ;
return std::make_pair(oss.str(), std::string("bool")) ;
}
auto dateVal = owner.get_as<cpptoml::datetime>(name) ;
if (dateVal)
{
auto dt = *dateVal ;
oss << std::setfill('0') ;
oss << std::setw(4) << dt.year << "-" << std::setw(2) << dt.month << "-" << std::setw(2) << dt.day ;
if (dt.hour || dt.minute || dt.second || dt.microsecond)
{
oss << "T" << std::setw(2) << dt.hour << ":" << std::setw(2) << dt.minute << ":" << std::setw(2)
<< dt.second ;
if (dt.microsecond)
oss << std::setw(6) << dt.microsecond ;
if (dt.hour_offset || dt.minute_offset) {
if (dt.hour_offset < 0) {
oss << "-" ;
dt.hour_offset *= -1 ;
}
oss << std::setw(2) << dt.hour_offset << ":" << std::setw(2) << dt.minute_offset ;
}
return std::make_pair(oss.str(), "datetime") ;
}
else {
return std::make_pair(oss.str(),"date") ;
}
}
return std::make_pair("" , "") ;
}
| 32.48125
| 132
| 0.552242
|
smangano
|
ecef06aa5811d7e2a8dc5e6fe6a6e2de24bc04c8
| 3,872
|
cpp
|
C++
|
libs/network/src/muddle/muddle_register.cpp
|
devjsc/ledger-1
|
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
|
[
"Apache-2.0"
] | null | null | null |
libs/network/src/muddle/muddle_register.cpp
|
devjsc/ledger-1
|
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
|
[
"Apache-2.0"
] | null | null | null |
libs/network/src/muddle/muddle_register.cpp
|
devjsc/ledger-1
|
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
|
[
"Apache-2.0"
] | null | null | null |
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
#include "network/muddle/muddle_register.hpp"
#include "network/management/abstract_connection.hpp"
#include "network/muddle/dispatcher.hpp"
namespace fetch {
namespace muddle {
/**
* Construct the connection register
*
* @param dispatcher The reference to the dispatcher
*/
MuddleRegister::MuddleRegister(Dispatcher &dispatcher)
: dispatcher_(dispatcher)
{}
/**
* Execute a specified callback over all elements of the connection map
*
* @param cb The specified callback to execute
*/
void MuddleRegister::VisitConnectionMap(MuddleRegister::ConnectionMapCallback const &cb)
{
LOG_STACK_TRACE_POINT;
FETCH_LOCK(connection_map_lock_);
cb(connection_map_);
}
/**
* Broadcast data to all active connections
*
* @param data The data to be broadcast
*/
void MuddleRegister::Broadcast(ConstByteArray const &data) const
{
LOG_STACK_TRACE_POINT;
FETCH_LOCK(connection_map_lock_);
FETCH_LOG_DEBUG(LOGGING_NAME, "Broadcasting message.");
// loop through all of our current connections
for (auto const &elem : connection_map_)
{
// ensure the connection is valid
auto connection = elem.second.lock();
if (connection)
{
// schedule sending of the data
connection->Send(data);
}
}
}
/**
* Lookup a connection given a specified handle
*
* @param handle The handle of the requested connection
* @return A valid connection if successful, otherwise an invalid one
*/
MuddleRegister::ConnectionPtr MuddleRegister::LookupConnection(ConnectionHandle handle) const
{
LOG_STACK_TRACE_POINT;
ConnectionPtr conn;
{
FETCH_LOCK(connection_map_lock_);
auto it = connection_map_.find(handle);
if (it != connection_map_.end())
{
conn = it->second;
}
}
return conn;
}
/**
* Callback triggered when a new connection is established
*
* @param ptr The new connection pointer
*/
void MuddleRegister::Enter(ConnectionPtr const &ptr)
{
LOG_STACK_TRACE_POINT;
FETCH_LOCK(connection_map_lock_);
auto strong_conn = ptr.lock();
#ifndef NDEBUG
// extra level of debug
if (connection_map_.find(strong_conn->handle()) != connection_map_.end())
{
FETCH_LOG_INFO(LOGGING_NAME, "Trying to update an existing connection ID");
return;
}
#endif // !NDEBUG
FETCH_LOG_DEBUG(LOGGING_NAME, "### Connection ", strong_conn->handle(),
" started type: ", strong_conn->Type());
// update
connection_map_[strong_conn->handle()] = ptr;
}
/**
* Callback triggered when a connection is destroyed
*
* @param id The handle of the dying connection
*/
void MuddleRegister::Leave(connection_handle_type id)
{
LOG_STACK_TRACE_POINT;
{
FETCH_LOCK(connection_map_lock_);
FETCH_LOG_DEBUG(LOGGING_NAME, "### Connection ", id, " ended");
auto it = connection_map_.find(id);
if (it != connection_map_.end())
{
connection_map_.erase(it);
}
}
// inform the dispatcher that the connection has failed (this can clear up all of the pending
// promises)
dispatcher_.NotifyConnectionFailure(id);
}
} // namespace muddle
} // namespace fetch
| 25.642384
| 95
| 0.684401
|
devjsc
|
ecf282b05d74a86c9e9ab28fa8f37754ea41f60a
| 745
|
cpp
|
C++
|
Test/Expect/test046.cpp
|
archivest/spin2cpp
|
8541238366076777717e683efac35458e3796859
|
[
"MIT"
] | 2
|
2021-05-27T18:22:01.000Z
|
2021-05-29T13:40:38.000Z
|
Test/Expect/test046.cpp
|
archivest/spin2cpp
|
8541238366076777717e683efac35458e3796859
|
[
"MIT"
] | 1
|
2020-10-24T22:25:37.000Z
|
2020-10-24T22:25:37.000Z
|
Test/Expect/test046.cpp
|
archivest/spin2cpp
|
8541238366076777717e683efac35458e3796859
|
[
"MIT"
] | null | null | null |
#include <propeller.h>
#include "test046.h"
void test046::Fun(int32_t X, int32_t Y)
{
int32_t _tmp__0000, _tmp__0001;
_tmp__0001 = X;
if (_tmp__0001 == 0) {
goto _case__0005;
}
if ((_tmp__0001 >= 10) && (_tmp__0001 <= 12)) {
goto _case__0006;
}
goto _case__0007;
_case__0005: ;
_tmp__0000 = Y;
if (_tmp__0000 == 0) {
goto _case__0002;
}
if (_tmp__0000 == 1) {
goto _case__0003;
}
goto _endswitch_0001;
_case__0002: ;
_OUTA ^= 0x1;
goto _endswitch_0001;
_case__0003: ;
_OUTA ^= 0x2;
goto _endswitch_0001;
_endswitch_0001: ;
goto _endswitch_0004;
_case__0006: ;
_OUTA ^= 0x4;
goto _endswitch_0004;
_case__0007: ;
_OUTA ^= 0x8;
goto _endswitch_0004;
_endswitch_0004: ;
}
| 18.170732
| 49
| 0.64698
|
archivest
|
ecf63bfdab2b037a2d5f8534c38e4858a146a757
| 7,584
|
cpp
|
C++
|
shared/lib_pv_incidence_modifier.cpp
|
JordanMalan/ssc
|
cadb7a9f3183d63c600b5c33f53abced35b6b319
|
[
"BSD-3-Clause"
] | 61
|
2017-08-09T15:10:59.000Z
|
2022-02-15T21:45:31.000Z
|
shared/lib_pv_incidence_modifier.cpp
|
JordanMalan/ssc
|
cadb7a9f3183d63c600b5c33f53abced35b6b319
|
[
"BSD-3-Clause"
] | 462
|
2017-07-31T21:26:46.000Z
|
2022-03-30T22:53:50.000Z
|
shared/lib_pv_incidence_modifier.cpp
|
JordanMalan/ssc
|
cadb7a9f3183d63c600b5c33f53abced35b6b319
|
[
"BSD-3-Clause"
] | 73
|
2017-08-24T17:39:31.000Z
|
2022-03-28T08:37:47.000Z
|
/**
BSD-3-Clause
Copyright 2019 Alliance for Sustainable Energy, LLC
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 name of the copyright holder 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, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES
DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 <math.h>
#include "lib_pv_incidence_modifier.h"
///Supporting function for IAM functions to calculate transmissance of a module cover at a specific angle- reference: duffie & beckman, Ch 5.3
double transmittance(double theta1_deg, /* incidence angle of incoming radiation (deg) */
double n_cover, /* refractive index of cover material, n_glass = 1.586 */
double n_incoming, /* refractive index of incoming material, typically n_air = 1.0 */
double k, /* proportionality constant assumed to be 4 (1/m) for derivation of Bouguer's law (set to zero to skip bougeur's law */
double l_thick, /* thickness of cover material (m), usually 2 mm for typical module (set to zero to skip Bouguer's law) */
double *_theta2_deg) /* returns angle of refraction in degrees */
{
// calculate angle of refraction
double theta1 = theta1_deg * M_PI / 180.0;
double theta2 = asin(n_incoming / n_cover * sin(theta1)); // angle of refraction, calculated using snell's law
if (_theta2_deg) *_theta2_deg = theta2 * 180 / M_PI; // return angle of refraction in degrees if requested in function call
// fresnel's equation for non-reflected unpolarized radiation as an average of perpendicular and parallel components
// reference https://pvpmc.sandia.gov/modeling-steps/1-weather-design-inputs/shading-soiling-and-reflection-losses/incident-angle-reflection-losses/physical-model-of-iam/
double tr = 1 - 0.5 *
(pow(sin(theta2 - theta1), 2) / pow(sin(theta2 + theta1), 2)
+ pow(tan(theta2 - theta1), 2) / pow(tan(theta2 + theta1), 2));
return tr * exp(-k * l_thick / cos(theta2));
}
///Incidence angle modifier not normalized relative to normal incidence (used as a supporting function to normalized IAM function)
double iam_nonorm(double theta, bool ar_glass)
{
if (theta < AOI_MIN) theta = AOI_MIN;
if (theta > AOI_MAX) theta = AOI_MAX;
if (ar_glass)
{
double theta2 = 1;
double tau_coating = transmittance(theta, n_arc, n_air, k_arc, l_arc, &theta2);
double tau_glass = transmittance(theta2, n_glass, n_arc, k_glass, l_glass);
return tau_coating * tau_glass;
}
else
{
return transmittance(theta, n_glass, n_air, k_glass, l_glass);
}
}
///Incidence angle modifier normalized relative to normal incidence- used by 61853 model and PVWatts
double iam(double theta, bool ar_glass) //jmf- we should rename this to something more descriptive
{
if (theta < AOI_MIN) theta = AOI_MIN;
if (theta > AOI_MAX) theta = AOI_MAX;
double normal = iam_nonorm(1, ar_glass);
double actual = iam_nonorm(theta, ar_glass);
return actual / normal;
}
///Only used in a test to compare against bifacial model
double iamSjerpsKoomen(double n2, double incidenceAngleRadians)
{
// Only calculates valid value for 0 <= inc <= 90 degrees
double cor = -9999.0;
// Reflectance at normal incidence, Beckman p217
double r0 = pow((n2 - 1.0) / (n2 + 1), 2);
if (incidenceAngleRadians == 0) {
cor = 1.0;
}
else if (incidenceAngleRadians > 0.0 && incidenceAngleRadians <= M_PI / 2.0) {
double refrAng = asin(sin(incidenceAngleRadians) / n2);
double r1 = (pow(sin(refrAng - incidenceAngleRadians), 2.0) / pow(sin(refrAng + incidenceAngleRadians), 2.0));
double r2 = (pow(tan(refrAng - incidenceAngleRadians), 2.0) / pow(tan(refrAng + incidenceAngleRadians), 2.0));
cor = 1.0 - 0.5 * (r1 + r2);
cor /= 1.0 - r0;
}
return cor;
}
///DeSoto IAM model used by CEC model
double calculateIrradianceThroughCoverDeSoto(
double theta, /* incidence angle in degrees */
double tilt, /* tilt angle in degrees */
double G_beam, /* poa beam */
double G_sky, /* poa sky diffuse */
double G_gnd, /* poa ground reflected diffuse */
bool antiReflectiveGlass)
{
// establish limits on incidence angle and zenith angle
if (theta < 1) theta = 1.0;
if (theta > 89) theta = 89.0;
// transmittance at angle normal to surface (0 deg), use 1 (deg) to avoid numerical probs.
// need to check for anti-reflective coating on glass here in order to avoid IAM > 1 below
double tau_norm = 1.0; //start with a factor of 1 to be modified
double theta_norm_after_coating = 1.0; //initialize this to an angle of 1.0 degrees for the calculation of tau_norm without AR coating
if (antiReflectiveGlass)
{
double tau_coating = transmittance(1.0, n_arc, 1.0, k_arc, l_arc, &theta_norm_after_coating);
tau_norm *= tau_coating;
}
tau_norm *= transmittance(theta_norm_after_coating, n_glass, 1.0, k_glass, l_glass);
// transmittance of beam radiation, at incidence angle
double tau_beam = 1.0; //start with a factor of 1 to be modified
double theta_after_coating = theta;
if (antiReflectiveGlass)
{
double tau_coating = transmittance(theta, n_arc, 1.0, k_arc, l_arc, &theta_after_coating);
tau_beam *= tau_coating;
}
tau_beam *= transmittance(theta_after_coating, n_glass, (antiReflectiveGlass ? n_arc : 1.0), k_glass, l_glass);
// transmittance of sky diffuse, at modified angle by (D&B Eqn 5.4.2)
double theta_sky = 59.7 - 0.1388*tilt + 0.001497*tilt*tilt;
double tau_sky = transmittance(theta_sky, n_glass, 1.0, k_glass, l_glass);
// transmittance of ground diffuse, at modified angle by (D&B Eqn 5.4.1)
double theta_gnd = 90.0 - 0.5788*tilt + 0.002693*tilt*tilt;
double tau_gnd = transmittance(theta_gnd, n_glass, 1.0, k_glass, l_glass);
// calculate component incidence angle modifiers, D&B Chap. 5 eqn 5.12.1, DeSoto'04
// check that the component incidence angle modifiers are not > 1 in case there's some funkiness with the calculations
double Kta_beam = tau_beam / tau_norm;
if (Kta_beam > 1.0) Kta_beam = 1.0;
double Kta_sky = tau_sky / tau_norm;
if (Kta_sky > 1.0) Kta_sky = 1.0;
double Kta_gnd = tau_gnd / tau_norm;
if (Kta_gnd > 1.0) Kta_gnd = 1.0;
// total effective irradiance absorbed by solar cell
double Geff_total = G_beam * Kta_beam + G_sky * Kta_sky + G_gnd * Kta_gnd;
if (Geff_total < 0) Geff_total = 0;
return Geff_total;
}
| 47.698113
| 174
| 0.734045
|
JordanMalan
|
ecf8754e50232012c40a4cf5311e853562ff70f0
| 2,251
|
cpp
|
C++
|
src/ripple_websocket/autosocket/LogWebsockets.cpp
|
latcoin/rippled
|
ca0740de23ec4366d53b0d3770d9a05fc83072db
|
[
"BSL-1.0"
] | null | null | null |
src/ripple_websocket/autosocket/LogWebsockets.cpp
|
latcoin/rippled
|
ca0740de23ec4366d53b0d3770d9a05fc83072db
|
[
"BSL-1.0"
] | null | null | null |
src/ripple_websocket/autosocket/LogWebsockets.cpp
|
latcoin/rippled
|
ca0740de23ec4366d53b0d3770d9a05fc83072db
|
[
"BSL-1.0"
] | null | null | null |
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
// VFALCO NOTE this looks like some facility for giving websocket
// a way to produce logging output.
//
namespace websocketpp
{
namespace log
{
using namespace ripple;
LogPartition websocketPartition ("WebSocket");
void websocketLog (websocketpp::log::alevel::value v, const std::string& entry)
{
using namespace ripple;
if ((v == websocketpp::log::alevel::DEVEL) || (v == websocketpp::log::alevel::DEBUG_CLOSE))
{
if (websocketPartition.doLog (lsTRACE))
Log (lsDEBUG, websocketPartition) << entry;
}
else if (websocketPartition.doLog (lsDEBUG))
Log (lsDEBUG, websocketPartition) << entry;
}
void websocketLog (websocketpp::log::elevel::value v, const std::string& entry)
{
using namespace ripple;
LogSeverity s = lsDEBUG;
if ((v & websocketpp::log::elevel::INFO) != 0)
s = lsINFO;
else if ((v & websocketpp::log::elevel::FATAL) != 0)
s = lsFATAL;
else if ((v & websocketpp::log::elevel::RERROR) != 0)
s = lsERROR;
else if ((v & websocketpp::log::elevel::WARN) != 0)
s = lsWARNING;
if (websocketPartition.doLog (s))
Log (s, websocketPartition) << entry;
}
}
}
// vim:ts=4
| 33.102941
| 95
| 0.627721
|
latcoin
|
a601d99ec6c3fd43f4caf1cfde442e51d739667d
| 2,642
|
cpp
|
C++
|
src/core/visual/win32/krmovie/ogg/iBE_Math.cpp
|
miahmie/krkrz
|
e4948f61393ca4a2acac0301a975165dd4efc643
|
[
"Unlicense",
"Apache-2.0",
"Libpng",
"FTL",
"IJG"
] | null | null | null |
src/core/visual/win32/krmovie/ogg/iBE_Math.cpp
|
miahmie/krkrz
|
e4948f61393ca4a2acac0301a975165dd4efc643
|
[
"Unlicense",
"Apache-2.0",
"Libpng",
"FTL",
"IJG"
] | null | null | null |
src/core/visual/win32/krmovie/ogg/iBE_Math.cpp
|
miahmie/krkrz
|
e4948f61393ca4a2acac0301a975165dd4efc643
|
[
"Unlicense",
"Apache-2.0",
"Libpng",
"FTL",
"IJG"
] | null | null | null |
//===========================================================================
//Copyright (C) 2003, 2004 Zentaro Kavanagh
//
//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 Zentaro Kavanagh nor the names of 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 ORGANISATION 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 "oggstdafx.h"
#include <iBE_Math.h>
iBE_Math::iBE_Math(void)
{
}
iBE_Math::~iBE_Math(void)
{
}
unsigned long iBE_Math::charArrToULong(unsigned char* inCharArray)
{
//Turns the next four bytes from the pointer in a long MSB (most sig. byte first/leftmost)
unsigned long locVal = 0;
for (int i = 0; i < 4; i++) {
locVal <<= 8;
locVal += inCharArray[i];
}
return locVal;
}
void iBE_Math::ULongToCharArr(unsigned long inLong, unsigned char* outCharArray)
{
//Writes a long MSB (Most sig. byte first/leftmost) out to the char arr
outCharArray[0] = (unsigned char) (inLong >> 24);
outCharArray[1] = (unsigned char) ((inLong << 8) >> 24);
outCharArray[2] = (unsigned char) ((inLong << 16) >> 24);
outCharArray[3] = (unsigned char) ((inLong << 24) >> 24);
}
unsigned short iBE_Math::charArrToUShort(unsigned char* inCharArray) {
unsigned short retShort = inCharArray[0];
retShort = (retShort << 8) + inCharArray[1];
return retShort;
}
| 38.852941
| 91
| 0.700227
|
miahmie
|
a607057f41683c7a0b919ac86a7b44c3ee7a58f7
| 11,127
|
cpp
|
C++
|
sdk/storage/azure-storage-files-datalake/src/datalake_directory_client.cpp
|
RickWinter/azure-sdk-for-cpp
|
b4fe751310f53669a941e00aa93072f2d10a4eba
|
[
"MIT"
] | 96
|
2020-03-19T07:49:39.000Z
|
2022-03-20T14:22:41.000Z
|
sdk/storage/azure-storage-files-datalake/src/datalake_directory_client.cpp
|
RickWinter/azure-sdk-for-cpp
|
b4fe751310f53669a941e00aa93072f2d10a4eba
|
[
"MIT"
] | 2,572
|
2020-03-18T22:54:53.000Z
|
2022-03-31T22:09:59.000Z
|
sdk/storage/azure-storage-files-datalake/src/datalake_directory_client.cpp
|
RickWinter/azure-sdk-for-cpp
|
b4fe751310f53669a941e00aa93072f2d10a4eba
|
[
"MIT"
] | 81
|
2020-03-19T09:42:00.000Z
|
2022-03-24T05:11:05.000Z
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
#include "azure/storage/files/datalake/datalake_directory_client.hpp"
#include <azure/core/http/policies/policy.hpp>
#include <azure/storage/common/crypt.hpp>
#include <azure/storage/common/internal/constants.hpp>
#include <azure/storage/common/internal/shared_key_policy.hpp>
#include <azure/storage/common/internal/storage_switch_to_secondary_policy.hpp>
#include <azure/storage/common/storage_common.hpp>
#include "azure/storage/files/datalake/datalake_file_client.hpp"
#include "private/datalake_utilities.hpp"
namespace Azure { namespace Storage { namespace Files { namespace DataLake {
DataLakeDirectoryClient DataLakeDirectoryClient::CreateFromConnectionString(
const std::string& connectionString,
const std::string& fileSystemName,
const std::string& directoryName,
const DataLakeClientOptions& options)
{
auto parsedConnectionString = _internal::ParseConnectionString(connectionString);
auto directoryUrl = std::move(parsedConnectionString.DataLakeServiceUrl);
directoryUrl.AppendPath(_internal::UrlEncodePath(fileSystemName));
directoryUrl.AppendPath(_internal::UrlEncodePath(directoryName));
if (parsedConnectionString.KeyCredential)
{
return DataLakeDirectoryClient(
directoryUrl.GetAbsoluteUrl(), parsedConnectionString.KeyCredential, options);
}
else
{
return DataLakeDirectoryClient(directoryUrl.GetAbsoluteUrl(), options);
}
}
DataLakeDirectoryClient::DataLakeDirectoryClient(
const std::string& directoryUrl,
std::shared_ptr<StorageSharedKeyCredential> credential,
const DataLakeClientOptions& options)
: DataLakePathClient(directoryUrl, credential, options)
{
}
DataLakeDirectoryClient::DataLakeDirectoryClient(
const std::string& directoryUrl,
std::shared_ptr<Core::Credentials::TokenCredential> credential,
const DataLakeClientOptions& options)
: DataLakePathClient(directoryUrl, credential, options)
{
}
DataLakeDirectoryClient::DataLakeDirectoryClient(
const std::string& directoryUrl,
const DataLakeClientOptions& options)
: DataLakePathClient(directoryUrl, options)
{
}
DataLakeFileClient DataLakeDirectoryClient::GetFileClient(const std::string& fileName) const
{
auto builder = m_pathUrl;
builder.AppendPath(_internal::UrlEncodePath(fileName));
auto blobClient = m_blobClient;
blobClient.m_blobUrl.AppendPath(_internal::UrlEncodePath(fileName));
return DataLakeFileClient(std::move(builder), std::move(blobClient), m_pipeline);
}
DataLakeDirectoryClient DataLakeDirectoryClient::GetSubdirectoryClient(
const std::string& subdirectoryName) const
{
auto builder = m_pathUrl;
builder.AppendPath(_internal::UrlEncodePath(subdirectoryName));
auto blobClient = m_blobClient;
blobClient.m_blobUrl.AppendPath(_internal::UrlEncodePath(subdirectoryName));
return DataLakeDirectoryClient(std::move(builder), std::move(blobClient), m_pipeline);
}
Azure::Response<DataLakeFileClient> DataLakeDirectoryClient::RenameFile(
const std::string& fileName,
const std::string& destinationFilePath,
const RenameFileOptions& options,
const Azure::Core::Context& context) const
{
std::string destinationFileSystem;
if (options.DestinationFileSystem.HasValue())
{
destinationFileSystem = options.DestinationFileSystem.Value();
}
else
{
const std::string& currentPath = m_pathUrl.GetPath();
destinationFileSystem = currentPath.substr(0, currentPath.find('/'));
}
auto sourceDfsUrl = m_pathUrl;
sourceDfsUrl.AppendPath(_internal::UrlEncodePath(fileName));
auto destinationDfsUrl = m_pathUrl;
destinationDfsUrl.SetPath(_internal::UrlEncodePath(destinationFileSystem));
destinationDfsUrl.AppendPath(_internal::UrlEncodePath(destinationFilePath));
_detail::DataLakeRestClient::Path::CreateOptions protocolLayerOptions;
protocolLayerOptions.Mode = _detail::PathRenameMode::Legacy;
protocolLayerOptions.SourceLeaseId = options.SourceAccessConditions.LeaseId;
protocolLayerOptions.LeaseIdOptional = options.AccessConditions.LeaseId;
protocolLayerOptions.IfMatch = options.AccessConditions.IfMatch;
protocolLayerOptions.IfNoneMatch = options.AccessConditions.IfNoneMatch;
protocolLayerOptions.IfModifiedSince = options.AccessConditions.IfModifiedSince;
protocolLayerOptions.IfUnmodifiedSince = options.AccessConditions.IfUnmodifiedSince;
protocolLayerOptions.SourceIfMatch = options.SourceAccessConditions.IfMatch;
protocolLayerOptions.SourceIfNoneMatch = options.SourceAccessConditions.IfNoneMatch;
protocolLayerOptions.SourceIfModifiedSince = options.SourceAccessConditions.IfModifiedSince;
protocolLayerOptions.SourceIfUnmodifiedSince = options.SourceAccessConditions.IfUnmodifiedSince;
protocolLayerOptions.RenameSource = "/" + sourceDfsUrl.GetPath();
auto result = _detail::DataLakeRestClient::Path::Create(
destinationDfsUrl, *m_pipeline, context, protocolLayerOptions);
auto renamedBlobClient
= Blobs::BlobClient(_detail::GetBlobUrlFromUrl(destinationDfsUrl), m_pipeline);
auto renamedFileClient = DataLakeFileClient(
std::move(destinationDfsUrl), std::move(renamedBlobClient), m_pipeline);
return Azure::Response<DataLakeFileClient>(
std::move(renamedFileClient), std::move(result.RawResponse));
}
Azure::Response<DataLakeDirectoryClient> DataLakeDirectoryClient::RenameSubdirectory(
const std::string& subdirectoryName,
const std::string& destinationDirectoryPath,
const RenameSubdirectoryOptions& options,
const Azure::Core::Context& context) const
{
std::string destinationFileSystem;
if (options.DestinationFileSystem.HasValue())
{
destinationFileSystem = options.DestinationFileSystem.Value();
}
else
{
const std::string& currentPath = m_pathUrl.GetPath();
destinationFileSystem = currentPath.substr(0, currentPath.find('/'));
}
auto sourceDfsUrl = m_pathUrl;
sourceDfsUrl.AppendPath(_internal::UrlEncodePath(subdirectoryName));
auto destinationDfsUrl = m_pathUrl;
destinationDfsUrl.SetPath(_internal::UrlEncodePath(destinationFileSystem));
destinationDfsUrl.AppendPath(_internal::UrlEncodePath(destinationDirectoryPath));
_detail::DataLakeRestClient::Path::CreateOptions protocolLayerOptions;
protocolLayerOptions.Mode = _detail::PathRenameMode::Legacy;
protocolLayerOptions.SourceLeaseId = options.SourceAccessConditions.LeaseId;
protocolLayerOptions.LeaseIdOptional = options.AccessConditions.LeaseId;
protocolLayerOptions.IfMatch = options.AccessConditions.IfMatch;
protocolLayerOptions.IfNoneMatch = options.AccessConditions.IfNoneMatch;
protocolLayerOptions.IfModifiedSince = options.AccessConditions.IfModifiedSince;
protocolLayerOptions.IfUnmodifiedSince = options.AccessConditions.IfUnmodifiedSince;
protocolLayerOptions.SourceIfMatch = options.SourceAccessConditions.IfMatch;
protocolLayerOptions.SourceIfNoneMatch = options.SourceAccessConditions.IfNoneMatch;
protocolLayerOptions.SourceIfModifiedSince = options.SourceAccessConditions.IfModifiedSince;
protocolLayerOptions.SourceIfUnmodifiedSince = options.SourceAccessConditions.IfUnmodifiedSince;
protocolLayerOptions.RenameSource = "/" + sourceDfsUrl.GetPath();
auto result = _detail::DataLakeRestClient::Path::Create(
destinationDfsUrl, *m_pipeline, context, protocolLayerOptions);
auto renamedBlobClient
= Blobs::BlobClient(_detail::GetBlobUrlFromUrl(destinationDfsUrl), m_pipeline);
auto renamedDirectoryClient = DataLakeDirectoryClient(
std::move(destinationDfsUrl), std::move(renamedBlobClient), m_pipeline);
return Azure::Response<DataLakeDirectoryClient>(
std::move(renamedDirectoryClient), std::move(result.RawResponse));
}
Azure::Response<Models::DeleteDirectoryResult> DataLakeDirectoryClient::Delete(
bool recursive,
const DeleteDirectoryOptions& options,
const Azure::Core::Context& context) const
{
DeletePathOptions deleteOptions;
deleteOptions.AccessConditions = options.AccessConditions;
deleteOptions.Recursive = recursive;
return DataLakePathClient::Delete(deleteOptions, context);
}
Azure::Response<Models::DeleteDirectoryResult> DataLakeDirectoryClient::DeleteIfExists(
bool recursive,
const DeleteDirectoryOptions& options,
const Azure::Core::Context& context) const
{
DeletePathOptions deleteOptions;
deleteOptions.AccessConditions = options.AccessConditions;
deleteOptions.Recursive = recursive;
return DataLakePathClient::DeleteIfExists(deleteOptions, context);
}
ListPathsPagedResponse DataLakeDirectoryClient::ListPaths(
bool recursive,
const ListPathsOptions& options,
const Azure::Core::Context& context) const
{
_detail::DataLakeRestClient::FileSystem::ListPathsOptions protocolLayerOptions;
protocolLayerOptions.Resource = _detail::FileSystemResource::Filesystem;
protocolLayerOptions.Upn = options.UserPrincipalName;
protocolLayerOptions.MaxResults = options.PageSizeHint;
protocolLayerOptions.RecursiveRequired = recursive;
const std::string currentPath = m_pathUrl.GetPath();
auto firstSlashPos = std::find(currentPath.begin(), currentPath.end(), '/');
const std::string fileSystemName(currentPath.begin(), firstSlashPos);
if (firstSlashPos != currentPath.end())
{
++firstSlashPos;
}
const std::string directoryPath(firstSlashPos, currentPath.end());
if (!directoryPath.empty())
{
protocolLayerOptions.Directory = directoryPath;
}
auto fileSystemUrl = m_pathUrl;
fileSystemUrl.SetPath(fileSystemName);
auto clientCopy = *this;
std::function<ListPathsPagedResponse(std::string, const Azure::Core::Context&)> func;
func = [func, clientCopy, protocolLayerOptions, fileSystemUrl](
std::string continuationToken, const Azure::Core::Context& context) {
auto protocolLayerOptionsCopy = protocolLayerOptions;
if (!continuationToken.empty())
{
protocolLayerOptionsCopy.ContinuationToken = continuationToken;
}
auto response = _detail::DataLakeRestClient::FileSystem::ListPaths(
fileSystemUrl,
*clientCopy.m_pipeline,
_internal::WithReplicaStatus(context),
protocolLayerOptionsCopy);
ListPathsPagedResponse pagedResponse;
pagedResponse.Paths = std::move(response.Value.Items);
pagedResponse.m_onNextPageFunc = func;
pagedResponse.CurrentPageToken = continuationToken;
pagedResponse.NextPageToken = response.Value.ContinuationToken;
pagedResponse.RawResponse = std::move(response.RawResponse);
return pagedResponse;
};
return func(options.ContinuationToken.ValueOr(std::string()), context);
}
}}}} // namespace Azure::Storage::Files::DataLake
| 43.127907
| 100
| 0.764986
|
RickWinter
|
a611437d2f6c1d9a6d439591540f5a3692af13c9
| 540
|
hpp
|
C++
|
Sources/OskGadgetCWrap/include/OskGadgetCWrap.hpp
|
opensmartkitchen/OSK-Bridge
|
42bb222f6db74dda43ea86849862f338efb72339
|
[
"Apache-2.0"
] | null | null | null |
Sources/OskGadgetCWrap/include/OskGadgetCWrap.hpp
|
opensmartkitchen/OSK-Bridge
|
42bb222f6db74dda43ea86849862f338efb72339
|
[
"Apache-2.0"
] | null | null | null |
Sources/OskGadgetCWrap/include/OskGadgetCWrap.hpp
|
opensmartkitchen/OSK-Bridge
|
42bb222f6db74dda43ea86849862f338efb72339
|
[
"Apache-2.0"
] | null | null | null |
#ifndef OSK_GADGET_CWRAP_
#define OSK_GADGET_CWRAP_
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
// Class Memory Management
void * oskGadgetCreate();
void oskGadgetDestroy(void* oskGadget);
bool oskGadgetInit(void* oskGadget);
void oskGadgetRun(void* oskGadget);
// Class Methods()
//float oskGadgetGetScaleWeight(void* oskGadget);
long oskGadgetGetLastTimestamp(void* oskGadget);
#ifdef __cplusplus
}
#endif
#endif // OSK_GADGET_CWRAP_
| 18.62069
| 53
| 0.716667
|
opensmartkitchen
|
a611e4e2ae22cbdbe3729bf20d7e9959001ca527
| 1,789
|
cpp
|
C++
|
solid/utility/test/test_workpool_context.cpp
|
solidoss/solidframe
|
92fa8ce5737b9e88f3df3f549a38e9df79b7bf96
|
[
"BSL-1.0"
] | 4
|
2020-12-05T23:33:32.000Z
|
2021-10-04T02:59:41.000Z
|
solid/utility/test/test_workpool_context.cpp
|
solidoss/solidframe
|
92fa8ce5737b9e88f3df3f549a38e9df79b7bf96
|
[
"BSL-1.0"
] | 1
|
2020-03-22T20:38:05.000Z
|
2020-03-22T20:38:05.000Z
|
solid/utility/test/test_workpool_context.cpp
|
solidoss/solidframe
|
92fa8ce5737b9e88f3df3f549a38e9df79b7bf96
|
[
"BSL-1.0"
] | 2
|
2021-01-30T09:08:52.000Z
|
2021-02-20T03:33:33.000Z
|
#include "solid/system/exception.hpp"
#include "solid/system/log.hpp"
#include "solid/utility/function.hpp"
#include "solid/utility/workpool.hpp"
#include <atomic>
#include <future>
#include <iostream>
using namespace solid;
using namespace std;
namespace {
const LoggerT logger("test_context");
struct Context {
string s_;
atomic<size_t> v_;
const size_t c_;
Context(const string& _s, const size_t _v, const size_t _c)
: s_(_s)
, v_(_v)
, c_(_c)
{
}
~Context()
{
}
};
} //namespace
int test_workpool_context(int argc, char* argv[])
{
solid::log_start(std::cerr, {".*:EWXS", "test_context:VIEWS"});
int wait_seconds = 500;
int loop_cnt = 5;
const size_t cnt{50000};
auto lambda = [&]() {
#if 1
for (int i = 0; i < loop_cnt; ++i) {
Context ctx{"test", 1, cnt + 1};
{
CallPool<void(Context&)> wp{
WorkPoolConfiguration(), 2,
std::ref(ctx)};
solid_log(generic_logger, Verbose, "wp started");
for (size_t i = 0; i < cnt; ++i) {
auto l = [](Context& _rctx) {
++_rctx.v_;
};
wp.push(l);
};
}
solid_check(ctx.v_ == ctx.c_, ctx.v_ << " != " << ctx.c_);
solid_log(logger, Verbose, "after loop");
}
#endif
};
auto fut = async(launch::async, lambda);
if (fut.wait_for(chrono::seconds(wait_seconds)) != future_status::ready) {
solid_throw(" Test is taking too long - waited " << wait_seconds << " secs");
}
fut.get();
solid_log(logger, Verbose, "after async wait");
return 0;
}
| 24.506849
| 85
| 0.515931
|
solidoss
|
a6140feaed8ba2fb2b40bedf8c886301415d5aa3
| 668
|
cpp
|
C++
|
DSA1_gfg/05_insertion_sort.cpp
|
yashlad27/codeforce-codechef-problems
|
4223dccb668e1d9ecabce4740178bc1bfe468023
|
[
"MIT"
] | null | null | null |
DSA1_gfg/05_insertion_sort.cpp
|
yashlad27/codeforce-codechef-problems
|
4223dccb668e1d9ecabce4740178bc1bfe468023
|
[
"MIT"
] | null | null | null |
DSA1_gfg/05_insertion_sort.cpp
|
yashlad27/codeforce-codechef-problems
|
4223dccb668e1d9ecabce4740178bc1bfe468023
|
[
"MIT"
] | null | null | null |
// INSERTION SORT:-
#include<bits/stdc++.h>
using namespace std;
void insertion_sort(int arr[], int n)
{
int i, key, j;
for (i = 0; i < n; i++)
{
key = arr[i];
j=i-1;
while(j>=0 && arr[j] > key)
{
arr[j+1] = arr[j];
j=j-1;
}
arr[j+1] = key;
}
}
void display(int arr[], int n)
{
int i, j;
for (i = 0; i < n; i++)
{
cout << arr[i] <<" ";
}
cout<<endl;
}
int main()
{
int arr[]={12,1,11,4,13,67,8};
int n = sizeof(arr)/sizeof(arr[0]);
insertion_sort(arr, n);
display(arr, n);
return 0;
}
| 15.904762
| 40
| 0.399701
|
yashlad27
|
a614cafd6c222ddcd37f6c1322341ba447edfa48
| 686
|
cpp
|
C++
|
common.cpp
|
FrozenCow/nzbtotar
|
c9760337c8cb690608149d71c107bebccad3dabc
|
[
"MIT"
] | null | null | null |
common.cpp
|
FrozenCow/nzbtotar
|
c9760337c8cb690608149d71c107bebccad3dabc
|
[
"MIT"
] | null | null | null |
common.cpp
|
FrozenCow/nzbtotar
|
c9760337c8cb690608149d71c107bebccad3dabc
|
[
"MIT"
] | null | null | null |
#include "common.h"
#define PRINTFILE "/tmp/trace2"
void printrarread(const char *buf,size_t size, size_t offset) {
FILE *f = fopen(PRINTFILE,"a");
fprintf(f,"RAR_READ %lld @ %lld\n",size,offset);
for(int i=0;i<size;i++) {
fprintf(f,"%02x ", buf[i] & 0xff);
}
fprintf(f,"\n");
fclose(f);
sleep(1);
}
void printrarseek(size_t nr, int type, size_t offset) {
FILE *f = fopen(PRINTFILE,"a");
size_t newoffset = offset;
switch(type) {
case SEEK_SET: newoffset = nr; break;
case SEEK_CUR: newoffset += nr; break;
case SEEK_END: newoffset = 999999; break;
}
fprintf(f,"RAR_SEEK %lld > %lld (%d)\n", offset, newoffset, type);
fclose(f);
sleep(1);
}
| 26.384615
| 68
| 0.632653
|
FrozenCow
|
a619763bda3f8ac8dd0bc1c935305855eafc0d91
| 3,527
|
hpp
|
C++
|
src/lib/driver/Driver.hpp
|
psrebniak/css-preprocessor
|
7b54fe3d47c22039239e0690eab39f5ebf027b83
|
[
"MIT"
] | null | null | null |
src/lib/driver/Driver.hpp
|
psrebniak/css-preprocessor
|
7b54fe3d47c22039239e0690eab39f5ebf027b83
|
[
"MIT"
] | null | null | null |
src/lib/driver/Driver.hpp
|
psrebniak/css-preprocessor
|
7b54fe3d47c22039239e0690eab39f5ebf027b83
|
[
"MIT"
] | null | null | null |
#ifndef __DRIVER_HPP__
#define __DRIVER_HPP__
#include <string>
#include <cstddef>
#include <istream>
#include <iostream>
#include <utility>
#include <map>
#include <queue>
#include "lib/types.hpp"
#include "lib/lexer/Lexer.hpp"
#include "lib/logger/Logger.hpp"
#include "lib/ast/node/Node.hpp"
#include "lib/generator/Generator.hpp"
#include "generated/parser.hpp"
namespace CSSP {
class Driver {
friend class Parser;
public:
/**
* Create new Driver
* @param os info/warning output stream
*/
Driver(std::ostream &os) :
log(os, Logger::colorCyan),
error(std::cerr, Logger::colorRed) {}
~Driver();
/**
* parse - parse from a file
* @param filename - valid string with input file
*/
int parse(const char *const filename);
/**
* parse - parse from a c++ input stream
* @param is - std::istream&, valid input stream
*/
int parse(std::istream &iss);
/**
* Create new generator with current fileToFreeMap
* @param minify should be output minified
* @return new Generator instance
*/
CSSP::Generator *getGenerator(bool minify = false);
/**
* Get access to fileToTreeMap
* @return fileToTreeMap
*/
const FileToTreeMapType *getFileToTreeMap() const;
protected:
/**
* helper method, parse given stream
* @param stream
* @return
*/
int parseHelper(std::istream &stream);
/**
* return true if file is already parsed
* @param filename
* @return
*/
bool isFileInTree(std::string filename);
/**
* main file directory name or current working directory in stream parse case
*/
std::string directory;
/**
* main file realpath
*/
std::string mainFileName;
/**
* current processed filename
*/
std::string currentFileName;
/**
* file to process queue
*/
std::queue<std::string> fileQueue;
/**
* realpath to tree map
*/
FileToTreeMapType fileToTreeMap;
/**
* warning logger
*/
Logger log;
/**
* error logger
*/
Logger error;
/**
* Parser instance
*/
CSSP::Parser *parser = nullptr;
/**
* Lexer instance
*/
CSSP::Lexer *lexer = nullptr;
/**
* get realpath of given file (as cwd is used directory parameter)
* @param path
* @return
*/
std::string getRealPath(std::string path);
/**
* run queue and proceed used files
* @return
*/
int processQueue();
/**
* run queue and use DebugString method instead of generate
* @return
*/
int debugQueue();
/**
* Parse partial with given filename
* @return
*/
int parsePartial(std::string);
/**
* Push new file to queue
* @param filename
*/
void pushFileToQueue(std::string filename);
/**
* Set tree for currently parsed element (used by lexer)
* @param nodes
*/
void setNodesAsCurrentTreeElement(NodeListType *nodes);
};
}
#endif
| 22.322785
| 85
| 0.516019
|
psrebniak
|
a619981023bae18c2816d723dde2a121c4af02a8
| 3,246
|
cpp
|
C++
|
Codeforces/Codeforces Round #492 (Div. 2)/C. Tesla.cpp
|
edwinsun98/Competitive-Programming-Solutions
|
67d79a2193e6912a644d27b9a399ba02a60766b7
|
[
"MIT"
] | null | null | null |
Codeforces/Codeforces Round #492 (Div. 2)/C. Tesla.cpp
|
edwinsun98/Competitive-Programming-Solutions
|
67d79a2193e6912a644d27b9a399ba02a60766b7
|
[
"MIT"
] | null | null | null |
Codeforces/Codeforces Round #492 (Div. 2)/C. Tesla.cpp
|
edwinsun98/Competitive-Programming-Solutions
|
67d79a2193e6912a644d27b9a399ba02a60766b7
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#define f first
#define s second
#define all(vec) begin(vec), end(vec)
#define pf push_front
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define mk make_pair
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<ll,int> pli;
void solve(){
int n, k;
cin >> n >> k;
vector<vector<int>> a(5, vector<int>(n+1));
for(int i = 1; i <= 4; i++){
for(int j = 1; j <= n; j++){
cin >> a[i][j];
}
}
if(k == 2*n){
bool ok = 0;
for(int j = 1; j <= n; j++){
if(a[1][j] == a[2][j])ok = 1;
}
for(int j = 1; j <= n; j++){
if(a[4][j] == a[3][j])ok = 1;
}
if(!ok){
cout << -1 << '\n';
return;
}
}
vector<int> ansi, ansr, ansc;
int cnt = 0;
while(1){
for(int j = 1; j <= n; j++){
if(a[2][j] == 0)continue;
if(a[1][j] == a[2][j]){
ansi.pb(a[2][j]);
ansr.pb(1);
ansc.pb(j);
a[2][j] = 0;
cnt++;
}
}
for(int j = 1; j <= n; j++){
if(a[3][j] == 0)continue;
if(a[4][j] == a[3][j]){
ansi.pb(a[3][j]);
ansr.pb(4);
ansc.pb(j);
a[3][j] = 0;
cnt++;
}
}
if(cnt == k)break;
vector<vector<bool>> vis(5, vector<bool>(n+1));
for(int j = 1; j <= n; j++){
if(a[2][j] == 0 || vis[2][j])continue;
if(j < n){
if(a[2][j+1] == 0){
ansi.pb(a[2][j]);
ansr.pb(2);
ansc.pb(j+1);
swap(a[2][j], a[2][j+1]);
vis[2][j+1] = 1;
}
}else{
if(a[3][j] == 0){
ansi.pb(a[2][j]);
ansr.pb(3);
ansc.pb(j);
swap(a[2][j], a[3][j]);
vis[3][j] = 1;
}
}
}
for(int j = n; j >= 1; j--){
if(a[3][j] == 0 || vis[3][j])continue;
if(j > 1){
if(a[3][j-1] == 0){
ansi.pb(a[3][j]);
ansr.pb(3);
ansc.pb(j-1);
swap(a[3][j], a[3][j-1]);
vis[3][j-1] = 1;
}
}else{
if(a[2][j] == 0){
ansi.pb(a[3][j]);
ansr.pb(2);
ansc.pb(j);
swap(a[3][j], a[2][j]);
vis[2][j] = 1;
}
}
}
}
cout << ansi.size() << '\n';
for(int i = 0; i < ansi.size(); i++){
cout << ansi[i] << " " << ansr[i] << " " << ansc[i] << '\n';
}
}
int main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
// freopen("input.in", "r", stdin);
// freopen("output.out", "w", stdout);
int tc = 1;
// cin >> tc;
while(tc--){
solve();
}
}
| 26.826446
| 68
| 0.331793
|
edwinsun98
|
a61dc97200203ca53ebbdc1b2128cf2b22fcedb3
| 1,596
|
cpp
|
C++
|
test/test_ultrasonic_sensor.cpp
|
nr-parikh/acme_robotics_perception_module
|
c681454b8b77c5e0aa7f990cc1fd6345f717920f
|
[
"MIT"
] | null | null | null |
test/test_ultrasonic_sensor.cpp
|
nr-parikh/acme_robotics_perception_module
|
c681454b8b77c5e0aa7f990cc1fd6345f717920f
|
[
"MIT"
] | null | null | null |
test/test_ultrasonic_sensor.cpp
|
nr-parikh/acme_robotics_perception_module
|
c681454b8b77c5e0aa7f990cc1fd6345f717920f
|
[
"MIT"
] | 2
|
2017-10-16T03:16:35.000Z
|
2020-12-12T20:18:20.000Z
|
/**
* @file test_ultrasonic_sensor.cpp
* @author nrparikh
* @copyright MIT license
*
* @brief DESCRIPTION
* Testing file for the UltrasonicSensor.
*/
#include <gtest/gtest.h>
#include <stdlib.h>
#include <ctime>
#include <iostream>
#include "ultrasonic_sensor.hpp"
/**
* @brief Class to test the working of Ultrasonic sensor. Create an
* instance of ultrasonic sensor which can be used for testing
*/
class TestUltrasonicSensor : public ::testing::Test {
protected:
UltrasonicSensor sensor; // Create an instance of Ultrasonic sensor
};
/**
* @brief Dummy test to check the working of tests
*/
TEST_F(TestUltrasonicSensor, dummyTest) {
EXPECT_EQ(1, 1); // Dummy test to check the working of tests
}
/**
* @brief Test to check the working of ultrasonic sensor
*/
TEST_F(TestUltrasonicSensor, isAlive) {
// Test to check whether ultrasonic sensor is working or not
EXPECT_EQ(sensor.isAlive(), true);
}
/**
* @brief Test to check the method of setting maximum distance
*/
TEST_F(TestUltrasonicSensor, setMaxDistance) {
sensor.setMaxDistance(10.03); // Set the max distance using the method
// Test to check if setter and getter methods work correctly
EXPECT_NEAR(sensor.getMaxDistance(), 10.03, 0.0001);
}
/**
* @brief Test to check the reading of ultrasonic sensor
*/
TEST_F(TestUltrasonicSensor, sensorReading) {
sensor.setSeed(0); // Set the seed to a constant value
sensor.process(); // Take the reading of the sensor
// Test the closeness of the two readings
EXPECT_NEAR(sensor.getOutput(), 5.000471475, 0.00001);
}
| 29.555556
| 73
| 0.714912
|
nr-parikh
|
a61f93b8b0f87f7c287a1b62cb396dfac256b0ec
| 269
|
cpp
|
C++
|
problems/problem152/main.cpp
|
PoH314/Algorithms-and-Data-Structures
|
b295379d6b6515921702e2dc358b02680df3960a
|
[
"MIT"
] | 1
|
2022-03-01T15:47:08.000Z
|
2022-03-01T15:47:08.000Z
|
problems/problem152/main.cpp
|
PoH314/Algorithms-and-Data-Structures
|
b295379d6b6515921702e2dc358b02680df3960a
|
[
"MIT"
] | 1
|
2022-03-21T20:01:08.000Z
|
2022-03-21T20:01:08.000Z
|
problems/problem152/main.cpp
|
PoH314/Algorithms-and-Data-Structures
|
b295379d6b6515921702e2dc358b02680df3960a
|
[
"MIT"
] | 1
|
2022-03-21T17:53:34.000Z
|
2022-03-21T17:53:34.000Z
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, c;
int v[3];
cin >> a >> b >> c;
v[0] = b*2 + c*4;
v[1] = a*2 + c*2;
v[2] = b*2 + a*4;
sort(v, v + 3);
cout << v[0] << endl;
return 0;
}
| 12.809524
| 25
| 0.36803
|
PoH314
|
98ae9b01ba3e47e3f7efdb0c534d05cdfaf7b976
| 3,832
|
hpp
|
C++
|
libstm/algs/RedoRAWUtils.hpp
|
nmadduri/rstm
|
5f4697f987625379d99bca1f32b33ee8e821c8a5
|
[
"BSD-3-Clause"
] | 8
|
2016-12-05T19:39:55.000Z
|
2021-07-22T07:00:40.000Z
|
libstm/algs/RedoRAWUtils.hpp
|
hlitz/rstm_zsim_tm
|
1c66824b124f84c8812ca25f4a9aa225f9f1fa34
|
[
"BSD-3-Clause"
] | null | null | null |
libstm/algs/RedoRAWUtils.hpp
|
hlitz/rstm_zsim_tm
|
1c66824b124f84c8812ca25f4a9aa225f9f1fa34
|
[
"BSD-3-Clause"
] | 2
|
2018-06-02T07:46:33.000Z
|
2020-06-26T02:12:34.000Z
|
/**
* Copyright (C) 2011
* University of Rochester Department of Computer Science
* and
* Lehigh University Department of Computer Science and Engineering
*
* License: Modified BSD
* Please see the file LICENSE.RSTM for licensing information
*/
#ifndef STM_REDO_RAW_CHECK_HPP
#define STM_REDO_RAW_CHECK_HPP
#include <stm/config.h>
/**
* Redo-log TMs all need to perform a read-after-write check in their read_rw
* barriers in order to find any previous transactional writes. This is
* complicated when we're byte logging, because we may have written only part
* of a word, and be attempting to read a superset of the word bytes.
*
* This file provides three config-dependent macros to assist in dealing with
* the case where we need to merge a read an write to get the "correct" value.
*/
#if defined(STM_WS_WORDLOG)
/**
* When we're word logging the RAW check is trivial. If we found the value it
* was returned as log.val, so we can simply return it.
*/
#define REDO_RAW_CHECK(found, log, mask) \
if (__builtin_expect(found, false)) \
return log.val;
/**
* When we're word logging the RAW check is trivial. If we found the value
* it was returned as log.val, so we can simply return it. ProfileApp
* version logs the event.
*/
#define REDO_RAW_CHECK_PROFILEAPP(found, log, mask) \
if (__builtin_expect(found, false)) { \
++profiles[0].read_rw_raw; \
return log.val; \
}
/**
* No RAW cleanup is required when word logging, we can just return the
* unadulterated value from the log. ProfileApp version logs the event.
*/
#define REDO_RAW_CLEANUP(val, found, log, mask)
#elif defined(STM_WS_BYTELOG)
/**
* When we are byte logging and the writeset says that it found the address
* we're looking for, it could mean one of two things. We found the requested
* address, and the requested mask is a subset of the logged mask, or we found
* some of the bytes that were requested. The log.mask tells us which of the
* returned bytes in log.val are valid.
*
* We perform a subset test (i.e., mask \in log.mask) and just return log.val
* if it's successful. If mask isn't a subset of log.mask we'll deal with it
* during REDO_RAW_CLEANUP.
*/
#define REDO_RAW_CHECK(found, log, pmask) \
if (__builtin_expect(found, false)) \
if ((pmask & log.mask) == pmask) \
return log.val;
/**
* ProfileApp version logs the event.
*
* NB: Byte logging exposes new possible statistics, should we record them?
*/
#define REDO_RAW_CHECK_PROFILEAPP(found, log, pmask) \
if (__builtin_expect(found, false)) { \
if ((pmask & log.mask) == pmask) { \
++profiles[0].read_rw_raw; \
return log.val; \
} \
}
/**
* When we're byte logging we may have had a partial RAW hit, i.e., the
* write log had some of the bytes that we needed, but not all.
*
* Check for a partial hit. If we had one, we need to mask out the recently
* read bytes that correspond to the valid bytes from the log, and then merge
* in the logged bytes.
*/
#define REDO_RAW_CLEANUP(value, found, log, mask) \
if (__builtin_expect(found, false)) { \
/* can't do masking on a void* */ \
uintptr_t v = reinterpret_cast<uintptr_t>(value); \
v &= ~log.mask; \
v |= reinterpret_cast<uintptr_t>(log.val) & log.mask; \
value = reinterpret_cast<void*>(v); \
}
#else
#error "Preprocessor configuration error: STM_WS_(WORD|BYTE)LOG not defined."
#endif
#endif // STM_REDO_RAW_CHECK_HPP
| 36.495238
| 79
| 0.634656
|
nmadduri
|
98af66ad112c887b8ceae40f93ebf51354227d01
| 1,045
|
cpp
|
C++
|
src/widget-wifi-signal.cpp
|
9ae8sdf76/odbii-pilot
|
8ea5ba7c7001d5b9c293ab4d3a375d44bfd2d145
|
[
"MIT"
] | null | null | null |
src/widget-wifi-signal.cpp
|
9ae8sdf76/odbii-pilot
|
8ea5ba7c7001d5b9c293ab4d3a375d44bfd2d145
|
[
"MIT"
] | 1
|
2021-05-11T16:04:44.000Z
|
2021-05-11T16:04:44.000Z
|
src/widget-wifi-signal.cpp
|
9ae8sdf76/odbii-pilot
|
8ea5ba7c7001d5b9c293ab4d3a375d44bfd2d145
|
[
"MIT"
] | 2
|
2021-01-31T13:04:05.000Z
|
2022-01-12T12:01:17.000Z
|
#include "widget-wifi-signal.h"
using namespace dbuddy;
extern "C" void cb_time_change_task_handler(lv_task_t *);
void WifiSignal::init() {
Widget * time_container = get_ui()->get_widget(WIDGET_TIME_CONTAINER);
Widget * time_label = get_ui()->get_widget(WIDGET_TIME_LABEL);
set_self(lv_label_create(time_container->get_self(), time_label->get_self()));
set_pos(time_label->get_width() + DEFAULT_PADDING, DEFAULT_PADDING / 2);
lv_label_set_text(get_self(), LV_SYMBOL_WIFI);
add_style(LV_LABEL_PART_MAIN, get_ui()->get_styles()->get_text_color_gray(LV_STATE_DEFAULT));
// Keep the symbol to the right of the time label
get_ui()->create_task(cb_time_change_task_handler, 500);
}
void cb_time_change_task_handler(lv_task_t * task) {
auto * ui = (Ui *)task->user_data;
Widget * wifi_signal = ui->get_widget(WIDGET_WIFI_SIGNAL);
Widget * time_label = ui->get_widget(WIDGET_TIME_LABEL);
lv_obj_set_pos(wifi_signal->get_self(), time_label->get_width() + DEFAULT_PADDING, DEFAULT_PADDING / 2);
}
| 34.833333
| 108
| 0.742584
|
9ae8sdf76
|
98b18d6b66815637b76fe5242075360f32657839
| 2,365
|
cpp
|
C++
|
DistributedTrees/ForestManager.cpp
|
palvaradomoya/forests
|
eec6a5e003a2849367fdeef18b7b5340b6d0e480
|
[
"BSD-3-Clause"
] | null | null | null |
DistributedTrees/ForestManager.cpp
|
palvaradomoya/forests
|
eec6a5e003a2849367fdeef18b7b5340b6d0e480
|
[
"BSD-3-Clause"
] | null | null | null |
DistributedTrees/ForestManager.cpp
|
palvaradomoya/forests
|
eec6a5e003a2849367fdeef18b7b5340b6d0e480
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: TreeManager.cpp
* Author: gabo
*
* Created on May 17, 2018, 4:24 PM
*/
#include "ForestManager.h"
rdf::ForestManager::ForestManager() {
_status=false;
}
rdf::ForestManager::ForestManager(const ForestManager& orig) {
}
rdf::ForestManager::~ForestManager() {
}
void rdf::ForestManager::initializeForest() {
for(int i = 0; i < TREE_AMOUNT; i++){
rdf::Task newTask;
newTask.setRank(0);
newTask.setTree(i);
newTask.setNode(1);
newTask.setStatus(false);
_matrixSteps.push_back(newTask);
rdf::NodeResult node;
_resultMap.insert(std::make_pair(newTask,node));
}
}
void rdf::ForestManager::showQueue() {
for(int i=0; i<_matrixSteps.size(); i++){
rdf::Task temp = _matrixSteps[i];
temp.showTask();
}
}
rdf::Task & rdf::ForestManager::getNextTask() {
std::cout << "Queue Size: " << _matrixSteps.size()<< "\n";
rdf::Task &test = _matrixSteps[0];
//_matrixSteps.erase(_matrixSteps.begin());
return test;
}
bool rdf::ForestManager::addResuld(NodeResult& pResult) {
std::cout<<"REDUCE: " << pResult.getResultSize() << "\n";
_resultMap.find(pResult.getTask())->second.reduce(pResult);
//_result.reduce(pResult);
//_result.showTask();
Task leftChild;
Task rightChild;
leftChild.setRank(pResult.getTask().getRank());
leftChild.setTree(pResult.getTask().getTree());
leftChild.setNode(2 * pResult.getTask().getNode());
leftChild.setStatus(pResult.getTask().isStatus());
rightChild.setRank(pResult.getTask().getRank());
rightChild.setTree(pResult.getTask().getTree());
rightChild.setNode(2 * pResult.getTask().getNode()-1);
rightChild.setStatus(pResult.getTask().isStatus());
_matrixSteps.push_back(leftChild);
_matrixSteps.push_back(rightChild);
std::cout<< "Adding child nodes, size: "<<_matrixSteps.size()<<"\n";
NodeResult result;
_resultMap.insert(std::make_pair(leftChild,result));
_resultMap.insert(std::make_pair(leftChild,result));
//leftChild.showTask();
//rightChild.showTask();
return true;
}
| 25.430108
| 79
| 0.645666
|
palvaradomoya
|
98be8a2b186d1c350434bba3bbef42aee864e222
| 4,770
|
cpp
|
C++
|
applicationsSrc/simpleCatoms3D/simpleCatom3DBlockCode.cpp
|
claytronics/visiblesim
|
2762a88a23e50516d0f166dd9629f1ac7290fded
|
[
"Apache-2.0"
] | 4
|
2016-08-18T03:19:49.000Z
|
2020-09-20T03:29:26.000Z
|
applicationsSrc/simpleCatoms3D/simpleCatom3DBlockCode.cpp
|
claytronics/visiblesim
|
2762a88a23e50516d0f166dd9629f1ac7290fded
|
[
"Apache-2.0"
] | 2
|
2016-08-18T03:25:07.000Z
|
2016-08-29T17:51:50.000Z
|
applicationsSrc/simpleCatoms3D/simpleCatom3DBlockCode.cpp
|
claytronics/visiblesim
|
2762a88a23e50516d0f166dd9629f1ac7290fded
|
[
"Apache-2.0"
] | 3
|
2015-05-14T07:29:55.000Z
|
2021-07-18T23:45:36.000Z
|
/*
* catom2D1BlockCode.cpp
*
* Created on: 12 avril 2013
* Author: ben
*/
#include <iostream>
#include <sstream>
#include "catoms3DWorld.h"
#include "simpleCatom3DBlockCode.h"
#include "scheduler.h"
#include "events.h"
#include <memory>
#define verbose 1
using namespace std;
using namespace Catoms3D;
SimpleCatom3DBlockCode::SimpleCatom3DBlockCode(Catoms3DBlock *host):Catoms3DBlockCode(host) {
cout << "SimpleCatom3DBlockCode constructor" << endl;
scheduler = getScheduler();
catom = (Catoms3DBlock*)hostBlock;
}
SimpleCatom3DBlockCode::~SimpleCatom3DBlockCode() {
cout << "SimpleCatom3DBlockCode destructor" << endl;
}
void SimpleCatom3DBlockCode::startup() {
stringstream info;
info << "Starting ";
/*int n=0;
for (int i=0; i<12; i++) {
if (catom->getInterface(i)->connectedInterface!=NULL) {
n++;
}
}
switch (n) {
case 0 : catom->setColor(DARKGREY); break;
case 1 : catom->setColor(RED); break;
case 2 : catom->setColor(ORANGE); break;
case 3 : catom->setColor(PINK); break;
case 4 : catom->setColor(YELLOW); break;
case 5 : catom->setColor(GREEN); break;
case 6 : catom->setColor(LIGHTGREEN); break;
case 7 : catom->setColor(LIGHTBLUE); break;
case 8 : catom->setColor(BLUE); break;
case 9 : catom->setColor(MAGENTA); break;
case 10 : catom->setColor(GOLD); break;
case 11 : catom->setColor(DARKORANGE); break;
case 12 : catom->setColor(WHITE); break;
}*/
/* skeleton test */
Catoms3DWorld*wrl = Catoms3DWorld::getWorld();
Vector3D pos(catom->ptrGlBlock->position[0],catom->ptrGlBlock->position[1],catom->ptrGlBlock->position[2]);
potentiel = wrl->getSkeletonPotentiel(pos);
catom->setColor(potentiel>1.0?YELLOW:DARKORANGE);
info << potentiel;
scheduler->trace(info.str(),hostBlock->blockId);
if (catom->blockId==1) {
Vector3D position=wrl->lattice->gridToWorldPosition(Cell3DPosition(2,1,0));
int id=1000000;
int i=0;
Catoms3DBlock *voisin=NULL;
P2PNetworkInterface *p2p;
while (i<12) {
p2p = catom->getInterface(i);
if(p2p->connectedInterface && p2p->connectedInterface->hostBlock->blockId<id) {
voisin = (Catoms3DBlock*)p2p->connectedInterface->hostBlock;
id = voisin->blockId;
}
i++;
}
Matrix m_1;
voisin->getGlBlock()->mat.inverse(m_1);
// recherche le voisin d'indice minimum
//Rotations3D rotations(catom,voisin,m_1*Vector3D(0,1,0),35.2643896828,m_1*Vector3D(-1,1, -M_SQRT2),35.2643896828);
Rotations3D rotations(catom,voisin,m_1*Vector3D(0,0,1),45.0,m_1*Vector3D(-1,1,0),45.0);
Time t = scheduler->now()+2000;
scheduler->schedule(new Rotation3DStartEvent(t,catom,rotations));
#ifdef verbose
stringstream info;
info.str("");
info << "Rotation3DStartEvent(" << t << ") around #" << voisin->blockId;
scheduler->trace(info.str(),catom->blockId,LIGHTGREY);
#endif
}
}
void SimpleCatom3DBlockCode::processLocalEvent(EventPtr pev) {
MessagePtr message;
stringstream info;
switch (pev->eventType) {
case EVENT_ROTATION3D_END: {
#ifdef verbose
info.str("");
info << "rec.: EVENT_MOTION_END";
scheduler->trace(info.str(),hostBlock->blockId);
#endif
Catoms3DBlock *voisin=NULL;
P2PNetworkInterface *p2p;
int i=0,id=10000;
while (i<12) {
p2p = catom->getInterface(i);
if(p2p->connectedInterface && p2p->connectedInterface->hostBlock->blockId<id) {
voisin = (Catoms3DBlock*)p2p->connectedInterface->hostBlock;
id = voisin->blockId;
}
i++;
}
Matrix m_1;
voisin->getGlBlock()->mat.inverse(m_1);
// Rotations3D rotations(catom,voisin,m_1*Vector3D(-1,1,M_SQRT2),35.26,m_1*Vector3D(-1,-1, -M_SQRT2),35.26);
Rotations3D rotations(catom,voisin,m_1*Vector3D(-1,-1,0),45.0,m_1*Vector3D(0,0,1),45.0);
Time t = scheduler->now()+1002000;
// scheduler->schedule(new Rotation3DStartEvent(t,catom,rotations));
}
break;
case EVENT_NI_RECEIVE: {
message = (std::static_pointer_cast<NetworkInterfaceReceiveEvent>(pev))->message;
P2PNetworkInterface * recv_interface = message->destinationInterface;
}
break;
}
}
// bool SimpleCatom3DBlockCode::getAttribute(const string &att,ostringstream &sout) {
// if (att=="potentiel") {
// sout << potentiel << endl;
// return true;
// }
// return Catoms3DBlockCode::getAttribute(att,sout);
// }
| 32.896552
| 123
| 0.621593
|
claytronics
|
98bf4134e6cd2192628fcc10118ac305f981d354
| 3,085
|
cpp
|
C++
|
local.1.genesis/app.loaderTest/c_getopt.cpp
|
manxinator/aok
|
b8d7908dec4c04508f6eabf252684b105c14608b
|
[
"MIT"
] | null | null | null |
local.1.genesis/app.loaderTest/c_getopt.cpp
|
manxinator/aok
|
b8d7908dec4c04508f6eabf252684b105c14608b
|
[
"MIT"
] | null | null | null |
local.1.genesis/app.loaderTest/c_getopt.cpp
|
manxinator/aok
|
b8d7908dec4c04508f6eabf252684b105c14608b
|
[
"MIT"
] | null | null | null |
/*------------------------------------------------------------------------------
Copyright (c) 2015 manxinator
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.
--------------------------------------------------------------------------------
c_getopt.cpp
------------------------------------------------------------------------------*/
#include "c_getopt.h"
#include <unistd.h>
#include <libgen.h>
//------------------------------------------------------------------------------
char g_progName[SML_STR_SIZE] = "GetOptions";
char g_fileName[SML_STR_SIZE] = "NOT_DEFINED";
int optv = 0;
int opth = 0;
//------------------------------------------------------------------------------
extern int getopt(int argc, char * const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
//------------------------------------------------------------------------------
void printUsage(int exitVal)
{
printf("Usage: %s <options>\n",g_progName);
printf(" -f <s> Input Filename (%s)\n",g_fileName);
printf("--------------------------------------------------\n");
printf(" -v increase verbosity: 0x%x\n",optv);
printf(" -h print help and exit\n");
exit(exitVal);
}
void parseArgs (int argc, char *argv[])
{
strcpy(g_progName,basename(argv[0]));
int c = 0;
opterr = 0;
while ((c = getopt(argc,argv,"f:vh")) != -1)
switch (c)
{
case 'f':
strcpy(g_fileName,optarg);
break;
case 'v':
optv = (optv<<1) | 1;
break;
case '?':
switch (optopt)
{
case 'f':
break;
default:
if (isprint(optopt))
fprintf(stderr,"ERROR: Unknown option `-%c'.\n",optopt);
else
fprintf(stderr,"ERROR: Unknown option character `\\x%x'.\n",optopt);
break;
}
printf("\n\n");
printUsage(-1);
break;
default:
printUsage(-1);
}
for (int index = optind; index < argc; index++)
printf("Extra Argument: %s\n",argv[index]);
if (opth)
printUsage(EXIT_SUCCESS);
}
| 31.161616
| 80
| 0.544246
|
manxinator
|
98c05af6895832daab7d7259165ff6ad855e7bec
| 1,196
|
cxx
|
C++
|
all-tests/test-dblbuff.cxx
|
Hungerarray/winbgim
|
4a0bc7da71cacba61bcf6dcb7d3e2ad1ef8ebb82
|
[
"MIT"
] | null | null | null |
all-tests/test-dblbuff.cxx
|
Hungerarray/winbgim
|
4a0bc7da71cacba61bcf6dcb7d3e2ad1ef8ebb82
|
[
"MIT"
] | null | null | null |
all-tests/test-dblbuff.cxx
|
Hungerarray/winbgim
|
4a0bc7da71cacba61bcf6dcb7d3e2ad1ef8ebb82
|
[
"MIT"
] | null | null | null |
// FILE: dblbuff.cpp
// Demostrates double-buffering with the winbgim library.
// Michael Main -- Nov 25, 1998
#include <stdio.h> // Provides sprintf function
#include "winbgim.h" // Provides Windows BGI functions
int main( )
{
const int COLUMNS = 8;
const int ROWS = 16;
int x, y; // x and y pixel locations
int row, column; // Row and column number
int box_width; // Width of a color box in pixels
int box_height; // Height of a color box in pixels
int color; // Color number, now ranging from 0 to 127
// Initialize the graphics window and set the box size.
initwindow(400,300);
box_width = getmaxx( ) / COLUMNS;
box_height = getmaxy( ) / ROWS;
// Draw some items on pages 1 and 0:
setactivepage(1);
line(0, 0, getmaxx( ), getmaxy( ));
outtextxy(100, 100, "This is page #1.");
outtextxy(100, 120, "Press a key to end the program.");
setactivepage(0);
line(getmaxx( ), 0, 0, getmaxy( ));
outtextxy(100, 100, "This is page #0.");
outtextxy(100, 120, "Press a key to see page #1.");
// Get the user to press a key to move to page 1:
getch( );
setvisualpage(1);
getch( );
}
| 28.47619
| 63
| 0.620401
|
Hungerarray
|
98c2f3d6736670bb307f7d0dda5a6ad941ba850f
| 10,524
|
cpp
|
C++
|
FamilyTree.cpp
|
TomerDvir123/ancestor-tree-b
|
013b89ae3c47408f177abf6fa94de53a01a8013e
|
[
"MIT"
] | null | null | null |
FamilyTree.cpp
|
TomerDvir123/ancestor-tree-b
|
013b89ae3c47408f177abf6fa94de53a01a8013e
|
[
"MIT"
] | null | null | null |
FamilyTree.cpp
|
TomerDvir123/ancestor-tree-b
|
013b89ae3c47408f177abf6fa94de53a01a8013e
|
[
"MIT"
] | null | null | null |
//#include "FamilyTree.hpp"
//#include <iostream>
//#include <string>
//
//
//
//using namespace std;
//using namespace family;
#include "FamilyTree.hpp"
#include <string>
#include <stdexcept>
#include <iostream>
#include <cstring>
using namespace std;
using namespace family;
Tree::Tree(string name) {
this->MyName = name;
this->Father = NULL;
this->Mother = NULL;
this->depth = 0;
this->key = 0;
this->rel = "";
this->found=false;
}
// Tree::~Tree()
// {
// if()
// delete this->Father;
// delete this->Mother;
// // cout << "ETEDE";
// }
Tree *Tree::curr(Tree *where, string who) {
if (where == NULL)
{
return NULL;
}
if (who.compare(where->MyName) == 0)
{
return where;
}
else
{
Tree *f = curr(where->Father, who);
if (f != NULL)
{
return f;
}
Tree *m = curr(where->Mother, who);
if (m != NULL)
{
return m;
}
}
return NULL;
}
Tree &Tree::addFather(string name, string father) {
Tree *temp = this;
Tree *temp2 = curr(this, name);
if(temp2 == NULL)
{
throw std::invalid_argument(name + " doesnt exist\n");
}
this->key = 0;
if (temp2->MyName.compare(name) == 0) {
if (temp2->Father == NULL) {
temp2->Father = new Tree(father);
temp2->Father->MyName = father;
string temp3 = curr2(this, name, "");
this->key = 0;
int i = 0;
while (temp->MyName != name) {
if (temp3[i] == 'f') {
temp = temp->Father;
i++;
}
if (temp3[i] == 'm') {
temp = temp->Mother;
i++;
}
}
temp2->Father->depth = i + 1;
int r = i + 1;
if (r == 0) {
cout << name + " it's me";
} else if (r == 1) {
temp2->Father->rel = "father";
} else if (r == 2) {
temp2->Father->rel = "grandfather";
} else if (r > 2) {
string times = "";
int k = 2;
while (k < r) {
times = times + "great-";
k++;
}
temp2->Father->rel = times + "grandfather";
}
temp->Father = temp2->Father;
}
else {
// cout << name + " has father\n";
throw std::invalid_argument(name + " has a father\n");
}
}
else {
cout << name + " doesnt exist\n";
throw std::invalid_argument(name + " doesnt exist\n");
}
return *this;
}
Tree &Tree::addMother(string name, string mother) {
Tree *temp = this;
Tree *temp4 = curr(temp, name);
if(temp4 == NULL)
{
throw std::invalid_argument(name + " doesnt exist\n");
}
this->key = 0;
if (temp4->MyName == name) {
if (temp4->Mother == NULL) {
temp4->Mother = new Tree(mother);
temp4->Mother->MyName = mother;
string temp3 = curr2(temp, name, "");
this->key = 0;
int i = 0;
while (temp->MyName != name) {
if (temp3[i] == 'f') {
temp = temp->Father;
i++;
}
if (temp3[i] == 'm') {
temp = temp->Mother;
i++;
}
}
temp4->Mother->depth = i + 1;
int r = i + 1;
if (r == 0) {
cout << name + " it's me";
} else if (r == 1) {
temp4->Mother->rel = "mother";
} else if (r == 2) {
temp4->Mother->rel = "grandmother";
} else if (r > 2) {
string times = "";
int k = 2;
while (k < r) {
times = times + "great-";
k++;
}
temp4->Mother->rel = times + "grandmother";
}
temp->Mother = temp4->Mother;
}
else {
throw std::invalid_argument(name + " has a mother\n");
}
}
else {
throw std::invalid_argument(name + " doesnt exist\n");
}
return *this;
}
string Tree::relation(string name) {
// this->key=0;
// cout << name +" is ";
if(this->MyName.compare(name)==0)
{
return "me";
}
Tree *temp = this;
Tree *temp2 = curr(temp, name);
if(temp2 == NULL)
{
// throw std::invalid_argument(name + " doesnt exist\n");
return "unrelated";
}
this->key = 0;
this->found = false;
return temp2->rel;
//cout << temp2.MyName << " is: " << temp2.depth << "\n";
// string temp3 = curr2(temp, name, "");
// this->key = 0;
// this->found = false;
//cout << temp3;
// int i = 2;
// int r = 0;
// r = temp2->depth;
// if (r == 0) {
// cout << name + " it's me\n";
// return name;
// } else if (r == 1) {
// if (temp3[0] == 'm') {
// cout << name + " it's the mother of " + temp->MyName+"\n";
// return "mother";
// } else {
// cout << name + " it's the father of " + temp->MyName+"\n";
// return "father";
// }
// } else if (r == 2) {
// if (temp3[1] == 'm') {
// cout << name + " it's the grandmother of " + temp->MyName+"\n";
// return "grandmother";
// } else {
// cout << name + " it's the grandfather of " + temp->MyName+"\n";
// return "grandfather";
// }
// } else if (r > 2)
// {
// string times = "";
// while(i<r)
// {
// times = times + "great-";
// i++;
// }
// if (temp3[(temp2->depth)-1] == 'm') {
// cout << name + " it's the "+ times +"grandmother of " + temp->MyName+"\n";
// return times + "grandmother";
// } else {
// cout << name + " it's the "+ times +"grandfather of " + temp->MyName+"\n";
// return times + "grandfather";
// }
// }
}
////////////////
string Tree::find_helper(Tree *now, string name ) {
//Tree temp = *now;
string n = now->MyName;
if ((now->rel).compare(name) == 0) {
this->key = 1;
this->found = true;
return n;
}
if (now->Mother != NULL && now->rel != name && this->key != 1 && this->found!=true) {
n = find_helper(now->Mother, name);
}
if (now->Father != NULL && now->rel != name && this->key != 1 && this->found!=true) {
n = find_helper(now->Father, name);
}
if (now->rel == name) {
this->found = true;
return n;
}
if (this->key == 1) {
this->found = true;
return n;
}
if(this->found==false )
{
return "";
}
return "";
}
/////////////////
string Tree::find(string rel) {
// string p = new string();
string p = find_helper(this, rel);
this->key=0;
this->found=false;
if(p.compare("")==0)
{
//cout << "\nnot found";
//string test = "Could'nt find '" + rel + "'";
// throw invalid_argument("test");
throw runtime_error("asd");
}
//cout << p;
// delete &rel;
return p;
}
void Tree:: printT(Tree *temp) {
if (temp != nullptr)
{
cout << temp->rel + ": " + temp->MyName << endl;
if (temp->Father != NULL && temp->Mother != NULL)
{
printT(temp->Father);
printT(temp->Mother);
}
else if (temp->Father != NULL)
{
printT(temp->Father);
}
else if (temp->Mother != NULL)
{
printT(temp->Mother);
}
}
}
void Tree::display() {
Tree *temp = this;
printT(temp);
}
void Tree::del(Tree *root) {
if(root != nullptr) {
if (root->Mother != nullptr) {
root->Mother = nullptr;
}
if (root->Father != nullptr) {
root->Father = nullptr;
}
delete root;
}
}
void Tree::remove(string name) {
Tree *temp = this;
Tree *temp9 = this;
int i = 0;
// Tree temp2 = curr(temp, name);
this->key=0;
string temp2 = curr2(temp,name,"");
if(temp2.length()==0 || this->MyName.compare(name)==0 )
{
throw std::invalid_argument(name + " cant delete\n");
}
else{
while (temp->MyName != name) {
if (temp2[i] == 'f') {
temp = temp->Father;
i++;
}
if (temp2[i] == 'm') {
temp = temp->Mother;
i++;
}
}
i = 0;
if(temp2.length()==1)
{
//f
}
else {
while (i<temp2.length()-1) {
if (temp2[i] == 'f') {
temp9 = temp9->Father;
i++;
}
else {
temp9 = temp9->Mother;
i++;
}
}
}
//temp = &temp2;
this->found = false;
this->key = 0;
// delete temp;
// del(temp);
// delete temp9;
if(temp2[i]=='f'){
delete temp9->Father;
temp9->Father = nullptr;
}
if(temp2[i]=='m')
{
delete temp9->Mother;
temp9->Mother = nullptr;
}
//cout<<"a";
}
this->key=0;
this->found=false;
}
/**
* Tree temp = *now;
if(now->MyName==name)
{
this->key=1;
return temp;
}
if(now->Mother!=NULL && now->MyName!=name && this->key!=1)
{
temp = curr(now->Mother,name);
}
if(now->Father!=NULL && now->MyName!=name && this->key!=1 )
{
temp = curr(now->Father,name);
}
if(temp.MyName==name)
return temp;
*/
string Tree::curr2(Tree *now, string name, string ans) {
//Tree temp = *now;
string t = ans;
if (now->MyName.compare(name)==0) {
this->key = 1;
return t;
}
if (now->Father != NULL && now->MyName != name && this->key != 1) {
t = curr2(now->Father, name, ans + "f");
}
if (now->Mother != NULL && now->MyName != name && this->key != 1) {
t = curr2(now->Mother, name, ans + "m");
}
if (this->key == 1) {
return t;
}
return "";
}
| 22.779221
| 90
| 0.418757
|
TomerDvir123
|
98c3b175988236bcb60c1ce5cf9f831b9a1788ba
| 1,614
|
cpp
|
C++
|
thrift/lib/cpp2/protocol/nimble/EncodeNimbleBlock.cpp
|
andywei/fbthrift
|
59330df4969ecde98c09a5e2ae6e78a31735418f
|
[
"Apache-2.0"
] | null | null | null |
thrift/lib/cpp2/protocol/nimble/EncodeNimbleBlock.cpp
|
andywei/fbthrift
|
59330df4969ecde98c09a5e2ae6e78a31735418f
|
[
"Apache-2.0"
] | null | null | null |
thrift/lib/cpp2/protocol/nimble/EncodeNimbleBlock.cpp
|
andywei/fbthrift
|
59330df4969ecde98c09a5e2ae6e78a31735418f
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2019-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdexcept>
#include <utility>
#include <folly/Portability.h>
#include <thrift/lib/cpp2/protocol/nimble/ControlBitHelpers.h>
#include <thrift/lib/cpp2/protocol/nimble/EncodeNimbleBlock.h>
namespace apache {
namespace thrift {
namespace detail {
namespace {
constexpr NimbleBlockEncodeData encodeDataForControlByte(std::uint8_t byte) {
NimbleBlockEncodeData result;
result.sum = 0;
for (int i = 0; i < kChunksPerBlock; ++i) {
int size = controlBitPairToSize(byte, i);
result.sizes[i] = size;
result.sum += size;
}
return result;
}
template <std::size_t... Indices>
constexpr std::array<NimbleBlockEncodeData, 256> encodeDataFromIndices(
std::index_sequence<Indices...>) {
return {{encodeDataForControlByte(Indices)...}};
}
} // namespace
FOLLY_STORAGE_CONSTEXPR const std::array<NimbleBlockEncodeData, 256>
nimbleBlockEncodeData =
encodeDataFromIndices(std::make_index_sequence<256>{});
} // namespace detail
} // namespace thrift
} // namespace apache
| 28.821429
| 77
| 0.737299
|
andywei
|
98c48edaf8079e3633fca88e0dac2b69c771448a
| 6,349
|
cc
|
C++
|
src/post.cc
|
smirolo/tero
|
8db171a22e6723bc1eed0b235f17cc962528b93d
|
[
"BSD-3-Clause"
] | 1
|
2020-06-27T00:27:10.000Z
|
2020-06-27T00:27:10.000Z
|
src/post.cc
|
smirolo/tero
|
8db171a22e6723bc1eed0b235f17cc962528b93d
|
[
"BSD-3-Clause"
] | null | null | null |
src/post.cc
|
smirolo/tero
|
8db171a22e6723bc1eed0b235f17cc962528b93d
|
[
"BSD-3-Clause"
] | null | null | null |
/* Copyright (c) 2009-2013, Fortylines LLC
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 fortylines 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 Fortylines LLC ''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 Fortylines LLC 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 "mail.hh"
#include "markup.hh"
#include "decorator.hh"
#include "contrib.hh"
#include "composer.hh"
/** Posts.
Primary Author(s): Sebastien Mirolo <smirolo@fortylines.com>
*/
namespace tero {
sessionVariable titleVar("title","title of a post");
sessionVariable authorVar("author","author of a post");
sessionVariable authorEmail("authorEmail","email for the author of a post");
sessionVariable descrVar("descr","content of a post");
void
postAddSessionVars( boost::program_options::options_description& opts,
boost::program_options::options_description& visible )
{
using namespace boost::program_options;
options_description localOptions("posts");
localOptions.add(titleVar.option());
localOptions.add(authorVar.option());
localOptions.add(authorEmail.option());
localOptions.add(descrVar.option());
opts.add(localOptions);
visible.add(localOptions);
}
void post::normalize() {
title = tero::normalize(title);
guid = tero::strip(guid);
content = tero::strip(content);
}
bool post::valid() const {
/* If there are any whitespaces in the guid, Thunderbird 3 will
hang verifying the rss feed... */
for( size_t i = 0; i < guid.size(); ++i ) {
if( isspace(guid[i]) ) {
return false;
}
}
return (!title.empty() & !author->email.empty() & !content.empty());
}
void passThruFilter::flush() {
if( next ) next->flush();
}
void retainedFilter::provide() {
first = posts.begin();
last = posts.end();
}
void retainedFilter::flush()
{
if( next ) {
provide();
for( const_iterator p = first; p != last; ++p ) {
next->filters(*p);
}
next->flush();
}
}
void contentHtmlwriter::filters( const post& p ) {
*ostr << html::div().classref("postBody");
*ostr << p.content;
*ostr << html::div::end;
}
void titleHtmlwriter::filters( const post& p ) {
/* caption for the post */
*ostr << html::div().classref("postCaption");
if( !p.link.empty() ) {
*ostr << p.link << std::endl;
} else if( !p.title.empty() ) {
*ostr << html::a().href(p.guid)
<< html::h(1) << p.title << html::h(1).end()
<< html::a::end << std::endl;
}
*ostr << by(p.author) << " on " << p.time;
*ostr << html::div::end;
if( next ) {
next->filters(p);
}
}
void contactHtmlwriter::filters( const post& p ) {
if( next ) {
next->filters(p);
}
*ostr << html::div().classref("postContact");
*ostr << html::div().classref("contactAuthor");
*ostr << "Contact the author "
<< html::div() << contact(p.author) << html::div::end;
*ostr << html::div::end << html::div::end;
}
void stripedHtmlwriter::filters( const post& p ) {
(*ostr).imbue(std::locale((*ostr).getloc(), pubDate::shortFormat()));
*ostr << html::div().classref( (postNum % 2 == 0) ?
"postEven" : "postOdd");
if( next ) {
next->filters(p);
}
*ostr << html::div::end;
++postNum;
}
void htmlwriter::filters( const post& p ) {
striped.filters(p);
}
void mailwriter::filters( const post& p ) {
(*ostr).imbue(std::locale((*ostr).getloc(), pubDate::format()));
*ostr << "From " << from(p.author) << std::endl;
*ostr << "Subject: " << (!p.title.empty() ? p.title : "(No Subject)")
<< std::endl;
*ostr << "Date: " << p.time << std::endl;
*ostr << "From: " << from(p.author) << std::endl;
*ostr << "Score: " << p.score << std::endl;
for( post::headersMap::const_iterator header = p.moreHeaders.begin();
header != p.moreHeaders.end(); ++header ) {
*ostr << header->first << ": " << header->second << std::endl;
}
*ostr << std::endl << std::endl;
if( !p.link.empty() ) {
*ostr << p.link << std::endl;
}
/* \todo avoid description starting with "From " */
*ostr << p.content << std::endl << std::endl;
}
void rsswriter::filters( const post& p ) {
htmlEscaper esc;
*ostr << item();
*ostr << title() << p.title << title::end;
*ostr << rsslink() << p.guid << rsslink::end;
*ostr << description() << "<![CDATA[";
if( !p.link.empty() ) {
*ostr << p.link << std::endl;
}
*ostr << html::p()
<< by(p.author) << ":" << "<br />"
<< p.content << html::p::end
<< "]]>" << description::end;
*ostr << author();
esc.attach(*ostr);
*ostr << p.author->email;
esc.detach();
*ostr << author::end;
#if 0
*ostr << "<guid isPermaLink=\"true\">";
#endif
*ostr << guid() << p.guid << guid::end;
*ostr << pubDate(p.time);
*ostr << item::end;
}
void subjectWriter::filters( const post& p ) {
*ostr << html::a().href(p.guid) << p.title << html::a::end
<< "<br/>" << std::endl;
}
}
| 28.34375
| 80
| 0.606867
|
smirolo
|
98c5aa208506bbc593f4d18ce839c305dc7ab179
| 10,983
|
cpp
|
C++
|
src/3rdparty/qt-components/src/mx/qmxtoplevelitem.cpp
|
qtmediahub/qtmediahub-ruins
|
844c71dbd7bcbd94a6ba76b952b7d1850e3ddc67
|
[
"BSD-3-Clause"
] | null | null | null |
src/3rdparty/qt-components/src/mx/qmxtoplevelitem.cpp
|
qtmediahub/qtmediahub-ruins
|
844c71dbd7bcbd94a6ba76b952b7d1850e3ddc67
|
[
"BSD-3-Clause"
] | null | null | null |
src/3rdparty/qt-components/src/mx/qmxtoplevelitem.cpp
|
qtmediahub/qtmediahub-ruins
|
844c71dbd7bcbd94a6ba76b952b7d1850e3ddc67
|
[
"BSD-3-Clause"
] | null | null | null |
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Components project on Qt Labs.
**
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions contained
** in the Technology Preview License Agreement accompanying this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
****************************************************************************/
#include "qmxtoplevelitem.h"
#include "qmxtoplevelitem_p.h"
#include <QGraphicsScene>
QMxTopLevelItemPrivate::QMxTopLevelItemPrivate() :
targetItem(0), transformDirty(0), keepInside(0)
{
}
QMxTopLevelItemPrivate::~QMxTopLevelItemPrivate()
{
}
void QMxTopLevelItemPrivate::clearDependencyList()
{
Q_Q(QMxTopLevelItem);
for (int i = dependencyList.count() - 1; i >= 0; --i) {
dependencyList.takeAt(i)->disconnect(this);
}
q->setTransform(QTransform());
q->setOpacity(1);
q->setVisible(false);
}
/*!
\internal
Set data bindings between the TopLevelItem and all the items it depend upon,
including the targetItem and its ancestors.
*/
void QMxTopLevelItemPrivate::initDependencyList()
{
Q_Q(QMxTopLevelItem);
if (!targetItem || !targetItem->parentItem())
return;
// ### We are not listening for childrenChange signals in our parent
// but that seems a little bit too much overhead. It can be done if
// required in the future.
setZFromSiblings();
// The width of the TopLevelItem is the width of the targetItem
connect(targetItem, SIGNAL(widthChanged()), SLOT(updateWidthFromTarget()));
connect(targetItem, SIGNAL(heightChanged()), SLOT(updateHeightFromTarget()));
// Now bind to events that may change the position and/or transforms of
// the TopLevelItem
// ### If we had access to QDeclarativeItem private we could do this
// in a better way, by adding ourselves to the changeListeners list
// in each item.
// The benefit is that we could update our data based on the change
// rather than having to recalculate the whole tree.
QDeclarativeItem *item = targetItem;
while (item->parentItem()) {
dependencyList << item;
// We listen for events that can change the visibility and/or geometry
// of the targetItem or its ancestors.
connect(item, SIGNAL(opacityChanged()), SLOT(updateOpacity()));
connect(item, SIGNAL(visibleChanged()), SLOT(updateVisible()));
// ### We are not listening to changes in the "transform" property
// 'updateTransform' may be expensive, so instead of calling it several
// times, we call the schedule method instead, that also compresses
// these events.
connect(item, SIGNAL(xChanged()), SLOT(scheduleUpdateTransform()));
connect(item, SIGNAL(yChanged()), SLOT(scheduleUpdateTransform()));
connect(item, SIGNAL(rotationChanged()), SLOT(scheduleUpdateTransform()));
connect(item, SIGNAL(scaleChanged()), SLOT(scheduleUpdateTransform()));
connect(item, SIGNAL(transformOriginChanged(TransformOrigin)), SLOT(scheduleUpdateTransform()));
// parentChanged() may be emitted from destructors and other sensible code regions.
// By making this connection Queued we wait for the control to reach the event loop
// allow for the scene to be in a stable state before doing our changes.
connect(item, SIGNAL(parentChanged()), SLOT(updateParent()), Qt::QueuedConnection);
item = item->parentItem();
}
// 'item' is the root item in the scene, make it our parent
q->setParentItem(item);
// Note that we did not connect to signals regarding opacity, visibility or
// transform changes of our parent, that's because we take that effect
// automatically, as it is our parent
// OTOH we need to listen to changes in its size to re-evaluate the keep-inside
// functionality.
connect(item, SIGNAL(widthChanged()), SLOT(updateWidthFromTarget()));
// Call slots for the first time
updateHeightFromTarget();
updateTransform();
updateOpacity();
updateVisible();
}
void QMxTopLevelItemPrivate::scheduleUpdateTransform()
{
if (transformDirty)
return;
transformDirty = 1;
QMetaObject::invokeMethod(this, "updateTransform", Qt::QueuedConnection);
}
void QMxTopLevelItemPrivate::updateTransform()
{
Q_ASSERT(targetItem);
Q_Q(QMxTopLevelItem);
q->setTransform(targetItem->itemTransform(q->parentItem()));
updateWidthFromTarget();
transformDirty = 0;
}
void QMxTopLevelItemPrivate::updateOpacity()
{
Q_ASSERT(targetItem);
Q_Q(QMxTopLevelItem);
q->setOpacity(targetItem->effectiveOpacity());
}
void QMxTopLevelItemPrivate::updateVisible()
{
Q_ASSERT(targetItem);
Q_Q(QMxTopLevelItem);
q->setVisible(targetItem->isVisibleTo(q->parentItem()));
}
void QMxTopLevelItemPrivate::updateParent()
{
Q_ASSERT(targetItem);
clearDependencyList();
initDependencyList();
}
void QMxTopLevelItemPrivate::updateWidthFromTarget()
{
Q_ASSERT(targetItem);
Q_Q(QMxTopLevelItem);
// Reset position and size to those of the targetItem
qreal newX = 0;
qreal newWidth = targetItem->width();
if (!keepInside) {
q->setX(newX);
q->setWidth(newWidth);
return;
}
const QTransform screenToParentTransform = q->parentItem()->sceneTransform().inverted();
const QTransform itemToParentTransform = q->QGraphicsItem::transform();
if (screenToParentTransform.isRotating() || itemToParentTransform.isRotating()) {
qWarning() << "QMxTopLevelItem: KeepInside feature is not supported together with rotation transforms";
q->setX(newX);
q->setWidth(newWidth);
return;
}
// We use a compromise solution here. The real deal is that we have a scene with items
// and possibly one or more views to that scene. We don't know exactly where these
// views are, but we need a reference to constrain the items.
// So we assume from current "qml runtime" implementation that usually the scene
// has only one view and that view has the size of the root-item in the scene.
const qreal screenWidth = q->parentItem()->width();
// Now we map to _root item coordinates_ the following info:
// 1) The edges of the "screen".
// 2) The edges of our transformed item, ie. the place where our targetItem is.
// 3) The respective widths
const qreal leftScreenEdgeAtParent = screenToParentTransform.map(QPointF(0, 0)).x();
const qreal rightScreenEdgeAtParent = screenToParentTransform.map(QPointF(screenWidth, 0)).x();
const qreal leftItemEdgeAtParent = itemToParentTransform.map(QPointF(0, 0)).x();
const qreal rightItemEdgeAtParent = itemToParentTransform.map(QPointF(newWidth, 0)).x();
const qreal screenWidthAtParent = rightScreenEdgeAtParent - leftScreenEdgeAtParent;
const qreal itemWidthAtParent = rightItemEdgeAtParent - leftItemEdgeAtParent;
// Now with all sizes in the same coordinate system we can apply offsets to
// our item's width and/or position to keep it inside the screen.
if (itemWidthAtParent > screenWidthAtParent) {
// Is the item too large?
newWidth *= screenWidthAtParent / itemWidthAtParent;
newX = leftScreenEdgeAtParent - leftItemEdgeAtParent;
} else if (leftScreenEdgeAtParent > leftItemEdgeAtParent) {
// Does item go beyond left edge ?
newX = leftScreenEdgeAtParent - leftItemEdgeAtParent;
} else if (rightItemEdgeAtParent > rightScreenEdgeAtParent) {
// Does item go beyond right edge ?
newX = rightScreenEdgeAtParent - rightItemEdgeAtParent;
}
q->setX(newX);
q->setWidth(newWidth);
}
void QMxTopLevelItemPrivate::updateHeightFromTarget()
{
Q_ASSERT(targetItem);
Q_Q(QMxTopLevelItem);
q->setHeight(targetItem->height());
}
void QMxTopLevelItemPrivate::setZFromSiblings()
{
Q_Q(QMxTopLevelItem);
int maxZ = 0;
const QList<QGraphicsItem *> siblings = q->parentItem()->childItems();
for (int i = siblings.count() - 1; i >= 0; --i) {
// Skip other topLevelItems
QGraphicsObject *obj = siblings[i]->toGraphicsObject();
if (qobject_cast<QMxTopLevelItem *>(obj))
continue;
if (siblings[i]->zValue() > maxZ)
maxZ = siblings[i]->zValue();
}
q->setZValue(maxZ + 1);
}
QMxTopLevelItem::QMxTopLevelItem(QDeclarativeItem *parent) :
QDeclarativeItem(parent), d_ptr(new QMxTopLevelItemPrivate)
{
d_ptr->q_ptr = this;
}
QMxTopLevelItem::QMxTopLevelItem(QMxTopLevelItemPrivate &dd, QDeclarativeItem *parent) :
QDeclarativeItem(parent), d_ptr(&dd)
{
d_ptr->q_ptr = this;
}
QMxTopLevelItem::~QMxTopLevelItem()
{
}
bool QMxTopLevelItem::keepInside() const
{
Q_D(const QMxTopLevelItem);
return d->keepInside;
}
void QMxTopLevelItem::setKeepInside(bool keepInside)
{
Q_D(QMxTopLevelItem);
if (keepInside == d->keepInside)
return;
d->keepInside = keepInside;
if (d->targetItem)
d->updateWidthFromTarget();
emit keepInsideChanged(keepInside);
}
QVariant QMxTopLevelItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
Q_D(QMxTopLevelItem);
if (d->targetItem == 0) {
// The original parent of this item (declared in QML) will be our
// 'target' item, ie, the item which size and position we will follow.
// ### To find that parent, we could listen to ItemParentChange but that
// does not work due to the fact QDeclarativeItem::data adds children
// w/o trigerring such event. (QGraphicsItem::get(child)->setParentItemHelper())
// Our workarround is to assume that the parent is set before the item is
// added to the scene, so we listen for the latter and get the info we need.
if (change == ItemSceneHasChanged)
d->targetItem = parentItem();
// Let the changes be finished before we start initDependencyList
QMetaObject::invokeMethod(d, "initDependencyList", Qt::QueuedConnection);
}
return QDeclarativeItem::itemChange(change, value);
}
| 35.201923
| 111
| 0.688792
|
qtmediahub
|
98c9dd552d306a0b0642eff4e09097777e3a0f7e
| 1,729
|
hpp
|
C++
|
include/Utilities/MoveList.hpp
|
NicolasAlmerge/chess_game
|
5f10d911cea40ac8d09cf418bdc14facaa1ecd4e
|
[
"MIT"
] | 1
|
2022-02-05T10:38:48.000Z
|
2022-02-05T10:38:48.000Z
|
include/Utilities/MoveList.hpp
|
NicolasAlmerge/chess_game
|
5f10d911cea40ac8d09cf418bdc14facaa1ecd4e
|
[
"MIT"
] | null | null | null |
include/Utilities/MoveList.hpp
|
NicolasAlmerge/chess_game
|
5f10d911cea40ac8d09cf418bdc14facaa1ecd4e
|
[
"MIT"
] | null | null | null |
#pragma once
#include <list>
#include <iterator>
#include <SFML/Graphics.hpp>
#include "../Components/Board.hpp"
#include "Move.hpp"
#include "PieceTransition.hpp"
using namespace sf;
class MoveList
{
public:
MoveList(Board&, PieceTransition&);
list<shared_ptr<Move>>::iterator getNewIterator() { return m_moves.begin(); }
list<shared_ptr<Move>>::iterator getIterator() { return m_moveIterator; }
list<shared_ptr<Move>> getMoves() const { return m_moves; }
PieceTransition& getTransitioningPiece() const { return m_transitioningPiece; }
int getIteratorIndex() { return std::distance(m_moves.begin(), m_moveIterator); }
int getMoveListSize() const { return m_moves.size(); }
void highlightLastMove(RenderWindow&) const;
void reset() { m_moves.clear(); m_moveIterator = m_moves.begin(); };
void goToPreviousMove(bool, vector<Arrow>&);
void goToNextMove(bool, vector<Arrow>&);
void goToCurrentMove(vector<Arrow>& arrowList) { while(hasMovesAfter()) goToNextMove(false, arrowList); }
void goToInitialMove(vector<Arrow>& arrowList) { while(hasMovesBefore()) goToPreviousMove(false, arrowList); }
void addMove(shared_ptr<Move>&, vector<Arrow>& arrowList);
bool hasMovesBefore() const { return m_moveIterator != m_moves.end(); }
bool hasMovesAfter() const { return m_moveIterator != m_moves.begin(); }
private:
list<shared_ptr<Move>> m_moves;
list<shared_ptr<Move>>::iterator m_moveIterator = m_moves.begin();
PieceTransition& m_transitioningPiece;
Board& game;
void applyMove(shared_ptr<Move>&, bool, bool, vector<Arrow>&); // called inside GameThread ?
void applyMove(bool, vector<Arrow>&);
void undoMove(bool, vector<Arrow>&);
};
| 39.295455
| 114
| 0.716021
|
NicolasAlmerge
|
98cb18f4fa2d6fe4ee76e9133bf2eecbdb51b72c
| 3,337
|
cpp
|
C++
|
MineFLTKDRM/Minesweeper.cpp
|
i-anton/MineFLTK
|
70e268b5559f982e666c63bfae808e3476c9b503
|
[
"Unlicense"
] | 1
|
2019-12-01T20:23:05.000Z
|
2019-12-01T20:23:05.000Z
|
MineFLTKDRM/Minesweeper.cpp
|
i-anton/MineFLTK
|
70e268b5559f982e666c63bfae808e3476c9b503
|
[
"Unlicense"
] | null | null | null |
MineFLTKDRM/Minesweeper.cpp
|
i-anton/MineFLTK
|
70e268b5559f982e666c63bfae808e3476c9b503
|
[
"Unlicense"
] | null | null | null |
#include "Minesweeper.h"
#include <queue>
#include "Vector2i.h"
Cell::Cell() :
marked(false),
opened(false),
neighbours(0)
{}
Minesweeper::Minesweeper() :
current_state(GameState::Playing),
unmarked_mines(0),
not_mined(TABLE_ROWS*TABLE_ROWS),
total_cells(not_mined)
{}
Minesweeper::~Minesweeper()
{}
bool Minesweeper::reveal(unsigned int x, unsigned int y)
{
if (cells[y][x].marked)
{
return true;
}
if (cells[y][x].neighbours == MINE_VALUE)
{
//fail
for (size_t y_inn = 0; y_inn < TABLE_ROWS; ++y_inn)
{
for (size_t x_inn = 0; x_inn < TABLE_ROWS; x_inn++)
{
cells[y_inn][x_inn].opened = true;
}
}
current_state = GameState::Lose;
return false;
}
reveal_wave(x, y);
if (not_mined == 0)
{
for (size_t y_inn = 0; y_inn < TABLE_ROWS; ++y_inn)
{
for (size_t x_inn = 0; x_inn < TABLE_ROWS; x_inn++)
{
cells[y_inn][x_inn].opened = true;
}
}
current_state = GameState::Win;
}
return true;
}
void Minesweeper::mark(unsigned int x, unsigned int y)
{
cells[y][x].marked = !cells[y][x].marked;
}
void Minesweeper::generate(unsigned int x, unsigned int y, unsigned int mines_count)
{
unmarked_mines = mines_count;
not_mined = total_cells - mines_count;
assert(unmarked_mines > 0);
assert(not_mined + mines_count > not_mined);
std::vector<unsigned int> v_not_mined;
v_not_mined.reserve(total_cells);
unsigned int exclude_id = x + y * TABLE_ROWS;
for (size_t i = 0; i < total_cells; ++i)
{
if (i != exclude_id)
v_not_mined.push_back(i);
}
for (size_t i = 0; i < mines_count; ++i)
{
int idx = rand() % v_not_mined.size();
int id = v_not_mined[idx];
int y = id / TABLE_ROWS;
int x = id - y * TABLE_ROWS;
assert(x >= 0);
assert(x < TABLE_ROWS);
v_not_mined.erase(v_not_mined.begin() + idx);
cells[y][x].neighbours = MINE_VALUE;
mark_neighbours(x, y);
}
}
void Minesweeper::reveal_wave(int x, int y)
{
std::queue<Vector2i> q;
q.push(Vector2i(x, y));
while (!q.empty())
{
auto vect = q.front();
q.pop();
if (cells[vect.y][vect.x].opened)
continue;
not_mined--;
cells[vect.y][vect.x].opened = true;
cells[vect.y][vect.x].marked = false;
if (cells[vect.y][vect.x].neighbours > 0)
continue;
int ymax = MIN(vect.y + 1, TABLE_ROWS - 1);
int ymin = MAX(vect.y - 1, 0);
int xmin = MAX(vect.x - 1, 0);
int xmax = MIN(vect.x + 1, TABLE_ROWS - 1);
for (int y_i = ymin; y_i <= ymax; ++y_i)
{
for (int x_i = xmin; x_i <= xmax; ++x_i)
{
auto cell = cells[y_i][x_i];
if (y_i == vect.y && x_i == vect.x) continue;
if (!cell.opened && cell.neighbours != MINE_VALUE)
q.push(Vector2i(x_i, y_i));
}
}
}
}
void Minesweeper::mark_neighbours(unsigned int x, unsigned int y)
{
mark_neighbour_one(x - 1, y - 1);
mark_neighbour_one(x, y - 1);
mark_neighbour_one(x + 1, y - 1);
mark_neighbour_one(x - 1, y);
mark_neighbour_one(x + 1, y);
mark_neighbour_one(x - 1, y + 1);
mark_neighbour_one(x, y + 1);
mark_neighbour_one(x + 1, y + 1);
}
void Minesweeper::mark_neighbour_one(unsigned int x, unsigned int y)
{
if (x < 0 || x >= TABLE_ROWS ||
y < 0 || y >= TABLE_ROWS) return;
if (cells[y][x].neighbours != MINE_VALUE)
{
cells[y][x].neighbours++;
}
}
| 23.666667
| 85
| 0.611328
|
i-anton
|
98cd6c7f68e741510ffc669f2385e806cdeb8e0c
| 83
|
cpp
|
C++
|
raygame/Condition.cpp
|
MatthewRagas/AI_Agents
|
7c513fe63956929bb55ee1f5e6fdf756422497fc
|
[
"MIT"
] | null | null | null |
raygame/Condition.cpp
|
MatthewRagas/AI_Agents
|
7c513fe63956929bb55ee1f5e6fdf756422497fc
|
[
"MIT"
] | null | null | null |
raygame/Condition.cpp
|
MatthewRagas/AI_Agents
|
7c513fe63956929bb55ee1f5e6fdf756422497fc
|
[
"MIT"
] | null | null | null |
#include "Condition.h"
Condition::Condition()
{
}
Condition::~Condition()
{
}
| 6.384615
| 23
| 0.638554
|
MatthewRagas
|
98d24ada6d0581a80f79fa313d4ebafb8cb975c0
| 1,348
|
cpp
|
C++
|
system/zombie/backup_dancer.cpp
|
dnartz/PvZ-Emulator
|
3954f36f4e0f22cee07d6a86003d3892f0938b8b
|
[
"BSD-2-Clause"
] | 1
|
2022-03-29T23:49:55.000Z
|
2022-03-29T23:49:55.000Z
|
system/zombie/backup_dancer.cpp
|
dnartz/PvZ-Emulator
|
3954f36f4e0f22cee07d6a86003d3892f0938b8b
|
[
"BSD-2-Clause"
] | 2
|
2021-03-10T18:17:07.000Z
|
2021-05-11T13:59:22.000Z
|
system/zombie/backup_dancer.cpp
|
dnartz/PvZ-Emulator
|
3954f36f4e0f22cee07d6a86003d3892f0938b8b
|
[
"BSD-2-Clause"
] | 1
|
2021-10-18T18:29:47.000Z
|
2021-10-18T18:29:47.000Z
|
#include <cmath>
#include "zombie.h"
namespace pvz_emulator::system {
using namespace pvz_emulator::object;
void zombie_backup_dancer::update(zombie& z) {
if (z.is_eating) {
return;
}
if (z.status == zombie_status::backup_spawning) {
z.dy = static_cast<float>(round(z.countdown.action * (-4/3)));
if (z.countdown.action) {
return;
}
}
auto next_status = get_status_by_clock(z);
if (next_status != z.status) {
z.status = next_status;
switch (next_status) {
case zombie_status::dancing_walking:
reanim.set(z, zombie_reanim_name::anim_walk, reanim_type::repeat, 0);
break;
case zombie_status::dancing_armrise1:
reanim.set(z, zombie_reanim_name::anim_armraise, reanim_type::repeat, 18);
z.reanim.progress = 0.60000002f;
break;
default:
reanim.set(z, zombie_reanim_name::anim_armraise, reanim_type::repeat, 18);
break;
}
}
}
void zombie_backup_dancer::init(zombie& z, unsigned int row) {
z._ground = _ground.data();
zombie_base::init(z, zombie_type::backup_dancer, row);
z.status = zombie_status::dancing_walking;
reanim.set(z, zombie_reanim_name::anim_armraise, reanim_type::repeat, 12);
set_common_fields(z);
}
}
| 24.962963
| 86
| 0.626113
|
dnartz
|
98d8e2d19b2350c7ebdbcdfa7c1a74983942dfea
| 21,492
|
cpp
|
C++
|
Info/Info/Quests/QuestsInfo.cpp
|
Teles1/LuniaAsio
|
62e404442cdb6e5523fc6e7a5b0f64a4471180ed
|
[
"MIT"
] | null | null | null |
Info/Info/Quests/QuestsInfo.cpp
|
Teles1/LuniaAsio
|
62e404442cdb6e5523fc6e7a5b0f64a4471180ed
|
[
"MIT"
] | null | null | null |
Info/Info/Quests/QuestsInfo.cpp
|
Teles1/LuniaAsio
|
62e404442cdb6e5523fc6e7a5b0f64a4471180ed
|
[
"MIT"
] | null | null | null |
#include <Info/Info/Quests/QuestsInfo.h>
namespace Lunia {
namespace XRated {
namespace Database {
namespace Info {
const int QuestInfo::Condition::NonUseGuildLevel = -1;
QuestInfo::QuestInfo()
{
}
void QuestInfo::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo");
out.Write(L"AcceptCondition", AcceptCondition);
out.Write(L"CompleteCondition", CompleteCondition);
out.Write(L"AcceptReward", AcceptReward);
out.Write(L"CompleteReward", CompleteReward);
out.Write(L"Objectives", Objectives);
out.Write(L"MaximumCompleteableCount", MaximumCompleteableCount);
out.Write(L"AcceptLocation", AcceptLocation);
out.Write(L"AcceptSourceHash", AcceptSourceHash);
out.Write(L"CompleteTarget", CompleteTarget);
out.Write(L"PlayingStage", PlayingStage);
out.Write(L"PossibleToShare", PossibleToShare);
out.Write(L"EventQuestType", EventQuestType);
out.Write(L"QuestLumpComplete", QuestLumpComplete);
//ResetWeekField
bool temp;
if ((ResetWeekField & (0x01 << DateTime::Week::Sunday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekSunday", temp);
if ((ResetWeekField & (0x01 << DateTime::Week::Monday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekMonday", temp);
if ((ResetWeekField & (0x01 << DateTime::Week::Tuesday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekTuesday", temp);
if ((ResetWeekField & (0x01 << DateTime::Week::Wednesday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekWednesday", temp);
if ((ResetWeekField & (0x01 << DateTime::Week::Thursday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekThursday", temp);
if ((ResetWeekField & (0x01 << DateTime::Week::Friday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekFriday", temp);
if ((ResetWeekField & (0x01 << DateTime::Week::Saturday))) { temp = true; }
else { temp = false; }
out.Write(L"ResetWeekSaturday", temp);
out.Write(L"Tags", Tags);
}
void QuestInfo::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo");
in.Read(L"AcceptCondition", AcceptCondition, Condition());
in.Read(L"CompleteCondition", CompleteCondition, Condition());
in.Read(L"AcceptReward", AcceptReward, Reward());
in.Read(L"CompleteReward", CompleteReward, Reward());
in.Read(L"Objectives", Objectives, std::vector<Objective>());
in.Read(L"MaximumCompleteableCount", MaximumCompleteableCount, uint32(1));
in.Read(L"AcceptLocation", AcceptLocation);
in.Read(L"AcceptSourceHash", AcceptSourceHash);
in.Read(L"CompleteTarget", CompleteTarget);
in.Read(L"PlayingStage", PlayingStage, XRated::StageLocation(0, 0));
in.Read(L"PossibleToShare", PossibleToShare, true);
in.Read(L"EventQuestType", EventQuestType, uint8(0));
in.Read(L"QuestLumpComplete", QuestLumpComplete, true);
ResetWeekField = 0;
bool temp;
in.Read(L"ResetWeekSunday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Sunday;
in.Read(L"ResetWeekMonday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Monday;
in.Read(L"ResetWeekTuesday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Tuesday;
in.Read(L"ResetWeekWednesday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Wednesday;
in.Read(L"ResetWeekThursday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Thursday;
in.Read(L"ResetWeekFriday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Friday;
in.Read(L"ResetWeekSaturday", temp, false);
if (temp == true) ResetWeekField |= 0x01 << DateTime::Week::Saturday;
if (AcceptCondition.Quests.empty() == false) {
PossibleToShare = false;
}
in.Read(L"Tags", Tags, std::vector< std::wstring >());
}
void QuestInfo::Condition::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo::Condition");
out.Write(L"ScriptOnly", ScriptOnly);
out.Write(L"Class", Class);
out.Write(L"Level", Level);
out.Write(L"MaxLevel", MaxLevel);
out.Write(L"PvpLevel", PvpLevel);
out.Write(L"PvpMaxLevel", PvpMaxLevel);
out.Write(L"WarLevel", WarLevel);
out.Write(L"WarMaxLevel", WarMaxLevel);
out.Write(L"StoredLevel", StoredLevel);
out.Write(L"StoredMaxLevel", StoredMaxLevel);
out.Write(L"RebirthCount", RebirthCount);
out.Write(L"RebirthMaxCount", RebirthMaxCount);
out.Write(L"Life", Life);
out.Write(L"Money", Money);
out.Write(L"GuildLevel", GuildLevel);
out.Write(L"Items", Items);
out.Write(L"Licenses", Licenses);
out.Write(L"Quests", Quests);
}
void QuestInfo::Condition::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo::Condition");
in.Read(L"ScriptOnly", ScriptOnly, false);
in.Read(L"Class", Class, uint16(XRated::Constants::ClassType::AnyClassType));
in.Read(L"Level", Level, uint16(0));
in.Read(L"MaxLevel", MaxLevel, uint16(99));
in.Read(L"PvpLevel", PvpLevel, uint16(0));
in.Read(L"PvpMaxLevel", PvpMaxLevel, uint16(99));
in.Read(L"WarLevel", WarLevel, uint16(1));
in.Read(L"WarMaxLevel", WarMaxLevel, uint16(99));
in.Read(L"StoredLevel", StoredLevel, uint16(1));
in.Read(L"StoredMaxLevel", StoredMaxLevel, Constants::StoredMaxLevel);
in.Read(L"RebirthCount", RebirthCount, uint16(0));
in.Read(L"RebirthMaxCount", RebirthMaxCount, Constants::RebirthMaxCount);
in.Read(L"Life", Life, uint16(0));
in.Read(L"Money", Money, uint32(0));
in.Read(L"GuildLevel", GuildLevel, NonUseGuildLevel);
in.Read(L"Items", Items, std::vector<Condition::Item>());
in.Read(L"Licenses", Licenses, std::vector<StageLicense>());
in.Read(L"Quests", Quests, std::vector< uint32>());
}
bool QuestInfo::Condition::IsGuildQuest() const
{
if (NonUseGuildLevel < GuildLevel) {
return true;
}
return false;
}
bool QuestInfo::IsShareQuest() const
{
return PossibleToShare;
}
bool QuestInfo::IsPlayingStage() const
{
if (PlayingStage.StageGroupHash != 0) {
return true;
}
return false;
}
bool QuestInfo::IsEventQuest() const
{
return EventQuestType != 0;
}
uint8 QuestInfo::GetEventType() const
{
return EventQuestType;
}
bool QuestInfo::IsQuestLumpComplete() const
{
return QuestLumpComplete;
}
void QuestInfo::Condition::Item::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo::Condition::Item");
out.Write(L"ItemHash", ItemHash);
out.Write(L"Count", Count);
}
void QuestInfo::Condition::Item::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo::Condition::Item");
in.Read(L"ItemHash", ItemHash);
in.Read(L"Count", Count);
}
void QuestInfo::Objective::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo::Objective");
out.Write(L"Type", Condition->GetType());
out.Write(L"Condition", *Condition);
}
void QuestInfo::Objective::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo::Objective");
String type;
in.Read(L"Type", type, String());
if (type.empty()) return;
/* TODO: make condition factory to create detail condition */
if (type == L"DefeatNpcs")
Condition = std::make_shared<DefeatNpcs>();
else if (type == L"ProtectNpc")
Condition = std::make_shared<ProtectNpc>();
else
throw Exception(L"invalid obective type : [{}]", type.c_str());
in.Read(L"Condition", *Condition.get());
}
uint32 QuestInfo::Objective::Condition::UpdateParameter(const String& conditionName, uint32 oldParameter, uint32 target, int count) const
{
if (conditionName != GetConditionName()) return oldParameter;
if (std::find(Targets.begin(), Targets.end(), target) == Targets.end()) return oldParameter; // nothing matched
return (oldParameter + count) >= Count ? Count : (oldParameter + count);
}
void QuestInfo::Objective::Condition::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo::Objective::Condition");
out.Write(L"Targets", Targets);
out.Write(L"Count", Count);
}
void QuestInfo::Objective::Condition::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo::Objective::Condition");
in.Read(L"Targets", Targets);
in.Read(L"Count", Count);
}
void QuestInfo::Reward::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo::Reward");
out.Write(L"Exp", Exp);
out.Write(L"WarExp", WarExp);
out.Write(L"StateBundleHash", StateBundleHash);
out.Write(L"Money", Money);
out.Write(L"Items", Items);
out.Write(L"Licenses", Licenses);
out.Write(L"SelectableItems", SelectableItems);
}
void QuestInfo::Reward::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo::Reward");
in.Read(L"Exp", Exp, uint32(0));
in.Read(L"WarExp", WarExp, uint32(0));
in.Read(L"StateBundleHash", StateBundleHash, uint32(0));
in.Read(L"Money", Money, int(0));
in.Read(L"Items", Items, std::vector<Reward::Item>());
in.Read(L"Licenses", Licenses, std::vector<StageLicense>());
in.Read(L"SelectableItems", SelectableItems, std::vector<Reward::Item>());
}
void QuestInfo::Reward::Item::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::Database::Info::QuestInfo::Reward::Item");
out.Write(L"ItemHash", ItemHash);
out.Write(L"Count", Count);
out.Write(L"Instance", Instance);
out.Write(L"TakeAway", TakeAway);
}
void QuestInfo::Reward::Item::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::Database::Info::QuestInfo::Reward::Item");
in.Read(L"ItemHash", ItemHash);
in.Read(L"Count", Count);
//in.Read(L"Instance", Instance);
in.Read(L"TakeAway", TakeAway);
}
bool QuestInfo::Condition::IsValid(const PlayerData& player) const
{
BasicCharacterInfo info;
info.Class = player.Job;
info.Level = player.BaseCharacter.Level;
info.PvpLevel = player.PvpLevel;
info.WarLevel = player.WarLevel;
info.Life = player.Life;
info.Money = player.BaseCharacter.Money;
info.StoredLevel = player.StoredLevel;
info.RebirthCount = player.RebirthCount;
return IsValid(info);
}
bool QuestInfo::Condition::IsValid(const BasicCharacterInfo& player) const
{
if (Level > player.Level || MaxLevel < player.Level)// stage level should be in the range
return false;
if (PvpLevel > player.PvpLevel || PvpMaxLevel < player.PvpLevel)// pvp level should be in the range
return false;
if (WarLevel > player.WarLevel || WarMaxLevel < player.WarLevel)// war level should be in the range
return false;
if (StoredLevel > player.StoredLevel || StoredMaxLevel < player.StoredLevel)// stored level should be in the range
return false;
if (RebirthCount > player.RebirthCount || RebirthMaxCount < player.RebirthCount)// trans count should be in the range
return false;
if (Life > player.Life)// life should be enough
return false;
if (Money > player.Money)// money should be enough
return false;
if (Class != (uint16)XRated::Constants::ClassType::AnyClassType && Class != (uint16)player.Class)// this class cannot work for this quest
return false;
return true;
}
uint8 QuestInfo::UpdateParameter(const String& conditionName, uint32 target, int count, bool isSameTeam, std::vector<uint32>& param/*out*/) const
{
int totalCount(0), failCount(0), successCount(0);
for (std::vector<Objective>::const_iterator i = Objectives.begin(); i != Objectives.end(); ++i)
{
if (i->Condition->GetType() == std::wstring(L"DefeatNpcs") && isSameTeam)
{
++totalCount;
continue;
}
uint32 val(param[totalCount] = i->Condition->UpdateParameter(conditionName, param[totalCount], target, count));
if (i->Condition->IsFailed(val))
{
if (i->Condition->MakeAllFail())
{
return Quest::State::Failed;
}
++failCount;
}
else if (i->Condition->IsSucceeded(val))
{
if (i->Condition->MakeAllSuccess())
{
return Quest::State::Succeeded;
}
++successCount;
}
++totalCount;
}
if (totalCount > failCount + successCount)
{
return Quest::State::Working;
}
else if (totalCount == successCount)
{
return Quest::State::Succeeded;
}
else if (totalCount == failCount)
{
return Quest::State::Failed;
}
LoggerInstance().Error("unalbe to decide the quest result. temporarily treated as FAIL");
return Quest::State::Failed;
}
bool QuestInfo::IsRelayQuest() const
{
if (AcceptCondition.Quests.empty() == false || Next.first != 0) return true;
return false;
}
bool QuestInfo::IsFirstQuest() const
{
if (AcceptCondition.Quests.empty()) return true;
return false;
}
bool QuestInfo::IsLastQuest() const
{
if (Next.first == 0) return true;
return false;
}
bool QuestInfo::IsRepeatQuest() const
{
return MaximumCompleteableCount > 1;
}
bool QuestInfo::IsRepeatQuest(uint32 completeCount) const
{
return MaximumCompleteableCount > completeCount;
}
bool QuestInfo::IsGuildQuest() const
{
return (AcceptCondition.IsGuildQuest() || CompleteCondition.IsGuildQuest());
}
uint32 QuestInfo::GetLeftDay(const DateTime& now, const DateTime& expiredDate) const
{
if (ResetWeekField == 0) {
return 0;
}
if (now.GetDate() <= expiredDate.GetDate()) {
return static_cast<int>(expiredDate.GetDate().GetCumulatedDay()) - static_cast<int>(now.GetDate().GetCumulatedDay()) + 1;
}
return 0;
}
bool QuestInfo::IsPossibleDate(const DateTime& now, const DateTime& ExpiredDate) const
{
if (ResetWeekField == 0) {
return true;
}
if (now.GetDate() > ExpiredDate.GetDate()) {
return true;
}
return false;
}
bool QuestInfo::IsPossibleWeek(DateTime::Week::type type) const
{
if ((0x01 << type) & ResetWeekField) {
return true;
}
return false;
}
bool QuestInfo::IsHaveResetDate() const
{
if (ResetWeekField == 0) {
return false;
}
return true;
}
DateTime QuestInfo::GetExpiredDate(const DateTime& acceptDate) const
{
if (ResetWeekField == 0) {
return DateTime(XRated::Quest::NotUsedDate);
}
const uint32 MaxWeek = DateTime::Week::Saturday + 1;
uint32 week = acceptDate.GetDate().GetDayOfWeek();
for (uint32 i = 0; i < MaxWeek; ++i)
{
week = (week + 1) % MaxWeek;
if ((0x01 << week) & ResetWeekField) {
DateTime::Date returnDate(acceptDate.GetDate());
returnDate.SetCumulatedDay(i, true, acceptDate.GetDate());
return DateTime(returnDate, acceptDate.GetTime());
//return true;
}
}
return DateTime(XRated::Quest::NotUsedDate);
}
void QuestInfo::SetResetweek(const std::wstring& value, DateTime::Week::type day)
{
bool boolValue = false;
if ((!value.compare(L"1")) || (!value.compare(L"true")) || (!value.compare(L"TRUE")))
{
boolValue = true;
}
else if ((!value.compare(L"0")) || (!value.compare(L"false")) || (!value.compare(L"FALSE")))
{
boolValue = false;
}
else
{
throw Exception(L"Invalid value in Day of Week. ");
}
uint32 temp = 0xff ^ (0x01 << day); //11011111
uint32 temp2 = ResetWeekField & temp;
if (boolValue == false) ResetWeekField = temp2;
else
{
ResetWeekField = temp2 | (0x01 << day);
}
}
void QuestInfo::SetResetweek(bool sunday, bool monday, bool tuesday, bool wednesday, bool thursday, bool friday, bool saturday)
{
uint32 temp;
temp = temp & 0x00;
if (sunday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Sunday);
}
if (monday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Monday);
}
if (tuesday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Tuesday);
}
if (wednesday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Wednesday);
}
if (thursday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Thursday);
}
if (friday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Friday);
}
if (saturday == TRUE)
{
temp = temp | (0x01 << DateTime::Week::Saturday);
}
ResetWeekField = temp;
}
bool QuestInfo::IsResetday(DateTime::Week::type day) const
{
bool temp;
if ((ResetWeekField & (0x01 << day))) { temp = true; }
else { temp = false; }
return temp;
}
void ClientQuestInfo::AcceptEvent::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::LuniaBase::Info::QuestInfo::AcceptEvent");
out.Write(L"Type", Type);
out.Write(L"Param_1", Param_1);
out.Write(L"Param_2", Param_2);
out.Write(L"Param_3", Param_3);
}
void ClientQuestInfo::AcceptEvent::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::LuniaBase::Info::QuestInfo::AcceptEvent");
in.Read(L"Type", Type);
in.Read(L"Param_1", Param_1);
in.Read(L"Param_2", Param_2);
in.Read(L"Param_3", Param_3);
}
void ClientQuestInfo::SuccessEvent::Serialize(Serializer::IStreamWriter& out) const///by kpongky( 09.07.09 ) BMS 6691
{
out.Begin(L"AllM::XRated::LuniaBase::Info::QuestInfo::SuccessEvent");
out.Write(L"Type", Type);
out.Write(L"Param_1", Param_1);
out.Write(L"Param_2", Param_2);///by kpongky( 09.07.10 ) BMS 6691
}
void ClientQuestInfo::SuccessEvent::Deserialize(Serializer::IStreamReader& in)///by kpongky( 09.07.09 ) BMS 6691
{
in.Begin(L"AllM::XRated::LuniaBase::Info::QuestInfo::SuccessEvent");
in.Read(L"Type", Type);
in.Read(L"Param_1", Param_1);
in.Read(L"Param_2", Param_2);///by kpongky( 09.07.10 ) BMS 6691
}
//////////////////////////////////////////////////////////////////////////////////////////////
// ClientQuestInfo
void ClientQuestInfo::Serialize(Serializer::IStreamWriter& out) const
{
out.Begin(L"AllM::XRated::LuniaBase::Info::QuestInfo");
out.Write(L"Type", Type);
out.Write(L"ShortComment", ShortComment);
out.Write(L"MainTopic", MainTopic);
out.Write(L"Category", Category);
out.Write(L"DisplayName", DisplayName);
out.Write(L"BeginDescription", BeginDescription);
out.Write(L"EndDescription", EndDescription);
out.Write(L"ClearConditionDescription", ClearConditionDescription);
out.Write(L"AcceptInfo", AcceptInfo);
out.Write(L"FlashPath", FlashPath);
out.Write(L"ShowNextQuest", ShowNextQuest);
out.Write(L"ShowNoticeArrow", ShowNoticeArrow);
out.Write(L"AutomaticAddQuestProgress", AutomaticAddQuestProgress);
//out.Write(L"ShowAutomaticAddQuestProgressExplain", ShowAutomaticAddQuestProgressExplain);
out.Write(L"ShowAddQuickSlotItemExplain", ShowAddQuickSlotItemExplain);
out.Write(L"QuestAcceptEvent", QuestAcceptEvent);
out.Write(L"QuestSuccessEvent", QuestSuccessEvent);
out.Write(L"Tags", Tags);
}
void ClientQuestInfo::Deserialize(Serializer::IStreamReader& in)
{
in.Begin(L"AllM::XRated::LuniaBase::Info::QuestInfo");
in.Read(L"Type", Type);
in.Read(L"ShortComment", ShortComment);
in.Read(L"MainTopic", MainTopic);
in.Read(L"Category", Category);
in.Read(L"DisplayName", DisplayName);
in.Read(L"BeginDescription", BeginDescription);
in.Read(L"EndDescription", EndDescription);
in.Read(L"ClearConditionDescription", ClearConditionDescription);
in.Read(L"AcceptInfo", AcceptInfo, std::wstring());
in.Read(L"FlashPath", FlashPath);
in.Read(L"ShowNextQuest", ShowNextQuest, false);
in.Read(L"ShowNoticeArrow", ShowNoticeArrow, false);
in.Read(L"AutomaticAddQuestProgress", AutomaticAddQuestProgress, false);
//in.Read(L"ShowAutomaticAddQuestProgressExplain", ShowAutomaticAddQuestProgressExplain, false);
in.Read(L"ShowAddQuickSlotItemExplain", ShowAddQuickSlotItemExplain, false);
in.Read(L"QuestAcceptEvent", QuestAcceptEvent, AcceptEvent());
in.Read(L"QuestSuccessEvent", QuestSuccessEvent, SuccessEvent());
in.Read(L"Tags", Tags, std::vector< std::wstring >());
}
}
}
}
}
| 35.348684
| 149
| 0.640238
|
Teles1
|
98daca3368b733539d9fab918f657c1c1c477cf7
| 1,015
|
cpp
|
C++
|
p173_Binary_Search_Tree_Iterator/p173.cpp
|
Song1996/Leetcode
|
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
|
[
"MIT"
] | null | null | null |
p173_Binary_Search_Tree_Iterator/p173.cpp
|
Song1996/Leetcode
|
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
|
[
"MIT"
] | null | null | null |
p173_Binary_Search_Tree_Iterator/p173.cpp
|
Song1996/Leetcode
|
ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <memory>
#include <vector>
#include <stack>
#include <map>
#include <string>
#include <assert.h>
#include <stdlib.h>
#include <fstream>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class BSTIterator {
public:
TreeNode* ans;
TreeNode* r;
BSTIterator(TreeNode *root) {
r = root;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(r==NULL) return false;
if(r->left==NULL) {
ans = r;
r = r->right;
return true;
}
TreeNode* par = r;
ans = par->left;
while(ans->left!=NULL) {
par = ans;
ans = ans->left;
}
par->left = ans->right;
return true;
}
/** @return the next smallest number */
int next() {
return ans->val;
}
};
int main () {
return 0;
}
| 19.150943
| 57
| 0.529064
|
Song1996
|
98dd474cc006efd11bf59e94f1eefd4b99d8da0c
| 1,818
|
cpp
|
C++
|
Graph/GetPath_BFS.cpp
|
ayushhsinghh/DSASolutions
|
f898b35484b86519f73fdca969f7d579be98804e
|
[
"MIT"
] | null | null | null |
Graph/GetPath_BFS.cpp
|
ayushhsinghh/DSASolutions
|
f898b35484b86519f73fdca969f7d579be98804e
|
[
"MIT"
] | null | null | null |
Graph/GetPath_BFS.cpp
|
ayushhsinghh/DSASolutions
|
f898b35484b86519f73fdca969f7d579be98804e
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<utility>
#include<map>
using namespace std;
vector<int> getPath(int **edges , int nVertex , int start , int end){
bool *visited = new bool[nVertex];
for(int i = 0 ; i < nVertex ; i++){
visited[i] = false;
}
map<int , int> mpp;
queue<int> q;
bool found = false;
vector<int> ans;
q.push(start);
while(q.size() != 0){
int front = q.front();
if(front == end){
found = true;
break;
}
visited[front] = true;
q.pop();
for(int i = 0 ; i<nVertex ; i++){
if(i==0){
continue;
}
if(visited[i]){
continue;
}
if(edges[i][front] == 1){
q.push(i);
mpp[i] = front;
}
}
}
if(found){
ans.push_back(end);
while(end != start){
ans.push_back(mpp[end]);
end = mpp[end];
}
}
return ans;
}
int main(){
int nVertex , nEdge;
cout<<"Enter no of Vertex ";
cin>>nVertex;
cout<< "Enter no of Edge ";
cin>>nEdge;
int **edges = new int*[nVertex];
for(int i = 0 ; i < nVertex ; i++){
edges[i] = new int[nVertex];
for(int j = 0 ; j<nVertex ;++j){
edges[i][j] = 0;
}
}
for(int i = 0 ; i < nEdge ; i++){
int fVertex , sVertex;
cout<<"Enter"<<i<<"th Edge ";
cin>>fVertex>>sVertex;
edges[fVertex][sVertex] = 1;
edges[sVertex][fVertex] = 1;
}
int start = 2;
int end = 5;
vector<int> ans = getPath(edges , nVertex , start , end);
if(ans.size() == 0) cout<<"No Path";
for(int it: ans){
cout<<it<<" ";
}
return 0;
}
| 20.659091
| 69
| 0.459296
|
ayushhsinghh
|
98e43dc5cec0add6ee5418aa39dc5042224c1779
| 871
|
hpp
|
C++
|
test/mock/core/consensus/grandpa/chain_mock.hpp
|
FlorianFranzen/kagome
|
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
|
[
"Apache-2.0"
] | null | null | null |
test/mock/core/consensus/grandpa/chain_mock.hpp
|
FlorianFranzen/kagome
|
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
|
[
"Apache-2.0"
] | null | null | null |
test/mock/core/consensus/grandpa/chain_mock.hpp
|
FlorianFranzen/kagome
|
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef KAGOME_TEST_MOCK_CORE_CONSENSUS_GRANDPA_CHAIN_MOCK_HPP
#define KAGOME_TEST_MOCK_CORE_CONSENSUS_GRANDPA_CHAIN_MOCK_HPP
#include <gmock/gmock.h>
#include "consensus/grandpa/chain.hpp"
namespace kagome::consensus::grandpa {
struct ChainMock : public Chain {
~ChainMock() override = default;
MOCK_CONST_METHOD2(getAncestry,
outcome::result<std::vector<primitives::BlockHash>>(
const primitives::BlockHash &base,
const BlockHash &block));
MOCK_CONST_METHOD1(bestChainContaining,
outcome::result<BlockInfo>(const BlockHash &base));
};
} // namespace kagome::consensus::grandpa
#endif // KAGOME_TEST_MOCK_CORE_CONSENSUS_GRANDPA_CHAIN_MOCK_HPP
| 30.034483
| 75
| 0.692308
|
FlorianFranzen
|
98e486358337d37f335709045df2b528399ecccc
| 3,511
|
hpp
|
C++
|
sdk/cpp/core/src/netconf_provider.hpp
|
YDK-Solutions/ydk
|
7ab961284cdc82de8828e53fa4870d3204d7730e
|
[
"ECL-2.0",
"Apache-2.0"
] | 125
|
2016-03-15T17:04:13.000Z
|
2022-03-22T02:46:17.000Z
|
sdk/cpp/core/src/netconf_provider.hpp
|
YDK-Solutions/ydk
|
7ab961284cdc82de8828e53fa4870d3204d7730e
|
[
"ECL-2.0",
"Apache-2.0"
] | 818
|
2016-03-17T17:06:00.000Z
|
2022-03-28T03:56:17.000Z
|
sdk/cpp/core/src/netconf_provider.hpp
|
YDK-Solutions/ydk
|
7ab961284cdc82de8828e53fa4870d3204d7730e
|
[
"ECL-2.0",
"Apache-2.0"
] | 93
|
2016-03-15T19:18:55.000Z
|
2022-02-24T13:55:07.000Z
|
/* ----------------------------------------------------------------
Copyright 2016 Cisco Systems
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 _NETCONF_PROVIDER_H_
#define _NETCONF_PROVIDER_H_
#include <memory>
#include <string>
#include "netconf_client.hpp"
#include "path_api.hpp"
#include "service_provider.hpp"
namespace ydk {
class NetconfServiceProvider : public ServiceProvider {
public:
NetconfServiceProvider(path::Repository & repo,
const std::string& address,
const std::string& username,
const std::string& password,
int port = 830,
const std::string& protocol = "ssh",
bool on_demand = true,
int timeout = -1);
NetconfServiceProvider(const std::string& address,
const std::string& username,
const std::string& password,
int port = 830,
const std::string& protocol = "ssh",
bool on_demand = true,
bool common_cache = false,
int timeout = -1);
NetconfServiceProvider(path::Repository& repo,
const std::string& address,
const std::string& username,
const std::string& private_key_path,
const std::string& public_key_path,
int port = 830,
bool on_demand = true,
int timeout = -1);
NetconfServiceProvider(const std::string& address,
const std::string& username,
const std::string& private_key_path,
const std::string& public_key_path,
int port = 830,
bool on_demand = true,
bool common_cache = false,
int timeout = -1);
~NetconfServiceProvider();
EncodingFormat get_encoding() const;
const path::Session& get_session() const;
std::vector<std::string> get_capabilities() const;
inline const std::string get_provider_type() const {
return "NetconfServiceProvider";
}
std::shared_ptr<Entity> execute_operation(const std::string & operation, Entity & entity, std::map<std::string,std::string> params);
std::vector<std::shared_ptr<Entity>> execute_operation(const std::string & operation, std::vector<Entity*> entity_list, std::map<std::string,std::string> params);
private:
const path::NetconfSession session;
};
}
#endif /*_NETCONF_PROVIDER_H_*/
| 42.817073
| 170
| 0.522928
|
YDK-Solutions
|
98e6387f57e12ab0a0cd9d3adaba20e2137c9c5a
| 297
|
cpp
|
C++
|
src/Support/ContextTransition.cpp
|
G-o-T-o/CircuitOS
|
383bd4794b4f3f55f8249d602f1f7bd10b336a84
|
[
"MIT"
] | 14
|
2020-03-22T13:21:46.000Z
|
2021-12-10T04:28:44.000Z
|
src/Support/ContextTransition.cpp
|
G-o-T-o/CircuitOS
|
383bd4794b4f3f55f8249d602f1f7bd10b336a84
|
[
"MIT"
] | 5
|
2020-04-14T19:35:16.000Z
|
2021-08-30T03:02:36.000Z
|
src/Support/ContextTransition.cpp
|
G-o-T-o/CircuitOS
|
383bd4794b4f3f55f8249d602f1f7bd10b336a84
|
[
"MIT"
] | 5
|
2021-02-10T09:02:43.000Z
|
2021-08-24T04:56:04.000Z
|
#include "../../Setup.hpp"
#include "ContextTransition.h"
bool ContextTransition::transitionRunning = false;
bool ContextTransition::isRunning(){
return transitionRunning;
}
#ifdef CIRCUITOS_LOWRAM
#include "LowRamContextTransition.impl"
#else
#include "StandardContextTransition.impl"
#endif
| 22.846154
| 50
| 0.794613
|
G-o-T-o
|
98e691599abd777f53fa861969a4e6c64dec5037
| 790
|
cpp
|
C++
|
src/cxx11-detection-idiom.cpp
|
mariokonrad/cppug-sfinae-concepts
|
aeb633261d15fe5f63bf36c79e30247c8db88cfc
|
[
"CC-BY-4.0"
] | null | null | null |
src/cxx11-detection-idiom.cpp
|
mariokonrad/cppug-sfinae-concepts
|
aeb633261d15fe5f63bf36c79e30247c8db88cfc
|
[
"CC-BY-4.0"
] | null | null | null |
src/cxx11-detection-idiom.cpp
|
mariokonrad/cppug-sfinae-concepts
|
aeb633261d15fe5f63bf36c79e30247c8db88cfc
|
[
"CC-BY-4.0"
] | 1
|
2019-05-29T05:08:30.000Z
|
2019-05-29T05:08:30.000Z
|
#include <iostream>
#include <type_traits>
namespace cxx11_detection_idom
{
template <class T>
struct has_add
{
template <class U>
static constexpr decltype(std::declval<U>().add(int(), int()), bool()) test(int)
{ return true; }
template <class U>
static constexpr bool test(...)
{ return false; }
static constexpr bool value = test<T>(int());
};
template <class T, typename std::enable_if<has_add<T>::value, int>::type = 0>
void func(T t, int a, int b)
{ std::cout << __PRETTY_FUNCTION__ << ": " << t.add(a, b) << '\n'; }
}
struct foo { int add(int a, int b) { return a + b; } };
struct bar { int sub(int a, int b) { return a - b; } };
int main(int, char **)
{
//cxx11_detection_idom::func(bar(), 1, 2); // ERROR
cxx11_detection_idom::func(foo(), 1, 2); // OK
return 0;
}
| 22.571429
| 81
| 0.634177
|
mariokonrad
|
98eeaee5dbb9d6687efcf9789bd08c67f5654c54
| 1,058
|
hpp
|
C++
|
makepad/ChakraCore/pal/src/include/pal/event.hpp
|
makepaddev/makepad
|
25d2f18c8a7c190fd1b199762817b6514118e045
|
[
"MIT"
] | 8,664
|
2016-01-13T17:33:19.000Z
|
2019-05-06T19:55:36.000Z
|
makepad/ChakraCore/pal/src/include/pal/event.hpp
|
makepaddev/makepad
|
25d2f18c8a7c190fd1b199762817b6514118e045
|
[
"MIT"
] | 5,058
|
2016-01-13T17:57:02.000Z
|
2019-05-04T15:41:54.000Z
|
makepad/ChakraCore/pal/src/include/pal/event.hpp
|
makepaddev/makepad
|
25d2f18c8a7c190fd1b199762817b6514118e045
|
[
"MIT"
] | 1,367
|
2016-01-13T17:54:57.000Z
|
2019-04-29T18:16:27.000Z
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*++
Module Name:
event.hpp
Abstract:
Event object structure definition.
--*/
#ifndef _PAL_EVENT_H_
#define _PAL_EVENT_H_
#include "corunix.hpp"
namespace CorUnix
{
extern CObjectType otManualResetEvent;
extern CObjectType otAutoResetEvent;
PAL_ERROR
InternalCreateEvent(
CPalThread *pThread,
LPSECURITY_ATTRIBUTES lpEventAttributes,
BOOL bManualReset,
BOOL bInitialState,
LPCWSTR lpName,
HANDLE *phEvent
);
PAL_ERROR
InternalSetEvent(
CPalThread *pThread,
HANDLE hEvent,
BOOL fSetEvent
);
PAL_ERROR
InternalOpenEvent(
CPalThread *pThread,
DWORD dwDesiredAccess,
BOOL bInheritHandle,
LPCWSTR lpName,
HANDLE *phEvent
);
}
#endif //PAL_EVENT_H_
| 15.114286
| 71
| 0.646503
|
makepaddev
|
98eefbe0c57de60318f9579bd07ee5dfe66172c8
| 930
|
hpp
|
C++
|
source/quantum-script.lib/quantum-script-iterator.hpp
|
g-stefan/quantum-script
|
479c7c9bc3831ecafa79071c40fa766985130b59
|
[
"MIT",
"Unlicense"
] | null | null | null |
source/quantum-script.lib/quantum-script-iterator.hpp
|
g-stefan/quantum-script
|
479c7c9bc3831ecafa79071c40fa766985130b59
|
[
"MIT",
"Unlicense"
] | null | null | null |
source/quantum-script.lib/quantum-script-iterator.hpp
|
g-stefan/quantum-script
|
479c7c9bc3831ecafa79071c40fa766985130b59
|
[
"MIT",
"Unlicense"
] | null | null | null |
//
// Quantum Script
//
// Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com>
// Created by Grigore Stefan <g_stefan@yahoo.com>
//
// MIT License (MIT) <http://opensource.org/licenses/MIT>
//
#ifndef QUANTUM_SCRIPT_ITERATOR_HPP
#define QUANTUM_SCRIPT_ITERATOR_HPP
#ifndef QUANTUM_SCRIPT_VARIABLE_HPP
#include "quantum-script-variable.hpp"
#endif
namespace Quantum {
namespace Script {
class Iterator;
};
};
namespace XYO {
namespace ManagedMemory {
template<>
class TMemory<Quantum::Script::Iterator>:
public TMemoryPoolActive<Quantum::Script::Iterator> {};
};
};
namespace Quantum {
namespace Script {
using namespace XYO;
class Iterator :
public virtual Object {
XYO_DISALLOW_COPY_ASSIGN_MOVE(Iterator);
public:
inline Iterator() {
};
QUANTUM_SCRIPT_EXPORT virtual bool next(Variable *out);
};
};
};
#endif
| 16.909091
| 63
| 0.673118
|
g-stefan
|
98f00cbc4f5031658cec1d50210652783d5be6fc
| 10,343
|
cpp
|
C++
|
src/exactextract/test/test_raster_cell_intersection.cpp
|
dbaston/exactextractr
|
15ec58e8b40d5ea84752e51d0b914376b5122d5d
|
[
"Apache-2.0"
] | null | null | null |
src/exactextract/test/test_raster_cell_intersection.cpp
|
dbaston/exactextractr
|
15ec58e8b40d5ea84752e51d0b914376b5122d5d
|
[
"Apache-2.0"
] | null | null | null |
src/exactextract/test/test_raster_cell_intersection.cpp
|
dbaston/exactextractr
|
15ec58e8b40d5ea84752e51d0b914376b5122d5d
|
[
"Apache-2.0"
] | null | null | null |
#include <geos_c.h>
#include "catch.hpp"
#include "geos_utils.h"
#include "raster_cell_intersection.h"
using namespace exactextract;
void check_cell_intersections(const RasterCellIntersection & rci, const std::vector<std::vector<float>> & v) {
const Matrix<float>& actual = rci.overlap_areas();
Matrix<float> expected{v};
REQUIRE( expected.rows() == actual.rows() );
REQUIRE( expected.cols() == actual.cols() );
for (size_t i = 0; i < expected.rows(); i++) {
for (size_t j = 0; j < expected.cols(); j++) {
CHECK ( actual(i, j) == expected(i, j) );
}
}
}
static void init_geos() {
static bool initialized = false;
if (!initialized) {
initGEOS(nullptr, nullptr);
initialized = true;
}
}
TEST_CASE("Basic", "[raster-cell-intersection]" ) {
init_geos();
Extent ex{0, 0, 3, 3, 1, 1}; // 3x3 grid
auto g = GEOSGeom_read("POLYGON ((0.5 0.5, 2.5 0.5, 2.5 2.5, 0.5 2.5, 0.5 0.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.5, 0.25},
{0.50, 1.0, 0.50},
{0.25, 0.5, 0.25}
});
}
TEST_CASE("Diagonals", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 3, 3, 1, 1}; // 3x3 grid
auto g = GEOSGeom_read("POLYGON ((1.5 0.5, 2.5 1.5, 1.5 2.5, 0.5 1.5, 1.5 0.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.00, 0.25, 0.00},
{0.25, 1.00, 0.25},
{0.00, 0.25, 0.00},
});
}
TEST_CASE("Starting on cell boundary", "[raster-cell-intersection]") {
init_geos();
// Situation found in Canada using 0.5-degree global grid
Extent ex{0, 0, 2, 2, 1, 1}; // 2x2 grid
auto g = GEOSGeom_read("POLYGON ((1 1.5, 1.5 1.5, 1.5 0.5, 0.5 0.5, 0.5 1.5, 1 1.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.25},
{0.25, 0.25},
});
}
TEST_CASE("Bouncing off boundary", "[raster-cell-intersection]") {
init_geos();
// Situation found in Trinidad and Tobago using 0.5-degree global grid
Extent ex{0, -1, 2, 2, 1, 1}; // 3x2 grid
auto g = GEOSGeom_read("POLYGON ((0.5 1.5, 0.5 0.5, 0.5 0, 1.5 0.5, 1.5 1.5, 0.5 1.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.25},
{0.4375, 0.3125},
{0.0, 0.0},
});
}
TEST_CASE("Bouncing off boundary (2)", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 2, 2, 1, 1};
auto g = GEOSGeom_read("POLYGON ((0.5 0.5, 1.5 0.5, 1.5 1.5, 0.5 1.5, 1 1.2, 0.5 0.5))");
CHECK_NOTHROW( RasterCellIntersection(ex, g.get()) );
}
TEST_CASE("Follows grid boundary", "[raster-cell-intersection]") {
init_geos();
// Occurs on the Libya-Egypt border, for example
Extent ex{0, 0, 3, 3, 1, 1};
auto g = GEOSGeom_read("POLYGON ((0.5 0.5, 2 0.5, 2 1.5, 2 2.5, 0.5 2.5, 0.5 0.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.5, 0.0},
{0.50, 1.0, 0.0},
{0.25, 0.5, 0.0},
});
}
TEST_CASE("Starts on vertical boundary, moving up", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 4, 3, 1, 1}; // 4x3 grid
auto g = GEOSGeom_read("POLYGON ((3 0.5, 3 2.5, 0.5 2.5, 0.5 0.5, 3 0.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.5, 0.5, 0.0},
{0.50, 1.0, 1.0, 0.0},
{0.25, 0.5, 0.5, 0.0},
});
}
TEST_CASE("Starts on vertical boundary, moving down", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 4, 3, 1, 1}; // 4x3 grid
auto g = GEOSGeom_read("POLYGON ((0.5 2.5, 0.5 0.5, 3 0.5, 3 2.5, 0.5 2.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.5, 0.5, 0.0},
{0.50, 1.0, 1.0, 0.0},
{0.25, 0.5, 0.5, 0.0},
});
}
TEST_CASE("Starts on vertical boundary, moving down at rightmost extent of grid", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 3, 3, 1, 1}; // 3x3 grid
auto g = GEOSGeom_read("POLYGON ((3 2.5, 3 0.5, 0.5 0.5, 0.5 2.5, 3 2.5))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.5, 0.5},
{0.50, 1.0, 1.0},
{0.25, 0.5, 0.5},
});
}
TEST_CASE("Starts on horizontal boundary, moving right", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 3, 4, 1, 1}; // 3x4 grid
auto g = GEOSGeom_read("POLYGON ((0.5 1, 2.5 1, 2.5 3.5, 0.5 3.5, 0.5 1))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.25, 0.5, 0.25},
{0.50, 1.0, 0.50},
{0.50, 1.0, 0.50},
{0.00, 0.0, 0.00},
});
}
TEST_CASE("Starts on horizontal boundary, moving left", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 3, 4, 1, 1}; // 3x4 grid
auto g = GEOSGeom_read("POLYGON ((2.5 3, 0.5 3, 0.5 3.5, 0.25 3.5, 0.25 0.5, 2.5 0.5, 2.5 3))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.125, 0.00, 0.00},
{0.750, 1.00, 0.50},
{0.750, 1.00, 0.50},
{0.375, 0.50, 0.25},
});
}
TEST_CASE("Regression test - Fiji", "[raster-cell-intersection]") {
init_geos();
// Just make sure this polygon doesn't throw an exception. It caused some problems where the
// rightmost edge was interpreted to be exactly on a cell wall.
Extent ex{-180.5, -90.5, 180.5, 90.5, 0.5, 0.5};
auto g = GEOSGeom_read("MULTIPOLYGON (((178.3736000000001 -17.33992000000002, 178.71806000000007 -17.62845999999996, 178.5527099999999 -18.150590000000008, 177.93266000000008 -18.287990000000036, 177.38145999999992 -18.164319999999975, 177.28504000000007 -17.72464999999997, 177.67087 -17.381139999999974, 178.12557000000007 -17.50480999999995, 178.3736000000001 -17.33992000000002)), ((179.36414266196417 -16.801354076946836, 178.7250593629972 -17.012041674368007, 178.5968385951172 -16.63915000000003, 179.0966093629972 -16.43398427754741, 179.4135093629972 -16.379054277547382, 180.00000000000003 -16.06713266364241, 180.00000000000003 -16.555216566639146, 179.36414266196417 -16.801354076946836)), ((-179.91736938476527 -16.501783135649347, -179.99999999999997 -16.555216566639146, -179.99999999999997 -16.06713266364241, -179.79332010904858 -16.020882256741217, -179.91736938476527 -16.501783135649347)))");
CHECK_NOTHROW( RasterCellIntersection(ex, g.get()) );
}
TEST_CASE("Small polygon", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 10, 10, 10, 10}; // Single cell
auto g = GEOSGeom_read("POLYGON ((3 3, 4 3, 4 4, 3 4, 3 3))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {{0.01}});
}
TEST_CASE("Fill handled correctly", "[raster-cell-intersection]") {
init_geos();
Extent ex{0, 0, 3, 5, 1, 1}; // 3x5 grid
auto g = GEOSGeom_read("POLYGON ((0.5 0.2, 2.2 0.2, 2.2 0.4, 0.7 0.4, 0.7 2.2, 2.2 2.2, 2.2 0.6, 2.4 0.6, 2.4 4.8, 0.5 4.8, 0.5 0.2))");
RasterCellIntersection rci{ex, g.get()};
check_cell_intersections(rci, {
{0.40, 0.80, 0.32},
{0.50, 1.00, 0.40},
{0.44, 0.80, 0.36},
{0.20, 0.00, 0.20},
{0.22, 0.20, 0.12},
});
}
TEST_CASE("Result indexing is correct", "[raster-cell-intersection]") {
init_geos();
Extent ex{-20, -15, 40, 30, 0.5, 1};
auto g = GEOSGeom_read("POLYGON ((0.25 0.20, 2.75 0.20, 2.75 4.5, 0.25 4.5, 0.25 0.20))");
RasterCellIntersection rci{ex, g.get()};
size_t n_rows = rci.max_row() - rci.min_row();
size_t n_cols = rci.max_col() - rci.min_col();
CHECK( n_rows == 5 );
CHECK( n_cols == 6 );
CHECK( rci.min_col() == 40 );
CHECK( rci.max_col() == 46 );
CHECK( rci.min_row() == 25 );
CHECK( rci.max_row() == 30 );
Matrix<float> actual{n_rows, n_cols};
for (size_t i = rci.min_row(); i < rci.max_row(); i++) {
for (size_t j = rci.min_col(); j < rci.max_col(); j++) {
actual(i - rci.min_row(), j - rci.min_col()) = rci.get(i, j);
}
}
Matrix<float> expected{{
{0.25, 0.50, 0.50, 0.50, 0.50, 0.25},
{0.50, 1.00, 1.00, 1.00, 1.00, 0.50},
{0.50, 1.00, 1.00, 1.00, 1.00, 0.50},
{0.50, 1.00, 1.00, 1.00, 1.00, 0.50},
{0.40, 0.80, 0.80, 0.80, 0.80, 0.40}
}};
CHECK( actual == expected );
}
TEST_CASE("Sensible error when geometry extent is larger than raster", "[raster-cell-intersection]") {
init_geos();
Extent ex{-180, -90, 180, 90, 0.5, 0.5};
auto g = GEOSGeom_read("POLYGON ((-179 0, 180.000000004 0, 180 1, -179 0))");
CHECK_THROWS_WITH( RasterCellIntersection(ex, g.get()),
Catch::Matchers::Contains("geometry extent larger than the raster") );
}
TEST_CASE("Sensible error when hole is outside of shell", "[raster-cell-intersection]") {
init_geos();
Extent ex{-180, -90, 180, 90, 0.5, 0.5};
auto g = GEOSGeom_read("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (9 9, 9 9.1, 10.6 9.1, 9 9))");
CHECK_THROWS_WITH( RasterCellIntersection(ex, g.get()),
Catch::Matchers::Contains("hole outside of its shell") );
}
TEST_CASE("Robustness regression test #1", "[raster-cell-intersection]") {
// This test exercises some challenging behavior where a polygon follows
// ymin, but the grid resolution is such that ymin < (ymax - ny*dy)
init_geos();
Extent ex{-180, -90, 180, 90, 1.0/6, 1.0/6};
auto g = GEOSGeom_read(
#include "resources/antarctica.wkt"
);
CHECK_NOTHROW( RasterCellIntersection(ex, g.get()) );
}
TEST_CASE("Robustness regression test #2", "[raster-cell-intersection]") {
// This test exercises some challenging behavior where a polygon follows
// xmax, but the grid resolution is such that xmax < (xmin + nx*dx)
init_geos();
Extent ex{-180, -90, 180, 90, 1.0/6, 1.0/6};
auto g = GEOSGeom_read(
#include "resources/russia.wkt"
);
CHECK_NOTHROW( RasterCellIntersection(ex, g.get()) );
}
| 30.510324
| 916
| 0.580102
|
dbaston
|
98f371c857935fc189e6b85e571ea24df47ec046
| 9,706
|
cpp
|
C++
|
src/Library/Core/FileSystem/Path.cpp
|
cowlicks/library-core
|
9a872ab7aa6bc4aba22734705b72dc22ea35ee77
|
[
"Apache-2.0"
] | null | null | null |
src/Library/Core/FileSystem/Path.cpp
|
cowlicks/library-core
|
9a872ab7aa6bc4aba22734705b72dc22ea35ee77
|
[
"Apache-2.0"
] | null | null | null |
src/Library/Core/FileSystem/Path.cpp
|
cowlicks/library-core
|
9a872ab7aa6bc4aba22734705b72dc22ea35ee77
|
[
"Apache-2.0"
] | 1
|
2020-12-01T14:50:50.000Z
|
2020-12-01T14:50:50.000Z
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Library ▸ Core
/// @file Library/Core/FileSystem/Path.cpp
/// @author Lucas Brémond <lucas@loftorbital.com>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <Library/Core/FileSystem/Path.hpp>
#include <Library/Core/Error.hpp>
#include <Library/Core/Utilities.hpp>
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace library
{
namespace core
{
namespace fs
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Path::Impl
{
public:
boost::filesystem::path path_ ;
Impl ( const boost::filesystem::path& aPath ) ;
} ;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Path::Impl::Impl ( const boost::filesystem::path& aPath )
: path_(aPath)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Path::Path ( const Path& aPath )
: implUPtr_((aPath.implUPtr_ != nullptr) ? std::make_unique<Path::Impl>(*aPath.implUPtr_) : nullptr)
{
}
Path::~Path ( )
{
}
Path& Path::operator = ( const Path& aPath )
{
if (this != &aPath)
{
implUPtr_.reset((aPath.implUPtr_ != nullptr) ? new Path::Impl(*aPath.implUPtr_) : nullptr) ;
}
return *this ;
}
bool Path::operator == ( const Path& aPath ) const
{
if ((!this->isDefined()) || (!aPath.isDefined()))
{
return false ;
}
return implUPtr_->path_ == aPath.implUPtr_->path_ ;
}
bool Path::operator != ( const Path& aPath ) const
{
return !((*this) == aPath) ;
}
Path Path::operator + ( const Path& aPath ) const
{
Path path = { *this } ;
path += aPath ;
return path ;
}
Path& Path::operator += ( const Path& aPath )
{
if (!aPath.isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
try
{
implUPtr_->path_ /= aPath.implUPtr_->path_ ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return *this ;
}
std::ostream& operator << ( std::ostream& anOutputStream,
const Path& aPath )
{
library::core::utils::Print::Header(anOutputStream, "Path") ;
library::core::utils::Print::Line(anOutputStream) << (aPath.isDefined() ? aPath.toString() : "Undefined") ;
library::core::utils::Print::Footer(anOutputStream) ;
return anOutputStream ;
}
bool Path::isDefined ( ) const
{
return implUPtr_ != nullptr ;
}
bool Path::isAbsolute ( ) const
{
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
return implUPtr_->path_.is_absolute() ;
}
bool Path::isRelative ( ) const
{
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
return implUPtr_->path_.is_relative() ;
}
Path Path::getParentPath ( ) const
{
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
Path path ;
try
{
path.implUPtr_ = std::make_unique<Path::Impl>(implUPtr_->path_.parent_path()) ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return path ;
}
String Path::getLastElement ( ) const
{
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
try
{
return implUPtr_->path_.filename().string() ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return String::Empty() ;
}
Path Path::getNormalizedPath ( ) const
{
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
Path path ;
try
{
path.implUPtr_ = std::make_unique<Path::Impl>(boost::filesystem::weakly_canonical(implUPtr_->path_)) ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return path ;
}
Path Path::getAbsolutePath ( const Path& aBasePath ) const
{
if (!aBasePath.isDefined())
{
throw library::core::error::runtime::Undefined("Base path") ;
}
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
Path path ;
try
{
path.implUPtr_ = std::make_unique<Path::Impl>(boost::filesystem::absolute(implUPtr_->path_, aBasePath.implUPtr_->path_)) ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return path ;
}
// Path Path::getRelativePathTo ( const Path& aReferencePath ) const
// {
// }
String Path::toString ( ) const
{
if (!this->isDefined())
{
throw library::core::error::runtime::Undefined("Path") ;
}
try
{
return implUPtr_->path_.string() ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return String::Empty() ;
}
Path Path::Undefined ( )
{
return {} ;
}
Path Path::Root ( )
{
Path path ;
path.implUPtr_ = std::make_unique<Path::Impl>("/") ;
return path ;
}
Path Path::Current ( )
{
Path path ;
try
{
path.implUPtr_ = std::make_unique<Path::Impl>(boost::filesystem::current_path()) ;
}
catch (const boost::filesystem::filesystem_error& e)
{
throw library::core::error::RuntimeError(e.what()) ;
}
return path ;
}
Path Path::Parse ( const String& aString )
{
if (aString.isEmpty())
{
throw library::core::error::runtime::Undefined("String") ;
}
Path path ;
path.implUPtr_ = std::make_unique<Path::Impl>(aString) ;
return path ;
}
// Path Path::Strings ( const std::initializer_list<types::String> aStringList )
// {
// }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Path::Path ( )
: implUPtr_(nullptr)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 26.961111
| 170
| 0.360396
|
cowlicks
|
98f6b6d9e5042144e5430e5364c8dae30a9ce48c
| 827
|
hpp
|
C++
|
alignment/datastructures/anchoring/AnchorParameters.hpp
|
ggraham/blasr_libcpp
|
4abef36585bbb677ebc4acb9d4e44e82331d59f7
|
[
"RSA-MD"
] | 4
|
2015-07-03T11:59:54.000Z
|
2018-05-17T00:03:22.000Z
|
alignment/datastructures/anchoring/AnchorParameters.hpp
|
ggraham/blasr_libcpp
|
4abef36585bbb677ebc4acb9d4e44e82331d59f7
|
[
"RSA-MD"
] | 79
|
2015-06-29T18:07:21.000Z
|
2018-09-19T13:38:39.000Z
|
alignment/datastructures/anchoring/AnchorParameters.hpp
|
ggraham/blasr_libcpp
|
4abef36585bbb677ebc4acb9d4e44e82331d59f7
|
[
"RSA-MD"
] | 19
|
2015-06-23T08:43:29.000Z
|
2021-04-28T18:37:47.000Z
|
#ifndef _BLASR_ANCHOR_PARAMETERS_HPP_
#define _BLASR_ANCHOR_PARAMETERS_HPP_
#include <fstream>
#include <iostream>
#include <pbdata/DNASequence.hpp>
#include <pbdata/qvs/QualityValue.hpp>
class AnchorParameters
{
public:
QualityValue branchQualityThreshold;
DNALength minMatchLength;
int maxMatchScore;
int expand;
int contextAlignLength;
bool useLookupTable;
int numBranches;
UInt maxAnchorsPerPosition;
int advanceExactMatches;
int maxLCPLength;
bool stopMappingOnceUnique;
int verbosity;
bool removeEncompassedMatches;
std::ostream *lcpBoundsOutPtr;
int branchExpand;
AnchorParameters();
AnchorParameters &Assign(const AnchorParameters &rhs);
AnchorParameters &operator=(const AnchorParameters &rhs);
};
#endif // _BLASR_ANCHOR_PARAMETERS_HPP_
| 22.351351
| 61
| 0.76179
|
ggraham
|
98f8a704a0b525a01c23915877bac44396e8be00
| 2,523
|
cpp
|
C++
|
src/MentalMux8.cpp
|
CommanderAsdasd/asdasd_modules
|
b3270044623430f3a5e5565327b89296bcbfd181
|
[
"BSD-3-Clause"
] | null | null | null |
src/MentalMux8.cpp
|
CommanderAsdasd/asdasd_modules
|
b3270044623430f3a5e5565327b89296bcbfd181
|
[
"BSD-3-Clause"
] | null | null | null |
src/MentalMux8.cpp
|
CommanderAsdasd/asdasd_modules
|
b3270044623430f3a5e5565327b89296bcbfd181
|
[
"BSD-3-Clause"
] | null | null | null |
///////////////////////////////////////////////////
//
// 8 to 1 Mux with Binary Decoder selector VCV Module
//
// Strum 2017
//
///////////////////////////////////////////////////
#include "mental.hpp"
struct MentalMux8 : Module {
enum ParamIds {
NUM_PARAMS
};
enum InputIds {
INPUT_1,
INPUT_2,
INPUT_4,
SIG_INPUT,
NUM_INPUTS = SIG_INPUT + 8
};
enum OutputIds {
OUTPUT,
NUM_OUTPUTS
};
enum LightIds {
INPUT_LEDS,
NUM_LIGHTS = INPUT_LEDS + 8
};
float in_1 = 0.0;
float in_2 = 0.0;
float in_4 = 0.0;
int one, two, four, decoded;
MentalMux8() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) {}
void step() override;
};
void MentalMux8::step()
{
for ( int i = 0 ; i < 8 ; i ++)
{
lights[INPUT_LEDS + i].value = 0.0;
}
outputs[OUTPUT].value = 0.0;
in_1 = inputs[INPUT_1].value;
in_2 = inputs[INPUT_2].value;
in_4 = inputs[INPUT_4].value;
if (in_1 > 0.0 )
{
one = 1;
} else
{
one = 0;
}
if (in_2 > 0.0)
{
two = 2;
} else
{
two = 0;
}
if (in_4 > 0.0)
{
four = 4;
} else
{
four = 0;
}
decoded = one + two + four;
outputs[OUTPUT].value = inputs[SIG_INPUT + decoded].value;
lights[INPUT_LEDS + decoded].value = 1.0;
}
//////////////////////////////////////////////////////////////
struct MentalMux8Widget : ModuleWidget {
MentalMux8Widget(MentalMux8 *module);
};
MentalMux8Widget::MentalMux8Widget(MentalMux8 *module) : ModuleWidget(module)
{
setPanel(SVG::load(assetPlugin(plugin, "res/MentalMux8.svg")));
int spacing = 25;
int top_space = 15;
addInput(Port::create<GateInPort>(Vec(3, top_space), Port::INPUT, module, MentalMux8::INPUT_1));
addInput(Port::create<GateInPort>(Vec(3, top_space + spacing), Port::INPUT, module, MentalMux8::INPUT_2));
addInput(Port::create<GateInPort>(Vec(3, top_space + spacing * 2), Port::INPUT, module, MentalMux8::INPUT_4));
for (int i = 0; i < 8 ; i++)
{
addInput(Port::create<InPort>(Vec(3, top_space + spacing * i + 100), Port::INPUT, module, MentalMux8::SIG_INPUT + i));
addChild(ModuleLightWidget::create<MedLight<BlueLED>>(Vec(33, top_space + spacing * i + 8 + 100), module, MentalMux8::INPUT_LEDS + i));
}
addOutput(Port::create<OutPort>(Vec(30, top_space + spacing), Port::OUTPUT, module, MentalMux8::OUTPUT));
}
Model *modelMentalMux8 = Model::create<MentalMux8, MentalMux8Widget>("mental", "MentalMux8", "8 Way Multiplexer", UTILITY_TAG);
| 23.579439
| 139
| 0.584621
|
CommanderAsdasd
|
98fa4ff52209303b062549ba0ae526fc9d2dcbe8
| 7,261
|
cpp
|
C++
|
Test/PikeVM.cpp
|
AirGuanZ/Utils
|
6ededbd838697682430a2c0746bfd3b36ff14a5b
|
[
"MIT"
] | 10
|
2018-10-30T14:19:57.000Z
|
2021-12-06T07:46:59.000Z
|
Test/PikeVM.cpp
|
AirGuanZ/Utils
|
6ededbd838697682430a2c0746bfd3b36ff14a5b
|
[
"MIT"
] | null | null | null |
Test/PikeVM.cpp
|
AirGuanZ/Utils
|
6ededbd838697682430a2c0746bfd3b36ff14a5b
|
[
"MIT"
] | 3
|
2019-04-24T13:42:02.000Z
|
2021-06-28T08:17:28.000Z
|
#include <AGZUtils/Utils/String.h>
#include "Catch.hpp"
using namespace AGZ;
void P8(const WStr &str)
{
(void)StrImpl::PikeVM::Parser<WUTF>().Parse(str);
}
void Gen(const WStr &str)
{
size_t slotCount;
(void)StrImpl::PikeVM::Backend<WUTF>().Generate(
StrImpl::PikeVM::Parser<WUTF>().Parse(str), &slotCount);
}
TEST_CASE("VMEngEx")
{
SECTION("Parser")
{
REQUIRE_NOTHROW(P8("minecraft"));
REQUIRE_NOTHROW(P8("a|b|c|d|e"));
REQUIRE_NOTHROW(P8("[abc]|[a-zA-Zdef0-9.\\\\..\\\\][m-x]"));
REQUIRE_NOTHROW(P8("[abcA-Z]+*??*+"));
REQUIRE_NOTHROW(P8("^abcde(abc$|[def]$)"));
REQUIRE_NOTHROW(P8("abc&def&ghi"));
REQUIRE_NOTHROW(P8("abc.\\.def.ghi\\..\\\\\\.."));
REQUIRE_NOTHROW(P8("(abcdef)[xyz]{ 10 }"));
REQUIRE_NOTHROW(P8("(abcdef)[xyz]{3, 18}"));
REQUIRE_NOTHROW(P8("(abcdef)[xyz]{0, 18}"));
REQUIRE_NOTHROW(P8("abc&@{![a-zA-Z]|([d-f]&(A|Z))}"));
REQUIRE_NOTHROW(P8("abc\\d\\c\\w\\s\\h\\\\\\.\\\\\\...\\d"));
}
SECTION("Backend")
{
REQUIRE_NOTHROW(Gen("minecraft"));
REQUIRE_NOTHROW(Gen("a|b|c|d|e"));
REQUIRE_NOTHROW(Gen("[abc]|[a-zA-Zdef0-9.\\\\..\\\\][m-x]"));
REQUIRE_NOTHROW(Gen("[abcA-Z]+*??*+"));
REQUIRE_NOTHROW(Gen("^abcde(abc$|[def]$)"));
REQUIRE_NOTHROW(Gen("abc&def&ghi"));
REQUIRE_NOTHROW(Gen("abc.\\.def.ghi\\..\\\\\\.."));
REQUIRE_NOTHROW(Gen("(abcdef)[xyz]{ 10 }"));
REQUIRE_NOTHROW(Gen("(abcdef)[xyz]{3, 18}"));
REQUIRE_NOTHROW(Gen("(abcdef)[xyz]{0, 18}"));
REQUIRE_NOTHROW(Gen("a&@{![a-z]|([d-f]&(A|Z))}"));
REQUIRE_NOTHROW(Gen("abc\\d\\c\\w\\s\\h\\\\\\.\\\\\\...\\d"));
}
SECTION("Match")
{
REQUIRE(Regex8(u8"abc").Match(u8"abc"));
REQUIRE(!Regex8(u8"abc").Match(u8"ac"));
REQUIRE(Regex8(u8"abc[def]").Match(u8"abcd"));
REQUIRE(Regex8(u8"abc*").Match(u8"abccc"));
REQUIRE(Regex8(u8"abc*").Match(u8"ab"));
REQUIRE(Regex8(u8"ab.\\.c+").Match(u8"abe.cc"));
REQUIRE(Regex8(u8"abc?").Match(u8"ab"));
REQUIRE(Regex8(u8"ab[def]+").Match(u8"abdefdeffeddef"));
REQUIRE(Regex16(u8"今天(天气)+不错啊?\\?").Match(u8"今天天气天气天气天气不错?"));
REQUIRE(Regex8(u8".*").Match(u8"今天天气不错啊"));
REQUIRE(Regex8(u8"今天.*啊").Match(u8"今天天气不错啊"));
REQUIRE(Regex8(u8"今天{ 5 \t }天气不错啊").Match(L"今天天天天天天气不错啊"));
REQUIRE(WRegex(L"今天{ 3 , 5 }气不错啊").Match(u8"今天天天气不错啊"));
REQUIRE(Regex16(u8"今天{3, 5\t}气不错啊").Match(u8"今天天天天气不错啊"));
REQUIRE(Regex32(u8"今天{3,\t5}气不错啊").Match(u8"今天天天天天气不错啊"));
REQUIRE(!Regex8(u8"今天{3, 5}气不错啊").Match(u8"今天天气不错啊"));
REQUIRE(!Regex8(u8"今天{3, 5}气不错啊").Match(u8"今天天天天天天气不错啊"));
REQUIRE_THROWS(Regex8(u8"今天{2, 1}天气不错啊").Match(u8"今天气不错啊"));
REQUIRE_THROWS(Regex8(u8"今天{0, 0}天气不错啊").Match(u8"今天气不错啊"));
REQUIRE_THROWS(Regex8(u8"今天{0}天气不错啊").Match(u8"今气不错啊"));
REQUIRE_NOTHROW(Regex8(u8"今天{0, 1}天气不错啊").Match(u8"今天气不错啊"));
{
auto m = Regex8(u8"&abc&(def)+&xyz&").Match(u8"abcdefdefxyz");
REQUIRE((m && m(0, 1) == u8"abc" && m(1, 2) == u8"defdef" && m(2, 3) == u8"xyz"));
}
REQUIRE(Regex8("mine|craft").Match("mine"));
REQUIRE(Regex8("mine|craft").Match("craft"));
REQUIRE(!Regex8("mine|craft").Match("minecraft"));
REQUIRE(Regex8("[a-z]+").Match("minecraft"));
REQUIRE(Regex8("\\d+").Match("123456"));
REQUIRE(!Regex8("\\d+").Match("12a3456"));
REQUIRE(Regex8("\\w+").Match("variableName"));
REQUIRE(Regex8("\\w+").Match("variable_name"));
REQUIRE(Regex8("\\w+").Match("0_variable_name_1"));
REQUIRE(!Regex8("\\w+").Match("0_va riable_name_1"));
REQUIRE(Regex8("\\s+").Match("\n \t \r "));
REQUIRE(!Regex8("\\s+").Match("\n !\t \r "));
REQUIRE(!Regex8("[a-z]+").Match("Minecraft"));
REQUIRE(!Regex8("@{![a-z]}+").Match("abcDefg"));
{
auto m = Regex8("&.*&\\.&@{!\\.}*&").Match("abc.x.y.z");
REQUIRE((m && m(0, 1) == "abc.x.y" && m(2, 3) == "z"));
}
REQUIRE(Regex8("@{[a-p]&[h-t]&!k|[+*?]}+").Match("hi?jl+mn*op"));
REQUIRE(!Regex8("@{[a-p]&[h-t]&!k}+").Match("hijklmnop"));
{
Str8 s0 = R"__("minecraft")__";
Str8 s1 = R"__("")__";
Str8 s2 = R"__("mine\"cr\"aft")__";
Str8 s3 = R"__("mine\"cr\"aft\")__";
Regex8 regex(R"__("&((@{!"}|\\")*@{!\\})?&")__");
REQUIRE(regex.Match(s0));
REQUIRE(regex.Match(s1));
REQUIRE(regex.Match(s2));
REQUIRE(!regex.Match(s3));
REQUIRE(regex.SearchPrefix(s0));
REQUIRE(regex.SearchPrefix(s1));
REQUIRE(regex.SearchPrefix(s2));
REQUIRE(!regex.SearchPrefix(s3));
REQUIRE(!regex.SearchPrefix("x" + s0));
REQUIRE(!regex.SearchPrefix("y" + s1));
REQUIRE(!regex.SearchPrefix("z" + s2));
REQUIRE(!regex.SearchPrefix("w" + s3));
}
{
Regex8 regex(R"__(&(\w|-)+&)__");
Str8 s0 = "-_abcdefg xsz0-";
REQUIRE(!regex.Match(s0));
REQUIRE(regex.SearchPrefix(s0)(0, 1) == "-_abcdefg");
REQUIRE(regex.SearchSuffix(s0)(0, 1) == "xsz0-");
}
}
SECTION("Search")
{
REQUIRE(Regex8(u8"今天天气不错").Search(u8"GoodMorning今天天气不错啊"));
REQUIRE(Regex8(u8"b").Search(u8"abc"));
REQUIRE(Regex16(u8"b+").Search(u8"abbbc"));
{
auto m = Regex8(u8"&b+&").Search(u8"abbbc");
REQUIRE((m && m(0, 1) == u8"bbb"));
}
{
auto m = Regex16(u8"&abcde&$").Search(u8"minecraftabcde");
REQUIRE((m && m(0, 1) == u8"abcde"));
}
{
auto m = Regex8("&[def]+&").Search("abcddeeffxyz");
auto n = m;
REQUIRE((n && n(0, 1) == "ddeeff"));
}
REQUIRE(Regex8(u8"mine").Search(u8"abcminecraft"));
REQUIRE(Regex32(u8"^mine").Search(u8"abcminecraft") == false);
}
SECTION("README")
{
// Example of basic usage
// Regex<...>::Match/Search returns a Result object
// which can be implicitly converted to a boolean value
// indicating whether the match/search succeeds
REQUIRE(Regex8(u8"今天天气不错minecraft").Match(u8"今天天气不错minecraft"));
REQUIRE(Regex8(u8"不错mine").Search(u8"今天天气不错minecraft"));
// Example of boolean expression
// Matches a non-empty string with each character satisfying one of the following:
// 1. in { +, *, ? }
// 2. in { c, d, e, ..., m, n } \ { h, k }
REQUIRE(Regex8("@{[+*?]|[c-n]&![hk]}+").Match("cde+fm?n"));
// Example of submatches tracking
// Each '&' defines a save point and can store a matched location.
// We can use two save points to slice the matched string.
auto result = Regex8("&abc&([def]|\\d)+&abc").Match("abcddee0099ff44abc");
REQUIRE(result);
REQUIRE(result(0, 1) == "abc");
REQUIRE(result(1, 2) == "ddee0099ff44");
REQUIRE(result(0, 2) == "abcddee0099ff44");
}
}
| 37.045918
| 94
| 0.519488
|
AirGuanZ
|
c70026920b9b42ade4db1c9d68a1fba2d951e98f
| 3,190
|
cpp
|
C++
|
cmdstan/stan/lib/stan_math/test/unit/math/fwd/mat/fun/array_builder_test.cpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
cmdstan/stan/lib/stan_math/test/unit/math/fwd/mat/fun/array_builder_test.cpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
cmdstan/stan/lib/stan_math/test/unit/math/fwd/mat/fun/array_builder_test.cpp
|
yizhang-cae/torsten
|
dc82080ca032325040844cbabe81c9a2b5e046f9
|
[
"BSD-3-Clause"
] | null | null | null |
#include <stan/math/fwd/mat.hpp>
#include <gtest/gtest.h>
using stan::math::fvar;
TEST(AgradFwdMatrixArrayBuilder,fvar_double) {
using std::vector;
using stan::math::array_builder;
EXPECT_EQ(0U, array_builder<fvar<double> >().array().size());
vector<fvar<double> > x
= array_builder<fvar<double> >()
.add(fvar<double>(1,4))
.add(fvar<double>(3,4))
.add(fvar<double>(2,4))
.array();
EXPECT_EQ(3U,x.size());
EXPECT_FLOAT_EQ(1.0, x[0].val_);
EXPECT_FLOAT_EQ(3.0, x[1].val_);
EXPECT_FLOAT_EQ(2.0, x[2].val_);
EXPECT_FLOAT_EQ(4.0, x[0].d_);
EXPECT_FLOAT_EQ(4.0, x[1].d_);
EXPECT_FLOAT_EQ(4.0, x[2].d_);
vector<vector<fvar<double> > > xx
= array_builder<vector<fvar<double> > >()
.add(array_builder<fvar<double> >()
.add(fvar<double>(1,4))
.add(fvar<double>(2,4)).array())
.add(array_builder<fvar<double> >()
.add(fvar<double>(3,4))
.add(fvar<double>(4,4)).array())
.add(array_builder<fvar<double> >()
.add(fvar<double>(5,4))
.add(fvar<double>(6,4)).array())
.array();
EXPECT_EQ(3U,xx.size());
for (size_t i = 0; i < 3; ++i)
EXPECT_EQ(2U,xx[i].size());
EXPECT_EQ(1,xx[0][0].val_);
EXPECT_EQ(2,xx[0][1].val_);
EXPECT_EQ(3,xx[1][0].val_);
EXPECT_EQ(4,xx[1][1].val_);
EXPECT_EQ(5,xx[2][0].val_);
EXPECT_EQ(6,xx[2][1].val_);
EXPECT_EQ(4,xx[0][0].d_);
EXPECT_EQ(4,xx[0][1].d_);
EXPECT_EQ(4,xx[1][0].d_);
EXPECT_EQ(4,xx[1][1].d_);
EXPECT_EQ(4,xx[2][0].d_);
EXPECT_EQ(4,xx[2][1].d_);
}
TEST(AgradFwdMatrixArrayBuilder,fvar_fvar_double) {
using std::vector;
using stan::math::array_builder;
EXPECT_EQ(0U, array_builder<fvar<fvar<double> > >().array().size());
vector<fvar<fvar<double> > > x
= array_builder<fvar<fvar<double> > >()
.add(fvar<fvar<double> >(1,4))
.add(fvar<fvar<double> >(3,4))
.add(fvar<fvar<double> >(2,4))
.array();
EXPECT_EQ(3U,x.size());
EXPECT_FLOAT_EQ(1.0, x[0].val_.val_);
EXPECT_FLOAT_EQ(3.0, x[1].val_.val_);
EXPECT_FLOAT_EQ(2.0, x[2].val_.val_);
EXPECT_FLOAT_EQ(4.0, x[0].d_.val_);
EXPECT_FLOAT_EQ(4.0, x[1].d_.val_);
EXPECT_FLOAT_EQ(4.0, x[2].d_.val_);
vector<vector<fvar<fvar<double> > > > xx
= array_builder<vector<fvar<fvar<double> > > >()
.add(array_builder<fvar<fvar<double> > >()
.add(fvar<fvar<double> >(1,4))
.add(fvar<fvar<double> >(2,4)).array())
.add(array_builder<fvar<fvar<double> > >()
.add(fvar<fvar<double> >(3,4))
.add(fvar<fvar<double> >(4,4)).array())
.add(array_builder<fvar<fvar<double> > >()
.add(fvar<fvar<double> >(5,4))
.add(fvar<fvar<double> >(6,4)).array())
.array();
EXPECT_EQ(3U,xx.size());
for (size_t i = 0; i < 3; ++i)
EXPECT_EQ(2U,xx[i].size());
EXPECT_EQ(1,xx[0][0].val_.val_);
EXPECT_EQ(2,xx[0][1].val_.val_);
EXPECT_EQ(3,xx[1][0].val_.val_);
EXPECT_EQ(4,xx[1][1].val_.val_);
EXPECT_EQ(5,xx[2][0].val_.val_);
EXPECT_EQ(6,xx[2][1].val_.val_);
EXPECT_EQ(4,xx[0][0].d_.val_);
EXPECT_EQ(4,xx[0][1].d_.val_);
EXPECT_EQ(4,xx[1][0].d_.val_);
EXPECT_EQ(4,xx[1][1].d_.val_);
EXPECT_EQ(4,xx[2][0].d_.val_);
EXPECT_EQ(4,xx[2][1].d_.val_);
}
| 30.09434
| 70
| 0.600627
|
yizhang-cae
|
c7009a6717d265862759f97ad4eae6dd772e7109
| 1,954
|
hpp
|
C++
|
src/para/peak_tolerance.hpp
|
toppic-suite/toppic-suite
|
b5f0851f437dde053ddc646f45f9f592c16503ec
|
[
"Apache-2.0"
] | 8
|
2018-05-23T14:37:31.000Z
|
2022-02-04T23:48:38.000Z
|
src/para/peak_tolerance.hpp
|
toppic-suite/toppic-suite
|
b5f0851f437dde053ddc646f45f9f592c16503ec
|
[
"Apache-2.0"
] | 9
|
2019-08-31T08:17:45.000Z
|
2022-02-11T20:58:06.000Z
|
src/para/peak_tolerance.hpp
|
toppic-suite/toppic-suite
|
b5f0851f437dde053ddc646f45f9f592c16503ec
|
[
"Apache-2.0"
] | 4
|
2018-04-25T01:39:38.000Z
|
2020-05-20T19:25:07.000Z
|
//Copyright (c) 2014 - 2020, The Trustees of Indiana University.
//
//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 TOPPIC_PARA_PEAK_TOLERANCE_HPP_
#define TOPPIC_PARA_PEAK_TOLERANCE_HPP_
#include <string>
#include <memory>
#include <vector>
#include "common/xml/xml_dom_element.hpp"
namespace toppic {
class XmlDOMDocument;
class PeakTolerance {
public:
PeakTolerance(double ppo);
explicit PeakTolerance(xercesc::DOMElement* element);
double compStrictErrorTole(double mass);
// consider zero ptm relaxed error
double compRelaxErrorTole(double m1, double m2);
double getPpo() {return ppo_;}
int getIntPpm() {return static_cast<int>(ppo_ * 1000000);}
bool isUseMinTolerance() {return use_min_tolerance_;}
double getMinTolerance() {return min_tolerance_;}
void setPpo(double ppo) {ppo_ = ppo;}
void setUseMinTolerance(bool use_min_tolerance) {
use_min_tolerance_ = use_min_tolerance;}
void setMinTolerance(double min_tolerance) {
min_tolerance_ = min_tolerance;}
void appendXml(XmlDOMDocument* xml_doc, xercesc::DOMElement* parent);
static std::string getXmlElementName() {return "peak_tolerance";}
private:
double ppo_;
/* whether or not use minimum tolerance */
bool use_min_tolerance_ = true;
double min_tolerance_ = 0.01;
};
typedef std::shared_ptr<PeakTolerance> PeakTolerancePtr;
typedef std::vector<PeakTolerancePtr> PeakTolerancePtrVec;
} /* namespace toppic */
#endif
| 27.138889
| 74
| 0.759468
|
toppic-suite
|
c7078a5b9c0dc68041b4e5bba29763e76c8c7cfc
| 1,185
|
cpp
|
C++
|
31_Next_Permutation.cpp
|
AvadheshChamola/LeetCode
|
b0edabfa798c4e204b015f4c367bfc5acfbd8277
|
[
"MIT"
] | null | null | null |
31_Next_Permutation.cpp
|
AvadheshChamola/LeetCode
|
b0edabfa798c4e204b015f4c367bfc5acfbd8277
|
[
"MIT"
] | null | null | null |
31_Next_Permutation.cpp
|
AvadheshChamola/LeetCode
|
b0edabfa798c4e204b015f4c367bfc5acfbd8277
|
[
"MIT"
] | null | null | null |
/*
31. Next Permutation
Medium
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).
The replacement must be in place and use only constant extra memory.
Example 1:
Input: nums = [1,2,3]
Output: [1,3,2]
Example 2:
Input: nums = [3,2,1]
Output: [1,2,3]
Example 3:
Input: nums = [1,1,5]
Output: [1,5,1]
Example 4:
Input: nums = [1]
Output: [1]
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
*/
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int r=nums.size()-2,l=nums.size()-1;
while(r>=0){
if(nums[r]<nums[r+1]){
break;
}
r--;
}
if(r<0){
reverse(nums.begin(),nums.end());
}else{
while(l>r){
if(nums[l]>nums[r]){
break;
}
l--;
}
swap(nums[l],nums[r]);
reverse(nums.begin()+r+1,nums.end());
}
}
};
| 17.954545
| 124
| 0.521519
|
AvadheshChamola
|
c71370c682704f2c244defe01bae201aacb14251
| 4,263
|
cpp
|
C++
|
test/impl/UniqueTokenStorage_test.cpp
|
mark-grimes/Communique
|
969a2a8851ac2eb9dfc0d5c4fdd8669073ad882a
|
[
"Apache-2.0"
] | null | null | null |
test/impl/UniqueTokenStorage_test.cpp
|
mark-grimes/Communique
|
969a2a8851ac2eb9dfc0d5c4fdd8669073ad882a
|
[
"Apache-2.0"
] | 1
|
2015-11-25T09:48:34.000Z
|
2015-11-25T09:48:34.000Z
|
test/impl/UniqueTokenStorage_test.cpp
|
mark-grimes/Communique
|
969a2a8851ac2eb9dfc0d5c4fdd8669073ad882a
|
[
"Apache-2.0"
] | null | null | null |
#include <communique/impl/UniqueTokenStorage.h>
#include "../catch.hpp"
#include <iostream>
#include <map>
SCENARIO( "Test that UniqueTokenStorage behaves as expected", "[UniqueTokenStorage][tools]" )
{
GIVEN( "A UniqueTokenStorage<uint64_t,uint32_t> instance" )
{
// Use a 32 bit unsigned int as the tokens, and a normal unsigned int for the values
communique::impl::UniqueTokenStorage<uint64_t,uint8_t> myTokenStorage;
WHEN( "I try to retrieve from an empty container" )
{
CHECK_THROWS( myTokenStorage.pop(9) );
CHECK_THROWS( myTokenStorage.pop(0) );
uint64_t result;
CHECK( myTokenStorage.pop(0,result)==false );
CHECK( myTokenStorage.pop(9,result)==false );
}
WHEN( "I try to retrieve previously stored items I get the correct ones back" )
{
std::vector< std::pair<uint64_t,uint8_t> > storedItems; // keep a record of what's stored so I can check
// Fill with random values
for( size_t index=0; index<200; ++index )
{
// Get a random number to store
uint64_t newValue=std::rand()*static_cast<float>(std::numeric_limits<uint64_t>::max())/RAND_MAX;
uint8_t newKey;
REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) );
storedItems.push_back( std::make_pair(newValue,newKey) );
}
// Try and retrieve each of these values and make sure the result is correct
for( const auto& valueKeyPair : storedItems )
{
uint64_t retrievedValue;
REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop( valueKeyPair.second ) );
CHECK( retrievedValue==valueKeyPair.first );
}
}
WHEN( "I try to completely fill a container" )
{
uint64_t newValue;
uint8_t newKey;
// Fill with arbitrary values, take out some as I go
for( uint64_t index=0; index<=std::numeric_limits<uint8_t>::max(); ++index )
{
REQUIRE_NOTHROW( newKey=myTokenStorage.push( index ) );
}
newValue=34;
CHECK_THROWS( newKey=myTokenStorage.push( newValue ) );
// Try and retrieve an arbitrary entry
uint8_t retrieveKey=64;
uint64_t retrievedValue;
REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop(retrieveKey) );
// Then try and add another entry
CHECK_NOTHROW( newKey=myTokenStorage.push( retrievedValue ) );
// Collection should be full again, so make sure I can't add anything else
CHECK_THROWS( newKey=myTokenStorage.push( newValue ) );
}
WHEN( "I fill then empty some items, I can still retrieve the correct ones back items" )
{
std::map<uint8_t,uint64_t> storedItems; // keep a record of what's stored so I can check
uint64_t newValue;
uint8_t newKey;
// Fill with random values
for( size_t index=0; index<=std::numeric_limits<uint8_t>::max(); ++index )
{
// Get a random number to store
newValue=std::rand()*static_cast<float>(std::numeric_limits<uint64_t>::max())/RAND_MAX;
REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) );
storedItems[newKey]=newValue;
}
// Check container is actually full
newValue=34;
CHECK_THROWS( newKey=myTokenStorage.push( newValue ) );
// Remove some arbitrary items
uint64_t retrievedValue;
REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop(0) );
REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop(1) );
REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop(2) );
REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop(65) );
REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop(128) );
newValue=5;
REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) );
storedItems[newKey]=newValue;
newValue=6;
REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) );
storedItems[newKey]=newValue;
newValue=7;
REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) );
storedItems[newKey]=newValue;
newValue=8;
REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) );
storedItems[newKey]=newValue;
newValue=9;
REQUIRE_NOTHROW( newKey=myTokenStorage.push( newValue ) );
storedItems[newKey]=newValue;
// Try and retrieve each of these values and make sure the result is correct
for( const auto& keyValuePair : storedItems )
{
uint64_t retrievedValue;
REQUIRE_NOTHROW( retrievedValue=myTokenStorage.pop( keyValuePair.first ) );
CHECK( retrievedValue==keyValuePair.second );
}
}
}
}
| 34.658537
| 107
| 0.71757
|
mark-grimes
|
c7171eaca46d7e99f6636ad5a650731d17054c21
| 2,108
|
cpp
|
C++
|
game/main.cpp
|
geoffwhitehead/moonbase-commander-game
|
8eb3664e1275e9f0d22fe22d25d334654a57a949
|
[
"MIT"
] | 1
|
2017-09-30T21:16:35.000Z
|
2017-09-30T21:16:35.000Z
|
game/main.cpp
|
geoffwhitehead/moonbase-commander-game
|
8eb3664e1275e9f0d22fe22d25d334654a57a949
|
[
"MIT"
] | null | null | null |
game/main.cpp
|
geoffwhitehead/moonbase-commander-game
|
8eb3664e1275e9f0d22fe22d25d334654a57a949
|
[
"MIT"
] | null | null | null |
#include "../nclgl/OGLRenderer.h"
#include "../engine-base/Camera.h"
#include "../engine-base/GameManager.h"
#include "../engine-audio/AudioManager.h"
#include "../engine-input/InputManager.h"
#include "../engine-base/GameLogicManager.h"
#include "../engine-physics/PhysicsManager.h"
#include "ContactListener.h"
#include "GameInput.h"
#include "GameAudio.h"
#include "GameLogic.h"
#include "GameIO.h"
#include <iostream>
#include <map>
// screen size
#define W_X 1600.0f
#define W_Y 900.0f
#define p_factor 12.0f
const float pixels_per_m = 20.0f;
//const float gravity = -pixels_per_m / 0.7f; // adjust
const float gravity = 0.0f;
void main(void) {
// GAME MANAGER
GameManager *gm = new GameManager(W_X, W_Y);
// PHYSICS
PhysicsManager* pm = new PhysicsManager(gm, gravity, pixels_per_m);
// FILE IO
GameIO* gio = new GameIO("./levels/", pm->b2_world, pm->pixels_per_m);
gm->addFileInput(gio);
gm->loadLevel("level_1.json");
// CAMERA
Camera* camera = new Camera(0.0f, 0.0f, Vector3(0, 0, 400), W_X, W_Y);
Camera::projMatrix = Matrix4::Orthographic(1, 1000, W_X/ pixels_per_m, -W_X/ pixels_per_m, W_Y/ pixels_per_m,-W_Y/ pixels_per_m);
//Camera::viewMatrix = Matrix4::BuildCamera(Vector3(0.0, 50.0, 20.0), Vector3(0.0, 0.0, 0.0));
//camera->BuildViewMatrix();
//ADD SYSTEM MANAGERS
AudioManager* am = new AudioManager(gio); // init with file input to cause it to load audio from file
InputManager* im = new InputManager();
GameLogicManager* glm = new GameLogicManager();
//CREATE SUB SYSTEMS
GameLogic* gl = new GameLogic(gm, glm, pm->b2_world, am, camera);
GameInput* gi = new GameInput(gl, camera);
ContactListener* cl = new ContactListener(gl);
GameAudio* ga = new GameAudio(gl, am); // created to seperate audio from game
//register managers
gm->addSystemManager(am);
pm->addListener(cl);
gm->addSystemManager(im);
gm->addSystemManager(glm);
gm->addSystemManager(pm);
//register sub systems
im->addSubSystem(camera);
glm->addSubSystem(gl);
im->addSubSystem(gi);
am->addSubSystem(ga); // register with audio manager so updates are called
gm->run();
}
| 28.106667
| 130
| 0.711575
|
geoffwhitehead
|
c71a59e885c1226bb0817675657235af87c80a5f
| 1,987
|
cpp
|
C++
|
ports/esp32/src/OTA.cpp
|
ygjukim/hFramework
|
994ea7550c34b4943e2fa2d5e9ca447aa555f39e
|
[
"MIT"
] | 33
|
2017-07-03T22:49:30.000Z
|
2022-03-31T19:32:55.000Z
|
ports/esp32/src/OTA.cpp
|
ygjukim/hFramework
|
994ea7550c34b4943e2fa2d5e9ca447aa555f39e
|
[
"MIT"
] | 6
|
2017-07-13T13:23:22.000Z
|
2019-10-25T17:51:28.000Z
|
ports/esp32/src/OTA.cpp
|
ygjukim/hFramework
|
994ea7550c34b4943e2fa2d5e9ca447aa555f39e
|
[
"MIT"
] | 17
|
2017-07-01T05:35:47.000Z
|
2022-03-22T23:33:00.000Z
|
#include <hFramework.h>
#include <cstring>
#include <utility>
#include "esp_ota_ops.h"
namespace hFramework {
namespace OTA {
const esp_partition_t* getOtaPartition()
{
const esp_partition_t* bootPartition = esp_ota_get_boot_partition();
const char* newname;
if (bootPartition == nullptr || strcmp("ota_0", bootPartition->label) == 0) {
fprintf(stderr, "OTA: currently running from partition 'ota_0'\n");
newname = "ota_1";
} else if (strcmp("ota_1", bootPartition->label) == 0) {
fprintf(stderr, "OTA: currently running from partition 'ota_1'\n");
newname = "ota_0";
} else {
fprintf(stderr, "OTA: invalid boot partition\n");
return nullptr;
}
return esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_ANY, newname);
}
bool run(uint32_t crc32, int length, hStreamDev& dev) {
const esp_partition_t* otaPart = getOtaPartition();
esp_ota_handle_t handle;
if (esp_ota_begin(otaPart, 0, &handle) != 0) {
fprintf(stderr, "OTA: esp_ota_begin error\n");
return false;
}
const int maxChunkSize = 4096;
char* chunkBuffer = (char*)malloc(maxChunkSize);
while (length > 0) {
int chunkSize = std::min(length, maxChunkSize);
if (dev.readAll(chunkBuffer, chunkSize) != chunkSize) {
fprintf(stderr, "OTA: steam read failed\n");
return false;
}
length -= chunkSize;
if (esp_ota_write(handle, chunkBuffer, chunkSize) != 0) {
fprintf(stderr, "OTA: esp_ota_write error\n");
return false;
}
}
if (esp_ota_end(handle) != 0) {
fprintf(stderr, "OTA: esp_ota_end failed\n");
return false;
}
// TODO: check crc32
if (esp_ota_set_boot_partition(otaPart) != 0) {
fprintf(stderr, "OTA: esp_ota_set_boot_partition\n");
return false;
}
fprintf(stderr, "OTA: finished successfully\n");
return true;
}
}
}
| 27.985915
| 96
| 0.630096
|
ygjukim
|
c72191e3edc2be1cb12de94a53cd84a52c58176d
| 215
|
cpp
|
C++
|
8_bit_manipulation/5_even_odd.cpp
|
ShyamNandanKumar/coding-ninja2
|
a43a21575342261e573f71f7d8eff0572f075a17
|
[
"MIT"
] | 11
|
2021-01-02T10:07:17.000Z
|
2022-03-16T00:18:06.000Z
|
8_bit_manipulation/5_even_odd.cpp
|
meyash/cp_master
|
316bf47db2a5b40891edd73cff834517993c3d2a
|
[
"MIT"
] | null | null | null |
8_bit_manipulation/5_even_odd.cpp
|
meyash/cp_master
|
316bf47db2a5b40891edd73cff834517993c3d2a
|
[
"MIT"
] | 5
|
2021-05-19T11:17:18.000Z
|
2021-09-16T06:23:31.000Z
|
// check if num is even or odd
// just check last bit
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
if((n&1)==1){
cout<<"Odd";
}else{
cout<<"Even";
}
}
| 14.333333
| 30
| 0.506977
|
ShyamNandanKumar
|
d17703ec69b9fc6ccbe5af7df0e6d0b9c75a85fa
| 2,918
|
hpp
|
C++
|
Safety/Libraries/Drivers/Inc/PPM.hpp
|
YashrajN/ZeroPilot-SW
|
3418f7050443af86bc0e7cc8e58177a95adc40eb
|
[
"BSD-4-Clause"
] | 15
|
2017-09-12T14:54:16.000Z
|
2021-09-21T23:28:57.000Z
|
Safety/Libraries/Drivers/Inc/PPM.hpp
|
YashrajN/ZeroPilot-SW
|
3418f7050443af86bc0e7cc8e58177a95adc40eb
|
[
"BSD-4-Clause"
] | 67
|
2017-10-31T02:04:44.000Z
|
2022-03-28T01:02:25.000Z
|
Safety/Libraries/Drivers/Inc/PPM.hpp
|
YashrajN/ZeroPilot-SW
|
3418f7050443af86bc0e7cc8e58177a95adc40eb
|
[
"BSD-4-Clause"
] | 48
|
2017-09-28T23:47:17.000Z
|
2022-01-08T18:30:40.000Z
|
/**
* Implements PPM driver. Support variable PPM, where the input can be
* from 8-12 channels. Note that the assumption is that we're going to be
* reading signals that range from 1-2ms. If you're trying to read outside of this range,
* modify the prescaler in the implementation, as we may get a timer overflow or get really bad precision!
* Its fine if the signals we're reading are around the same ranges however, like 800us to 2200us. In that case
* just modify the setLimits() so the percentages received are correct
* @author Serj Babayan
* @copyright Waterloo Aerial Robotics Group 2019
* https://raw.githubusercontent.com/UWARG/ZeroPilot-SW/devel/LICENSE.md
*
* Hardware Info:
*
* Timer14 - PPM
* PPM PIN - B1
*/
#include <stdint.h>
#include "GPIO.hpp"
#include "PWM.hpp"
static const int32_t MAX_PPM_CHANNELS = 12;
class PPMChannel {
public:
/**
* How many channels are we expecting in the input port?
* Usually this is only 8
* @param num_channels
* @param disconnect_timeout Number of ms to wait before we consider channel disconnected
*/
explicit PPMChannel(uint8_t num_channels = 8, uint32_t disconnect_timeout = 1000);
/**
* Reconfigure number of channels
* @param num_channels
*/
StatusCode setNumChannels(uint8_t num_channels);
/**
* Set expected input limits for a particular channel
* @param channel
* @param min Min time in us (for a 0% signal)
* @param max Max time in us (for 100% signal)
* @param deadzone time in us for deadzone. ie. if deadzone is set to 50, a signal that is received
* with a 1050us length will still be considered 0%
*/
StatusCode setLimits(uint8_t channel, uint32_t min, uint32_t max, uint32_t deadzone);
/**
* Set the disconnect timeout
* @param timeout
* @return
*/
StatusCode setTimeout(uint32_t timeout);
/**
* Setup timer14 with interrupts, gpios, etc..
* @return
*/
StatusCode setup();
/**
* Reset all pins to their default state. Stop the timer and interrupts
* @return
*/
StatusCode reset();
/**
* Returns a percent value that was most recently received from the PPM channel, as a percentage
* from 0-100
* @param num
* @return 0 if an invalid channel number was given
*/
uint8_t get(PWMChannelNum num);
/**
* Same as above function, but returns the captured value in microseconds instead
* @param num
* @return 0 if an invalid channel number was given
*/
uint32_t get_us(PWMChannelNum num);
/**
* Wether the channel has disconnected based on the timeout
* @param sys_time Current system time in ms
* @return
*/
bool is_disconnected(uint32_t sys_time);
private:
int32_t deadzones[MAX_PPM_CHANNELS];
int32_t min_values[MAX_PPM_CHANNELS]; //stores min tick values for each channel
int32_t max_values[MAX_PPM_CHANNELS]; //stores max tick values for each channel
uint32_t disconnect_timeout;
bool is_setup = false;
GPIOPin ppm_pin;
};
| 29.77551
| 111
| 0.724469
|
YashrajN
|
d17fd6d9180a3debe969e442111c13bb948ef421
| 9,853
|
cpp
|
C++
|
Src/Core/DeviceBridge.cpp
|
chowdaryd/C3
|
118a35f88d0cf3ca526af5052b1140f1b7d3ff4b
|
[
"BSD-3-Clause"
] | null | null | null |
Src/Core/DeviceBridge.cpp
|
chowdaryd/C3
|
118a35f88d0cf3ca526af5052b1140f1b7d3ff4b
|
[
"BSD-3-Clause"
] | 1
|
2020-05-05T21:25:16.000Z
|
2020-05-05T21:25:16.000Z
|
Src/Core/DeviceBridge.cpp
|
CX-4/C3
|
da84536f229999fb5cba43fe7d983dcc8f80b830
|
[
"BSD-3-Clause"
] | null | null | null |
#include "StdAfx.h"
#include "DeviceBridge.h"
#include "Relay.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FSecure::C3::Core::DeviceBridge::DeviceBridge(std::shared_ptr<Relay>&& relay, DeviceId did, HashT typeNameHash, std::shared_ptr<Device>&& device, bool isNegotiationChannel, bool isSlave, ByteVector args /*= ByteVector()*/)
: m_IsNegotiationChannel(isNegotiationChannel)
, m_IsSlave(isSlave)
, m_Did{ did }
, m_TypeNameHash(typeNameHash)
, m_Relay{ relay }
, m_Device{ std::move(device) }
{
if (!isNegotiationChannel)
return;
auto readView = ByteView{ args };
std::tie(m_InputId, m_OutpuId) = readView.Read<ByteVector, ByteVector>();
m_NonNegotiatiedArguments = readView;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::DeviceBridge::OnAttach()
{
GetDevice()->OnAttach(shared_from_this());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::DeviceBridge::Detach()
{
m_IsAlive = false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::DeviceBridge::Close()
{
auto relay = GetRelay();
relay->DetachDevice(GetDid());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::DeviceBridge::OnReceive()
{
GetDevice()->OnReceive();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::DeviceBridge::PassNetworkPacket(ByteView packet)
{
if (m_IsNegotiationChannel && !m_IsSlave) // negotiation channel does not support chunking. Just pass packet and leave.
return GetRelay()->OnPacketReceived(packet, shared_from_this());
m_QoS.PushReceivedChunk(packet);
auto nextPacket = m_QoS.GetNextPacket();
if (!nextPacket.empty())
GetRelay()->OnPacketReceived(nextPacket, shared_from_this());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::DeviceBridge::OnPassNetworkPacket(ByteView packet)
{
auto lock = std::lock_guard<std::mutex>{ m_ProtectWriteInConcurrentThreads };
if (m_IsNegotiationChannel) // negotiation channel does not support chunking. Just pass packet and leave.
{
auto sent = GetDevice()->OnSendToChannelInternal(packet);
if (sent != packet.size())
throw std::runtime_error{OBF("Negotiation channel does not support chunking. Packet size: ") + std::to_string(packet.size()) + OBF(" Channel sent: ") + std::to_string(sent)};
return;
}
auto oryginalSize = static_cast<uint32_t>(packet.size());
auto messageId = m_QoS.GetOutgouingPacketId();
uint32_t chunkId = 0u;
while (!packet.empty())
{
auto data = ByteVector{}.Write(messageId, chunkId, oryginalSize).Concat(packet);
auto sent = GetDevice()->OnSendToChannelInternal(data);
if (sent >= QualityOfService::s_MinFrameSize || sent == data.size()) // if this condition were not channel must resend data.
{
chunkId++;
packet.remove_prefix(sent - QualityOfService::s_HeaderSize);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::DeviceBridge::PostCommandToConnector(ByteView packet)
{
GetRelay()->PostCommandToConnector(packet, shared_from_this());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::DeviceBridge::OnCommandFromConnector(ByteView command)
{
auto lock = std::lock_guard<std::mutex>{ m_ProtectWriteInConcurrentThreads };
GetDevice()->OnCommandFromConnector(command);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FSecure::ByteVector FSecure::C3::Core::DeviceBridge::RunCommand(ByteView command)
{
return GetDevice()->OnRunCommand(command);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FSecure::ByteVector FSecure::C3::Core::DeviceBridge::WhoAreYou()
{
return GetDevice()->OnWhoAmI();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::DeviceBridge::Log(LogMessage const& message)
{
GetRelay()->Log(message, GetDid());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FSecure::C3::DeviceId FSecure::C3::Core::DeviceBridge::GetDid() const
{
return m_Did;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::DeviceBridge::StartUpdatingInSeparateThread()
{
std::thread{
[this, self = shared_from_this()]()
{
WinTools::StructuredExceptionHandling::SehWrapper([&]()
{
while (m_IsAlive)
try
{
std::this_thread::sleep_for(GetDevice()->GetUpdateDelay());
OnReceive();
}
catch (std::exception const& exception)
{
Log({ OBF_SEC("std::exception while updating: ") + exception.what(), LogMessage::Severity::Error });
}
catch (...)
{
Log({ OBF_SEC("Unknown exception while updating."), LogMessage::Severity::Error });
}
}, [this]()
{
# if defined _DEBUG
Log({ "Signal captured, ending thread execution.", LogMessage::Severity::Error });
# endif
});
}}.detach();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::DeviceBridge::SetUpdateDelay(std::chrono::milliseconds minUpdateDelayInMs, std::chrono::milliseconds maxUpdateDelayInMs)
{
GetDevice()->SetUpdateDelay(minUpdateDelayInMs, maxUpdateDelayInMs);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::DeviceBridge::SetUpdateDelay(std::chrono::milliseconds frequencyInMs)
{
GetDevice()->SetUpdateDelay(frequencyInMs);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::shared_ptr<FSecure::C3::Device> FSecure::C3::Core::DeviceBridge::GetDevice() const
{
return m_Device;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::shared_ptr<FSecure::C3::Core::Relay> FSecure::C3::Core::DeviceBridge::GetRelay() const
{
return m_Relay;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FSecure::HashT FSecure::C3::Core::DeviceBridge::GetTypeNameHash() const
{
return m_TypeNameHash;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool FSecure::C3::Core::DeviceBridge::IsChannel() const
{
auto device = GetDevice();
return device ? device->IsChannel() : false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool FSecure::C3::Core::DeviceBridge::IsNegotiationChannel() const
{
return m_IsNegotiationChannel && IsChannel();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::DeviceBridge::SetErrorStatus(std::string_view errorMessage)
{
m_Error = errorMessage;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string FSecure::C3::Core::DeviceBridge::GetErrorStatus()
{
return m_Error;
}
| 46.042056
| 222
| 0.383538
|
chowdaryd
|
d1830235551238a11afab51cc05d4121d8aa5921
| 3,168
|
cpp
|
C++
|
DigDuck/source/ipinfo.cpp
|
mickelfeng/qt_learning
|
1f565754c36f0c09888cf4fbffa6271298d0678b
|
[
"Apache-2.0"
] | 1
|
2016-01-05T07:24:32.000Z
|
2016-01-05T07:24:32.000Z
|
DigDuck/source/ipinfo.cpp
|
mickelfeng/qt_learning
|
1f565754c36f0c09888cf4fbffa6271298d0678b
|
[
"Apache-2.0"
] | null | null | null |
DigDuck/source/ipinfo.cpp
|
mickelfeng/qt_learning
|
1f565754c36f0c09888cf4fbffa6271298d0678b
|
[
"Apache-2.0"
] | null | null | null |
#include "ipinfo.h"
#include <QDebug>
ipInfo::ipInfo()
{
}
//返回字符串数组
QStringList ipInfo::ipAddr (const QString &ip)
{
QStringList address = ip.split (".");
return address;
}
//判断是否为IP格式
bool ipInfo::isIP (const QString &ip )
{
QStringList address = ip.split (".");
int num = 0;
for(int i =0 ;i<address.length ();i++){
if(address[i].toInt ()>0 && address[i].toInt ()<256)
num++;
}
if(num == 4)
return true;
return false;
// qDebug ()<<num;
}
//获取端口号
QStringList ipInfo::ipPort (const QString &port)
{
QStringList ipport = port.split (",");
return ipport;
}
//判断IP前两段是否一致
bool ipInfo::isSame_2 (const QString &begin, const QString &end)
{
QStringList one = begin.split (".");
QStringList two = end.split (".");
if(one[0] == two[0] && one[1] == two[1])
return true;
return false;
}
//判断IP前三段是否一致
bool ipInfo::isSame_3 (const QString &begin, const QString &end)
{
QStringList one = begin.split (".");
QStringList two = end.split (".");
if(one[0] == two[0] && one[1] == two[1] && one[2] == two[2])
return true;
return false;
}
//IP地址比较大小
bool ipInfo::isLarge (const QString &begin, const QString &end)
{
QStringList one = begin.split (".");
QStringList two = end.split (".");
int sum_1 = one[0].toInt ()*255*255*255 + one[1].toInt ()*255*255 +one[2].toInt ()*255 + one[3].toInt ();
int sum_2 = two[0].toInt ()*255*255*255 + two[1].toInt ()*255*255 +two[2].toInt ()*255 + two[3].toInt ();
if(sum_2 >= sum_1)
return true;
return false;
}
//从字典读取每一行文本内容
QStringList ipInfo::getFileContent (const QString &filePath)
{
QFile file (filePath);
if(!file.open (QIODevice::ReadOnly | QIODevice::Text))
// QMessageBox::warning (this,"error","file open failed!");
qDebug ()<<"file open failed!";
file.seek (0);
QString str;
QStringList array ;
str = file.readAll ();
array = str.split ("\n");
return array;
}
//遍历字典中每一行的IP段中所有的IP
QStringList ipInfo::getIP (const QString &begin,const QString &end)
{
QStringList begin_ip = begin.split (".");
QStringList end_ip = end.split (".");
QStringList ipAddress;
// 42.121.4.41 42.121.5.50
for(int a = begin_ip[2].toInt ();a<=end_ip[2].toInt ();a++){
for(int b= ( a == begin_ip[2].toInt ()? begin_ip[3].toInt (): 0);b<=( a == end_ip[2].toInt ()? end_ip[3].toInt ():255);b++){
QString str_a = QString::number (a,10);
QString str_b = QString::number (b,10);
ipAddress << begin_ip[0]+"."+begin_ip[1]+"."+str_a+"."+str_b;
}
}
return ipAddress;
}
//计算IP个数
int ipInfo::ipNum (QString begin_ip, QString end_ip)
{
QStringList begin = begin_ip.split (".");
QStringList end = end_ip.split (".");
int num = 0;
for(int a = begin[2].toInt ();a<=end[2].toInt ();a++){
for(int b= ( a == begin[2].toInt ()? begin[3].toInt (): 0);b<=( a == end[2].toInt ()? end[3].toInt ():255);b++){
num++;
}
}
return num;
}
| 28.035398
| 133
| 0.554924
|
mickelfeng
|
d18cea7cecb037520353bed7d78354a36a16e22e
| 1,094
|
cpp
|
C++
|
src/tile/Recovery.cpp
|
rbtnn/tile
|
8b0b896b6e69128e68a4b134d7b0fbf617894fb1
|
[
"MIT"
] | 1
|
2015-01-08T21:58:32.000Z
|
2015-01-08T21:58:32.000Z
|
src/tile/Recovery.cpp
|
rbtnn/tile
|
8b0b896b6e69128e68a4b134d7b0fbf617894fb1
|
[
"MIT"
] | null | null | null |
src/tile/Recovery.cpp
|
rbtnn/tile
|
8b0b896b6e69128e68a4b134d7b0fbf617894fb1
|
[
"MIT"
] | null | null | null |
#include <tile/common_headers.h>
#include <tile/common_functions.h>
#include <tile/wndproc_functions.h>
#include <tile/Recovery.h>
namespace Tile{
void Recovery::save(HWND const& hwnd_){
auto it = rects.find(hwnd_);
if(it == std::end(rects)){
RECT rect;
::GetWindowRect(hwnd_, &rect);
rects.insert(std::map<HWND, RECT>::value_type(hwnd_, rect));
styles.insert(std::map<HWND, LONG>::value_type(hwnd_, ::GetWindowLong(hwnd_, GWL_STYLE)));
exstyles.insert(std::map<HWND, LONG>::value_type(hwnd_, ::GetWindowLong(hwnd_, GWL_EXSTYLE)));
}
}
void Recovery::load(HWND const& hwnd_){
auto it = rects.find(hwnd_);
if(it != std::end(rects)){
RECT const rect = rects[hwnd_];
LONG const width = rect.right - rect.left;
LONG const height = rect.bottom - rect.top;
::SetWindowPos(hwnd_, HWND_NOTOPMOST, rect.left, rect.top, width, height, SWP_NOACTIVATE);
::SetWindowLong(hwnd_, GWL_STYLE, styles[hwnd_]);
::SetWindowLong(hwnd_, GWL_EXSTYLE, exstyles[hwnd_]);
::ShowWindow(hwnd_, SW_SHOWNORMAL);
}
}
}
| 35.290323
| 100
| 0.662706
|
rbtnn
|
d18d8dd0c5dde502ca871623aaa726f80e9494c6
| 681
|
cpp
|
C++
|
src/game/client/hl2/c_basehlcombatweapon.cpp
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | 6
|
2022-01-23T09:40:33.000Z
|
2022-03-20T20:53:25.000Z
|
src/game/client/hl2/c_basehlcombatweapon.cpp
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | null | null | null |
src/game/client/hl2/c_basehlcombatweapon.cpp
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | 1
|
2022-02-06T21:05:23.000Z
|
2022-02-06T21:05:23.000Z
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "c_basehlcombatweapon.h"
#include "igamemovement.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
IMPLEMENT_CLIENTCLASS_DT( C_HLMachineGun, DT_HLMachineGun, CHLMachineGun )
END_RECV_TABLE()
IMPLEMENT_CLIENTCLASS_DT( C_HLSelectFireMachineGun, DT_HLSelectFireMachineGun, CHLSelectFireMachineGun )
END_RECV_TABLE()
IMPLEMENT_CLIENTCLASS_DT( C_BaseHLBludgeonWeapon, DT_BaseHLBludgeonWeapon, CBaseHLBludgeonWeapon )
END_RECV_TABLE()
| 32.428571
| 104
| 0.687225
|
cstom4994
|
d18dad187d1681d93bb60d9045bcfcc87ecc5f3d
| 14,175
|
cpp
|
C++
|
Source/Structures/ModeMapper.cpp
|
vsicurella/SuperVirtualKeyboard
|
b59549281ea16b70f94b3136fe0b9a1f9fc355e2
|
[
"Unlicense"
] | 22
|
2019-06-26T12:41:49.000Z
|
2022-02-11T14:48:18.000Z
|
Source/Structures/ModeMapper.cpp
|
vsicurella/SuperVirtualKeyboard
|
b59549281ea16b70f94b3136fe0b9a1f9fc355e2
|
[
"Unlicense"
] | 18
|
2019-06-22T21:49:21.000Z
|
2021-05-15T01:33:57.000Z
|
Source/Structures/ModeMapper.cpp
|
vsicurella/SuperVirtualKeyboard
|
b59549281ea16b70f94b3136fe0b9a1f9fc355e2
|
[
"Unlicense"
] | null | null | null |
/*
==============================================================================
ModeMapper.cpp
Created: 30 May 2019 8:02:42pm
Author: Vincenzo
==============================================================================
*/
#include "ModeMapper.h"
ModeMapper::ModeMapper()
{
mappingNode = ValueTree(IDs::midiMapNode);
setMappingStyle(0);
setMapOrdersParameters(0, 0, 0, 0);
}
ModeMapper::ModeMapper(ValueTree modeMappingNodeIn)
{
mappingNode = modeMappingNodeIn;
mappingStyle = mappingNode[IDs::autoMappingStyle];
mapByOrderNum1 = mappingNode[IDs::mode1OrderMapping];
mapByOrderNum2 = mappingNode[IDs::mode2OrderMapping];
mapByOrderOffset1 = mappingNode[IDs::mode1OrderOffsetMapping];
mapByOrderOffset2 = mappingNode[IDs::mode2OrderOffsetMapping];
}
ValueTree ModeMapper::getMappingNode()
{
return mappingNode;
}
int ModeMapper::getMode1OrderNum() const
{
return mapByOrderNum1;
}
int ModeMapper::getMode2OrderNum() const
{
return mapByOrderNum2;
}
int ModeMapper::getMode1OrderOffset() const
{
return mapByOrderOffset1;
}
int ModeMapper::getMode2OrderOffset() const
{
return mapByOrderOffset2;
}
void ModeMapper::setMappingStyle(int mapTypeIn)
{
mappingStyle = mapTypeIn;
mappingNode.setProperty(IDs::autoMappingStyle, mapTypeIn, nullptr);
}
void ModeMapper::setMapOrdersParameters(int order1, int order2, int offset1, int offset2)
{
setMode1OrderNum(order1);
setMode2OrderNum(order2);
setMode1OrderOffset(offset1);
setMode2OrderOffset(offset2);
}
void ModeMapper::setMode1OrderNum(int orderNumber)
{
mapByOrderNum1 = orderNumber;
mappingNode.setProperty(IDs::mode1OrderMapping, mapByOrderNum1, nullptr);
}
void ModeMapper::setMode2OrderNum(int orderNumber)
{
mapByOrderNum2 = orderNumber;
mappingNode.setProperty(IDs::mode2OrderMapping, mapByOrderNum2, nullptr);
}
void ModeMapper::setMode1OrderOffset(int orderOffset)
{
mapByOrderOffset1 = orderOffset;
mappingNode.setProperty(IDs::mode1OrderOffsetMapping, mapByOrderOffset1, nullptr);
}
void ModeMapper::setMode2OrderOffset(int orderOffset)
{
mapByOrderOffset2 = orderOffset;
mappingNode.setProperty(IDs::mode2OrderOffsetMapping, mapByOrderOffset2, nullptr);
}
void ModeMapper::setPreviousOrderNoteMap(NoteMap prevNoteMapIn)
{
previousOrderMap = prevNoteMapIn;
}
NoteMap ModeMapper::map(const Mode& mode1, const Mode& mode2, NoteMap prevMap)
{
return map(mode1, mode2, mappingStyle, mapByOrderNum1, mapByOrderNum2, mapByOrderOffset1, mapByOrderOffset2, prevMap);
}
NoteMap ModeMapper::map(const Mode& mode1, const Mode& mode2, int mapStyleIn, int order1, int order2, int offset1, int offset2,
NoteMap prevMap)
{
NoteMap mapOut;
if (mapStyleIn < 0)
mapStyleIn = mappingStyle;
else
setMappingStyle(mapStyleIn);
mappingNode.setProperty(IDs::autoMappingStyle, mappingStyle, nullptr);
switch (mappingStyle)
{
case ModeToScale:
mapOut = mapToMode1Scale(mode1, mode2);
break;
case ModeByOrder:
setMapOrdersParameters(order1, order2, offset1, offset2);
previousOrderMap = prevMap;
mapOut = mapByOrder(mode1, mode2, mapByOrderNum1, mapByOrderNum2, mapByOrderOffset1, mapByOrderOffset2, previousOrderMap);
break;
default:
mapOut = mapFull(mode1, mode2);
break;
}
return mapOut;
}
Array<int> ModeMapper::getSelectedPeriodMap(const Mode& mode1, const Mode& mode2) const
{
Array<int> mapOut;
NoteMap fullMap;
switch (mappingStyle)
{
case ModeToScale:
if (mode1.getScaleSize() == mode2.getModeSize())
mapOut = getScaleToModePeriodMap(mode1, mode2);
else // TODO: improve
mapOut = mapFull(mode1, mode2).getValues();
break;
case ModeByOrder: // TODO: improve
mapOut = mapFull(mode1, mode2, previousOrderMap.getValues()).getValues();
break;
default: // ModeToMode
if (mode1.getModeSize() == mode2.getModeSize())
mapOut = getModeToModePeriodMap(mode1, mode2);
else
mapOut = degreeMapFullMode(mode1, mode2);
break;
}
return mapOut;
}
NoteMap ModeMapper::mapFull(const Mode& mode1, const Mode& mode2, Array<int> degreeMapIn)
{
if (degreeMapIn.size() != mode1.getOrders().size())
degreeMapIn = degreeMapFullMode(mode1, mode2);
else
degreeMapIn = getModeToModePeriodMap(mode1, mode2);
NoteMap mappingOut;
int midiNote;
for (int m = 0; m < mappingOut.getSize(); m++)
{
midiNote = degreeMapIn[m];
if (midiNote >= 0)
{
mappingOut.setValue(m, midiNote);
}
else
{
mappingOut.setValue(m, -1);
}
}
//DBG("Root note from mode 1 is " + String(mode1.getRootNote()) +
// " and it produces the note " + String(mappingOut.getValue(mode1.getRootNote())) +
// ". Root note from mode 2 is " + String(mode2.getRootNote()));
return mappingOut;
}
NoteMap ModeMapper::mapByOrder(const Mode& mode1, const Mode& mode2, int mode1Order, int mode2Order, int mode1Offset, int mode2Offset, NoteMap prevMap)
{
mode1Order = jlimit(0, mode1.getMaxStep() - 1, mode1Order);
mode2Order = jlimit(0, mode2.getMaxStep() - 1, mode2Order);
Array<int> midiNotesFrom = mode1.getNotesOfOrder(mode1Order);
Array<int> midiNotesTo = mode2.getNotesOfOrder(mode2Order);
mode1Offset = jlimit(0, midiNotesFrom.size() - 1, mode1Offset);
mode2Offset = jlimit(0, midiNotesTo.size() - 1, mode2Offset);
int rootNoteFrom = mode1.getRootNote();
int rootNoteTo = mode2.getRootNote();
int rootIndexFrom = mode1.getNotesOfOrder().indexOf(rootNoteFrom);
int rootIndexTo = mode2.getNotesOfOrder().indexOf(rootNoteTo);
int rootIndexOffset = rootIndexTo - rootIndexFrom + mode2Offset - mode1Offset;
int mode1Index, mode2Index;
int noteFrom, noteTo;
for (int m = 0; m < midiNotesFrom.size(); m++)
{
// might make more sense to not have a mode1Offset
mode1Index = totalModulus(m + mode1Offset, midiNotesFrom.size());
mode2Index = totalModulus(m + rootIndexOffset + mode2Offset, midiNotesTo.size());
noteFrom = midiNotesFrom[mode1Index];
noteTo = midiNotesTo[mode2Index];
if (noteFrom > 0)
prevMap.setValue(noteFrom, noteTo);
}
return prevMap;
}
NoteMap ModeMapper::mapToMode1Period(const Mode& mode1, const Mode& mode2, Array<int> degreeMapIn)
{
// ensure degree map is the same size as Mode1 Period
if (degreeMapIn.size() != mode1.getScaleSize())
degreeMapIn = getModeToModePeriodMap(mode1, mode2);
int rootNoteFrom = mode1.getRootNote();
int rootNoteTo = mode2.getRootNote();
int rootNoteOffset = rootNoteTo - rootNoteFrom;
int degreeOffset = rootNoteTo - (ceil(rootNoteTo / (float) mode2.getScaleSize())) * degreeMapIn.size();
int midiOffset = (int)(ceil(rootNoteTo / (float) mode2.getScaleSize())) * mode2.getScaleSize() - rootNoteTo + rootNoteOffset;
//DBG("Degree Offset is " + String(degreeOffset));
//DBG("Midi Offset is " + String(midiOffset));
NoteMap mappingOut;
int mapIndex;
int periods;
int midiNote;
for (int m = 0; m < mappingOut.getSize(); m++)
{
mapIndex = m - degreeOffset;
if (mapIndex >= 0)
{
periods = mapIndex / degreeMapIn.size();
midiNote = degreeMapIn[mapIndex % degreeMapIn.size()] + periods * mode2.getScaleSize() - midiOffset;
}
else
midiNote = -1;
mappingOut.setValue(m, midiNote);
//if (m == rootNoteFrom)
// DBG("Root Note From (" + String(rootNoteFrom) + ") produces note " + String(mappingOut.getValue(rootNoteFrom)) + " and comapre that to the Root note to (" + String(rootNoteTo) + ")");
}
return mappingOut;
}
NoteMap ModeMapper::mapToMode1Scale(const Mode& mode1, const Mode& mode2, int mode2Order)
{
Array<int> mode2ModalNotes = mode2.getNotesOfOrder(mode2Order);
int mode1RootIndex = mode1.getRootNote();
int mode2RootIndex = mode2ModalNotes.indexOf(mode2.getRootNote());
int rootIndexOffset = mode2RootIndex - mode1RootIndex;
NoteMap mappingOut;
int degToAdd;
int mode2ModeIndex = 0;
for (int m = 0; m < mode1.getOrders().size(); m++)
{
mode2ModeIndex = m + rootIndexOffset;
if (mode2ModeIndex < 0)
{
degToAdd = mode2ModeIndex;
}
else if (mode2ModeIndex >= mode2ModalNotes.size())
{
degToAdd = 128;
}
else
{
degToAdd = mode2ModalNotes[mode2ModeIndex];
}
mappingOut.setValue(m, degToAdd);
//if (m == mode1.getRootNote())
// DBG("Root Note From (" + String(mode1.getRootNote()) + ") produces note " + String(mappingOut.getValue(mode1.getRootNote())) + " and comapre that to the Root note to (" + String(mode2.getRootNote()) + ")");
}
return mappingOut;
}
NoteMap ModeMapper::stdMidiToMode(const Mode& modeMapped, int rootNoteStd)
{
Mode meantone7_12(STD_TUNING_MODE_NODE);
if (modeMapped.getModeSize() == meantone7_12.getModeSize())
return mapToMode1Period(meantone7_12, modeMapped);
else
return mapFull(meantone7_12, modeMapped);
}
Array<int> ModeMapper::getModeToModePeriodMap(const Mode& mode1, const Mode& mode2)
{
Array<int> degreeMapOut;
Array<int> mode1Steps = mode1.getSteps();
Array<int> mode2Steps = mode2.getSteps();
int mode1ModeSize = mode1.getModeSize();
int mode2ModeSize = mode2.getModeSize();
int mode2ScaleIndex = 0;
int degToAdd;
int degSub;
float stepFraction;
float mode1Step;
float mode2Step;
for (int m1 = 0; m1 < mode2ModeSize; m1++)
{
mode1Step = mode1Steps[m1 % mode1ModeSize];
mode2Step = mode2Steps[m1];
degreeMapOut.add(mode2ScaleIndex);
for (int d1 = 1; d1 < mode1Step; d1++)
{
stepFraction = d1 / mode1Step;
// round up to the next mode degree
degSub = mode2Step;
// find closest degree
for (int d2 = 1; d2 < mode2Step; d2++)
{
if (abs(d2 / mode2Step - stepFraction) < abs(degSub / mode2Step - stepFraction))
degSub = d2;
}
// resulting degree is the sum of previous steps, plus the next closest sub degree within the modal step
degToAdd = mode2ScaleIndex + degSub;
degreeMapOut.add(degToAdd);
}
mode2ScaleIndex += mode2Step;
}
//DBGArray(degreeMapOut, "Mode1 -> Mode2 Scale Degrees");
return degreeMapOut;
}
Array<int> ModeMapper::getScaleToModePeriodMap(const Mode& mode1, const Mode& mode2)
{
Array<int> degreeMapOut;
Array<int> mode2Steps = mode2.getSteps();
int mode2ScaleIndex = 0;
for (int i = 0; i < mode2Steps.size(); i++)
{
degreeMapOut.add(mode2ScaleIndex);
mode2ScaleIndex += mode2Steps[i];
}
//DBGArray(degreeMapOut, "Mode1 -> Mode2 Scale Degrees");
return degreeMapOut;
}
Array<int> ModeMapper::degreeMapFullMode(const Mode& mode1, const Mode& mode2)
{
Array<int> degreeMapOut;
//DBG("Mode1 Root: " + String(mode1.getRootNote()) + "\tMode2Root: " + String(mode2.getRootNote()));
Array<int> mode1Steps = Mode::foldOrdersToSteps(mode1.getOrders());
Array<int> mode2Steps = Mode::foldOrdersToSteps(mode2.getOrders());
Array<int> mode1MidiNotes = Mode::sumArray(mode1Steps, 0, true);
Array<int> mode2MidiNotes = Mode::sumArray(mode2Steps, 0, true);
int mode1RootIndex = mode1MidiNotes.indexOf(mode1.getRootNote());
int mode2RootIndex = mode2MidiNotes.indexOf(mode2.getRootNote());
int rootIndexOffset = mode2RootIndex - mode1RootIndex;
//DBG("Mode1 Root Index: " + String(mode1RootIndex) + "\tMode2Root: " + String(mode2RootIndex));
//DBGArray(mode2MidiNotes, "Mode2 Midi Notes");
int mode2ScaleIndex = 0;
if (rootIndexOffset > 0)
{
mode2ScaleIndex = sumUpToIndex(mode2Steps, rootIndexOffset);
}
int degToAdd, degSub;
float stepFraction;
float mode1Step, mode2Step;
int mode2ModeIndex = 0;
for (int m = 0; m < mode1Steps.size(); m++)
{
mode2ModeIndex = m + rootIndexOffset;
// this is assuming that the order will always start at 0
mode1Step = mode1Steps[m];
if (mode2ModeIndex < 0)
{
mode2Step = 0;
degToAdd = mode2ModeIndex;
}
else if (mode2ModeIndex >= mode2Steps.size())
{
mode2Step = 0;
degToAdd = 128;
}
else
{
mode2Step = mode2Steps[mode2ModeIndex];
degToAdd = mode2ScaleIndex;
}
degreeMapOut.add(degToAdd);
for (int d1 = 1; d1 < mode1Step; d1++)
{
stepFraction = d1 / mode1Step;
// round up to the next mode degree
degSub = mode2Step;
// find closest degree
for (int d2 = 1; d2 < mode2Step; d2++)
{
if (abs(d2 / mode2Step - stepFraction) < abs(degSub / mode2Step - stepFraction))
degSub = d2;
}
// resulting degree is the sum of previous steps, plus the next closest sub degree within the modal step
degToAdd = mode2ScaleIndex + degSub;
if (mode2ModeIndex < 0)
degreeMapOut.add(mode2ModeIndex);
else
degreeMapOut.add(degToAdd);
}
mode2ScaleIndex += mode2Step;
}
return degreeMapOut;
}
| 29.106776
| 220
| 0.621869
|
vsicurella
|
d18dfda5a300940a36a693815729262068d573ec
| 519
|
cpp
|
C++
|
golang/guess_number_higher_or_lower/guess_number_higher_or_lower.cpp
|
Hubstation/100challenges
|
68189cde28cadc91bcabe2d12a68703ce913099f
|
[
"MIT"
] | 43
|
2020-08-30T18:12:35.000Z
|
2022-03-08T05:03:05.000Z
|
golang/guess_number_higher_or_lower/guess_number_higher_or_lower.cpp
|
sangam14/challenges
|
d71cbb3960bc3adb43311959ca5694c1de63401c
|
[
"MIT"
] | 15
|
2020-08-30T18:12:24.000Z
|
2020-10-08T17:02:50.000Z
|
golang/guess_number_higher_or_lower/guess_number_higher_or_lower.cpp
|
sangam14/challenges
|
d71cbb3960bc3adb43311959ca5694c1de63401c
|
[
"MIT"
] | 24
|
2020-08-31T15:07:24.000Z
|
2021-02-28T09:56:46.000Z
|
// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);
class Solution {
public:
int guessNumber(int n) {
int left = 1, right = n;
int mid;
while (left <= right) {
mid = left + (right-left)/2;
cout << mid << endl;
if (guess(mid) == 0) break;
else if (guess(mid) > 0) left = mid+1;
else right = mid-1;
}
return mid;
}
};
| 25.95
| 81
| 0.535645
|
Hubstation
|
d19131e69731fa7a7bc8d6efc64169f17569cc7a
| 445
|
cpp
|
C++
|
oclint-rules/lib/util/StdUtil.cpp
|
BGU-AiDnD/oclint
|
484fed44ca0e34532745b3d4f04124cbf5bb42fa
|
[
"BSD-3-Clause"
] | 3,128
|
2015-01-01T06:00:31.000Z
|
2022-03-29T23:43:20.000Z
|
oclint-rules/lib/util/StdUtil.cpp
|
BGU-AiDnD/oclint
|
484fed44ca0e34532745b3d4f04124cbf5bb42fa
|
[
"BSD-3-Clause"
] | 432
|
2015-01-03T15:43:08.000Z
|
2022-03-29T02:32:48.000Z
|
oclint-rules/lib/util/StdUtil.cpp
|
BGU-AiDnD/oclint
|
484fed44ca0e34532745b3d4f04124cbf5bb42fa
|
[
"BSD-3-Clause"
] | 454
|
2015-01-06T03:11:12.000Z
|
2022-03-22T05:49:38.000Z
|
#include "oclint/util/StdUtil.h"
#include <algorithm>
bool isUnderscore(char aChar) {
return aChar == '_';
}
std::string removeUnderscores(std::string str) {
str.erase(remove_if(str.begin(), str.end(), &::isUnderscore), str.end());
return str;
}
std::string capitalizeFirstLetter(std::string str) {
if(str.length() > 0) {
std::transform(str.begin(), str.begin() + 1, str.begin(), ::toupper);
}
return str;
}
| 21.190476
| 77
| 0.631461
|
BGU-AiDnD
|
d19c8a04153b320011d0028c51e948cd0d6faf8c
| 2,575
|
hpp
|
C++
|
modules/core/base/include/nt2/predicates/functions/scalar/isequaln.hpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | 34
|
2017-05-19T18:10:17.000Z
|
2022-01-04T02:18:13.000Z
|
modules/core/base/include/nt2/predicates/functions/scalar/isequaln.hpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | null | null | null |
modules/core/base/include/nt2/predicates/functions/scalar/isequaln.hpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | 7
|
2017-12-02T12:59:17.000Z
|
2021-07-31T12:46:14.000Z
|
//==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_PREDICATES_FUNCTIONS_SCALAR_ISEQUALN_HPP_INCLUDED
#define NT2_PREDICATES_FUNCTIONS_SCALAR_ISEQUALN_HPP_INCLUDED
#include <nt2/predicates/functions/isequaln.hpp>
#include <nt2/include/functions/is_equal_with_equal_nans.hpp>
#include <boost/simd/include/functions/all.hpp>
namespace nt2 { namespace ext
{
BOOST_DISPATCH_IMPLEMENT ( isequaln_, tag::cpu_
, (A0)
, (scalar_<unspecified_<A0> >)
(scalar_<unspecified_<A0> >)
)
{
typedef bool result_type;
BOOST_FORCEINLINE
result_type operator()(const A0& a0, const A0& a1) const
{
return is_equal_with_equal_nans(a0,a1);
}
};
BOOST_DISPATCH_IMPLEMENT ( isequaln_, tag::cpu_
, (A0)(A1)
, (unspecified_<A0>)
(unspecified_<A1>)
)
{
typedef bool result_type;
BOOST_FORCEINLINE
result_type operator()(const A0& a0, const A1& a1) const
{
return a0 == a1;
}
};
BOOST_DISPATCH_IMPLEMENT ( isequaln_, tag::cpu_
, (A0)(A1)(X)
, ((simd_< unspecified_<A0>, X>))
((simd_< unspecified_<A1>, X>))
)
{
typedef bool result_type;
BOOST_FORCEINLINE
result_type operator()(const A0& a0, const A1& a1) const
{
return boost::simd::all(is_equal_with_equal_nans(a0, a1));
}
};
BOOST_DISPATCH_IMPLEMENT ( isequaln_, tag::cpu_
, (A0)(A1)(X)(T0)(N0)(T1)(N1)
, ((expr_< simd_< unspecified_<A0>, X>, T0, N0>))
((expr_< simd_< unspecified_<A1>, X>, T1, N1>))
)
{
typedef bool result_type;
BOOST_FORCEINLINE
result_type operator()(const A0& a0, const A1& a1) const
{
return boost::simd::all(is_equal_with_equal_nans(a0, a1))();
}
};
} }
#endif
| 32.1875
| 80
| 0.503689
|
psiha
|
d19d1daa41c2ed4687505e33e53667bf6024f8a9
| 416
|
cpp
|
C++
|
p1918_1.cpp
|
Alex-Amber/LuoguAlgorithmProblems
|
ae8abdb6110badc9faf03af1af42ea562ca1170c
|
[
"MIT"
] | null | null | null |
p1918_1.cpp
|
Alex-Amber/LuoguAlgorithmProblems
|
ae8abdb6110badc9faf03af1af42ea562ca1170c
|
[
"MIT"
] | null | null | null |
p1918_1.cpp
|
Alex-Amber/LuoguAlgorithmProblems
|
ae8abdb6110badc9faf03af1af42ea562ca1170c
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
unordered_map<int, int> um;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int N;
cin >> N;
for (int i = 1; i <= N; i++) {
int a;
cin >> a;
um[a] = i;
}
int Q;
cin >> Q;
while (Q) {
Q--;
int m;
cin >> m;
cout << (um.count(m) ? um[m] : 0) << "\n";
}
return 0;
}
| 16
| 50
| 0.40625
|
Alex-Amber
|
d1aef86ac4f6edd736f8f5c751f8ff3a63dc34e2
| 1,845
|
cpp
|
C++
|
util_file.cpp
|
blu/hello-chromeos-gles2
|
6ab863b734e053eef3b0185d17951353a49db359
|
[
"MIT"
] | 3
|
2018-09-03T20:55:24.000Z
|
2020-10-04T04:36:30.000Z
|
util_file.cpp
|
blu/hello-chromeos-gles2
|
6ab863b734e053eef3b0185d17951353a49db359
|
[
"MIT"
] | 4
|
2018-09-06T04:12:41.000Z
|
2020-10-06T14:43:14.000Z
|
util_file.cpp
|
blu/hello-chromeos-gles2
|
6ab863b734e053eef3b0185d17951353a49db359
|
[
"MIT"
] | null | null | null |
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "scoped.hpp"
#include "util_file.hpp"
namespace util {
template < typename T >
class generic_free
{
public:
void operator()(T* arg)
{
free(arg);
}
};
template <>
class scoped_functor< FILE >
{
public:
void operator()(FILE* arg)
{
fclose(arg);
}
};
bool get_file_size(
const char* const filename,
size_t& size)
{
assert(0 != filename);
struct stat filestat;
if (-1 == stat(filename, &filestat)) {
fprintf(stderr, "%s cannot stat file '%s'\n", __FUNCTION__, filename);
return false;
}
if (!S_ISREG(filestat.st_mode)) {
fprintf(stderr, "%s encountered a non-regular file '%s'\n", __FUNCTION__, filename);
return false;
}
size = filestat.st_size;
return true;
}
char* get_buffer_from_file(
const char* const filename,
size_t& size,
const size_t roundToIntegralMultiple)
{
assert(0 != filename);
assert(0 == (roundToIntegralMultiple & roundToIntegralMultiple - 1));
if (!get_file_size(filename, size)) {
fprintf(stderr, "%s cannot get size of file '%s'\n", __FUNCTION__, filename);
return 0;
}
const scoped_ptr< FILE, scoped_functor > file(fopen(filename, "rb"));
if (0 == file()) {
fprintf(stderr, "%s cannot open file '%s'\n", __FUNCTION__, filename);
return 0;
}
const size_t roundTo = roundToIntegralMultiple - 1;
scoped_ptr< char, generic_free > source(
reinterpret_cast< char* >(malloc((size + roundTo) & ~roundTo)));
if (0 == source()) {
fprintf(stderr, "%s cannot allocate memory for file '%s'\n", __FUNCTION__, filename);
return 0;
}
if (1 != fread(source(), size, 1, file())) {
fprintf(stderr, "%s cannot read from file '%s'\n", __FUNCTION__, filename);
return 0;
}
char* const ret = source();
source.reset();
return ret;
}
} // namespace util
| 19.62766
| 87
| 0.669919
|
blu
|
d1af1a5e3aced8e32979c69a0efe799f4aa4d042
| 31
|
hpp
|
C++
|
src/boost_units_pow.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_units_pow.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_units_pow.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/units/pow.hpp>
| 15.5
| 30
| 0.741935
|
miathedev
|
d1b9533804319bacf4c4605fe212b515b0d9d8da
| 824
|
hpp
|
C++
|
libs/fnd/cmath/include/bksge/fnd/cmath/is_negative.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 4
|
2018-06-10T13:35:32.000Z
|
2021-06-03T14:27:41.000Z
|
libs/fnd/cmath/include/bksge/fnd/cmath/is_negative.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 566
|
2017-01-31T05:36:09.000Z
|
2022-02-09T05:04:37.000Z
|
libs/fnd/cmath/include/bksge/fnd/cmath/is_negative.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 1
|
2018-07-05T04:40:53.000Z
|
2018-07-05T04:40:53.000Z
|
/**
* @file is_negative.hpp
*
* @brief is_negative 関数の定義
*
* @author myoukaku
*/
#ifndef BKSGE_FND_CMATH_IS_NEGATIVE_HPP
#define BKSGE_FND_CMATH_IS_NEGATIVE_HPP
#include <bksge/fnd/cmath/detail/is_negative_impl.hpp>
#include <bksge/fnd/concepts/arithmetic.hpp>
#include <bksge/fnd/concepts/detail/require.hpp>
#include <bksge/fnd/config.hpp>
namespace bksge
{
/**
* @brief 負の値かどうか調べる
*
* @tparam Arithmetic 算術型
*
* @param x 調べる値
*
* @return x < 0 ならtrue,そうでないならならfalse.
*
* x が 0 の場合、falseを返す。
* x が NaN の場合、falseを返す。
*/
template <BKSGE_REQUIRES_PARAM(bksge::arithmetic, Arithmetic)>
inline BKSGE_CONSTEXPR bool
is_negative(Arithmetic x) BKSGE_NOEXCEPT
{
return detail::is_negative_impl(x);
}
} // namespace bksge
#endif // BKSGE_FND_CMATH_IS_NEGATIVE_HPP
| 19.619048
| 63
| 0.703883
|
myoukaku
|
d1bad56dc0c7b3921031748396f21510c7980f94
| 5,139
|
hh
|
C++
|
include/seastar/util/std-compat.hh
|
elazarl/seastar
|
a79d4b337a5229b4ba4a1613a6436627ed67b03d
|
[
"Apache-2.0"
] | 6
|
2020-03-23T03:22:58.000Z
|
2021-05-12T11:42:16.000Z
|
include/seastar/util/std-compat.hh
|
elazarl/seastar
|
a79d4b337a5229b4ba4a1613a6436627ed67b03d
|
[
"Apache-2.0"
] | null | null | null |
include/seastar/util/std-compat.hh
|
elazarl/seastar
|
a79d4b337a5229b4ba4a1613a6436627ed67b03d
|
[
"Apache-2.0"
] | 1
|
2021-06-17T10:14:17.000Z
|
2021-06-17T10:14:17.000Z
|
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2018 ScyllaDB
*/
#pragma once
#ifdef SEASTAR_USE_STD_OPTIONAL_VARIANT_STRINGVIEW
#include <optional>
#include <string_view>
#include <variant>
#else
#include <experimental/optional>
#include <experimental/string_view>
#include <boost/variant.hpp>
#endif
#if __cplusplus >= 201703L && __has_include(<filesystem>)
#include <filesystem>
#else
#include <experimental/filesystem>
#endif
namespace seastar {
/// \cond internal
namespace compat {
#ifdef SEASTAR_USE_STD_OPTIONAL_VARIANT_STRINGVIEW
template <typename T>
using optional = std::optional<T>;
using nullopt_t = std::nullopt_t;
inline constexpr auto nullopt = std::nullopt;
template <typename T>
inline constexpr optional<std::decay_t<T>> make_optional(T&& value) {
return std::make_optional(std::forward<T>(value));
}
template <typename CharT, typename Traits = std::char_traits<CharT>>
using basic_string_view = std::basic_string_view<CharT, Traits>;
template <typename CharT, typename Traits = std::char_traits<CharT>>
std::string string_view_to_string(const basic_string_view<CharT, Traits>& v) {
return std::string(v);
}
template <typename... Types>
using variant = std::variant<Types...>;
template <std::size_t I, typename... Types>
constexpr std::variant_alternative_t<I, variant<Types...>>& get(variant<Types...>& v) {
return std::get<I>(v);
}
template <std::size_t I, typename... Types>
constexpr const std::variant_alternative_t<I, variant<Types...>>& get(const variant<Types...>& v) {
return std::get<I>(v);
}
template <std::size_t I, typename... Types>
constexpr std::variant_alternative_t<I, variant<Types...>>&& get(variant<Types...>&& v) {
return std::get<I>(v);
}
template <std::size_t I, typename... Types>
constexpr const std::variant_alternative_t<I, variant<Types...>>&& get(const variant<Types...>&& v) {
return std::get<I>(v);
}
template <typename U, typename... Types>
constexpr U& get(variant<Types...>& v) {
return std::get<U>(v);
}
template <typename U, typename... Types>
constexpr const U& get(const variant<Types...>& v) {
return std::get<U>(v);
}
template <typename U, typename... Types>
constexpr U&& get(variant<Types...>&& v) {
return std::get<U>(v);
}
template <typename U, typename... Types>
constexpr const U&& get(const variant<Types...>&& v) {
return std::get<U>(v);
}
template <typename U, typename... Types>
constexpr U* get_if(variant<Types...>* v) {
return std::get_if<U>(v);
}
template <typename U, typename... Types>
constexpr const U* get_if(const variant<Types...>* v) {
return std::get_if<U>(v);
}
#else
template <typename T>
using optional = std::experimental::optional<T>;
using nullopt_t = std::experimental::nullopt_t;
constexpr auto nullopt = std::experimental::nullopt;
template <typename T>
inline constexpr optional<std::decay_t<T>> make_optional(T&& value) {
return std::experimental::make_optional(std::forward<T>(value));
}
template <typename CharT, typename Traits = std::char_traits<CharT>>
using basic_string_view = std::experimental::basic_string_view<CharT, Traits>;
template <typename CharT, typename Traits = std::char_traits<CharT>>
std::string string_view_to_string(const basic_string_view<CharT, Traits>& v) {
return v.to_string();
}
template <typename... Types>
using variant = boost::variant<Types...>;
template<typename U, typename... Types>
U& get(variant<Types...>& v) {
return boost::get<U, Types...>(v);
}
template<typename U, typename... Types>
U&& get(variant<Types...>&& v) {
return boost::get<U, Types...>(v);
}
template<typename U, typename... Types>
const U& get(const variant<Types...>& v) {
return boost::get<U, Types...>(v);
}
template<typename U, typename... Types>
const U&& get(const variant<Types...>&& v) {
return boost::get<U, Types...>(v);
}
template<typename U, typename... Types>
U* get_if(variant<Types...>* v) {
return boost::get<U, Types...>(v);
}
template<typename U, typename... Types>
const U* get_if(const variant<Types...>* v) {
return boost::get<U, Types...>(v);
}
#endif
#if defined(__cpp_lib_filesystem)
namespace filesystem = std::filesystem;
#elif defined(__cpp_lib_experimental_filesystem)
namespace filesystem = std::experimental::filesystem;
#else
#error No filesystem header detected.
#endif
using string_view = basic_string_view<char>;
} // namespace compat
/// \endcond
} // namespace seastar
| 26.626943
| 101
| 0.70792
|
elazarl
|
d1bbc53a1160a3a001ca9b527334240a5478f9a4
| 2,802
|
cpp
|
C++
|
src/handler/list.cpp
|
npolar/reshp
|
6389f48a1bd745c2c0e9ef485bf6d163d73416a3
|
[
"MIT"
] | null | null | null |
src/handler/list.cpp
|
npolar/reshp
|
6389f48a1bd745c2c0e9ef485bf6d163d73416a3
|
[
"MIT"
] | 1
|
2015-01-13T10:15:56.000Z
|
2015-01-13T10:15:56.000Z
|
src/handler/list.cpp
|
npolar/reshp
|
6389f48a1bd745c2c0e9ef485bf6d163d73416a3
|
[
"MIT"
] | null | null | null |
/* * * * * * * * * * * * *\
|* ╔═╗ v0.4 *|
|* ╔═╦═╦═══╦═══╣ ╚═╦═╦═╗ *|
|* ║ ╔═╣ '╔╬═╗╚╣ ║ ║ '║ *|
|* ╚═╝ ╚═══╩═══╩═╩═╣ ╔═╝ *|
|* * * * * * * * * ╚═╝ * *|
|* Manipulation tool for *|
|* ESRI Shapefiles *|
|* * * * * * * * * * * * *|
|* http://www.npolar.no/ *|
\* * * * * * * * * * * * */
#include "../handler.hpp"
#include "../polygon.hpp"
#include <vector>
namespace reshp
{
void handler::list(const std::string& shapefile, const bool full)
{
reshp::shp shp;
if(!shp.load(shapefile))
return;
printf("Filename: %s\n", shapefile.c_str());
printf("Version: %i\n", shp.header.version);
printf("Type: %s\n", shp::typestr(shp.header.type));
printf("Bounding: [%.4f, %.4f] [%.4f, %.4f]\n", shp.header.box[0], shp.header.box[1], shp.header.box[2], shp.header.box[3]);
printf("Records: %lu\n\n", shp.records.size());
for(unsigned i = 0; i < shp.records.size(); ++i)
{
const char* type = shp::typestr(shp.records[i].type);
printf(" record %05i (%s)", shp.records[i].number, type);
if(shp.records[i].polygon)
{
reshp::polygon poly(*shp.records[i].polygon);
unsigned rings = poly.rings.size();
unsigned points = 0;
for(unsigned r = 0; r < rings; ++r)
points += poly.rings[r].segments.size();
if(full)
{
printf(": %i point%c", points, (points == 1 ? ' ' : 's'));
printf(", %i ring%c\n", rings, (rings == 1 ? ' ' : 's'));
for(unsigned r = 0; r < poly.rings.size(); ++r)
{
printf(" ring %i (%s, %lu segments):\n", r, (poly.rings[r].type == reshp::polygon::ring::inner ? "inner" : "outer"), poly.rings[r].segments.size());
for(unsigned s = 0; s < poly.rings[r].segments.size(); ++s)
{
printf(" [%8.4f, %8.4f] -> [%8.4f, %8.4f]\n", poly.rings[r].segments[s].start.x, poly.rings[r].segments[s].start.y, poly.rings[r].segments[s].end.x, poly.rings[r].segments[s].end.y);
}
}
}
else
{
printf(":%*s%5i point%c", int(13 - strlen(type)), " ", points, (points == 1 ? ' ' : 's'));
printf(", %5i ring%c\n", rings, (rings == 1 ? ' ' : 's'));
}
}
else printf("\n");
} // records
} // handler::list()
} // namespace reshp
| 38.916667
| 215
| 0.390079
|
npolar
|
d1bfa1f4463cb16e84bb1b2a8c7f2058dbcaf576
| 207
|
cpp
|
C++
|
src/player.cpp
|
warlord500/space_invaders2
|
71d5acc30f95352b325ada61cb9b1389c9732961
|
[
"MIT"
] | null | null | null |
src/player.cpp
|
warlord500/space_invaders2
|
71d5acc30f95352b325ada61cb9b1389c9732961
|
[
"MIT"
] | 1
|
2015-05-29T04:49:09.000Z
|
2015-05-29T04:49:09.000Z
|
src/player.cpp
|
warlord500/space_invaders2
|
71d5acc30f95352b325ada61cb9b1389c9732961
|
[
"MIT"
] | null | null | null |
#include "player.h"
player::player(int lives,const sf::Texture& texture,const sf::Vector2f& pos) : sprite(texture),
lives(lives)
{
this->sprite.setPosition(pos);
}
player::~player()
{
//dtor
}
| 15.923077
| 95
| 0.657005
|
warlord500
|
d1c04c48d1e548478df18de8485b93004cf294d0
| 533
|
cpp
|
C++
|
recursion/pailndrome.cpp
|
AyushVerma-code/DSA-in-C-
|
4694ad771a1cff8dd81cb127887804d7c67fcb83
|
[
"MIT"
] | 1
|
2021-06-01T03:20:42.000Z
|
2021-06-01T03:20:42.000Z
|
recursion/pailndrome.cpp
|
AyushVerma-code/DSA-in-C-
|
4694ad771a1cff8dd81cb127887804d7c67fcb83
|
[
"MIT"
] | null | null | null |
recursion/pailndrome.cpp
|
AyushVerma-code/DSA-in-C-
|
4694ad771a1cff8dd81cb127887804d7c67fcb83
|
[
"MIT"
] | null | null | null |
bool checkPalindrome(char input[])
{
bool check =1;
int c;
for(int i=0;input[i]!='\0';i++)
{
c=c+1;
}
int arr[100];
for(int i=0;i<c;i++)
{
arr[i]=input[i];
}
for(int i=0;i<c;i++)
{
if(arr[i]!=arr[c-1-i])
{
check=0;
break;
}
}
if(check)
return 1;
else
return 0;
}
| 18.37931
| 39
| 0.281426
|
AyushVerma-code
|
d1c2db20771197a50b5e506ad1f77be20d10b5fc
| 697
|
cpp
|
C++
|
uri/beginner/sum_of_consecutive_odd_numbers_2.cpp
|
Rkhoiwal/Competitive-prog-Archive
|
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
|
[
"MIT"
] | 1
|
2020-07-16T01:46:38.000Z
|
2020-07-16T01:46:38.000Z
|
uri/beginner/sum_of_consecutive_odd_numbers_2.cpp
|
Rkhoiwal/Competitive-prog-Archive
|
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
|
[
"MIT"
] | null | null | null |
uri/beginner/sum_of_consecutive_odd_numbers_2.cpp
|
Rkhoiwal/Competitive-prog-Archive
|
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
|
[
"MIT"
] | 1
|
2020-05-27T14:30:43.000Z
|
2020-05-27T14:30:43.000Z
|
#include <iostream>
#include <utility>
using namespace std;
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
unsigned int test_cases;
cin >> test_cases;
for (unsigned int i {0}; i < test_cases; ++i)
{
int lower;
int upper;
cin >> lower >> upper;
if (lower > upper)
{
swap(lower, upper);
}
if (lower % 2)
{
++lower;
}
int sum {0};
for (int i {lower + 1}; i < upper; i += 2)
{
sum += i;
}
cout << sum << '\n';
}
return 0;
}
| 14.22449
| 50
| 0.460545
|
Rkhoiwal
|
d1c5ac82de2e5da13eeca1b4598d12470b6f2ed3
| 3,636
|
cpp
|
C++
|
TA.NexDome.Rotator/HomeSensor.cpp
|
morzineIT/DomeProjectESP8266
|
c18ff2ee27ad3b38ce1bcc271369438f830eafd7
|
[
"MIT"
] | 3
|
2019-08-27T02:11:00.000Z
|
2021-01-16T16:31:52.000Z
|
TA.NexDome.Rotator/HomeSensor.cpp
|
thegrapesofwrath/Firmware
|
162cc2cdf081e26d0d6f3235b953f99edf01a982
|
[
"MIT"
] | 41
|
2019-08-28T21:32:18.000Z
|
2022-03-02T13:42:19.000Z
|
TA.NexDome.Rotator/HomeSensor.cpp
|
thegrapesofwrath/Firmware
|
162cc2cdf081e26d0d6f3235b953f99edf01a982
|
[
"MIT"
] | 4
|
2020-03-18T16:06:17.000Z
|
2021-06-15T04:29:42.000Z
|
/*
* Provides interrupt processing for the home sensor.
*
* The home sensor synchronizes the dome rotation step position when it is triggered.
* When rotating in the positive direction, we synchronise to the falling edge.
* When rotating in the negative direction, we synchronise to the rising edge.
* When not rotating, activity is ignored.
*
* Note: some fields have to be static because they are used during interrupts
*/
#include "NexDome.h"
#include "HomeSensor.h"
#pragma region static fields used within interrupt service routines
MicrosteppingMotor *HomeSensor::motor;
Home *HomeSensor::homeSettings;
uint8_t HomeSensor::sensorPin;
volatile HomingPhase HomeSensor::phase;
#pragma endregion
/*
* Creates a new HomeSensor instance.
* Note: sensorPin must correspond to a digital input pin that is valid for attaching interrupts.
* Not all pins on all platforms support attaching interrupts.
* Arduino Leonardo supports pins 0, 1, 2, 3, 7
*/
HomeSensor::HomeSensor(MicrosteppingMotor *stepper, Home *settings, const uint8_t sensorPin, CommandProcessor &processor)
: commandProcessor(processor)
{
motor = stepper;
HomeSensor::homeSettings = settings;
HomeSensor::sensorPin = sensorPin;
}
/*
* Triggered as an interrupt whenever the home sensor pin changes state.
* Synchronizes the current motor stop position to the calibrated home position.
*/
void HomeSensor::onHomeSensorChanged()
{
const auto state = digitalRead(sensorPin);
if (state == 0 && phase == Detecting)
foundHome();
}
/*
* Configures the hardware pin ready for use and attaches the interrupt.
*/
void HomeSensor::init()
{
pinMode(sensorPin, INPUT_PULLUP);
setPhase(Idle);
attachInterrupt(digitalPinToInterrupt(sensorPin), onHomeSensorChanged, CHANGE);
}
/// <summary>
/// Indicates whether the dome is currently in the home position
/// (only valid after a successful homing operation and before and slews occur)
/// </summary>
bool HomeSensor::atHome()
{
return phase == AtHome;
}
void HomeSensor::setPhase(HomingPhase newPhase)
{
phase = newPhase;
#ifdef DEBUG_HOME
std::cout << "Phase " << phase << std::endl;
#endif
}
/*
* Rotates up to 2 full rotations clockwise while attempting to detect the home sensor.
* Ignored if a homing operation is already in progress.
*/
void HomeSensor::findHome(int direction)
{
if (phase == Idle || phase == AtHome)
{
const auto distance = 2 * homeSettings->microstepsPerRotation; // Allow 2 full rotations only
setPhase(Detecting);
motor->moveToPosition(distance);
}
}
/*
* Stops a homing operation in progress.
*/
void HomeSensor::cancelHoming()
{
setPhase(Idle);
if (motor->isMoving())
motor->SoftStop();
}
/*
* Once the home sensor has been detected, we instruct the motor to soft-stop.
* We also set the flag performPostHomeSlew.
* At some point in the future, the onMotorStopped method will be called, which will
* then initiate the final slew to return exactly to the home sensor position.
*/
void HomeSensor::foundHome()
{
setPhase(Stopping);
motor->SetCurrentPosition(homeSettings->position);
motor->SoftStop();
}
/*
* Handles the onMotorStopped event. Action depends on the homing phase.
*/
void HomeSensor::onMotorStopped() const
{
#ifdef DEBUG_HOME
std::cout << "Hstop " << phase << std::endl;
#endif
if (phase == Reversing)
{
setPhase(AtHome);
return;
}
if (phase == Stopping)
{
setPhase(Reversing);
const auto target = commandProcessor.targetStepPosition(homeSettings->position);
motor->moveToPosition(target);
return;
}
setPhase(Idle);
}
bool HomeSensor::homingInProgress()
{
return !(phase == Idle || phase == AtHome);
}
| 26.347826
| 121
| 0.738999
|
morzineIT
|
d1c8c85928668b948689ab36bb95a7bca28b20b4
| 3,425
|
cpp
|
C++
|
src/main.cpp
|
Rocik/btree-file-index
|
04cb787c903a18e606b2f03f0cce345d879086f5
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
Rocik/btree-file-index
|
04cb787c903a18e606b2f03f0cce345d879086f5
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
Rocik/btree-file-index
|
04cb787c903a18e606b2f03f0cce345d879086f5
|
[
"MIT"
] | null | null | null |
#include <cstdlib>
#include <iostream>
#include "btree.h"
using namespace std;
static bool running = true;
static void printDiskStats() {
int reads = DiskFile::getStatReads();
int writes = DiskFile::getStatWrites();
char const* plurarReads = reads == 1 ? "" : "s";
char const* plurarWrites = writes == 1 ? "" : "s";
printf("[FILES] %d read%s and %d write%s\n",
reads, plurarReads,
writes, plurarWrites);
DiskFile::resetStats();
}
static void loadCommands(istream& stream, BTree& btree);
static void loadTestFile(const char* filename, BTree& btree) {
fstream stream(filename, ios_base::in);
loadCommands(stream, btree);
}
static void loadCommands(istream& stream, BTree& btree) {
int key, value;
string str;
if (!running)
return;
char c;
do {
stream >> c;
if (stream.eof())
return;
switch (c) {
// Read more commands from file
// <filename:string>
case 'f': {
stream >> str;
loadTestFile(str.c_str(), btree);
break;
}
// Inserting record
// <key:int> <value:int>
case 'w': {
stream >> key;
stream >> value;
if (key <= 0) {
printf("[INSERT] Key %d is incorrect, must be a Natural number", key);
break;
}
if (value <= 0) {
printf("[INSERT] Value %d is incorrect, must be a Natural number", value);
break;
}
Record record(key, value);
if (btree.insert(record))
printf("[INSERT] Key %d with value %d\n", key, value);
else
printf("[INSERT] Key %d could not be inserted, it exists\n", key);
break;
}
// Reading record
// <key:int>
case 'o': {
stream >> key;
if (key <= 0) {
printf("[READ] Key %d is incorrect, must be a Natural number", key);
break;
}
shared_ptr<Record> record;
if (btree.read(key, &record))
printf("[READ] Found key %d with value %d\n",
key, record->getValue());
else
printf("[READ] Key %d was not found\n", key);
break;
}
// Updating record
// <key:int> <value:int>
case 'a': {
stream >> key;
stream >> value;
if (key <= 0) {
printf("[UPDATE] Key %d is incorrect, must be a Natural number", key);
break;
}
if (value <= 0) {
printf("[UPDATE] Value %d is incorrect, must be a Natural number", value);
break;
}
Record record(key, value);
if (btree.update(record))
printf("[UPDATE] Key %d with value %d\n", key, value);
else
printf("[UPDATE] Key %d could not be updated, not found\n", key);
break;
}
// Deleting record
// <key:int>
case 'u': {
stream >> key;
if (key <= 0) {
printf("[DELETE] Key %d is incorrect, must be a Natural number", key);
break;
}
if (btree.remove(key))
printf("[DELETE] Key %d\n", key);
else
printf("[DELETE] Key %d could not be deleted, not found\n", key);
break;
}
// Viewing whole file and index sorted by key value
case 'p': {
btree.printInKeyOrder();
break;
}
// Do not save to files and remove any
case 'd': {
btree.dispose();
continue;
}
case 'q':
running = false;
return;
default:
printf("[ERROR] Unknown command: %c (%d)\n", c, c);
break;
}
if (stream.eof())
return;
printDiskStats();
} while (running && c != 0);
}
int main() {
string name = string("sample");
BTree tree(name, 3);
//loadTestFile("test_commands.txt", tree);
loadCommands(cin, tree);
return 0;
}
| 19.241573
| 78
| 0.585109
|
Rocik
|
d1c9774c9ec0af6b432f98e28d681408c664d91e
| 1,430
|
hpp
|
C++
|
src/converter_omerc.hpp
|
barendgehrels/tissot
|
b0d983a57bcd4d283c0f4ef8d23abea2e2893c3f
|
[
"BSL-1.0"
] | 1
|
2015-05-17T11:15:43.000Z
|
2015-05-17T11:15:43.000Z
|
src/converter_omerc.hpp
|
barendgehrels/tissot
|
b0d983a57bcd4d283c0f4ef8d23abea2e2893c3f
|
[
"BSL-1.0"
] | null | null | null |
src/converter_omerc.hpp
|
barendgehrels/tissot
|
b0d983a57bcd4d283c0f4ef8d23abea2e2893c3f
|
[
"BSL-1.0"
] | null | null | null |
#ifndef TISSOT_CONVERTER_OMERC_HPP
#define TISSOT_CONVERTER_OMERC_HPP
// Tissot, converts projecton source code (Proj4) to Boost.Geometry
// (or potentially other source code)
//
// Copyright (c) 2015 Barend Gehrels, Amsterdam, the Netherlands.
//
// Use, modification and distribution is subject to 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 "tissot_structs.hpp"
#include "tissot_util.hpp"
#include "converter_base.hpp"
namespace boost { namespace geometry { namespace proj4converter
{
class converter_cpp_bg_omerc : public converter_cpp_bg_default
{
public :
converter_cpp_bg_omerc(projection_properties& prop)
: m_prop(prop)
{
}
void convert()
{
// Initialize variable (for gcc warning)
// (actually there are many more uninitialized - we should possibly
// initialize all of them, TODO)
BOOST_FOREACH(derived& der, m_prop.derived_projections)
{
BOOST_FOREACH(std::string& line, der.constructor_lines)
{
boost::replace_all(line, ", alpha_c;", ", alpha_c=0.0;");
}
}
}
private :
projection_properties& m_prop;
};
}}} // namespace boost::geometry::proj4converter
#endif // TISSOT_CONVERTER_OMERC_HPP
| 26.981132
| 79
| 0.65035
|
barendgehrels
|
d1cd2c3833c6c157b12421690df1a2082416f76a
| 2,779
|
cpp
|
C++
|
clever_algorithms/demos/compact_genetic_algorithm.cpp
|
GreatV/CleverAlgorithms
|
4cda9e3469a6076128dfbbb62c6f82d3a1f12746
|
[
"MIT"
] | 2
|
2021-11-08T00:26:09.000Z
|
2021-12-21T08:16:43.000Z
|
clever_algorithms/demos/compact_genetic_algorithm.cpp
|
GreatV/CleverAlgorithms
|
4cda9e3469a6076128dfbbb62c6f82d3a1f12746
|
[
"MIT"
] | null | null | null |
clever_algorithms/demos/compact_genetic_algorithm.cpp
|
GreatV/CleverAlgorithms
|
4cda9e3469a6076128dfbbb62c6f82d3a1f12746
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <random>
#include <vector>
#include <string>
#include <algorithm>
#include <cfloat>
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_real_distribution<> distribution(0.0, 1.0);
auto random_ = []() { return distribution(generator); };
using candidate_solution = struct candidate_solution_st
{
std::string bit_string;
double fitness = DBL_MIN;
};
double onemax(const std::string& bit_string)
{
double sum = 0.0;
for (auto& item : bit_string)
{
if (item == '1')
{
sum++;
}
}
return sum;
}
void random_bit_string(std::string& bit_string, const size_t size)
{
bit_string.clear();
for (size_t i = 0; i < size; ++i)
{
bit_string.push_back(random_() < 0.5 ? '1' : '0');
}
}
void generate_candidate(candidate_solution& candidate, const std::vector<double>& vector)
{
candidate.bit_string.resize(vector.size());
for (size_t i = 0; i < vector.size(); ++i)
{
const auto& p = vector[i];
candidate.bit_string[i] = random_() < p ? '1' : '0';
}
candidate.fitness = onemax(candidate.bit_string);
}
void update_vector(std::vector<double>& vector,
const candidate_solution& winner,
const candidate_solution& loser,
const size_t pop_size)
{
for (size_t i = 0; i < vector.size(); ++i)
{
if (winner.bit_string[i] != loser.bit_string[i])
{
if (winner.bit_string[i] == '1')
{
vector[i] += 1.0 / pop_size;
}
else
{
vector[i] -= 1.0 / pop_size;
}
}
}
}
void search(candidate_solution& best,
const size_t num_bits,
const size_t max_iterations,
const size_t pop_size)
{
std::vector<double> vector(num_bits);
for (auto& v : vector)
{
v = 0.5;
}
for (size_t iter = 0; iter < max_iterations; ++iter)
{
candidate_solution c1, c2;
generate_candidate(c1, vector);
generate_candidate(c2, vector);
candidate_solution winner = c1.fitness > c2.fitness ? c1 : c2;
candidate_solution loser = c1.fitness > c2.fitness ? c2 : c1;
if (iter == 0)
{
best = winner;
}
if (winner.fitness > best.fitness)
{
best = winner;
}
update_vector(vector, winner, loser, pop_size);
std::cout << " > gen " << iter + 1 << ", f = "
<< best.fitness << ", b = "
<< best.bit_string << std::endl;
if (static_cast<size_t>(best.fitness) == num_bits)
{
break;
}
}
}
int main(int argc, char* argv[])
{
// problem configuration
const size_t num_bits = 32;
// algorithm configuration
const size_t max_iter = 200;
const size_t pop_size = 20;
// execute the algorithm
candidate_solution best;
search(best, num_bits, max_iter, pop_size);
std::cout << "Done! Solution: f = " << best.fitness;
std::cout << ", b = " << best.bit_string << std::endl;
return 0;
}
| 19.992806
| 89
| 0.627204
|
GreatV
|
d1cedcdd1430101a4631874c7807cefb6dae37d4
| 14,948
|
cpp
|
C++
|
main/pod_archiver.cpp
|
an-erd/blePOD
|
2f56763487b485b61d87e600e8b095702851b078
|
[
"MIT"
] | null | null | null |
main/pod_archiver.cpp
|
an-erd/blePOD
|
2f56763487b485b61d87e600e8b095702851b078
|
[
"MIT"
] | 2
|
2019-04-04T11:51:37.000Z
|
2019-04-04T11:52:20.000Z
|
main/pod_archiver.cpp
|
an-erd/blePOD
|
2f56763487b485b61d87e600e8b095702851b078
|
[
"MIT"
] | 1
|
2020-04-02T13:43:27.000Z
|
2020-04-02T13:43:27.000Z
|
#include <string.h>
#include "esp_vfs_fat.h"
#include "driver/sdmmc_host.h"
#include "driver/sdspi_host.h"
#include "sdmmc_cmd.h"
#include "pod_main.h"
static const char* TAG = "POD_ARCHIVER";
// data buffers to keep in RAM
// => CONFIG_SDCARD_NUM_BUFFERS=4 and CONFIG_SDCARD_BUFFER_SIZE=65536
static buffer_element_t buffers[CONFIG_SDCARD_NUM_BUFFERS][CONFIG_SDCARD_BUFFER_SIZE] EXT_RAM_ATTR;
static uint8_t current_buffer; // buffer to write next elements to
static uint32_t used_in_buffer[CONFIG_SDCARD_NUM_BUFFERS]; // position in resp. buffer
static uint8_t next_buffer_to_write; // next buffer to write to
static int s_ref_file_nr = -2;
static bool new_file = true;
EventGroupHandle_t pod_sd_evg;
// static archiver buffer event group
#define BUFFER_BLEADV_BIT (BIT0)
static EventGroupHandle_t buffer_evg;
// forward declaration
void pod_archiver_set_to_next_buffer();
static void clean_buffer(uint8_t num_buffer)
{
memset(buffers[num_buffer], 0, sizeof(buffers[num_buffer])+1);
used_in_buffer[num_buffer] = 0;
}
void pod_archiver_initialize()
{
buffer_evg = xEventGroupCreate();
for (int i = 0; i < CONFIG_SDCARD_NUM_BUFFERS; i++){
clean_buffer(i);
}
current_buffer = 0;
next_buffer_to_write = 0;
}
//TF card test begin
void listDir(fs::FS &fs, const char * dirname, uint8_t levels){
ESP_LOGD(TAG, "listDir() > , Listing directory: %s\n", dirname);
File root = fs.open(dirname);
if(!root){
ESP_LOGW(TAG, "listDir(), Failed to open directory");
return;
}
if(!root.isDirectory()){
ESP_LOGW(TAG, "listDir(), Not a directory");
return;
}
File file = root.openNextFile();
while(file){
if(file.isDirectory()){
ESP_LOGD(TAG, "listDir(), DIR: %s", file.name());
if(levels){
listDir(fs, file.name(), levels -1);
}
} else {
ESP_LOGD(TAG, "listDir(), FILE: %s, SIZE: %u", file.name(), file.size());
}
file = root.openNextFile();
}
ESP_LOGD(TAG, "listDir() <");
}
void readFile(fs::FS &fs, const char * path) {
ESP_LOGD(TAG, "readFile() >, Reading file: %s", path);
File file = fs.open(path);
if(!file){
ESP_LOGW(TAG, "readFile(), Failed to open file for reading");
return;
}
ESP_LOGD(TAG, "readFile(), Read from file: ");
while(file.available()){
int ch = file.read();
ESP_LOGD(TAG, "readFile(): %c", ch);
}
ESP_LOGD(TAG, "readFile() <");
}
void writeFile(fs::FS &fs, const char * path, const char * message){
ESP_LOGD(TAG, "writeFile() >, Writing file: %s", path);
File file = fs.open(path, FILE_WRITE);
if(!file){
ESP_LOGW(TAG, "writeFile(), Failed to open file for writing");
return;
}
if(file.print(message)){
ESP_LOGD(TAG, "writeFile() <, file written");
} else {
ESP_LOGE(TAG, "writeFile() <, write failed");
}
}
//TF card test end
static int read_sd_card_file_refnr()
{
// file handle and buffer to read
FILE* f;
char line[64];
int file_nr = -1;
struct stat st;
ESP_LOGD(TAG, "read_sd_card_file_refnr() >");
if (stat("/sd/refnr.txt", &st) == 0) {
f = fopen("/sd/refnr.txt", "r");
if (f == NULL) {
ESP_LOGE(TAG, "read_sd_card_file_refnr(): Failed to open file for reading");
return -1;
}
} else {
f = fopen("/sd/refnr.txt", "w");
if (f == NULL) {
ESP_LOGE(TAG, "read_sd_card_file_refnr(): Failed to open file for writing");
return -1;
}
fprintf(f, "0\n"); // start new file with (file_nr=) 0
fclose(f);
ESP_LOGD(TAG, "read_sd_card_file_refnr(): New file refnr.txt written");
f = fopen("/sd/refnr.txt", "r");
if (f == NULL) {
ESP_LOGE(TAG, "read_sd_card_file_refnr(): Failed to open file for reading (2)");
return -1;
}
}
fgets(line, sizeof(line), f);
fclose(f);
// strip newline
char* pos = strchr(line, '\n');
if (pos) {
*pos = '\0';
}
ESP_LOGD(TAG, "read_sd_card_file_refnr(): Read from file: '%s'", line);
sscanf(line, "%d", (int*)&file_nr);
s_ref_file_nr = file_nr;
ESP_LOGD(TAG, "read_sd_card_file_refnr() <, file_nr = %d", file_nr);
return file_nr;
}
static int write_sd_card_file_refnr(int new_refnr)
{
// file handle and buffer to read
FILE* f;
// char line[64];
struct stat st;
ESP_LOGD(TAG, "write_sd_card_file_refnr() >, new_refnr = %d", new_refnr);
if (stat("/sd/refnr.txt", &st) == 0) {
ESP_LOGD(TAG, "write_sd_card_file_refnr(), stat = 0");
f = fopen("/sd/refnr.txt", "w");
if (f == NULL) {
ESP_LOGE(TAG, "write_sd_card_file_refnr() <, Failed to open file for writing");
return -1;
}
fprintf(f, "%d\n", new_refnr);
fclose(f);
ESP_LOGD(TAG, "write_sd_card_file_refnr() <, File written");
}
return new_refnr;
}
int write_out_buffers(bool write_only_completed)
{
// file handle and buffer to read
FILE* f;
char line[64];
int file_nr;
char strftime_buf[64];
ESP_LOGD(TAG, "write_out_buffers() >");
// Read the last file number from file. If it does not exist, create a new and start with "0".
// If it exists, read the value and increase by 1.
file_nr = read_sd_card_file_refnr();
if(file_nr < 0)
ESP_LOGE(TAG, "write_out_buffers(): Ref. file could not be read or created - ABORT");
// generate a new reference number if requested and store in file for upcoming use
if(new_file){
file_nr++;
new_file = false;
write_sd_card_file_refnr(file_nr);
}
// generate new file name
sprintf(line, CONFIG_SDCARD_FILE_NAME, file_nr);
ESP_LOGD(TAG, "write_out_buffers(): generated file name '%s'", line);
f = fopen(line, "a");
if(f == NULL) {
f = fopen(line, "w");
if (f == NULL) {
ESP_LOGE(TAG, "write_out_buffers(): Failed to open file for writing");
return 0;
}
ESP_LOGD(TAG, "write_out_buffers(): Created new file for write");
} else {
ESP_LOGD(TAG, "write_out_buffers(): Opening file for append");
}
if(!write_only_completed){
// switch to next buffer to ensure no conflict of new incoming data
current_buffer = (current_buffer + 1) % CONFIG_SDCARD_NUM_BUFFERS;
used_in_buffer[current_buffer] = 0; // just to be sure
}
while( next_buffer_to_write != current_buffer ){
// write buffer next_buffer_to_write
// ESP_LOGD(TAG, "write_out_buffers(): write buffers[%u][0..%u]", next_buffer_to_write, used_in_buffer[next_buffer_to_write]);
// for(uint32_t i = 0; i < used_in_buffer[next_buffer_to_write]; i++){
// // check for timestamp: strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
// // TODO
// if(buffers[next_buffer_to_write][i].timeinfo.tm_year != 0){
// strftime(strftime_buf, sizeof(strftime_buf), "%c", &buffers[next_buffer_to_write][i].timeinfo);
// fprintf(f, "%u:%u,%s,%u,%u,%u\r\n", next_buffer_to_write, i, strftime_buf,
// buffers[next_buffer_to_write][i].cad, buffers[next_buffer_to_write][i].str, buffers[next_buffer_to_write][i].GCT);
// ESP_LOGD(TAG, "write_out_buffers(): Write: %u:%u,%s,%u,%u,%u\n", next_buffer_to_write, i, strftime_buf,
// buffers[next_buffer_to_write][i].cad, buffers[next_buffer_to_write][i].str, buffers[next_buffer_to_write][i].GCT);
// } else {
// fprintf(f, "%u:%u,,%u,%u,%u\r\n", next_buffer_to_write, i,
// buffers[next_buffer_to_write][i].cad, buffers[next_buffer_to_write][i].str, buffers[next_buffer_to_write][i].GCT);
// ESP_LOGD(TAG, "write_out_buffers(): Write: %u:%u,,,%u,%u,%u\n", next_buffer_to_write, i,
// buffers[next_buffer_to_write][i].cad, buffers[next_buffer_to_write][i].str, buffers[next_buffer_to_write][i].GCT);
// }
// }
clean_buffer(next_buffer_to_write);
next_buffer_to_write = (next_buffer_to_write + 1) % CONFIG_SDCARD_NUM_BUFFERS;
}
ESP_LOGD(TAG, "write_out_buffers(): Closing file");
fclose(f);
ESP_LOGD(TAG, "write_out_buffers() <");
return 1;
}
void pod_archiver_set_next_element()
{
// int complete = xEventGroupWaitBits(dispod_sd_evg, POD_SD_WRITE_COMPLETED_BUFFER_EVT, pdFALSE, pdFALSE, 0) & POD_SD_WRITE_COMPLETED_BUFFER_EVT;
// ESP_LOGD(TAG, "pod_archiver_set_next_element >: current_buffer %u, used in current buffer %u, size %u, complete %u",
// current_buffer, used_in_buffer[current_buffer], CONFIG_SDCARD_BUFFER_SIZE, complete);
used_in_buffer[current_buffer]++;
if(used_in_buffer[current_buffer] == CONFIG_SDCARD_BUFFER_SIZE){
pod_archiver_set_to_next_buffer();
}
// buffers[current_buffer][used_in_buffer[current_buffer]].timeinfo.tm_year = 0;
// buffers[current_buffer][used_in_buffer[current_buffer]].cad = 0;
// buffers[current_buffer][used_in_buffer[current_buffer]].GCT = 0;
// buffers[current_buffer][used_in_buffer[current_buffer]].str = 9; // TODO check, wheter this case happens?!
// complete = xEventGroupWaitBits(dispod_sd_evg, DISPOD_SD_WRITE_COMPLETED_BUFFER_EVT, pdFALSE, pdFALSE, 0) & DISPOD_SD_WRITE_COMPLETED_BUFFER_EVT;
// ESP_LOGD(TAG, "dispod_archiver_set_next_element <: current_buffer %u, used in current buffer %u, size %u, complete %u",
// current_buffer, used_in_buffer[current_buffer], CONFIG_SDCARD_BUFFER_SIZE, complete);
}
void pod_archiver_set_to_next_buffer()
{
ESP_LOGD(TAG, "pod_archiver_set_to_next_buffer >: current_buffer %u, used in current buffer %u ", current_buffer, used_in_buffer[current_buffer]);
if( used_in_buffer[current_buffer] != 0) {
// set to next (free) buffer and write (all and maybe incomplete) buffer but current
current_buffer = (current_buffer + 1) % CONFIG_SDCARD_NUM_BUFFERS;
used_in_buffer[current_buffer] = 0;
xEventGroupSetBits(pod_sd_evg, POD_SD_WRITE_COMPLETED_BUFFER_EVT);
} else {
// do nothing because current buffer is empty
ESP_LOGD(TAG, "pod_archiver_set_to_next_buffer: current_buffer empty, do nothing");
}
ESP_LOGD(TAG, "pod_archiver_set_to_next_buffer <: current_buffer %u, used in current buffer %u ", current_buffer, used_in_buffer[current_buffer]);
}
void pod_archiver_check_full_element()
{
EventBits_t uxBits;
// uxBits = xEventGroupWaitBits(buffer_evg, BUFFER_RSC_BIT | BUFFER_CUSTOM_BIT, pdTRUE, pdTRUE, 0);
// if( (uxBits & (BUFFER_RSC_BIT | BUFFER_CUSTOM_BIT) ) == (BUFFER_RSC_BIT | BUFFER_CUSTOM_BIT) ){
// pod_archiver_set_next_element();
// }
}
void dispod_archiver_add_bleadv_values(/* TODO */)
{
// buffers[current_buffer][used_in_buffer[current_buffer]].GCT = new_GCT;
// buffers[current_buffer][used_in_buffer[current_buffer]].str = new_str;
// xEventGroupSetBits(buffer_evg, BUFFER_CUSTOM_BIT);
pod_archiver_check_full_element();
}
void pod_archiver_add_time(tm timeinfo)
{
char strftime_buf[64];
buffers[current_buffer][used_in_buffer[current_buffer]].timeinfo = timeinfo;
strftime(strftime_buf, sizeof(strftime_buf), "%c", &buffers[current_buffer][used_in_buffer[current_buffer]].timeinfo);
ESP_LOGD(TAG, "pod_archiver_add_time(): TIME: %s", strftime_buf);
}
void pod_archiver_set_new_file()
{
new_file = true;
}
void pod_archiver_task(void *pvParameters)
{
ESP_LOGI(TAG, "pod_archiver_task: started");
EventBits_t uxBits;
bool write_only_completed = true;
for (;;)
{
uxBits = xEventGroupWaitBits(pod_sd_evg,
POD_SD_WRITE_COMPLETED_BUFFER_EVT | POD_SD_WRITE_ALL_BUFFER_EVT | POD_SD_PROBE_EVT | POD_SD_GENERATE_TESTDATA_EVT,
pdTRUE, pdFALSE, portMAX_DELAY);
ESP_LOGD(TAG, "pod_archiver_task(): uxBits = %u", uxBits);
if(uxBits & POD_SD_PROBE_EVT){
xEventGroupClearBits(pod_sd_evg, POD_SD_PROBE_EVT);
ESP_LOGD(TAG, "DISPOD_SD_PROBE_EVT: DISPOD_SD_PROBE_EVT");
ESP_LOGI(TAG, "SD card info %d, card size kb %llu, total kb %llu used kb %llu, used %3.1f perc.",
SD.cardType(), SD.cardSize()/1024, SD.totalBytes()/1024, SD.usedBytes()/1024, (SD.usedBytes() / (float) SD.totalBytes()));
// TF card test
// listDir(SD, "/", 0);
// writeFile(SD, "/hello.txt", "Hello world");
// readFile(SD, "/hello.txt");
if(SD.cardType() != CARD_NONE){
xEventGroupSetBits(pod_evg, POD_SD_AVAILABLE_BIT);
pod_screen_status_update_sd(&pod_screen_status, SD_AVAILABLE);
xEventGroupSetBits(pod_display_evg, POD_DISPLAY_UPDATE_BIT);
ESP_ERROR_CHECK(esp_event_post_to(pod_loop_handle, WORKFLOW_EVENTS, POD_SD_INIT_DONE_EVT, NULL, 0, portMAX_DELAY));
} else {
xEventGroupClearBits(pod_evg, POD_SD_AVAILABLE_BIT);
pod_screen_status_update_sd(&pod_screen_status, SD_NOT_AVAILABLE);
xEventGroupSetBits(pod_evg, POD_DISPLAY_UPDATE_BIT);
ESP_ERROR_CHECK(esp_event_post_to(pod_loop_handle, WORKFLOW_EVENTS, POD_SD_INIT_DONE_EVT, NULL, 0, portMAX_DELAY));
}
}
if((uxBits & POD_SD_WRITE_COMPLETED_BUFFER_EVT) == POD_SD_WRITE_COMPLETED_BUFFER_EVT){
write_only_completed = !( (uxBits & POD_SD_WRITE_ALL_BUFFER_EVT) == POD_SD_WRITE_ALL_BUFFER_EVT);
ESP_LOGD(TAG, "pod_archiver_task: POD_SD_WRITE_COMPLETED_BUFFER_EVT, write_only_completed=%d", write_only_completed);
if( xEventGroupWaitBits(pod_evg, POD_SD_AVAILABLE_BIT, pdFALSE, pdFALSE, portMAX_DELAY) & POD_SD_AVAILABLE_BIT){
write_out_buffers(write_only_completed);
} else {
ESP_LOGE(TAG, "pod_archiver_task: write out completed buffers but no SD mounted");
}
}
if((uxBits & POD_SD_GENERATE_TESTDATA_EVT) == POD_SD_GENERATE_TESTDATA_EVT){
ESP_LOGD(TAG, "dispod_archiver_task: POD_SD_GENERATE_TESTDATA_EVT start");
for(int i=0; i < CONFIG_SDCARD_NUM_BUFFERS; i++){
for(int j=0; j < CONFIG_SDCARD_BUFFER_SIZE; j++){
if(j%2){
// pod_archiver_add_RSCValues(180);
} else {
// pod_archiver_add_customValues(352,1);
}
if((i==(CONFIG_SDCARD_NUM_BUFFERS-1)) && j == (CONFIG_SDCARD_BUFFER_SIZE-4))
break;
}
}
ESP_LOGD(TAG, "pod_archiver_task: POD_SD_GENERATE_TESTDATA_EVT done");
}
}
}
| 38.230179
| 151
| 0.640888
|
an-erd
|
d1cf8b2fa29cd7c71130d8327c1348a397e69437
| 3,063
|
cpp
|
C++
|
server/homeserver/network/json/JsonApi.Scripting.cpp
|
williamkoehler/home-server
|
ce99af73ea2e53fea3939fe0c4442433e65ac670
|
[
"MIT"
] | 1
|
2021-07-05T21:11:59.000Z
|
2021-07-05T21:11:59.000Z
|
server/homeserver/network/json/JsonApi.Scripting.cpp
|
williamkoehler/home-server
|
ce99af73ea2e53fea3939fe0c4442433e65ac670
|
[
"MIT"
] | null | null | null |
server/homeserver/network/json/JsonApi.Scripting.cpp
|
williamkoehler/home-server
|
ce99af73ea2e53fea3939fe0c4442433e65ac670
|
[
"MIT"
] | null | null | null |
#include "JsonApi.hpp"
#include "../../scripting/ScriptManager.hpp"
#include "../../scripting/Script.hpp"
namespace server
{
// Scripting
void JsonApi::BuildJsonScriptSources(rapidjson::Value& output, rapidjson::Document::AllocatorType& allocator)
{
assert(output.IsObject());
Ref<ScriptManager> scriptManager = ScriptManager::GetInstance();
assert(scriptManager != nullptr);
boost::shared_lock_guard lock(scriptManager->mutex);
// ScriptSources
rapidjson::Value ScriptSourceListJson = rapidjson::Value(rapidjson::kArrayType);
boost::unordered::unordered_map<identifier_t, Ref<ScriptSource>>& scriptSourceList = scriptManager->scriptSourceList;
for (auto [id, scriptSource] : scriptSourceList)
{
assert(scriptSource != nullptr);
rapidjson::Value scriptSourceJson = rapidjson::Value(rapidjson::kObjectType);
BuildJsonScriptSource(scriptSource, scriptSourceJson, allocator);
ScriptSourceListJson.PushBack(scriptSourceJson, allocator);
}
output.AddMember("scriptsources", ScriptSourceListJson, allocator);
}
void JsonApi::BuildJsonScriptSource(Ref<ScriptSource> source, rapidjson::Value& output, rapidjson::Document::AllocatorType& allocator)
{
assert(source != nullptr);
assert(output.IsObject());
boost::lock_guard lock(source->mutex);
output.AddMember("name", rapidjson::Value(source->name.c_str(), source->name.size()), allocator);
output.AddMember("id", rapidjson::Value(source->sourceID), allocator);
std::string lang = StringifyScriptLanguage(source->language);
output.AddMember("language", rapidjson::Value(lang.c_str(), lang.size(), allocator), allocator);
std::string usage = StringifyScriptUsage(source->usage);
output.AddMember("usage", rapidjson::Value(usage.c_str(), usage.size(), allocator), allocator);
}
void JsonApi::DecodeJsonScriptSource(Ref<ScriptSource> source, rapidjson::Value& input)
{
assert(source != nullptr);
assert(input.IsObject());
// Decode script properties if they exist
{
rapidjson::Value::MemberIterator nameIt = input.FindMember("name");
if (nameIt != input.MemberEnd() && nameIt->value.IsString())
source->SetName(std::string(nameIt->value.GetString(), nameIt->value.GetStringLength()));
}
}
void JsonApi::BuildJsonScriptSourceData(Ref<ScriptSource> source, rapidjson::Value& output, rapidjson::Document::AllocatorType& allocator)
{
assert(source != nullptr);
assert(output.IsObject());
boost::lock_guard lock(source->mutex);
output.AddMember("data", rapidjson::Value((const char*)source->data.data(), source->data.size(), allocator), allocator);
}
void JsonApi::DecodeJsonScriptSourceData(Ref<ScriptSource> source, rapidjson::Value& input)
{
assert(source != nullptr);
assert(input.IsObject());
// Decode script properties if they exist
{
rapidjson::Value::MemberIterator sourceIt = input.FindMember("data");
if (sourceIt != input.MemberEnd() && sourceIt->value.IsString())
source->SetData(std::string_view((const char*)sourceIt->value.GetString(), sourceIt->value.GetStringLength()));
}
}
}
| 36.035294
| 139
| 0.738818
|
williamkoehler
|
d1dc4cac45a41455171ed2735fe0ccb3d0328347
| 198
|
hpp
|
C++
|
lib/src/include/deskgap/shell.hpp
|
perjonsson/DeskGap
|
5e74de37c057de3bac3ac16b3fabdb79b934d21e
|
[
"MIT"
] | 1,910
|
2019-02-08T05:41:48.000Z
|
2022-03-24T23:41:33.000Z
|
lib/src/include/deskgap/shell.hpp
|
perjonsson/DeskGap
|
5e74de37c057de3bac3ac16b3fabdb79b934d21e
|
[
"MIT"
] | 73
|
2019-02-13T02:58:20.000Z
|
2022-03-02T05:49:34.000Z
|
lib/src/include/deskgap/shell.hpp
|
ci010/DeskGap
|
b3346fea3dd3af7df9a0420131da7f4ac1518092
|
[
"MIT"
] | 88
|
2019-02-13T12:41:00.000Z
|
2022-03-25T05:04:31.000Z
|
#ifndef DESKGAP_SHELL_HPP
#define DESKGAP_SHELL_HPP
#include <string>
namespace DeskGap {
class Shell {
public:
static bool OpenExternal(const std::string& path);
};
}
#endif
| 14.142857
| 58
| 0.686869
|
perjonsson
|
d1e19fa80bce25417580c52feb9e6f87d52b607d
| 550
|
hpp
|
C++
|
src/Test.hpp
|
Vasile2k/ImageSubjectFocus
|
0eed32df07b74eb89a1e1130975aa4ddec2adf32
|
[
"Apache-2.0"
] | 3
|
2020-01-02T23:35:01.000Z
|
2021-01-25T11:02:06.000Z
|
src/Test.hpp
|
Vasile2k/ImageSubjectFocus
|
0eed32df07b74eb89a1e1130975aa4ddec2adf32
|
[
"Apache-2.0"
] | null | null | null |
src/Test.hpp
|
Vasile2k/ImageSubjectFocus
|
0eed32df07b74eb89a1e1130975aa4ddec2adf32
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "ImageColor.hpp"
namespace isf {
/**
* In order to perform the tests include this file somewhere in the project
* This never gets executed but is evaluated at compile time
* If everything is good it will do nothing
* Else it will throw a compile-time error
*/
class Test {
private:
Test() = delete;
bool testPacking() {
static_assert(sizeof(isf::ImageU8Color) == 3, "Packing does not work correctly");
static_assert(sizeof(isf::ImageDoubleColor) == 3 * sizeof(double), "Packing does not work correctly");
}
};
}
| 23.913043
| 104
| 0.72
|
Vasile2k
|
d1e2fa5a6f899afe2a0fdfe5d080d379d34a43a8
| 375
|
cpp
|
C++
|
src/io/github/technicalnotes/programming/examples/3-even.cpp
|
chiragbhatia94/programming-cpp
|
efd6aa901deacf416a3ab599e6599845a8111eac
|
[
"MIT"
] | null | null | null |
src/io/github/technicalnotes/programming/examples/3-even.cpp
|
chiragbhatia94/programming-cpp
|
efd6aa901deacf416a3ab599e6599845a8111eac
|
[
"MIT"
] | null | null | null |
src/io/github/technicalnotes/programming/examples/3-even.cpp
|
chiragbhatia94/programming-cpp
|
efd6aa901deacf416a3ab599e6599845a8111eac
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main()
{
vector<int> myVec(10);
// initialize the vector with 1 to 10 sequence
iota(begin(myVec), end(myVec), 1);
for (auto i : myVec)
{
if (i % 2 == 0)
{
cout << i << " ";
}
}
cout << endl;
return 0;
}
| 17.857143
| 51
| 0.477333
|
chiragbhatia94
|
d1e58215c9eb14c35c07f401f88efa685b16fd25
| 1,039
|
hpp
|
C++
|
src/Filesystem/File.hpp
|
tomas-krupa/ansi_iso_accuracy_test
|
a87600c1ff8997cd689539432e5badaa1bf8a776
|
[
"Apache-2.0"
] | null | null | null |
src/Filesystem/File.hpp
|
tomas-krupa/ansi_iso_accuracy_test
|
a87600c1ff8997cd689539432e5badaa1bf8a776
|
[
"Apache-2.0"
] | null | null | null |
src/Filesystem/File.hpp
|
tomas-krupa/ansi_iso_accuracy_test
|
a87600c1ff8997cd689539432e5badaa1bf8a776
|
[
"Apache-2.0"
] | null | null | null |
/**
* @file File.hpp
*
* @copyright Copyright (c) 2020 Innovatrics s.r.o. All rights reserved.
*
* @maintainer Tomas Krupa <tomas.krupa@innovatrics.com>
* @created 10.08.2020
*
*/
#pragma once
#include <fstream>
#include <utility>
#include <vector>
class Path;
/**
* @brief File
*
* Defines basic file operations and attributes.
*/
template<class TDerived>
class File
{
public:
void open() { static_cast<TDerived*>(this)->open(); }
void close() { static_cast<TDerived*>(this)->close(); }
void write(const std::string& data) { static_cast<TDerived*>(this)->write(data); }
std::vector<unsigned char> read() { return static_cast<TDerived*>(this)->read(); }
bool isOpen() { return static_cast<TDerived*>(this)->isOpen(); }
const Path& getPath() const noexcept
{
static_cast<TDerived*>(this)->getPath();
}
virtual ~File() = default;
File(const File&) = delete;
File(File&&) = delete;
File& operator=(const File&) = delete;
File& operator=(File&&) = delete;
protected:
File() = default;
};
| 19.980769
| 84
| 0.655438
|
tomas-krupa
|
d1e9946bba956b1a55af9c44e4b10e9978e5179a
| 1,045
|
cpp
|
C++
|
models/memory/CaffDRAM/Dreq.cpp
|
Basseuph/manifold
|
99779998911ed7e8b8ff6adacc7f93080409a5fe
|
[
"BSD-3-Clause"
] | 8
|
2016-01-22T18:28:48.000Z
|
2021-05-07T02:27:21.000Z
|
models/memory/CaffDRAM/Dreq.cpp
|
Basseuph/manifold
|
99779998911ed7e8b8ff6adacc7f93080409a5fe
|
[
"BSD-3-Clause"
] | 3
|
2016-04-15T02:58:58.000Z
|
2017-01-19T17:07:34.000Z
|
models/memory/CaffDRAM/Dreq.cpp
|
Basseuph/manifold
|
99779998911ed7e8b8ff6adacc7f93080409a5fe
|
[
"BSD-3-Clause"
] | 10
|
2015-12-11T04:16:55.000Z
|
2019-05-25T20:58:13.000Z
|
/*
* Dreq.cpp
*
* Created on: Jun 14, 2011
* Author: rishirajbheda
*/
#include "Dreq.h"
#include "math.h"
namespace manifold {
namespace caffdram {
Dreq::Dreq(unsigned long int reqAddr, unsigned long int currentTime, const Dsettings* dramSetting) {
// TODO Auto-generated constructor stub
this->generateId(reqAddr, dramSetting);
this->originTime = currentTime + dramSetting->t_CMD;
this->endTime = currentTime + dramSetting->t_CMD;
}
Dreq::~Dreq() {
// TODO Auto-generated destructor stub
}
void Dreq::generateId(unsigned long int reqAddr, const Dsettings* dramSetting)
{
this->rowId = (reqAddr>>(dramSetting->rowShiftBits))&(dramSetting->rowMask);
this->bankId = (reqAddr>>(dramSetting->bankShiftBits))&(dramSetting->bankMask);
this->rankId = (reqAddr>>(dramSetting->rankShiftBits))&(dramSetting->rankMask);
if (dramSetting->numChannels == 1)
{
this->chId = 0;
}
else
{
this->chId = (reqAddr>>(dramSetting->channelShiftBits))%(dramSetting->numChannels);
}
}
} //namespace caffdram
} //namespace manifold
| 22.234043
| 100
| 0.711005
|
Basseuph
|
d1f3be2f98486c2cc6ab4f353a2938953e2c009b
| 6,293
|
cpp
|
C++
|
tests/network/ipv6_address_tests.cpp
|
miraiworks/url
|
515c6d3f27cabe9fdb6718da82927c3f019d899c
|
[
"BSL-1.0"
] | null | null | null |
tests/network/ipv6_address_tests.cpp
|
miraiworks/url
|
515c6d3f27cabe9fdb6718da82927c3f019d899c
|
[
"BSL-1.0"
] | null | null | null |
tests/network/ipv6_address_tests.cpp
|
miraiworks/url
|
515c6d3f27cabe9fdb6718da82927c3f019d899c
|
[
"BSL-1.0"
] | null | null | null |
// Copyright 2018-20 Glyn Matthews.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt of copy at
// http://www.boost.org/LICENSE_1_0.txt)
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <skyr/network/ipv6_address.hpp>
TEST_CASE("ipv6_address_tests", "[ipv6]") {
using namespace std::string_literals;
SECTION("zero_test") {
auto address = std::array<unsigned short, 8>{{0, 0, 0, 0, 0, 0, 0, 0}};
auto instance = skyr::ipv6_address(address);
CHECK("::" == instance.serialize());
}
SECTION("loopback_test") {
auto address = std::array<unsigned short, 8>{{0, 0, 0, 0, 0, 0, 0, 1}};
auto instance = skyr::ipv6_address(address);
CHECK("::1" == instance.serialize());
}
SECTION("ipv6_address_test_1") {
const auto address = "1080:0:0:0:8:800:200C:417A"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("1080::8:800:200c:417a" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_address_test_2") {
const auto address = "2001:db8:85a3:8d3:1319:8a2e:370:7348"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("2001:db8:85a3:8d3:1319:8a2e:370:7348" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_address_test_3") {
const auto address = "2001:db8:85a3:0:0:8a2e:370:7334"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("2001:db8:85a3::8a2e:370:7334" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_address_test_4") {
const auto address = "2001:db8:85a3::8a2e:370:7334"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("2001:db8:85a3::8a2e:370:7334" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_address_test_5") {
const auto address = "2001:0db8:0000:0000:0000:0000:1428:57ab"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("2001:db8::1428:57ab" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_address_test_6") {
const auto address = "2001:0db8:0000:0000:0000::1428:57ab"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("2001:db8::1428:57ab" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_address_test_7") {
const auto address = "2001:0db8:0:0:0:0:1428:57ab"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("2001:db8::1428:57ab" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_address_test_8") {
const auto address = "2001:0db8:0:0::1428:57ab"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("2001:db8::1428:57ab" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_address_test_9") {
const auto address = "2001:0db8::1428:57ab"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("2001:db8::1428:57ab" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_address_test_10") {
const auto address = "2001:db8::1428:57ab"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("2001:db8::1428:57ab" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_address_test_11") {
const auto address = "::ffff:0c22:384e"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("::ffff:c22:384e" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_address_test_12") {
const auto address = "fe80::"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("fe80::" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_address_test_13") {
const auto address = "::ffff:c000:280"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("::ffff:c000:280" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_loopback_test_1") {
const auto address = "0000:0000:0000:0000:0000:0000:0000:0001"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("::1" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_v4inv6_test_1") {
const auto address = "::ffff:12.34.56.78"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("::ffff:c22:384e" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("ipv6_v4inv6_test_2") {
const auto address = "::ffff:192.0.2.128"s;
bool validation_error = false;
auto instance = skyr::parse_ipv6_address(address, &validation_error);
REQUIRE(instance);
CHECK("::ffff:c000:280" == instance.value().serialize());
CHECK(!validation_error);
}
SECTION("loopback_test") {
auto address = std::array<unsigned short, 8>{{0, 0, 0, 0, 0, 0, 0, 1}};
auto instance = skyr::ipv6_address(address);
std::array<unsigned char, 16> bytes{
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
}};
CHECK(bytes == instance.to_bytes());
}
}
| 35.156425
| 82
| 0.679485
|
miraiworks
|
d1fbe1ce96c03f1bf73fcda3db546b6e4f91947a
| 889
|
cpp
|
C++
|
leetcode.com/0650 2 Keys Keyboard/main.cpp
|
sky-bro/AC
|
29bfa3f13994612887e18065fa6e854b9a29633d
|
[
"MIT"
] | 1
|
2020-08-20T11:02:49.000Z
|
2020-08-20T11:02:49.000Z
|
leetcode.com/0650 2 Keys Keyboard/main.cpp
|
sky-bro/AC
|
29bfa3f13994612887e18065fa6e854b9a29633d
|
[
"MIT"
] | null | null | null |
leetcode.com/0650 2 Keys Keyboard/main.cpp
|
sky-bro/AC
|
29bfa3f13994612887e18065fa6e854b9a29633d
|
[
"MIT"
] | 1
|
2022-01-01T23:23:13.000Z
|
2022-01-01T23:23:13.000Z
|
#include <iostream>
#include <vector>
using namespace std;
// key is know how to prune
// no, 1000*1000 dp, no need to prune?
class Solution {
private:
int dfs(int n, int cur_n, int clip_len, vector<vector<int>>& dp) {
if (n == cur_n) return 0;
if (~dp[clip_len][cur_n]) return dp[clip_len][cur_n];
int res = -2;
if (cur_n * 2 <= n) {
// copy + paste
res = dfs(n, cur_n * 2, cur_n, dp);
if (res != -2) res += 2;
}
if (cur_n + clip_len <= n) {
// paste
int tmp = dfs(n, cur_n + clip_len, clip_len, dp);
if (tmp != -2) {
if (res == -2 || tmp + 1 < res) res = tmp + 1;
}
}
return dp[clip_len][cur_n] = res;
}
public:
int minSteps(int n) {
if (n == 1) return 0;
vector<vector<int>> dp(n + 1, vector<int>(n + 1, -1));
// already copied + pasted once
return 2 + dfs(n, 2, 1, dp);
}
};
| 24.694444
| 68
| 0.526434
|
sky-bro
|
d1fd6d3f89f18b58f12ed9b004c44644edaee289
| 12,127
|
hpp
|
C++
|
SDK/PUBG_WeaponAttachmentSlotWidget_parameters.hpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | 7
|
2019-03-06T11:04:52.000Z
|
2019-07-10T20:00:51.000Z
|
SDK/PUBG_WeaponAttachmentSlotWidget_parameters.hpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | null | null | null |
SDK/PUBG_WeaponAttachmentSlotWidget_parameters.hpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | 10
|
2019-03-06T11:53:46.000Z
|
2021-02-18T14:01:11.000Z
|
#pragma once
// PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_WeaponAttachmentSlotWidget_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetSlotItem
struct UWeaponAttachmentSlotWidget_C_GetSlotItem_Params
{
TScriptInterface<class USlotInterface> SlotItem; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetSlotContainer
struct UWeaponAttachmentSlotWidget_C_GetSlotContainer_Params
{
TScriptInterface<class USlotContainerInterface> SlotContainer; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.CheckFirstAttachableSlot
struct UWeaponAttachmentSlotWidget_C_CheckFirstAttachableSlot_Params
{
bool bAttachable; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.CheckAttachableByFocusSlot
struct UWeaponAttachmentSlotWidget_C_CheckAttachableByFocusSlot_Params
{
bool bAttachable; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.InputB
struct UWeaponAttachmentSlotWidget_C_InputB_Params
{
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.InputA
struct UWeaponAttachmentSlotWidget_C_InputA_Params
{
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.SetFocus
struct UWeaponAttachmentSlotWidget_C_SetFocus_Params
{
bool* NewFocus; // (Parm, ZeroConstructor, IsPlainOldData)
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnDrop
struct UWeaponAttachmentSlotWidget_C_OnDrop_Params
{
struct FGeometry* MyGeometry; // (Parm, IsPlainOldData)
struct FPointerEvent* PointerEvent; // (Parm)
class UDragDropOperation** Operation; // (Parm, ZeroConstructor, IsPlainOldData)
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetOptoins
struct UWeaponAttachmentSlotWidget_C_GetOptoins_Params
{
class FString Options; // (Parm, OutParm, ZeroConstructor)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetDragDroppingAttachableItem
struct UWeaponAttachmentSlotWidget_C_GetDragDroppingAttachableItem_Params
{
class UAttachableItem* DragDroppingAttachableItem; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnPrepass_2
struct UWeaponAttachmentSlotWidget_C_OnPrepass_2_Params
{
class UWidget** BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.On_AttachmentIcon_Prepass_1
struct UWeaponAttachmentSlotWidget_C_On_AttachmentIcon_Prepass_1_Params
{
class UWidget** BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.IsSlotMouseOver_Bp
struct UWeaponAttachmentSlotWidget_C_IsSlotMouseOver_Bp_Params
{
bool IsMouseOver; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnPrepass_1
struct UWeaponAttachmentSlotWidget_C_OnPrepass_1_Params
{
class UWidget** BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetItem_Bp
struct UWeaponAttachmentSlotWidget_C_GetItem_Bp_Params
{
class UItem* Item; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.IsSlotSubOn_Bp
struct UWeaponAttachmentSlotWidget_C_IsSlotSubOn_Bp_Params
{
bool SubOn; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.IsSlotOn_Bp
struct UWeaponAttachmentSlotWidget_C_IsSlotOn_Bp_Params
{
bool IsOn; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.IsOhterSlotMouseOver
struct UWeaponAttachmentSlotWidget_C_IsOhterSlotMouseOver_Params
{
bool IsOver; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.IsAttachable
struct UWeaponAttachmentSlotWidget_C_IsAttachable_Params
{
bool IsAttachable; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetAttachmentItem
struct UWeaponAttachmentSlotWidget_C_GetAttachmentItem_Params
{
class UAttachableItem* AttachmentItem; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.HasAttachmentSlot
struct UWeaponAttachmentSlotWidget_C_HasAttachmentSlot_Params
{
bool HasAttachmentSlot; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.MainPrepass_1
struct UWeaponAttachmentSlotWidget_C_MainPrepass_1_Params
{
class UWidget** BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnDragDetected
struct UWeaponAttachmentSlotWidget_C_OnDragDetected_Params
{
struct FGeometry* MyGeometry; // (Parm, IsPlainOldData)
struct FPointerEvent* PointerEvent; // (ConstParm, Parm, OutParm, ReferenceParm)
class UDragDropOperation* Operation; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnMouseButtonDown
struct UWeaponAttachmentSlotWidget_C_OnMouseButtonDown_Params
{
struct FGeometry* MyGeometry; // (Parm, IsPlainOldData)
struct FPointerEvent* MouseEvent; // (ConstParm, Parm, OutParm, ReferenceParm)
struct FEventReply ReturnValue; // (Parm, OutParm, ReturnParm)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetSlotVisibility
struct UWeaponAttachmentSlotWidget_C_GetSlotVisibility_Params
{
ESlateVisibility ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetSlotIcon
struct UWeaponAttachmentSlotWidget_C_GetSlotIcon_Params
{
struct FSlateBrush ReturnValue; // (Parm, OutParm, ReturnParm)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.GetAttachmentNameText
struct UWeaponAttachmentSlotWidget_C_GetAttachmentNameText_Params
{
struct FText ReturnValue; // (Parm, OutParm, ReturnParm)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnDragEnter
struct UWeaponAttachmentSlotWidget_C_OnDragEnter_Params
{
struct FGeometry* MyGeometry; // (Parm, IsPlainOldData)
struct FPointerEvent* PointerEvent; // (Parm)
class UDragDropOperation** Operation; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnDragLeave
struct UWeaponAttachmentSlotWidget_C_OnDragLeave_Params
{
struct FPointerEvent* PointerEvent; // (Parm)
class UDragDropOperation** Operation; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnMouseEnter
struct UWeaponAttachmentSlotWidget_C_OnMouseEnter_Params
{
struct FGeometry* MyGeometry; // (Parm, IsPlainOldData)
struct FPointerEvent* MouseEvent; // (ConstParm, Parm, OutParm, ReferenceParm)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.OnMouseLeave
struct UWeaponAttachmentSlotWidget_C_OnMouseLeave_Params
{
struct FPointerEvent* MouseEvent; // (ConstParm, Parm, OutParm, ReferenceParm)
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.Construct
struct UWeaponAttachmentSlotWidget_C_Construct_Params
{
};
// Function WeaponAttachmentSlotWidget.WeaponAttachmentSlotWidget_C.ExecuteUbergraph_WeaponAttachmentSlotWidget
struct UWeaponAttachmentSlotWidget_C_ExecuteUbergraph_WeaponAttachmentSlotWidget_Params
{
int* EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 52.497835
| 173
| 0.590336
|
realrespecter
|
06005216a53a429e6deabb7ea0a7de2f3c21ec9d
| 12,374
|
cpp
|
C++
|
src/sound/k054539.cpp
|
gameblabla/mame_nspire
|
83dfe1606aba906bd28608f2cb8f0754492ac3da
|
[
"Unlicense"
] | 33
|
2015-08-10T11:13:47.000Z
|
2021-08-30T10:00:46.000Z
|
src/sound/k054539.cpp
|
gameblabla/mame_nspire
|
83dfe1606aba906bd28608f2cb8f0754492ac3da
|
[
"Unlicense"
] | 13
|
2015-08-25T03:53:08.000Z
|
2022-03-30T18:02:35.000Z
|
src/sound/k054539.cpp
|
gameblabla/mame_nspire
|
83dfe1606aba906bd28608f2cb8f0754492ac3da
|
[
"Unlicense"
] | 40
|
2015-08-25T05:09:21.000Z
|
2022-02-08T05:02:30.000Z
|
/*********************************************************
Konami 054539 PCM Sound Chip
A lot of information comes from Amuse.
Big thanks to them.
*********************************************************/
#include "driver.h"
#include "k054539.h"
#include <math.h>
/* Registers:
00..ff: 20 bytes/channel, 8 channels
00..02: pitch (lsb, mid, msb)
03: volume (0=max, 0x40=-36dB)
04:
05: pan (1-f right, 10 middle, 11-1f left)
06:
07:
08..0a: loop (lsb, mid, msb)
0c..0e: start (lsb, mid, msb) (and current position ?)
100.1ff: effects?
13f: pan of the analog input (1-1f)
200..20f: 2 bytes/channel, 8 channels
00: type (b2-3), reverse (b5)
01: loop (b0)
214: keyon (b0-7 = channel 0-7)
215: keyoff ""
22c: channel active? ""
22d: data read/write port
22e: rom/ram select (00..7f == rom banks, 80 = ram)
22f: enable pcm (b0), disable registers updating (b7)
*/
#define MAX_K054539 2
struct K054539_channel {
UINT32 pos;
UINT32 pfrac;
INT32 val;
INT32 pval;
};
struct K054539_chip {
unsigned char regs[0x230];
unsigned char *ram;
int cur_ptr;
int cur_limit;
unsigned char *cur_zone;
void *timer;
unsigned char *rom;
UINT32 rom_size;
UINT32 rom_mask;
int stream;
struct K054539_channel channels[8];
};
static struct {
const struct K054539interface *intf;
double freq_ratio;
double voltab[256];
double pantab[0xf];
struct K054539_chip chip[MAX_K054539];
} K054539_chips;
static int K054539_regupdate(int chip)
{
return !(K054539_chips.chip[chip].regs[0x22f] & 0x80);
}
static void K054539_keyon(int chip, int channel)
{
if(K054539_regupdate(chip))
K054539_chips.chip[chip].regs[0x22c] |= 1 << channel;
}
static void K054539_keyoff(int chip, int channel)
{
if(K054539_regupdate(chip))
K054539_chips.chip[chip].regs[0x22c] &= ~(1 << channel);
}
static void K054539_update(int chip, INT16 **buffer, int length)
{
static INT16 dpcm[16] = {
0<<8, 1<<8, 4<<8, 9<<8, 16<<8, 25<<8, 36<<8, 49<<8,
-64<<8, -49<<8, -36<<8, -25<<8, -16<<8, -9<<8, -4<<8, -1<<8
};
int ch;
unsigned char *samples;
UINT32 rom_mask;
if(!Machine->sample_rate)
return;
memset(buffer[0], 0, length*2);
memset(buffer[1], 0, length*2);
if(!(K054539_chips.chip[chip].regs[0x22f] & 1))
return;
samples = K054539_chips.chip[chip].rom;
rom_mask = K054539_chips.chip[chip].rom_mask;
for(ch=0; ch<8; ch++)
if(K054539_chips.chip[chip].regs[0x22c] & (1<<ch)) {
unsigned char *base1 = K054539_chips.chip[chip].regs + 0x20*ch;
unsigned char *base2 = K054539_chips.chip[chip].regs + 0x200 + 0x2*ch;
struct K054539_channel *chan = (struct K054539_channel*)K054539_chips.chip[chip].channels + ch;
INT16 *bufl = buffer[0];
INT16 *bufr = buffer[1];
UINT32 cur_pos = (base1[0x0c] | (base1[0x0d] << 8) | (base1[0x0e] << 16)) & rom_mask;
INT32 cur_pfrac;
INT32 cur_val, cur_pval, rval;
INT32 delta = (base1[0x00] | (base1[0x01] << 8) | (base1[0x02] << 16)) * K054539_chips.freq_ratio;
INT32 fdelta;
int pdelta;
int pan = base1[0x05] >= 0x11 && base1[0x05] <= 0x1f ? base1[0x05] - 0x11 : 0x18 - 0x11;
int vol = base1[0x03] & 0x7f;
double lvol = K054539_chips.voltab[vol] * K054539_chips.pantab[pan];
double rvol = K054539_chips.voltab[vol] * K054539_chips.pantab[0xe - pan];
if(base2[0] & 0x20) {
delta = -delta;
fdelta = +0x10000;
pdelta = -1;
} else {
fdelta = -0x10000;
pdelta = +1;
}
if(cur_pos != chan->pos) {
chan->pos = cur_pos;
cur_pfrac = 0;
cur_val = 0;
cur_pval = 0;
} else {
cur_pfrac = chan->pfrac;
cur_val = chan->val;
cur_pval = chan->pval;
}
#define UPDATE_CHANNELS \
do { \
rval = (cur_pval*cur_pfrac + cur_val*(0x10000 - cur_pfrac)) >> 16; \
*bufl++ += (INT16)(rval*lvol); \
*bufr++ += (INT16)(rval*rvol); \
} while(0)
switch(base2[0] & 0xc) {
case 0x0: { // 8bit pcm
int i;
for(i=0; i<length; i++) {
cur_pfrac += delta;
while(cur_pfrac & ~0xffff) {
cur_pfrac += fdelta;
cur_pos += pdelta;
cur_pval = cur_val;
cur_val = (INT16)(samples[cur_pos] << 8);
if(cur_val == (INT16)0x8000) {
if(base2[1] & 1) {
cur_pos = (base1[0x08] | (base1[0x09] << 8) | (base1[0x0a] << 16)) & rom_mask;
cur_val = (INT16)(samples[cur_pos] << 8);
if(cur_val != (INT16)0x8000)
continue;
}
K054539_keyoff(chip, ch);
goto end_channel_0;
}
}
UPDATE_CHANNELS;
}
end_channel_0:
break;
}
case 0x4: { // 16bit pcm lsb first
int i;
cur_pos >>= 1;
for(i=0; i<length; i++) {
cur_pfrac += delta;
while(cur_pfrac & ~0xffff) {
cur_pfrac += fdelta;
cur_pos += pdelta;
cur_pval = cur_val;
cur_val = (INT16)(samples[cur_pos<<1] | samples[(cur_pos<<1)|1]<<8);
if(cur_val == (INT16)0x8000) {
if(base2[1] & 1) {
cur_pos = ((base1[0x08] | (base1[0x09] << 8) | (base1[0x0a] << 16)) & rom_mask) >> 1;
cur_val = (INT16)(samples[cur_pos<<1] | samples[(cur_pos<<1)|1]<<8);
if(cur_val != (INT16)0x8000)
continue;
}
K054539_keyoff(chip, ch);
goto end_channel_4;
}
}
UPDATE_CHANNELS;
}
end_channel_4:
cur_pos <<= 1;
break;
}
case 0x8: { // 4bit dpcm
int i;
cur_pos <<= 1;
cur_pfrac <<= 1;
if(cur_pfrac & 0x10000) {
cur_pfrac &= 0xffff;
cur_pos |= 1;
}
for(i=0; i<length; i++) {
cur_pfrac += delta;
while(cur_pfrac & ~0xffff) {
cur_pfrac += fdelta;
cur_pos += pdelta;
cur_pval = cur_val;
cur_val = samples[cur_pos>>1];
if(cur_val == 0x88) {
if(base2[1] & 1) {
cur_pos = ((base1[0x08] | (base1[0x09] << 8) | (base1[0x0a] << 16)) & rom_mask) << 1;
cur_val = samples[cur_pos>>1];
if(cur_val != 0x88)
goto next_iter;
}
K054539_keyoff(chip, ch);
goto end_channel_8;
}
next_iter:
if(cur_pos & 1)
cur_val >>= 4;
else
cur_val &= 15;
cur_val = cur_pval + dpcm[cur_val];
if(cur_val < -32768)
cur_val = -32768;
else if(cur_val > 32767)
cur_val = 32767;
}
UPDATE_CHANNELS;
}
end_channel_8:
cur_pfrac >>= 1;
if(cur_pos & 1)
cur_pfrac |= 0x8000;
cur_pos >>= 1;
break;
}
default:
logerror("Unknown sample type %x for channel %d\n", base2[0] & 0xc, ch);
break;
}
chan->pos = cur_pos;
chan->pfrac = cur_pfrac;
chan->pval = cur_pval;
chan->val = cur_val;
if(K054539_regupdate(chip)) {
base1[0x0c] = cur_pos & 0xff;
base1[0x0d] = (cur_pos >> 8) & 0xff;
base1[0x0e] = (cur_pos >> 16) & 0xff;
}
}
}
static void K054539_irq(int chip)
{
if(K054539_chips.chip[chip].regs[0x22f] & 0x20)
K054539_chips.intf->irq[chip] ();
}
static void K054539_init_chip(int chip, const struct MachineSound *msound)
{
char buf[2][50];
const char *bufp[2];
int vol[2];
int i;
memset(K054539_chips.chip[chip].regs, 0, sizeof(K054539_chips.chip[chip].regs));
K054539_chips.chip[chip].ram = (unsigned char *)malloc(0x4000);
K054539_chips.chip[chip].cur_ptr = 0;
K054539_chips.chip[chip].rom = memory_region(K054539_chips.intf->region[chip]);
K054539_chips.chip[chip].rom_size = memory_region_length(K054539_chips.intf->region[chip]);
K054539_chips.chip[chip].rom_mask = 0xffffffffU;
for(i=0; i<32; i++)
if((1U<<i) >= K054539_chips.chip[chip].rom_size) {
K054539_chips.chip[chip].rom_mask = (1U<<i) - 1;
break;
}
if(K054539_chips.intf->irq[chip])
// One or more of the registers must be the timer period
// And anyway, this particular frequency is probably wrong
K054539_chips.chip[chip].timer = timer_pulse(TIME_IN_HZ(500), 0, K054539_irq);
else
K054539_chips.chip[chip].timer = 0;
sprintf(buf[0], "%s.%d L", sound_name(msound), chip);
sprintf(buf[1], "%s.%d R", sound_name(msound), chip);
bufp[0] = buf[0];
bufp[1] = buf[1];
vol[0] = MIXER(K054539_chips.intf->mixing_level[chip][0], MIXER_PAN_LEFT);
vol[1] = MIXER(K054539_chips.intf->mixing_level[chip][1], MIXER_PAN_RIGHT);
K054539_chips.chip[chip].stream = stream_init_multi(2, bufp, vol, Machine->sample_rate, chip, K054539_update);
}
static void K054539_stop_chip(int chip)
{
free(K054539_chips.chip[chip].ram);
if (K054539_chips.chip[chip].timer)
timer_remove(K054539_chips.chip[chip].timer);
}
static void K054539_w(int chip, offs_t offset, data8_t data)
{
data8_t old = K054539_chips.chip[chip].regs[offset];
K054539_chips.chip[chip].regs[offset] = data;
switch(offset) {
case 0x13f: {
int pan = data >= 0x11 && data <= 0x1f ? data - 0x11 : 0x18 - 0x11;
if(K054539_chips.intf->apan[chip])
K054539_chips.intf->apan[chip](K054539_chips.pantab[pan], K054539_chips.pantab[0xe - pan]);
break;
}
case 0x214: {
int ch;
for(ch=0; ch<8; ch++)
if(data & (1<<ch))
K054539_keyon(chip, ch);
break;
}
case 0x215: {
int ch;
for(ch=0; ch<8; ch++)
if(data & (1<<ch))
K054539_keyoff(chip, ch);
break;
}
case 0x22d:
if(K054539_chips.chip[chip].regs[0x22e] == 0x80)
K054539_chips.chip[chip].cur_zone[K054539_chips.chip[chip].cur_ptr] = data;
K054539_chips.chip[chip].cur_ptr++;
if(K054539_chips.chip[chip].cur_ptr == K054539_chips.chip[chip].cur_limit)
K054539_chips.chip[chip].cur_ptr = 0;
break;
case 0x22e:
K054539_chips.chip[chip].cur_zone =
data == 0x80 ? K054539_chips.chip[chip].ram :
K054539_chips.chip[chip].rom + 0x20000*data;
K054539_chips.chip[chip].cur_limit = data == 0x80 ? 0x4000 : 0x20000;
K054539_chips.chip[chip].cur_ptr = 0;
break;
default:
if(old != data) {
if((offset & 0xff00) == 0) {
int chanoff = offset & 0x1f;
if(chanoff < 4 || chanoff == 5 ||
(chanoff >=8 && chanoff <= 0xa) ||
(chanoff >= 0xc && chanoff <= 0xe))
break;
}
if(1 || ((offset >= 0x200) && (offset <= 0x210)))
break;
logerror("K054539 %03x = %02x\n", offset, data);
}
break;
}
}
#if 0
static void reset_zones(void)
{
int chip;
for(chip=0; chip<K054539_chips.intf->num; chip++) {
int data = K054539_chips.chip[chip].regs[0x22e];
K054539_chips.chip[chip].cur_zone =
data == 0x80 ? K054539_chips.chip[chip].ram :
K054539_chips.chip[chip].rom + 0x20000*data;
K054539_chips.chip[chip].cur_limit = data == 0x80 ? 0x4000 : 0x20000;
}
}
#endif
static data8_t K054539_r(int chip, offs_t offset)
{
switch(offset) {
case 0x22d:
if(K054539_chips.chip[chip].regs[0x22f] & 0x10) {
data8_t res = K054539_chips.chip[chip].cur_zone[K054539_chips.chip[chip].cur_ptr];
K054539_chips.chip[chip].cur_ptr++;
if(K054539_chips.chip[chip].cur_ptr == K054539_chips.chip[chip].cur_limit)
K054539_chips.chip[chip].cur_ptr = 0;
return res;
} else
return 0;
case 0x22c:
break;
default:
logerror("K054539 read %03x\n", offset);
break;
}
return K054539_chips.chip[chip].regs[offset];
}
int K054539_sh_start(const struct MachineSound *msound)
{
int i;
K054539_chips.intf = (const K054539interface*)msound->sound_interface;
if(Machine->sample_rate)
K054539_chips.freq_ratio = (double)(K054539_chips.intf->clock) / (double)(Machine->sample_rate);
else
K054539_chips.freq_ratio = 1.0;
// Factor the 1/4 for the number of channels in the volume (1/8 is too harsh, 1/2 gives clipping)
// vol=0 -> no attenuation, vol=0x40 -> -36dB
for(i=0; i<256; i++)
K054539_chips.voltab[i] = pow(10.0, (-36.0 * (double)i / (double)0x40) / 20.0) / 4.0;
// Pan table for the left channel
// Right channel is identical with inverted index
// Formula is such that pan[i]**2+pan[0xe-i]**2 = 1 (constant output power)
// and pan[0] = 1 (full panning)
for(i=0; i<0xf; i++)
K054539_chips.pantab[i] = sqrt(0xe - i) / sqrt(0xe);
for(i=0; i<K054539_chips.intf->num; i++)
K054539_init_chip(i, msound);
return 0;
}
void K054539_sh_stop(void)
{
int i;
for(i=0; i<K054539_chips.intf->num; i++)
K054539_stop_chip(i);
}
WRITE_HANDLER( K054539_0_w )
{
K054539_w(0, offset, data);
}
READ_HANDLER( K054539_0_r )
{
return K054539_r(0, offset);
}
WRITE_HANDLER( K054539_1_w )
{
K054539_w(1, offset, data);
}
READ_HANDLER( K054539_1_r )
{
return K054539_r(1, offset);
}
| 25.725572
| 111
| 0.61702
|
gameblabla
|
0603be8069b9d685151cfed0143520a6a8e5c200
| 16,343
|
cpp
|
C++
|
Documents/RacimoAire/Libreria/ADS1115/ads1115.cpp
|
JoseSalamancaCoy/RACIMO_AIRE
|
628d6ff184a30af0efd25bff675b0006500d4ba2
|
[
"MIT"
] | null | null | null |
Documents/RacimoAire/Libreria/ADS1115/ads1115.cpp
|
JoseSalamancaCoy/RACIMO_AIRE
|
628d6ff184a30af0efd25bff675b0006500d4ba2
|
[
"MIT"
] | null | null | null |
Documents/RacimoAire/Libreria/ADS1115/ads1115.cpp
|
JoseSalamancaCoy/RACIMO_AIRE
|
628d6ff184a30af0efd25bff675b0006500d4ba2
|
[
"MIT"
] | null | null | null |
/**************************************************************************/
/*
Distributed with a free-will license.
Use it any way you want, profit or free, provided it fits in the licenses of its associated works.
ADS1115
This code is designed to work with the ADS1115_I2CADC I2C Mini Module available from ControlEverything.com.
https://www.controleverything.com/content/Analog-Digital-Converters?sku=ADS1115_I2CADC#tabs-0-product_tabset-2
*/
/**************************************************************************/
#include "ads1115.h"
#include <QDebug>
/**************************************************************************/
/*
Abstract away platform differences in Arduino wire library
*/
/**************************************************************************/
/*
Instantiates a new ADS1115 class with appropriate properties
*/
/**************************************************************************/
ADS1115::ADS1115(Crpigpio *cGPIO, uint8_t i2cAddress)
{
RA_cGPIO = cGPIO;
ads_i2cAddress = i2cAddress;
ads_conversionDelay = ADS1115_CONVERSIONDELAY;
ads_osmode = OSMODE_SINGLE;
ads_gain = GAIN_TWOTHIRDS;
ads_mode = MODE_CONTIN;
ads_rate = RATE_128;
/*ads_compmode = COMPMODE_TRAD;
ads_comppol = COMPPOL_LOW;
ads_complat = COMPLAT_NONLAT;
ads_compque = COMPQUE_NONE;
*/
RA_cGPIO->OpenI2C(1,ads_i2cAddress,0);
Measure_SingleEnded(0);
}
ADS1115::~ADS1115()
{
RA_cGPIO->CloseI2C();
delete RA_cGPIO;
}
/**************************************************************************/
/*
Writes 16-bits to the specified destination register
*/
/**************************************************************************/
void ADS1115::writeRegister(uint8_t reg, uint16_t value)
{
uint16_t value2= (value>>8 & 0xff) | (value<<8);
m_InitOk = RA_cGPIO->WriteDeviceI2C(reg,value2);
}
/**************************************************************************/
/*
Reads 16-bits to the specified destination register
*/
/**************************************************************************/
int16_t ADS1115::readRegister(uint8_t reg)
{
int16_t ReturnData;
char buf[2];
RA_cGPIO->ReadDeviceI2C(reg, &buf[0], 2);
ReturnData = ( buf[0] << 8 ) | buf[1];
//if((ReturnData & 0x8000) > 0)
//{
// ReturnData = ReturnData >> 1;
// ReturnData= ~ReturnData + 1 ;
// ReturnData= (-1)* ReturnData;
//}
return ReturnData;
}
int ADS1115::getInitOk() const
{
return m_InitOk;
}
/**************************************************************************/
/*
Sets the Operational status/single-shot conversion start
This determines the operational status of the device
*/
/**************************************************************************/
void ADS1115::setOSMode(adsOSMode_t osmode)
{
ads_osmode = osmode;
}
/**************************************************************************/
/*
Gets the Operational status/single-shot conversion start
*/
/**************************************************************************/
adsOSMode_t ADS1115::getOSMode()
{
return ads_osmode;
}
/**************************************************************************/
/*
Sets the gain and input voltage range
This configures the programmable gain amplifier
*/
/**************************************************************************/
void ADS1115::setGain(adsGain_t gain)
{
ads_gain = gain;
}
/**************************************************************************/
/*
Gets a gain and input voltage range
*/
/**************************************************************************/
adsGain_t ADS1115::getGain()
{
return ads_gain;
}
/**************************************************************************/
/*
Sets the Device operating mode
This controls the current operational mode of the ADS1115
*/
/**************************************************************************/
void ADS1115::setMode(adsMode_t mode)
{
ads_mode = mode;
}
/**************************************************************************/
/*
Gets the Device operating mode
*/
/**************************************************************************/
adsMode_t ADS1115::getMode()
{
return ads_mode;
}
/**************************************************************************/
/*
Sets the Date Rate
This controls the data rate setting
*/
/**************************************************************************/
void ADS1115::setRate(adsRate_t rate)
{
ads_rate = rate;
}
/**************************************************************************/
/*
Gets the Date Rate
*/
/**************************************************************************/
adsRate_t ADS1115::getRate()
{
return ads_rate;
}
/**************************************************************************/
/*
Sets the Comparator mode
This controls the comparator mode of operation
*/
/**************************************************************************/
void ADS1115::setCompMode(adsCompMode_t compmode)
{
ads_compmode = compmode;
}
/**************************************************************************/
/*
Gets the Comparator mode
*/
/**************************************************************************/
adsCompMode_t ADS1115::getCompMode()
{
return ads_compmode;
}
/**************************************************************************/
/*
Sets the Comparator polarity
This controls the polarity of the ALERT/RDY pin
*/
/**************************************************************************/
void ADS1115::setCompPol(adsCompPol_t comppol)
{
ads_comppol = comppol;
}
/**************************************************************************/
/*
Gets the Comparator polarity
*/
/**************************************************************************/
adsCompPol_t ADS1115::getCompPol()
{
return ads_comppol;
}
/**************************************************************************/
/*
Sets the Latching comparator
This controls whether the ALERT/RDY pin latches once asserted
or clears once conversions are within the
margin of the upper and lower threshold values
*/
/**************************************************************************/
void ADS1115::setCompLat(adsCompLat_t complat)
{
ads_complat = complat;
}
/**************************************************************************/
/*
Gets the Latching comparator
*/
/**************************************************************************/
adsCompLat_t ADS1115::getCompLat()
{
return ads_complat;
}
/**************************************************************************/
/*
Sets the Comparator queue and disable
This perform two functions.
It can disable the comparator function and put the
ALERT/RDY pin into a high state.
It also can control the number of successive
conversions exceeding the upper or lower thresholds
required before asserting the ALERT/RDY pin
*/
/**************************************************************************/
void ADS1115::setCompQue(adsCompQue_t compque)
{
ads_compque = compque;
}
/**************************************************************************/
/*
Gets the Comparator queue and disable
*/
/**************************************************************************/
adsCompQue_t ADS1115::getCompQue()
{
return ads_compque;
}
/**************************************************************************/
/*
Sets the low threshold value
*/
/**************************************************************************/
void ADS1115::setLowThreshold(int16_t threshold)
{
ads_lowthreshold = threshold;
writeRegister(ADS1115_REG_POINTER_LOWTHRESH, ads_lowthreshold);
}
/**************************************************************************/
/*
Gets the low threshold value
*/
/**************************************************************************/
int16_t ADS1115::getLowThreshold()
{
return ads_lowthreshold;
}
/**************************************************************************/
/*
Sets the high threshold value
*/
/**************************************************************************/
void ADS1115::setHighThreshold(int16_t threshold)
{
ads_highthreshold = threshold;
writeRegister(ADS1115_REG_POINTER_HITHRESH, ads_highthreshold);
}
/**************************************************************************/
/*
Gets the high threshold value
*/
/**************************************************************************/
int16_t ADS1115::getHighThreshold()
{
return ads_highthreshold;
}
/**************************************************************************/
/*
Reads the conversion results, measuring the voltage
for a single-ended ADC reading from the specified channel
Negative voltages cannot be applied to this circuit because the
ADS1115 can only accept positive voltages
*/
/**************************************************************************/
uint16_t ADS1115::Measure_SingleEnded(uint8_t channel)
{
if (channel > 3)
{
return 0;
}
// Start with default values
uint16_t config=0;
config = ADS1115_REG_CONFIG_CQUE_NONE | // Disable the comparator (default val)
ADS1115_REG_CONFIG_CLAT_NONLAT | // Non-latching (default val)
ADS1115_REG_CONFIG_CPOL_ACTVLOW | // Alert/Rdy active low (default val)
ADS1115_REG_CONFIG_CMODE_TRAD; // Traditional comparator (default val)
// Set Operational status/single-shot conversion start
config |= ads_osmode;
// Set PGA/voltage range
config |= ads_gain;
// Set Device operating mode
config |= ads_mode;
// Set Data rate
config |= ads_rate;
// Set single-ended input channel
switch (channel)
{
case (0):
config |= ADS1115_REG_CONFIG_MUX_SINGLE_0;
break;
case (1):
config |= ADS1115_REG_CONFIG_MUX_SINGLE_1;
break;
case (2):
config |= ADS1115_REG_CONFIG_MUX_SINGLE_2;
break;
case (3):
config |= ADS1115_REG_CONFIG_MUX_SINGLE_3;
break;
}
// Write config register to the ADC
writeRegister(ADS1115_REG_POINTER_CONFIG, config);
// Wait for the conversion to complete
QThread::msleep(ads_conversionDelay);
// Read the conversion results
// 16-bit unsigned results for the ADS1115
return readRegister(ADS1115_REG_POINTER_CONVERT);
}
/**************************************************************************/
/*
Reads the conversion results, measuring the voltage
difference between the P (AIN#) and N (AIN#) input
Generates a signed value since the difference can be either
positive or negative
*/
/**************************************************************************/
int16_t ADS1115::Measure_Differential(uint8_t channel)
{
// Start with default values
uint16_t config = ADS1115_REG_CONFIG_CQUE_NONE | // Disable the comparator (default val)
ADS1115_REG_CONFIG_CLAT_NONLAT | // Non-latching (default val)
ADS1115_REG_CONFIG_CPOL_ACTVLOW | // Alert/Rdy active low (default val)
ADS1115_REG_CONFIG_CMODE_TRAD; // Traditional comparator (default val)
// Set Operational status/single-shot conversion start
config |= ads_osmode;
// Set PGA/voltage range
config |= ads_gain;
// Set Device operating mode
config |= ads_mode;
// Set Data rate
config |= ads_rate;
// Set Differential input channel
switch (channel)
{
case (01):
config |= ADS1115_REG_CONFIG_MUX_DIFF_0_1; // AIN0 = P, AIN1 = N
break;
case (03):
config |= ADS1115_REG_CONFIG_MUX_DIFF_0_3; // AIN0 = P, AIN3 = N
break;
case (13):
config |= ADS1115_REG_CONFIG_MUX_DIFF_1_3; // AIN1 = P, AIN3 = N
break;
case (23):
config |= ADS1115_REG_CONFIG_MUX_DIFF_2_3; // AIN2 = P, AIN3 = N
break;
}
// Write config register to the ADC
writeRegister(ADS1115_REG_POINTER_CONFIG, config);
// Wait for the conversion to complete
QThread::msleep(ads_conversionDelay);
// Read the conversion results
uint16_t raw_adc = readRegister(ADS1115_REG_POINTER_CONVERT);
return (int16_t)raw_adc;
}
/**************************************************************************/
/*
Sets up the comparator causing the ALERT/RDY pin to assert
(go from high to low) when the ADC value exceeds the
specified upper or lower threshold
ADC is single-ended input channel
*/
/**************************************************************************/
int16_t ADS1115::Comparator_SingleEnded(uint8_t channel)
{
// Start with default values
uint16_t config;
// Set Operational status/single-shot conversion start
config |= ads_osmode;
// Set PGA/voltage range
config |= ads_gain;
// Set Device operating mode
config |= ads_mode;
// Set Data rate
config |= ads_rate;
// Set Comparator mode
config |= ads_compmode;
// Set Comparator polarity
config |= ads_comppol;
// Set Latching comparator
config |= ads_complat;
// Set Comparator queue and disable
config |= ads_compque;
// Set single-ended input channel
switch (channel)
{
case (0):
config |= ADS1115_REG_CONFIG_MUX_SINGLE_0;
break;
case (1):
config |= ADS1115_REG_CONFIG_MUX_SINGLE_1;
break;
case (2):
config |= ADS1115_REG_CONFIG_MUX_SINGLE_2;
break;
case (3):
config |= ADS1115_REG_CONFIG_MUX_SINGLE_3;
break;
}
// Write config register to the ADC
writeRegister(ADS1115_REG_POINTER_CONFIG, config);
// Wait for the conversion to complete
QThread::msleep(ads_conversionDelay);
// Read the conversion results
uint16_t raw_adc = readRegister(ADS1115_REG_POINTER_CONVERT);
return (int16_t)raw_adc;
}
/**************************************************************************/
/*
Sets up the comparator causing the ALERT/RDY pin to assert
(go from high to low) when the ADC value exceeds the
specified upper or lower threshold
ADC is Differential input channel
*/
/**************************************************************************/
int16_t ADS1115::Comparator_Differential(uint8_t channel)
{
// Start with default values
uint16_t config;
// Set Operational status/single-shot conversion start
config |= ads_osmode;
// Set PGA/voltage range
config |= ads_gain;
// Set Device operating mode
config |= ads_mode;
// Set Data rate
config |= ads_rate;
// Set Comparator mode
config |= ads_compmode;
// Set Comparator polarity
config |= ads_comppol;
// Set Latching comparator
config |= ads_complat;
// Set Comparator queue and disable
config |= ads_compque;
// Set Differential input channel
switch (channel)
{
case (01):
config |= ADS1115_REG_CONFIG_MUX_DIFF_0_1; // AIN0 = P, AIN1 = N
break;
case (03):
config |= ADS1115_REG_CONFIG_MUX_DIFF_0_3; // AIN0 = P, AIN3 = N
break;
case (13):
config |= ADS1115_REG_CONFIG_MUX_DIFF_1_3; // AIN1 = P, AIN3 = N
break;
case (23):
config |= ADS1115_REG_CONFIG_MUX_DIFF_2_3; // AIN2 = P, AIN3 = N
break;
}
// Write config register to the ADC
writeRegister(ADS1115_REG_POINTER_CONFIG, config);
// Wait for the conversion to complete
QThread::msleep(ads_conversionDelay);
// Read the conversion results
uint16_t raw_adc = readRegister(ADS1115_REG_POINTER_CONVERT);
return (int16_t)raw_adc;
}
| 29.76867
| 111
| 0.478248
|
JoseSalamancaCoy
|
060bf33a5baa649811745c1a7cd1363a608a57e5
| 1,744
|
hpp
|
C++
|
src/gui/MissionView/MissionView.hpp
|
tomcreutz/planning-templ
|
55e35ede362444df9a7def6046f6df06851fe318
|
[
"BSD-3-Clause"
] | 1
|
2022-03-31T12:15:15.000Z
|
2022-03-31T12:15:15.000Z
|
src/gui/MissionView/MissionView.hpp
|
tomcreutz/planning-templ
|
55e35ede362444df9a7def6046f6df06851fe318
|
[
"BSD-3-Clause"
] | null | null | null |
src/gui/MissionView/MissionView.hpp
|
tomcreutz/planning-templ
|
55e35ede362444df9a7def6046f6df06851fe318
|
[
"BSD-3-Clause"
] | 1
|
2021-12-29T10:38:07.000Z
|
2021-12-29T10:38:07.000Z
|
#ifndef TEMPL_GUI_MISSION_VIEW_HPP
#define TEMPL_GUI_MISSION_VIEW_HPP
#include <QTreeWidget>
#include <QWidget>
#include <QProcess>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsGridLayout>
#include <QTreeView>
#include <QStandardItem>
#include <QDomNode>
#include <graph_analysis/Graph.hpp>
#include "../../Mission.hpp"
namespace templ {
namespace gui {
class MissionView : public QTreeView
{
Q_OBJECT
public:
MissionView(QWidget* parent = NULL);
~MissionView();
QString getClassName() const
{
return "templ::gui::MissionView";
}
Mission::Ptr getMission() const { return mpMission; }
private:
QStandardItem* mpItem;
Mission::Ptr mpMission;
QString mFilename;
void updateVisualization();
void loadXML(const QString& missionSpec);
void refreshView();
QStandardItem* createRoot(const QString& name);
QStandardItem* createChild(QStandardItem* item, const QDomNode& node);
void setItem(QStandardItemModel* model);
void preOrder(QDomNode node, QStandardItemModel* model, QStandardItem* item = 0);
public slots:
void on_planMission_clicked();
// Adding/Removing Constraints
void on_addConstraintButton_clicked();
void on_removeConstraintButton_clicked();
/**
* Loading/Storing Missions
* \return True, when mission was loaded, false otherwise
*/
bool loadMission(const QString& settingsLabel ="IOMission", const QString& filename = "");
void on_saveButton_clicked();
void on_updateButton_clicked();
void on_clearButton_clicked();
const QString& getFilename() const { return mFilename; }
};
} // end namespace gui
} // end namespace templ
#endif // TEMPL_GUI_MISSION_VIEW_HPP
| 23.567568
| 94
| 0.71961
|
tomcreutz
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.