blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
50af7ec7d902b1964cfb831857f27ddb02146314 | bf7cf4c0f777dc3648be7831bb4f05793cd2cf8d | /GN_FinalAssignment_UDPx/MineSweepers_UDPServer/MyCursor.h | f6852233449ee49903f42851120fc4ac98c34892 | [] | no_license | aCordion/CK_2018-01-02 | c846ca48ea2599f343046cedb454f60709d02b9d | 7bb2c8448b10e1fccd4a06ae4489f523b0b25821 | refs/heads/master | 2021-08-22T15:31:39.403543 | 2018-12-19T11:12:32 | 2018-12-19T11:12:32 | 148,662,280 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 644 | h | #pragma once
class CMyCursor
{
int m_x; //커서 좌표
int m_y; //커서 좌표
int m_width; //화면 가로 크기
int m_height; //화면 세로 크기
bool isHide;
public:
CMyCursor();
~CMyCursor();
CMyCursor(int x, int y, int w, int h, bool hide = true) : m_x(x), m_y(y), m_width(w), m_height(h), isHide(hide){}
int getX() { return m_x; }
int getY() { return m_y; }
void goUp() { m_y - 1 < 0 ? 0 : m_y--; }
void goDown() { m_y + 1 > m_height - 1 ? 0 : m_y++; }
void goLeft() { m_x - 1 < 0 ? 0 : m_x--; }
void goRight() { m_x + 1 > m_width - 1 ? 0 : m_x++; }
void setHide(bool hide) { isHide = hide; }
void draw();
};
| [
"39215817+aCordion@users.noreply.github.com"
] | 39215817+aCordion@users.noreply.github.com |
2f8490aaa091d7ece7860b51ab82932c3849068f | 9eaee5c68f53ee3749167fb8d941f6d4d841ba9e | /Editor/QStringAndQVariant.h | c6f52b06d37fd5ce32206049fd9f42931de69e76 | [] | no_license | 0xlitf/Editor | ad78293b27a198b1699c0f0ae5b062e8fe772c7e | 61baaf8fcf2f516eb2b2e66970dcddb1bc421f69 | refs/heads/master | 2023-05-24T02:39:01.996225 | 2016-01-02T17:00:25 | 2016-01-02T17:00:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | h | #ifndef QStringAndQVariant_h__
#define QStringAndQVariant_h__
#include <QString>
#include <QVariant>
class QStringAndQVariant
{
public:
QStringAndQVariant(void);
~QStringAndQVariant(void);
static QVariant stringToVariant(QVariant::Type type, const QString &);
static QString vairantToString(const QVariant &);
};
#endif // QStringAndQVariant_h__
| [
"calciferlorain@gmail.com"
] | calciferlorain@gmail.com |
163278772b2d2d310ad675d9e9ee21f6aaf1c466 | 4258763312424d1fbd34ad597216491f934e12f9 | /Swan/src/Scene/Scene.cpp | 5f864a17506798a7f5d299217a04512caed32cf2 | [
"MIT"
] | permissive | ranoke/swan3d | cbe97736e9aa093991fe4562352f1f56a7972bf2 | 4ce1f0461b38f12cee73b2fc2d2a28c7e1e0b31d | refs/heads/main | 2023-02-16T02:30:10.052093 | 2021-01-14T18:59:27 | 2021-01-14T18:59:27 | 311,061,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,096 | cpp | #include "pch.h"
#include "Scene.h"
#include "Renderer/Renderer.h"
#include "Entity.h"
namespace Swan
{
Entity Scene::CreateEntity(const std::string& name)
{
Entity entity = { m_Registry.create(), this };
entity.AddComponent<TransformComponent>();
auto& tag = entity.AddComponent<TagComponent>();
tag.Tag = name.empty() ? "Entity" : name;
return entity;
}
void Scene::DestroyEntity(Entity entity)
{
m_Registry.destroy(entity);
}
void Scene::OnLoad()
{
}
void Scene::OnUpdate(Timestep ts, Camera& camera)
{
glm::mat4 view = glm::mat4(1.0f);
view = glm::translate(view, glm::vec3(0.f, 3.f, 5.0f));
Renderer::BeginScene(camera, view);
auto group = m_Registry.group<TransformComponent>(entt::get<MeshComponent>);
for (auto entity : group)
{
const auto [transform, mesh] = group.get<TransformComponent, MeshComponent>(entity);
auto t = transform.GetTransform();
Renderer::RenderBuffer(mesh.mesh, t, glm::vec3(255), nullptr);
}
Renderer::EndScene();
}
}// namespace Swan
| [
"ranokpvp@gmail.com"
] | ranokpvp@gmail.com |
f49b250cae82aa2cac8d228e9e2338f8729050d8 | 1e82e51bfca5cfbaf8e4c0c3fa018101036791e1 | /src/core/public/query/DgR2QueryDiskDisk.h | 5d73d48cf6444195f25b6196a0d43625f024e07a | [
"MIT"
] | permissive | int-Frank/DgLib-deprecated | 74bc2df68fed9b60359189d9a03601f7fa3331dc | 2683c48d84b995b00c6fb13f9e02257d3c93e80c | refs/heads/master | 2022-04-02T17:05:22.205320 | 2020-01-04T07:49:23 | 2020-01-04T07:49:23 | 33,456,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | h | //! @file DgR3QueryLineSphere.h
//!
//! @author: Adapted from http://www.geometrictools.com
//! @date 29/05/2016
//!
//! Class declaration: TIQuery
#ifndef DGR3QUERYDISKDISK_H
#define DGR3QUERYDISKDISK_H
#include "..\impl\DgFPCQueryHypersphereHypersphere.h"
namespace Dg
{
namespace R2
{
template<typename Real>
using FPCDiskDisk = impl::FPCQuery<Real, 2, impl::Hypersphere_generic<Real, 2>, impl::Hypersphere_generic<Real, 2>>;
}
}
#endif | [
"frankhart010@gmail.com"
] | frankhart010@gmail.com |
2a077ac5955bfbbd79cc1fc6f8689c4346073803 | e7810ab9687b6e929eb081f4e50e4fec43330b8a | /fit_curve/fit_curve.cpp | 9ab000802a0e92109edf835f2c194f5ac00c66fb | [] | no_license | marcel1hruska/fit_curve | a0a28167ed8f9761ce6e46bfd8f33b77ff49ac77 | d4435f82877972f6957ab5200a6d8de819434e7f | refs/heads/master | 2020-09-13T14:29:50.308480 | 2019-11-20T00:32:43 | 2019-11-20T00:32:43 | 222,816,672 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,959 | cpp | /*
C++ implementation of
An Algorithm for Automatically Fitting Digitized Curves
by Philip J. Schneider
from "Graphics Gems", Academic Press, 1990
*/
#include<string>
#include<iostream>
#include<cmath>
#include"fit_curve.h"
#define MAXPOINTS 1000
using namespace std;
/*
* FitCurve :
* Fit a Bezier curve to a set of points.
*/
vector<BezierCurve> FitCurve(vector<cv::Point2d> const& d, int startIndex, int endIndex, double error)
{
if (error <= 0.0) throw "error value must be greater than 0.0";
cv::Point2d tHat1, tHat2; // Unit tangent vectors at endpoints.
vector<BezierCurve> bezCurves; // The vector that will store the BezierCurve
// values to be returned once the curve fitting
// is complete.
// if startIndex is the beginning of the curve.
tHat1 = computeLeftTangent(d, startIndex);
// if endIndex is the end of the curve.
tHat2 = computeRightTangent(d, endIndex - 1);
FitCubic(d, &bezCurves, startIndex, endIndex - 1, tHat1, tHat2, error);
return bezCurves;
}
void addBezierCurve(vector<cv::Vec2d> const& bezCurve, vector<BezierCurve>* bezCurves)
{
// add curve to an array of curves which will then be returned on FitCurve.
BezierCurve newBezier;
newBezier.pt1 = bezCurve[0];
newBezier.pt2 = bezCurve[3];
newBezier.c1 = bezCurve[1];
newBezier.c2 = bezCurve[2];
bezCurves->push_back(newBezier);
}
/*
* FitCubic :
* Fit a Bezier curve to a (sub)set of points
*/
void FitCubic(vector<cv::Point2d> const& d, vector<BezierCurve>* bezCurves,
int first, int last, cv::Vec2d tHat1, cv::Vec2d tHat2, double error)
{
// Control points of fitted Bezier curve;
vector<cv::Vec2d> bezCurve(4);
// Parameter values for point
vector<double>* u = new vector<double>(last - first + 1);
// Improved parameter values
vector<double>* uPrime = new vector<double>(last - first + 1);
double maxError; // Maximum fitting error
int splitPoint; // Point to split point set at
int nPts; // Number of points in subset
double iterationError; // Error below which you try iterating
int maxIterations = 20; // Max times to try iterating
cv::Point2d tHatCenter; // Unit tangent vector at splitPoint
int i;
iterationError = error * error;
nPts = last - first + 1;
if (nPts == 1)
{
cout << "Only have 1 point, so no fitting" << endl;
return;
}
// Use heuristic if region only has two points in it
if (nPts == 2)
{
double dist = getDistance(d[last], d[first]) / 3.0;
bezCurve[0] = d[first];
bezCurve[3] = d[last];
bezCurve[1] = bezCurve[0] + scaleVec(tHat1, dist);
bezCurve[2] = bezCurve[3] + scaleVec(tHat2, dist);
addBezierCurve(bezCurve, bezCurves);
cout << "Fit 2 Points, use heuristic" << endl;
return;
}
// Parameterize points, and attempt to fit curve
chordLengthParameterize(d, first, last, u);
generateBezier(d, &bezCurve, first, last, *u, tHat1, tHat2);
// Find max deviation of points to fitted curve
maxError = computeMaxError(d, first, last, &bezCurve, *u, &splitPoint);
//cout << maxError << endl;
//cout << splitPoint << endl;
if (maxError < error) {
addBezierCurve(bezCurve, bezCurves);
return;
}
// If error not too large, try some reparameterization
// and iteration
if (maxError < iterationError) {
for (i = 0; i < maxIterations; ++i) {
uPrime = reparameterize(d, first, last, *u, &bezCurve);
generateBezier(d, &bezCurve, first, last, *uPrime, tHat1, tHat2);
maxError = computeMaxError(d, first, last, &bezCurve, *uPrime, &splitPoint);
if (maxError < error) {
addBezierCurve(bezCurve, bezCurves);
return;
}
u = uPrime;
}
}
// Fitting failed -- split at max error point and fit recursively
tHatCenter = computeCenterTangent(d, splitPoint);
FitCubic(d, bezCurves, first, splitPoint, tHat1, tHatCenter, error);
FitCubic(d, bezCurves, splitPoint, last, -tHatCenter, tHat2, error);
}
void generateBezier(vector<cv::Point2d> const& d, vector<cv::Vec2d>* bezCurve,
int first, int last, vector<double> const& uPrime, cv::Vec2d tHat1, cv::Vec2d tHat2)
{
cv::Vec2d A[MAXPOINTS][2]; // Precomputed rhs for eqn
int nPts; // Number of pts in sub-curve
double C[2][2]; // Matrix C
double X[2]; // Matrix X
double det_C0_C1, det_C0_X, det_X_C1; // Determinants of matrices
double alpha_l, alpha_r; // Alpha values, left and right
cv::Point2d tmp; // Utility variable
nPts = last - first + 1;
// Compute the A
for (int i = 0; i < nPts; ++i)
{
cv::Vec2d v1, v2;
v1 = scaleVec(tHat1, B1(uPrime[i]));
v2 = scaleVec(tHat2, B2(uPrime[i]));
A[i][0] = v1;
A[i][1] = v2;
}
// Create the C and X matrices
C[0][0] = 0.0;
C[0][1] = 0.0;
C[1][0] = 0.0;
C[1][1] = 0.0;
X[0] = 0.0;
X[1] = 0.0;
for (int i = 0; i < nPts; i++) {
C[0][0] += A[i][0].dot(A[i][0]);
C[0][1] += A[i][0].dot(A[i][1]);
C[1][0] = C[0][1];
C[1][1] += A[i][1].dot(A[i][1]);
tmp = (d[first + i]) -
((d[first] * B0(uPrime[i])) +
((d[first] * B1(uPrime[i])) +
((d[last] * B2(uPrime[i])) +
(d[last] * B3(uPrime[i])))));
X[0] += A[i][0].dot(tmp);
X[1] += A[i][1].dot(tmp);
}
// Compute the determinants of C and X
det_C0_C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1];
det_C0_X = C[0][0] * X[1] - C[1][0] * X[0];
det_X_C1 = X[0] * C[1][1] - X[1] * C[0][1];
// Finally, derive alpha values
alpha_l = (det_C0_C1 == 0) ? 0.0 : det_X_C1 / det_C0_C1;
alpha_r = (det_C0_C1 == 0) ? 0.0 : det_C0_X / det_C0_C1;
// Checks for "dangerous" points, meaning that the alpha_l or alpha_r are abnormally large
// from here http://newsgroups.derkeiler.com/Archive/Comp/comp.graphics.algorithms/2005-08/msg00419.html
// This is a common problem with this algoithm.
double dif1 = getDistance(d[first], d[last]);
bool danger = false;
if ((alpha_l > dif1 * 2) || (alpha_r > dif1 * 2)) {
first += 0;
danger = true;
}
// If alpha negative, use the Wu/Barsky heuristic (see text)
// (if alpha is 0, you get coincident control points that lead to
// divide by zero in any subsequent NewtonRaphsonRootFind() call.
double segLength = getDistance(d[first], d[last]);
double epsilon = 1.0e-6 * segLength;
if (alpha_l < epsilon || alpha_r < epsilon || danger)
{
// fall back on standard (probably inaccurate) formula, and subdivide further if needed.
double dist = segLength / 3.0;
bezCurve->at(0) = d[first];
bezCurve->at(3) = d[last];
bezCurve->at(1) = bezCurve->at(0) + scaleVec(tHat1, dist);
bezCurve->at(2) = bezCurve->at(3) + scaleVec(tHat2, dist);
return; //bezCurve;
}
// First and last control points of the Bezier curve are
// positioned exactly at the first and last data points
// Control points 1 and 2 are positioned an alpha distance out
// on the tangent vectors, left and right, respectively
bezCurve->at(0) = d[first];
bezCurve->at(3) = d[last];
bezCurve->at(1) = bezCurve->at(0) + scaleVec(tHat1, alpha_l);
bezCurve->at(2) = bezCurve->at(3) + scaleVec(tHat2, alpha_r);
}
/*
* Reparameterize:
* Given set of points and their parameterization, try to find
* a better parameterization.
*/
vector<double>* reparameterize(vector<cv::Point2d> const& d, int first, int last, vector<double> const& u, vector<cv::Vec2d>* bezCurve)
{
int nPts = last - first + 1;
vector<double>* uPrime = new vector<double>(nPts); // New parameter values
for (int i = first; i <= last; i++) {
uPrime->at(i - first) = newtonRaphsonRootFind(*bezCurve, d[i], u.at(i - first));
}
return uPrime;
}
/*
* NewtonRaphsonRootFind :
* Use Newton-Raphson iteration to find better root.
*/
double newtonRaphsonRootFind(vector<cv::Vec2d> const& Q, cv::Point2d P, double u)
{
double numerator, denominator;
vector<cv::Vec2d> Q1(3), Q2(2); // Q' and Q''
cv::Vec2d Q_u, Q1_u, Q2_u; // u evaluated at Q, Q', & Q''
double uPrime; // Improved u
// Compute Q(u)
Q_u = bezierII(3, Q, u);
// Generate control vertices for Q'
for (int i = 0; i <= 2; i++) {
Q1[i][0] = (Q[i + 1][0] - Q[i][0]) * 3.0;
Q1[i][1] = (Q[i + 1][1] - Q[i][1]) * 3.0;
}
// Generate control vertices for Q''
for (int i = 0; i <= 1; i++) {
Q2[i][0] = (Q1[i + 1][0] - Q1[i][0]) * 2.0;
Q2[i][1] = (Q1[i + 1][1] - Q1[i][1]) * 2.0;
}
// Compute Q'(u) and Q''(u)
Q1_u = bezierII(2, Q1, u);
Q2_u = bezierII(1, Q2, u);
// Compute f(u)/f'(u)
numerator = (Q_u[0] - P.x) * (Q1_u[0]) + (Q_u[1] - P.y) * (Q1_u[1]);
denominator = (Q1_u[0]) * (Q1_u[0]) + (Q1_u[1]) * (Q1_u[1]) +
(Q_u[0] - P.x) * (Q2_u[0]) + (Q_u[1] - P.y) * (Q2_u[1]);
if (denominator == 0.0) return u;
// u = u - f(u)/f'(u)
uPrime = u - (numerator / denominator);
return (uPrime);
}
/*
* Bezier :
* Evaluate a Bezier curve at a particular parameter value
*/
cv::Point2d bezierII(int degree, vector<cv::Vec2d> const& V, double t)
{
cv::Point2d Q; // Point on curve at parameter t
cv::Vec2d* Vtemp; // Local copy of control points
// copy array
Vtemp = new cv::Vec2d[degree + 1];
for (int i = 0; i <= degree; ++i)
{
Vtemp[i] = V[i];
}
// Triangle computation
for (int i = 1; i <= degree; i++) {
for (int j = 0; j <= degree - i; j++) {
Vtemp[j][0] = (1.0 - t) * Vtemp[j][0] + t * Vtemp[j + 1][0];
Vtemp[j][1] = (1.0 - t) * Vtemp[j][1] + t * Vtemp[j + 1][1];
}
}
Q = Vtemp[0];
return Q;
}
/*
* B0, B1, B2, B3 :
* Bezier multipliers
*/
double B0(double u)
{
double tmp = 1.0 - u;
return (tmp * tmp * tmp);
}
double B1(double u)
{
double tmp = 1.0 - u;
return (3 * u * (tmp * tmp));
}
double B2(double u)
{
double tmp = 1.0 - u;
return (3 * u * u * tmp);
}
double B3(double u)
{
return (u * u * u);
}
/*
* ComputeLeftTangent, ComputeRightTangent, ComputeCenterTangent :
* Approximate unit tangents at endpoints and "center" of the curve.
*/
cv::Vec2d computeLeftTangent(vector<cv::Point2d> const& d, int end)
{
cv::Vec2d tHat1;
if (end == 0)
{
tHat1 = d[end + 1] - d[end];
}
else {
tHat1 = d[end + 1] - d[end - 1];
}
cv::normalize(tHat1, tHat1);
return tHat1;
}
cv::Vec2d computeRightTangent(vector<cv::Point2d> const& d, int end)
{
cv::Vec2d tHat2;
if (end == d.size() - 1)
{
tHat2 = d[end - 1] - d[end];
}
else {
tHat2 = d[end - 1] - d[end + 1];
}
cv::normalize(tHat2, tHat2);
return tHat2;
}
cv::Vec2d computeCenterTangent(vector<cv::Point2d> const& d, int center)
{
cv::Vec2d V1, V2, tHatCenter;
V1 = d[center - 1] - d[center];
V2 = d[center] - d[center + 1];
tHatCenter[0] = (V1[0] + V2[0]) / 2.0;
tHatCenter[1] = (V1[1] + V2[1]) / 2.0;
cv::normalize(tHatCenter, tHatCenter);
return tHatCenter;
}
/*
* ChordLengthParameterize :
* Assign parameter values to points
* using relative distances between points.
*/
void chordLengthParameterize(vector<cv::Point2d> const& d, int first, int last, vector<double>* u)
{
int i;
u->at(0) = 0.0;
for (i = first + 1; i <= last; ++i)
{
u->at(i - first) = u->at(i - first - 1) + getDistance(d[i], d[i - 1]);
}
for (i = first + 1; i <= last; ++i)
{
u->at(i - first) = u->at(i - first) / u->at(last - first);
}
}
/*
* ComputeMaxError :
* Find the maximum squared distance of digitized points
* to fitted curve.
*/
double computeMaxError(vector<cv::Point2d> const& d, int first, int last,
vector<cv::Vec2d>* bezCurve, vector<double> const& u, int* splitPoint)
{
double maxDist; // Maximum error
double dist; // Current error
cv::Point2d P; // Point on curve
cv::Vec2d v; // Vector from point to curve
*splitPoint = (last - first + 1) / 2;
maxDist = 0.0;
for (int i = first + 1; i < last; ++i)
{
P = bezierII(3, *bezCurve, u[i - first]);
v = P - d[i];
dist = v[0] * v[0] + v[1] * v[1];
if (dist >= maxDist)
{
maxDist = dist;
*splitPoint = i;
}
}
return (maxDist);
}
double getDistance(cv::Point2d p0, cv::Point p1)
{
double dx = p0.x - p1.x;
double dy = p0.y - p1.y;
return sqrt(dx * dx + dy * dy);
}
cv::Vec2d scaleVec(cv::Vec2d v, double newlen)
{
double len = sqrt(v[0] * v[0] + v[1] * v[1]);
if (len != 0.0)
{
v[0] *= newlen / len;
v[1] *= newlen / len;
}
return v;
} | [
"marcel1hruska@gmail.com"
] | marcel1hruska@gmail.com |
4388689d95289590cd1c6f9d84e7bb4c58728da0 | 7ea36abac559442702154d80254ea218c2b176d0 | /cpp/cpp2/cpp2.cpp | ee3c7b064ab7d4d2f1823636a2f2f6611fcfbcf8 | [] | no_license | danzaleta/c_cpp | 9dd30f112cf01cc784a1729139d69571684ac660 | 4cd9c31e223ccc241ded4a915a28e061e84ed710 | refs/heads/master | 2023-07-18T04:42:48.326575 | 2021-09-07T17:04:07 | 2021-09-07T17:04:07 | 304,169,853 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,156 | cpp | #include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
// SETTINGS
bool gameOn = true;
//USER INFO
string name;
int edad;
int peso;
// CASES
int option;
int arr[10];
while (gameOn)
{
cout << "[0] Nueva partida \n[1] Continuar \n[2] Cargar \n[3] Salir" << endl;
cin >> option;
switch (option)
{
case 0:
cout << "Usuario:" << endl;
cin >> name;
cout << "Edad:" << endl;
cin >> edad;
cout << "Peso:" << endl;
cin >> peso;
cout << "Usuario: " << name <<endl;
cout << "Edad: " << edad << " anios" << endl;
cout << "Peso: " << peso << " kg" <<endl;
break;
case 1:
break;
case 2:
break;
case 3:
cout << "Saliendo..." << endl;
gameOn = false;
break;
default:
cout << "Entrada incorrecta" << endl;
break;
}
}
return 0;
}
| [
"zaletadaniel@gmail.com"
] | zaletadaniel@gmail.com |
732c47ab46c1ee26b2216524892e3c34d20f3a34 | 2ce066f36aaa5e24ed8d07c3039b6b9e5cf12877 | /View/ModulAccount/account_view.h | 15acd05cc1c71e66098b6d852a1f78666d3d6909 | [] | no_license | Euclidis/Dictionary | b638c968dba1bc84e5467afca5ab1e601aaca07e | a9fc540a13b64c0eca480829780742218ecb8d48 | refs/heads/master | 2020-12-24T16:50:22.218791 | 2016-03-13T11:59:37 | 2016-03-13T11:59:37 | 52,585,927 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,071 | h | #ifndef ACCOUNTVIEW_H
#define ACCOUNTVIEW_H
#ifndef ACCOUNTVIEWINTERFACE_H
#include "account_viewinterface.h"
#endif
namespace Ui {
class AccountView;
}
class AccountView :
public QWidget,
public AccountViewInterface
{
Q_OBJECT
public:
explicit AccountView(QWidget *parent = 0);
~AccountView();
//______________AccountViewInterfaceAccount__
void messageNameUserEmpty();
void messageNameUserExist();
void messageNameUserNotFound();
void showView();
void hideView();
void setListLK(QAbstractItemModel* model);
void setListLL(QAbstractItemModel* model);
void initialize_();
//____________________________________
private:
QAbstractItemModel* listLK_ = nullptr;
QAbstractItemModel* listLL_ = nullptr;
private:
void message(const QString& text);
private slots:
void on_pbLogin_clicked();
void on_pbRegister_clicked();
void on_lwLK_clicked(const QModelIndex &index);
void on_lwLL_clicked(const QModelIndex &index);
private:
Ui::AccountView *ui;
};
#endif // ACCOUNTVIEW_H
| [
"amirberetar@gmail.com"
] | amirberetar@gmail.com |
98f0a7efd60a341164a4326f2c01b0ecf89741b3 | 300980256f6482567c5d9dc1795bb01aa20f01c7 | /leetcode/leetcode-019.cc | b70e5c750be13fa59c68788d2105ae0c05b0b4c2 | [] | no_license | zgnMark/Algorithm | 50886932c426be3575caaff152b09e85c70c861f | 7c6e2c2848e3aa0cd484f51a175fd57d3d135b4a | refs/heads/master | 2020-07-29T06:20:52.208876 | 2018-10-28T12:30:58 | 2018-10-28T12:30:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,013 | cc | #include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
} ;
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head == NULL)
return head;
/*if (head->next == NULL)
return NULL;*/
ListNode* p = NULL;
ListNode* q = NULL;
while (/*p->next != NULL && */n > 0) {
if (p == NULL)
p = head;
else
p = p->next;
--n;
}
while (p->next != NULL) {
p = p->next;
if (q == NULL)
q = head;
else
q = q->next;
}
ListNode* tmp = NULL;
if (q == NULL) {
tmp = head;
head = head->next;
} else {
tmp = q->next;
q->next = q->next->next;
}
delete tmp;
return head;
}
};
// No need debug | [
"nitingge@126.com"
] | nitingge@126.com |
377387af2c1646aefa7ae6715f9b2eaa332bb3de | a9acfe1965a5a6c197cffe6ebcdd35140b0ee1ca | /main.cpp | 25715b5e867017c7679b335e6aaf5140932b04af | [] | no_license | kindow/LaneLineDetection | d50d6b6cd44a3b59029d8a16d7fce9df8ceaeae3 | 7406792fe49cf82c30715e2fa20cb84447f879d2 | refs/heads/master | 2022-01-10T13:39:13.276112 | 2019-07-09T17:32:34 | 2019-07-09T17:32:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,860 | cpp | //
// main.cpp
// opencv4_test
//
// Created by Rahul Aggarwal on 6/26/19.
// Copyright © 2019 Rahul Aggarwal. All rights reserved.
//
#include <opencv2/opencv.hpp>
#include "cpuUtils.hpp"
#include <iostream>
#include <stdio.h>
#include "LaneLine.hpp"
#include "LaneLineHistory.hpp"
#include "AdvancedLaneDetectorWithMemory.hpp"
int main(int argc, char** argv)
{
cv::String imageNames[8];
for (int i = 1; i < 7; i++) {
imageNames[i-1] = cv::String("/Users/Infinity/Desktop/test_images/test" + std::to_string(i) + ".jpg");
}
imageNames[6] = cv::String("/Users/Infinity/Desktop/test_images/straight_lines1.jpg");
imageNames[7] = cv::String("/Users/Infinity/Desktop/test_images/straight_lines2.jpg");
cv::Mat straight_lines1 = cv::imread(imageNames[7], cv::IMREAD_COLOR);
cv:: Mat test6 = cv::imread(imageNames[5], cv::IMREAD_COLOR);
cv::Mat test5 = cv::imread(imageNames[4], cv::IMREAD_COLOR);
if(test6.empty() || straight_lines1.empty() || test5.empty()) {
std::cout << "Could not open or find the image" << std::endl;
return -1;
}
//Video testing
//cv::VideoCapture cap(cv::String("/Users/Infinity/Desktop/test_images/project_video.mp4"));
cv::VideoCapture cap(0);
cv::Mat frame;
if (!cap.isOpened()) {
throw "Error when reading the file";
}
//std::vector<cv::Point2f> src_pts{cv::Point2f(210, 720 - 1), cv::Point2f(595, 450), cv::Point2f(690, 450), cv::Point2f(1110, 720 - 1)};
//std::vector<cv::Point2f> dst_pts{cv::Point2f(200, 720 - 1), cv::Point2f(200, 0), cv::Point2f(1000, 0), cv::Point2f(1000, 720 - 1)};
std::vector<cv::Point2f> src_pts{cv::Point2f(105, 359), cv::Point2f(297, 225), cv::Point2f(345, 225), cv::Point2f(555, 359)};
std::vector<cv::Point2f> dst_pts{cv::Point2f(100, 359), cv::Point2f(100, 0), cv::Point2f(500, 0), cv::Point2f(500, 359)};
cv::Mat M_psp = cv::getPerspectiveTransform(src_pts, dst_pts);
//AdvancedLaneDetectorWithMemory ld(src_pts, dst_pts, 20, 100, 50);
AdvancedLaneDetectorWithMemory ld(src_pts, dst_pts, 20, 100, 50, cv::Size(640, 360));
cv::Mat channels[3];
while(true) {
cap >> frame;
//std::cout << frame.size() << std::endl;
if(frame.empty()) {
break;
}
/*cv::resize(frame, frame, cv::Size(640, 360));
cv::Mat test = cpu::combinedSobelThresholdImage(frame);
cv::warpPerspective(test, test, M_psp, cv::Size(test.cols, test.rows));
std::array<LaneLine, 2> laneLines = ld.computeLaneLines(test);
ld.drawLaneLines(test, frame, laneLines[0], laneLines[1]);*/
ld.processImage(frame);
cv::imshow("Display Window", frame);
if(cv::waitKey(1) >= 0) {
break;
}
}
cv::waitKey(0);
return 0;
}
| [
"rahulaggarwal965@gmail.com"
] | rahulaggarwal965@gmail.com |
a8d893e3dd4256a000b1ee55026810f0f3cd3561 | c7e26dc37573e8766e472990ab09ae046f49b3ef | /src/media/audio/audio_core/channel_attributes_unittest.cc | 27cf2e0d6d81dfcb2d9c7869f53c8d2da2e95612 | [
"BSD-2-Clause"
] | permissive | lambdaxymox/fuchsia | 03b72b387cbe14360868c98875ed0ed2d2bd8bf5 | 27dc297f40159d6fbd1368830b894d1299710cb5 | refs/heads/master | 2022-11-15T02:50:25.363189 | 2022-10-19T16:49:21 | 2022-10-19T16:49:21 | 296,795,562 | 1 | 2 | BSD-2-Clause | 2022-10-19T07:11:19 | 2020-09-19T05:47:00 | C++ | UTF-8 | C++ | false | false | 3,636 | cc | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/media/audio/audio_core/channel_attributes.h"
#include <fuchsia/media/cpp/fidl.h>
#include <vector>
#include <gtest/gtest.h>
namespace media::audio {
namespace {
constexpr uint32_t kTestAudibleFrequency = 2000;
constexpr uint32_t kTestUltrasonicFrequency = 27000;
// Return true if it overlaps the audible range at all. Must include more than just boundary value.
TEST(ChannelAttributesTest, ChannelIncludesAudible) {
EXPECT_FALSE(ChannelAttributes().IncludesAudible());
EXPECT_FALSE(ChannelAttributes(0, 0).IncludesAudible());
EXPECT_FALSE(ChannelAttributes(ChannelAttributes::kAudibleUltrasonicBoundaryHz,
fuchsia::media::MAX_PCM_FRAMES_PER_SECOND)
.IncludesAudible());
EXPECT_TRUE(ChannelAttributes(0, 1).IncludesAudible());
EXPECT_TRUE(ChannelAttributes(ChannelAttributes::kAudibleUltrasonicBoundaryHz - 1,
ChannelAttributes::kAudibleUltrasonicBoundaryHz)
.IncludesAudible());
EXPECT_TRUE(ChannelAttributes(kTestAudibleFrequency, kTestAudibleFrequency).IncludesAudible());
}
// Return true if it overlaps ultrasonic range. Must include more than just the boundary value.
TEST(ChannelAttributesTest, ChannelIncludesUltrasonic) {
EXPECT_FALSE(ChannelAttributes().IncludesUltrasonic());
EXPECT_FALSE(
ChannelAttributes(0, ChannelAttributes::kAudibleUltrasonicBoundaryHz).IncludesUltrasonic());
EXPECT_FALSE(ChannelAttributes(fuchsia::media::MAX_PCM_FRAMES_PER_SECOND / 2,
fuchsia::media::MAX_PCM_FRAMES_PER_SECOND)
.IncludesUltrasonic());
EXPECT_TRUE(ChannelAttributes(0, ChannelAttributes::kAudibleUltrasonicBoundaryHz + 1)
.IncludesUltrasonic());
EXPECT_TRUE(ChannelAttributes(fuchsia::media::MAX_PCM_FRAMES_PER_SECOND / 2 - 1,
fuchsia::media::MAX_PCM_FRAMES_PER_SECOND)
.IncludesUltrasonic());
EXPECT_TRUE(
ChannelAttributes(kTestUltrasonicFrequency, kTestUltrasonicFrequency).IncludesUltrasonic());
}
// If any channel includes any of the range, then the channel set supports audible
TEST(ChannelAttributesTest, VectorIncludesAudible) {
std::vector<ChannelAttributes> channel_attribs;
EXPECT_FALSE(ChannelAttributes::IncludesAudible(channel_attribs));
channel_attribs.push_back({0, 0});
channel_attribs.push_back(
{ChannelAttributes::kAudibleUltrasonicBoundaryHz, fuchsia::media::MAX_PCM_FRAMES_PER_SECOND});
EXPECT_FALSE(ChannelAttributes::IncludesAudible(channel_attribs));
channel_attribs.push_back({kTestAudibleFrequency, kTestAudibleFrequency});
EXPECT_TRUE(ChannelAttributes::IncludesAudible(channel_attribs));
}
// The set of channels must cover the entire ultrasonic range, contiguously
TEST(ChannelAttributesTest, VectorIncludesUltrasonic) {
std::vector<ChannelAttributes> channel_attribs;
EXPECT_FALSE(ChannelAttributes::IncludesUltrasonic(channel_attribs));
channel_attribs.push_back({0, ChannelAttributes::kAudibleUltrasonicBoundaryHz});
channel_attribs.push_back(
{fuchsia::media::MAX_PCM_FRAMES_PER_SECOND / 2, fuchsia::media::MAX_PCM_FRAMES_PER_SECOND});
EXPECT_FALSE(ChannelAttributes::IncludesUltrasonic(channel_attribs));
channel_attribs.push_back({kTestUltrasonicFrequency, kTestUltrasonicFrequency});
EXPECT_TRUE(ChannelAttributes::IncludesUltrasonic(channel_attribs));
}
} // namespace
} // namespace media::audio
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
6cc99318098544f33729114d233f057e23e4fb23 | bada30d01f229cbfb5c315d44f31b0038f15a523 | /ability/node/ChangeAbilityInfoNode.cpp | a65231b534dc6be08cdab7d42fb03330cd74a64f | [] | no_license | calmackenzie/VG1819 | 97d8c6d5823a1dbb618fd1ca7c21c5393fd8aff3 | 7bc8f3ba380209668ce281054fd9e024b4455d82 | refs/heads/master | 2021-10-26T12:24:19.940811 | 2019-04-11T19:59:10 | 2019-04-11T19:59:10 | 133,898,562 | 1 | 2 | null | 2019-04-11T01:21:31 | 2018-05-18T03:32:31 | C++ | UTF-8 | C++ | false | false | 358 | cpp | #pragma once
#include "ability/node/AbilityNode.h"
#include "ability/AbilityInfoPackage.h"
//Rock
namespace ability
{
ChangeAbilityInfoNode::ChangeAbilityInfoNode()
{
}
int ChangeAbilityInfoNode::effect(ability::AbilityInfoPackage* p_pack, const std::string& p_valueName, int p_value)
{
p_pack->m_intValue[p_valueName] += p_value;
return 0;
}
} | [
"you0rock0@gmail.com"
] | you0rock0@gmail.com |
7dbbf7696884555192b07035e46d5067928e43a3 | 9fccdc430b35121301d9a2e3ef4143f4a74e0f36 | /include/nbdl/concept/Store.hpp | db0a91f4193024b3fec7d32e56a17a8dc2413066 | [
"BSL-1.0"
] | permissive | drorspei/nbdl | 2668e49e1fa5147a59a2788e21af57d4aa579dc2 | 6ebac56d8d6910e7271819432febb5d0b76be68b | refs/heads/master | 2020-05-21T01:05:02.193382 | 2019-02-12T03:35:33 | 2019-02-12T03:35:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 641 | hpp | //
// Copyright Jason Rice 2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NBDL_CONCEPT_STORE_HPP
#define NBDL_CONCEPT_STORE_HPP
#include <nbdl/fwd/concept/Store.hpp>
#include <nbdl/fwd/match.hpp>
#include <boost/hana/core/default.hpp>
#include <boost/hana/core/tag_of.hpp>
namespace nbdl
{
namespace hana = boost::hana;
template <typename T>
struct Store
{
using Tag = typename hana::tag_of<T>::type;
static constexpr bool value = !hana::is_default<nbdl::match_impl<Tag>>::value;
};
}
#endif
| [
"ricejasonf@gmail.com"
] | ricejasonf@gmail.com |
a35314ff40e9b258dc9ab9cf3b6c51c7e47aa229 | 500396f79d674e893c607db3b42d0d04a9d6ee89 | /MGL/MGLFileLoaderMGL.cpp | fdb3d63136c07123b94eed3cdab558b2a0d0298d | [] | no_license | MrMCG/MGL_old | a682a9e69c4fe9022411fa1cd1717f476dac50b6 | 82a5a2aae78d4cb788a1c65fc65476ac0129ab13 | refs/heads/master | 2021-06-05T13:03:44.988814 | 2016-09-22T01:00:42 | 2016-09-22T01:00:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,422 | cpp | #include "stdafx.h"
#include "MGLFileLoaderMGL.h"
#include "MGLMesh.h"
#include "MGLExceptions.h"
#include "MGLLog.h"
#include "MGLTimer.h"
#include "MGLMeshGenerator.h"
MGLMesh* MGLFileLoaderMGL::Load(std::string fileName) {
MGLTimer timer = MGLTimer();
timer.Start();
std::vector<GLfloat>* buffer = LoadFileToVec<GLfloat>(fileName);
#ifdef MGL_USER_INCLUDE_FILETC
try {
// buffers not null
MGLException_IsNullptr::Test(buffer);
// buffer size is large enough (for DetermineFileSize())
MGLException_IsLessThan::Test(buffer->size(), (std::size_t)MGL_FILELOADERMGL_BUFFERMINSIZE);
// buffer size is what is expected
MGLException_IsNotEqual::Test(DetermineFileSize(
(GLuint)buffer->at(2), (GLuint)buffer->at(3), (GLint)buffer->at(4)) + 1, buffer->size());
}
catch (MGLException_IsNullptr& e) {
//std::cerr << e.what() << ": FILE SIZE ERROR " << fileName << std::endl;
MGLI_Log->AddLog(MGL_LOG_ERROR, GL_TRUE, "%s%s", e.what(), ": Null Buffer");
delete buffer;
return MGLMeshGenerator::Triangle();
}
catch (MGLException& e) {
//std::cerr << e.what() << ": FILE SIZE ERROR " << fileName << std::endl;
MGLI_Log->AddLog(MGL_LOG_ERROR, GL_TRUE, "%s%s%s", e.what(), ": FILE SIZE ERROR ", fileName.c_str());
delete buffer;
return MGLMeshGenerator::Triangle();
}
#endif // MGL_USER_INCLUDE_FILETC
MGLMesh* mesh = LoadMesh(buffer);
mesh->BufferAllData();
delete buffer;
timer.End();
MGLI_Log->AddLog(MGL_LOG_MAIN, GL_TRUE, "MGL Load: %s : %i vertices in %f", fileName.c_str(), mesh->GetNumVertices(), timer.GetTime());
return mesh;
}
std::size_t MGLFileLoaderMGL::DetermineFileSize(const GLuint numVertices, const GLuint numIndices, const GLint colourVal) const {
// number of floats in vectors
GLuint vec4Size = 4;
GLuint vec3Size = 3;
GLuint vec2Size = 2;
GLuint total = 5; // fileVersion, type, numVertices, numIndices, colourVal
total += numVertices * (vec3Size * 2); // vertices, normals
total += numVertices * vec2Size; // texCoords
if (colourVal == -1) {
total += vec4Size; // colours
}
else if (colourVal > 0) {
total += colourVal * vec4Size; // colours
}
total += numIndices;
return (std::size_t)total;
}
MGLMesh* MGLFileLoaderMGL::LoadMesh(const MGLvecf* buffer) {
GLuint fileVersion, type, numVertices, numIndices;
GLint colourVal;
GLuint loc = 0;
// build mesh from vector
fileVersion = (GLuint)buffer->at(loc);
type = (GLuint)buffer->at(++loc);
numVertices = (GLuint)buffer->at(++loc);
numIndices = (GLuint)buffer->at(++loc);
colourVal = (GLint)buffer->at(++loc);
MGLvecv3* vertices = new MGLvecv3(numVertices);
MGLvecv2* texCoords = new MGLvecv2(numVertices);
MGLvecv3* normals = new MGLvecv3(numVertices);
MGLvecv4* colours = new MGLvecv4(numVertices);
MGLvecu* indices = new MGLvecu(numIndices);
MGLMesh* mesh = new MGLMesh();
mesh->SetNumIndices(numIndices);
mesh->SetNumVertices(numVertices);
mesh->SetType(type);
// vertices
for (GLuint i = 0; i < numVertices; ++i) {
glm::vec3 vec;
vec.x = buffer->at(++loc);
vec.y = buffer->at(++loc);
vec.z = buffer->at(++loc);
vertices->at(i) = vec;
}
mesh->SetVertices(vertices);
// TexCoords
for (GLuint i = 0; i < numVertices; ++i) {
glm::vec2 vec;
vec.x = buffer->at(++loc);
vec.y = buffer->at(++loc);
texCoords->at(i) = vec;
}
mesh->SetTexCoords(texCoords);
// Normals
for (GLuint i = 0; i < numVertices; ++i) {
glm::vec3 vec;
vec.x = buffer->at(++loc);
vec.y = buffer->at(++loc);
vec.z = buffer->at(++loc);
normals->at(i) = vec;
}
mesh->SetNormals(normals);
// Colours
if (colourVal < 1)
{
glm::vec4 vec;
if (colourVal == -1) {
vec.x = buffer->at(++loc);
vec.y = buffer->at(++loc);
vec.z = buffer->at(++loc);
vec.w = buffer->at(++loc);
}
else if (colourVal == 0) {
vec = MGL::WHITE;
}
mesh->SetColours(colours);
mesh->SetNewColours(vec, GL_FALSE);
}
else {
for (GLuint i = 0; i < numVertices; ++i) {
glm::vec4 vec;
vec.x = buffer->at(++loc);
vec.y = buffer->at(++loc);
vec.z = buffer->at(++loc);
vec.w = buffer->at(++loc);
colours->at(i) = vec;
}
mesh->SetColours(colours);
}
// Indices
for (GLuint i = 0; i < numIndices; ++i) {
GLuint temp;
temp = (GLuint)buffer->at(++loc);
indices->at(i) = temp;
}
mesh->SetIndices(indices);
vertices = nullptr;
texCoords = nullptr;
normals = nullptr;
colours = nullptr;
indices = nullptr;
return mesh;
} | [
"mark.gentles@hotmail.co.uk"
] | mark.gentles@hotmail.co.uk |
d6b1ca364b4ac467d7cbf340d378ed3d638cfbaa | 853398fb9eec1bb663577837bb4f9da759b7cd56 | /2D_shooter_v2/src/DebugEngine.cpp | 75ee733ad6070e93692810c786cac375a4b2bbe0 | [] | no_license | kelj0/gamedevplayground | ab597b42aeb2408f3cf7a5b07fb8c901aa3e924d | 0b538293b32bd9a2c61d53250918abe045d73fdf | refs/heads/master | 2023-05-01T07:37:44.644478 | 2021-05-24T11:41:25 | 2021-05-24T11:41:25 | 342,294,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 892 | cpp | #include "DebugEngine.h"
DebugEngine::DebugEngine(sf::RenderWindow &window, std::vector<Player*> players, sf::Font font) {
this->_window = &window;
this->_font = font;
this->_players = players;
}
void DebugEngine::updateData(){
sf::Text t;
t.setFont(_font);
std::string b = "";
for (Player *p: _players) {
b += p->name + ": " + std::to_string(p->x) + ", " + std::to_string(p->y) + "\n";
b += "m_vector: " + std::to_string(p->vec_movement.x) + ", " + std::to_string(p->vec_movement.y) + "\n";
b += "speed: " + std::to_string(p->getSpeed()) + "\n";
b += "on_floor: " + std::to_string(p->on_floor) + "\n";
}
t.setString(b);
t.setCharacterSize(20);
t.setFillColor(sf::Color::Red);
this->_window->draw(t);
}
void DebugEngine::tick() {
this->_window->clear();
updateData();
this->_window->display();
}
| [
"kelj0@protonmail.com"
] | kelj0@protonmail.com |
45c46a692879a16f68fa28c542755cc18cb49df4 | 2dbbcbdceb9c3e1647a401103bf55afabe156eac | /sca/samples/BigBank/Accounts/AccountServiceImpl_AccountDataService_Proxy.h | ff5c6e6d8779052b58496ce94cef81dc805df470 | [
"Apache-2.0"
] | permissive | lelou13/tuscany-sca-cpp | bd30f5967f0c3a95382d80f38ee41a16ec7420ca | b06cb5b2608c0802c15c75c708589e82a9c60e2d | refs/heads/cpp-M1 | 2021-01-15T08:04:32.276885 | 2009-11-16T06:23:13 | 2009-11-16T06:23:13 | 49,079,719 | 0 | 0 | null | 2016-01-05T16:58:49 | 2016-01-05T16:58:49 | null | UTF-8 | C++ | false | false | 1,513 | h | /*
* Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
*
* 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.
*/
#if defined(WIN32) || defined (_WINDOWS)
#pragma warning(disable: 4786)
#endif
#ifndef AccountServiceImpl_AccountDataService_Proxy_h
#define AccountServiceImpl_AccountDataService_Proxy_h
#include "AccountDataService.h"
#include "tuscany/sca/core/ServiceWrapper.h"
class AccountServiceImpl_AccountDataService_Proxy : public com::bigbank::account::AccountDataService
{
public:
AccountServiceImpl_AccountDataService_Proxy(tuscany::sca::ServiceWrapper*);
virtual ~AccountServiceImpl_AccountDataService_Proxy();
virtual commonj::sdo::DataObjectPtr getCheckingAccount(const char* id);
virtual commonj::sdo::DataObjectPtr getSavingsAccount(const char* id);
virtual commonj::sdo::DataObjectPtr getStockAccount(const char* id);
private:
tuscany::sca::ServiceWrapper* target;
};
#endif // AccountServiceImpl_AccountDataService_Proxy_h
| [
"edslattery@apache.org"
] | edslattery@apache.org |
361bc814380c7552c0b6323d528e1030dce21798 | 0bf4e9718ac2e2845b2227d427862e957701071f | /google_code_jam/all/final_09/d/lq.cpp | 4d0367312899483f5b9035bdf0a0ad70a85535ad | [] | no_license | unjambonakap/prog_contest | adfd6552d396f4845132f3ad416f98d8a5c9efb8 | e538cf6a1686539afb1d06181252e9b3376e8023 | refs/heads/master | 2022-10-18T07:33:46.591777 | 2022-09-30T14:44:47 | 2022-09-30T15:00:33 | 145,024,455 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,640 | cpp | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <algorithm>
#include <numeric>
#include <utility>
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>
//#include <ext/hash_map>
using namespace std;
using namespace __gnu_cxx;
#define PI asin(1)*2.
#define EPS 10e-8
#define REP(i,n) for(i = 0; i < (n); i++)
#define REPC(i,n,c) for(i = 0; (i < (n)) && (c); i++)
#define REPV(i, n) for (i = (n) - 1; i >= 0; i--)
#define REPVC(i, n, c) for (i = (n) - 1; (i >= 0) && (c); i--)
#define FOR(i, a, b) for(i = (a); i <= (b); i++)
#define FORC(i, a, b, c) for(i = (a); (i <= (b)) && (c); i++)
#define FORV(i, a, b) for(i = (a); i >= (b); i--)
#define FORVC(i, a, b, c) for(i = (a); (i >= (b)) && (c); i--)
#define FE(i,t) for (typeof(t.begin())i=t.begin();i!=t.end();i++)
#define FEV(i,t) for (typeof(t.rbegin())i=t.rbegin();i!=t.rend();i++)
#define MAX(a,b) (((a) < (b)) ? (b) : (a))
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#define pb push_back
#define ST first
#define ND second
#define SZ(a) ((a).size())
#define two(x) (1 << (x))
#define twoll(x) (1LL << (x))
#define ALL(a) (a).begin(), (a).end()
#define CLR(a) (a).clear()
#define SWAP(a,b,c) (c=a, a=b, b=c)
#define SQR(x) (pow((x),2))
#define DIST(x,y) (SQR(x)+SQR(y))
#define MDIST(x,y,a,b) (abs((a)-(x))+abs((b)-(y)))
#define CMP(x,y) ((fabs((x)-(y)) < EPS) ? 0 : ((x) < (y)) ? -1 : 1)
#define ST first
#define ND second
#define ll long long
inline int count_bit(int n){return (n == 0)?0:(n&1)+count_bit(n>>1);}
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<string> vs;
typedef queue<int> qi;
#define MAX_N 500
class WT{
public:
WT(){}
//WT(int _x, int _y, int _c, int _r){x=_x, y=_y, c=_c, r=_r;}
int x, y, c, r;
};
vi edge[MAX_N];
WT wl[MAX_N];
int n;
int solve(){
int i, j, k, c, nc;
vi::iterator it;
c=-1;
REP(i, two(n)){
nc=0;
REP(k, n)
if (i&two(k)){
nc+=wl[k].c;
for(it=edge[k].begin(); it!=edge[k].end(); it++)
if (!(i&two(*it)))break;
if (it != edge[k].end())break;
}
if (k != n)continue;
c=MAX(c, nc);
}
return c;
}
int main(){
int i, j, k, T;
scanf("%d", &T);
REP(i, T){
scanf("%d", &n);
REP(j, n)
scanf("%d %d %d %d", &wl[j].x, &wl[j].y, &wl[j].r, &wl[j].c);
REP(j, n){
CLR(edge[j]);
REP(k, n)
if (DIST(wl[k].x-wl[j].x, wl[k].y-wl[j].y) <= SQR(wl[j].r))
edge[j].pb(k);
}
printf("Case #%d: %d\n", i+1, solve());
}
return EXIT_SUCCESS;
}
| [
"benoit@uuu.com"
] | benoit@uuu.com |
2de3bf4747419ebbc7c192ded50ec98231e7b421 | 2aef8e6ed65c879ba9557d34bb5c8ae6a7eda4f1 | /cpp/nearest_lucky_numbers_329.cpp | 0cdfd3ea807417be782e304cf729a48cddbd53d7 | [] | no_license | Anarcroth/daily-code-challenges | 987d1597eb0bd96b4f932874f084e41deb6fee69 | 46e9add896855aee3028858c06f7e46eb453d4aa | refs/heads/master | 2021-06-04T17:30:03.339100 | 2018-12-29T16:31:14 | 2020-01-10T12:35:05 | 109,251,734 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,331 | cpp | // Description
//
// A Lucky Number is a natural number in a set which is generated by a certain "sieve". This sieve is similar to the Sieve of Eratosthenes that generates the primes, but it eliminates numbers based on their position in the remaining set, instead of their value (or position in the initial set of natural numbers).
// The set of lucky numbers can be obtained by:-
// Begin with a list of integers starting with 1:
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Starting with 1, remove every other element (i.e. every even number) from this set. We are left with:
// 1 3 5 7 9 11 13 15 17 19 21 23 25
// After 1, the next number in the set is 3. So, remove every 3rd number. Clearly, 5 is removed because it's the third number in the above set. Go on and keep removing every 3rd number.
// Your new set is:
// 1 3 7 9 13 15 19 21 25...
// Here, the next remaining number you have after 3 is 7. Now, at this point, it's obvious that there's no way 1 and 3 are ever getting eliminated. Thus, we can conclude that 1 and 3 are lucky numbers.
// Now remove every 7th number. Clearly, 19 would be the first to be wiped out.
// You're left with:
// 1 3 7 9 13 15 21 25 ...
// Now it's time to proceed to the next remaining number after 7, i.e., 9. Remove every 9th number. Note that at this point, 7 cannot be eliminated. 7 is a lucky number too.
// Keep proceeding in a similar fashion in order to get a list of lucky numbers.
// Numbers remaining after this procedure has been carried out completely are called lucky numbers. The first few are
// 1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, ...
// Today's challenge is to find the nearest lucky number. This might remind you of Challenge #326. In fact, this has been inspired from it. Bruteforcing is the most obvious option, but it's certainly not the most efficient.
// Input Description
//
// The input will be a positive integer.
// Output Description
//
// The output will be
// previous lucky number < n < next lucky number
// where n is your input.
// If n is a lucky number, then display
// n is a lucky number.
// Challenge Input
//
// 103
// 225
// 997
// Challenge Output
//
// 99 < 103 < 105
// 223 < 225 < 231
// 997 is a lucky number
// Bonus
//
// Find every lucky number all the way up to 500010,000,000 and post your the time it took to run. This is so that you can compete amongst everyone else to see who has the most efficient one.
#include <iostream>
#include <vector>
int main()
{
std::cout << "Enter a number: ";
int n;
std::cin >> n;
std::vector<int> numbers;
for (int i = 1; i <= n; i++)
{
numbers.push_back(i);
}
for (size_t i = 1; i < numbers.size(); i++)
{
numbers.erase(numbers.begin() + i);
}
int step = 1;
while (step < (int)numbers.size())
{
for (int i = numbers.at(step) - 1; i < (int)numbers.size(); i += numbers[step] - 1)
{
numbers.erase(numbers.begin() + step);
}
step += 1;
}
for (auto it = numbers.begin(); it != numbers.end(); ++it)
{
if (*it == n)
{
std::cout << "The Lucky number is: " << *it << std::endl;
}
else
{
std::cout << *--it << " " << n << " " << *++it << std::endl;
}
}
return 0;
}
| [
"mnestorov@protonmail.com"
] | mnestorov@protonmail.com |
fc5d646cc8688b837dc675cab8cdeb150220f334 | be4952850ad6a8b0abe50de671c495c6add9fae7 | /codeforce/CF_58A.cpp | 338bb2f8d98709eb0a6f016afb436c3bdedd197b | [] | no_license | ss5ssmi/OJ | 296cb936ecf7ef292e91f24178c9c08bd2d241b5 | 267184cef5f1bc1f222950a71fe705bbc5f0bb3e | refs/heads/master | 2022-10-29T18:15:14.290028 | 2022-10-12T04:42:47 | 2022-10-12T04:42:47 | 103,818,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | cpp | #include<stdio.h>
#include<string.h>
int main(){
char s[100];
int i,h,e,l1,l2,o;
while(scanf("%s",&s)!=EOF){
h=e=l1=l2=o=0;
for(i=0;i<strlen(s);i++){
if(s[i]=='h'){
h=i;
break;
}
}
for(i+=1;i<strlen(s);i++){
if(s[i]=='e'){
e=i;
break;
}
}
for(i+=1;i<strlen(s);i++){
if(s[i]=='l'){
l1=i;
break;
}
}
for(i+=1;i<strlen(s);i++){
if(s[i]=='l'){
l2=i;
break;
}
}
for(i+=1;i<strlen(s);i++){
if(s[i]=='o'){
o=i;
break;
}
}
if(o>l2 && l2>l1 && l1>e && e>h){
printf("YES\n");
}else{
printf("NO\n");
}
}
return 0;
}
| [
"imss5ss@outlook.com"
] | imss5ss@outlook.com |
519f2cf03e22949615bcbdee8e9c7641dc8b2b03 | 2748d0af8c89e0975bdfde2a24b5e567bfcac0ab | /perception/pointcloud_tools/sq_fitting/tests/es_tests_2.cpp | 72afd2347779eee0130ef2f7f06a5f731aa0d725 | [] | no_license | shenglixu/golems | 184384574958112690719c9295e9c08b75ccb093 | ae516ce6d70cfd07e8806f243686536ca42d662d | refs/heads/master | 2021-01-22T21:37:32.705276 | 2016-11-14T23:44:29 | 2016-11-14T23:44:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,465 | cpp | /**
* @file es_tests_2.cpp
* @brief Test a set of random cases for noise and partiality using threads
*/
#include "perception/pointcloud_tools/sq_fitting/evaluated_eqs.h"
#include "perception/pointcloud_tools/sq_fitting/SQ_utils.h"
#include <pcl/common/centroid.h>
#include <pcl/filters/voxel_grid.h>
#include <future>
#include <thread>
typedef pcl::PointXYZ PointT;
/**
* @brief Structure used to store output lines
*/
struct output_sq{
SQ_parameters par;
double t;
double er_g, er_r;
double er_v;
double er_e1;
double er_e2;
};
// Global variables
const int gnF = 5;
char* fx_names[gnF] = { "Radial", "Solina", "Ichim", "Chevalier", "F5"};
int fx_sq[gnF] = {SQ_FX_RADIAL, SQ_FX_SOLINA, SQ_FX_ICHIM, SQ_FX_CHEVALIER, SQ_FX_5};
const double gDev = 0.0025;
const int gNum_threads = 7;
int gT = 50;
std::string gFilename;
double gD = 0.015;
// Global variables to generate noise
std::random_device rd;
std::mt19937 gen(rd());
// Functions to get partial and noisy versions of original pointcloud
pcl::PointCloud<PointT>::Ptr downsampling( const pcl::PointCloud<PointT>::Ptr &_input,
const double &_voxelSize );
pcl::PointCloud<PointT>::Ptr cut_cloud( const pcl::PointCloud<PointT>::Ptr &_cloud );
pcl::PointCloud<PointT>::Ptr get_noisy( const pcl::PointCloud<PointT>::Ptr &_cloud,
const double &_dev );
double getRand( const double &_minVal, const double &_maxVal );
double beta( double z,double w);
double volSQ( double a, double b, double c, double e1, double e2 );
void saveParams( std::ofstream &_output, const SQ_parameters &_par, double _t,
double _eg, double _er,
double _e_e1, double _e_e2,
double _e_v );
std::vector<output_sq> createCases( int _id );
std::vector<output_sq> createCase();
/**
* @function main
*/
int main( int argc, char*argv[] ) {
/* initialize random seed: */
srand (time(NULL));
// Initialize, in case user does not enter values of e1 and e2
gFilename = std::string("test_2_result.txt");
int v;
while( (v=getopt(argc, argv, "t:n:h")) != -1 ) {
switch(v) {
case 'n' : {
gFilename.assign(optarg);
} break;
case 't' : {
gT = atoi(optarg);
} break;
case 'h' : {
printf("Executable to save T randomized runs to test noise and partial view \n");
printf("Usage: ./executable -t T -n output_filename.txt \n");
return 0;
} break;
} // switch end
}
struct timespec start, finish;
double elapsed;
clock_gettime(CLOCK_MONOTONIC, &start);
srand(time(NULL));
std::ofstream output( gFilename.c_str(), std::ofstream::out );
output << gT << std::endl;
// Launch threads
std::vector<std::future< std::vector<output_sq> > > futures;
for( int i = 0; i < gNum_threads; ++i ) {
futures.push_back( std::async( std::launch::async, &createCases, i) );
}
for( size_t i = 0; i < futures.size(); ++i ) {
futures[i].wait();
}
for( size_t i = 0; i < futures.size(); ++i ) {
std::vector<output_sq> s;
s = futures[i].get();
for( int m = 0; m < s.size(); ++m ) {
saveParams( output, s[m].par, s[m].t, s[m].er_g, s[m].er_r,
s[m].er_e1, s[m].er_e2, s[m].er_v );
}
}
clock_gettime(CLOCK_MONOTONIC, &finish);
elapsed = (finish.tv_sec - start.tv_sec);
elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
printf("* Total time: %f \n", elapsed );
output.close();
return 0;
}
/**
* @function createCases
* @brief Create cases per each thread
*/
std::vector<output_sq> createCases(int _id ) {
std::vector<output_sq> ss;
std::vector<output_sq> si;
for( int i = _id; i < gT; i = i + gNum_threads ) {
si = createCase();
for( int j = 0; j < si.size(); ++j ) {
ss.push_back( si[j] );
}
}
return ss;
}
/**
* @function createCase
* @brief Create individual case (base + 6*4 tests)
*/
std::vector<output_sq> createCase() {
std::vector<output_sq> output;
pcl::PointCloud<PointT>::Ptr input( new pcl::PointCloud<PointT>() );
pcl::PointCloud<PointT>::Ptr down( new pcl::PointCloud<PointT>() );
std::vector<pcl::PointCloud<PointT>::Ptr> testCloud(4);
SQ_parameters par;
double er_g, er_r, er_d;
evaluated_sqs es;
// Dimensions
par.dim[0] = getRand(0.025, 0.39);
par.dim[1] = getRand(0.025, 0.39);
par.dim[2] = getRand(0.025, 0.39);
// Translations
par.trans[0] = getRand(-0.8, 0.8);
par.trans[1] = getRand(-0.8, 0.8);
par.trans[2] = getRand(0.3, 1.4);
// Rotation
par.rot[0] = getRand(-M_PI, M_PI);
par.rot[1] = getRand(-M_PI, M_PI);
par.rot[2] = getRand(-M_PI, M_PI);
// E parameters
par.e[0] = getRand(0.1,1.9);
par.e[1] = getRand(0.1,1.9);
// Store original data
output_sq base;
base.par = par;
base.er_r = 0; base.er_g = 0; base.t = 0; base.er_v = 0;
base.er_e1 = 0; base.er_e2 = 0;
output.push_back( base );
// 1. Generate clean pointcloud
input = sampleSQ_uniform<PointT>( par );
struct timespec ts, tf;
double elapsed;
double d;
double vr, vc;
output_sq oi;
if( gD == 0 ) { down = input; }
else { down = downsampling( input, gD ); }
testCloud[0] = down;
testCloud[1]= get_noisy( testCloud[0], gDev );
testCloud[2] = cut_cloud( testCloud[0] );
testCloud[3] = cut_cloud( testCloud[1] );
for( int i = 0; i < gnF; ++i ) {
for( int j = 0; j < 4; ++j ) {
clock_gettime(CLOCK_MONOTONIC, &ts);
es.minimize( testCloud[j], par, er_g, er_r, er_d, fx_sq[i] );
clock_gettime(CLOCK_MONOTONIC, &tf);
error_metric<PointT>( par,input, er_g, er_r, er_d );
elapsed = (tf.tv_sec - ts.tv_sec);
elapsed += (tf.tv_nsec - ts.tv_nsec) / 1000000000.0;
oi.par = par;
oi.er_g = er_g; oi.er_r = er_r; oi.t = elapsed;
oi.er_e1 = fabs(base.par.e[0] - par.e[0]);
oi.er_e2 = fabs(base.par.e[1] - par.e[1]);
vc = volSQ(par.dim[0], par.dim[1], par.dim[2], par.e[0], par.e[1]);
vr = volSQ(base.par.dim[0],base.par.dim[1],base.par.dim[2], base.par.e[0], base.par.e[1] );
oi.er_v = (vc - vr)/vr*100.0;
output.push_back( oi );
}
}
return output;
}
/**
* @function downsampling
*/
pcl::PointCloud<PointT>::Ptr downsampling( const pcl::PointCloud<PointT>::Ptr &_input,
const double &_voxelSize ) {
pcl::PointCloud<PointT>::Ptr cloud_downsampled( new pcl::PointCloud<PointT>() );
// Create the filtering object
pcl::VoxelGrid< PointT > downsampler;
// Set input cloud
downsampler.setInputCloud( _input );
// Set size of voxel
downsampler.setLeafSize( _voxelSize, _voxelSize, _voxelSize );
// Downsample
downsampler.filter( *cloud_downsampled );
return cloud_downsampled;
}
/**
* @function cut_cloud
* @brief Slice cloud by half, leaving only the "visible"points (points towards the eye point (0,0,0))
*/
pcl::PointCloud<PointT>::Ptr cut_cloud( const pcl::PointCloud<PointT>::Ptr &_cloud ) {
pcl::PointCloud<PointT>::Ptr output( new pcl::PointCloud<PointT>() );
// Get eigenvectors and centroid of pointcloud
Eigen::Vector4d c;
pcl::compute3DCentroid( *_cloud, c );
// Get the normal w.r.t. the centroid
Eigen::Vector3d N; N = Eigen::Vector3d(0,0,0) - Eigen::Vector3d(c(0), c(1), c(2) );
double d;
// Plane equation n(0)x + n(1)y + n(2)z + d = 0. Find d using the centroid
d = -( N(0)*c(0) + N(1)*c(1) + N(2)*c(2) );
// Cut it
for( pcl::PointCloud<PointT>::iterator it = _cloud->begin();
it != _cloud->end(); it++ ) {
if( (N(0)*((*it).x) + N(1)*((*it).y) + N(2)*((*it).z) + d) > 0 ) {
PointT p;
p = *it;
output->points.push_back( p );
}
}
output->height = 1; output->width = output->points.size();
return output;
}
/**
* @function get_noisy
*/
pcl::PointCloud<PointT>::Ptr get_noisy( const pcl::PointCloud<PointT>::Ptr &_cloud,
const double &_dev ) {
pcl::PointCloud<PointT>::Ptr output( new pcl::PointCloud<PointT>() );
std::normal_distribution<double> d(0,_dev);
// Make it dirty
for( pcl::PointCloud<PointT>::iterator it = _cloud->begin();
it != _cloud->end(); it++ ) {
PointT p;
p.x = (*it).x + d(gen);
p.y = (*it).y + d(gen);
p.z = (*it).z + d(gen);
output->points.push_back( p );
}
output->height = 1; output->width = output->points.size();
return output;
}
/**
* @function getRand
*/
double getRand( const double &_minVal, const double &_maxVal ) {
return _minVal + (_maxVal - _minVal)*((double)rand() / (double)RAND_MAX);
}
double beta( double z,double w) {
double gz, gw, gzw;
gz = tgamma(z);
gw = tgamma(w);
gzw = tgamma(z+w);
return gz*gw/gzw;
}
double volSQ( double a, double b, double c, double e1, double e2 ) {
return 2*a*b*c*e1*e2*beta(e1*0.5, e1+1)*beta(e2*0.5, e2*0.5+1);
}
/**
* @function saveParams
*/
void saveParams( std::ofstream &_output,
const SQ_parameters &_par,
double _t,
double _eg, double _er,
double _e_e1, double _e_e2,
double _e_v ) {
_output << _par.dim[0] << " " << _par.dim[1] << " " << _par.dim[2] << " "
<< _par.e[0] << " " << _par.e[1] << " "
<< _par.trans[0] << " " << _par.trans[1] << " " << _par.trans[2] << " "
<< _par.rot[0] << " " << _par.rot[1] << " " << _par.rot[2]
<< " " << _t << " "<< _eg << " " << _er << " " << _e_e1 << " "
<< _e_e2 << " "<< _e_v << std::endl;
}
| [
"ahuaman3@gatech.edu"
] | ahuaman3@gatech.edu |
e9676507c5ee1fee7c8ab9a193980c18cb47fd9d | df05196c665c668dd8862df136f09a20b057829c | /release/moc_board_model.cpp | 400c74d7054b3d8f7f432928b9aaa3bf6ef3d566 | [] | no_license | Hjvf01/15 | 8ed81198fff6df49d9890574e1fd6f6724ccc0d6 | b0add06d8e65c425dc653c7279348c7777c5d9aa | refs/heads/master | 2021-06-27T11:18:33.265997 | 2017-09-12T13:25:04 | 2017-09-12T13:25:04 | 102,881,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,134 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'board_model.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.6.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/board_model.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'board_model.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.6.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_BoardModel_t {
QByteArrayData data[4];
char stringdata0[29];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_BoardModel_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_BoardModel_t qt_meta_stringdata_BoardModel = {
{
QT_MOC_LITERAL(0, 0, 10), // "BoardModel"
QT_MOC_LITERAL(1, 11, 11), // "sizeChanged"
QT_MOC_LITERAL(2, 23, 0), // ""
QT_MOC_LITERAL(3, 24, 4) // "size"
},
"BoardModel\0sizeChanged\0\0size"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_BoardModel[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
1, 20, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x06 /* Public */,
// signals: parameters
QMetaType::Void,
// properties: name, type, flags
3, QMetaType::Int, 0x00495001,
// properties: notify_signal_id
0,
0 // eod
};
void BoardModel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
BoardModel *_t = static_cast<BoardModel *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->sizeChanged(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (BoardModel::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&BoardModel::sizeChanged)) {
*result = 0;
return;
}
}
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty) {
BoardModel *_t = static_cast<BoardModel *>(_o);
Q_UNUSED(_t)
void *_v = _a[0];
switch (_id) {
case 0: *reinterpret_cast< int*>(_v) = _t->size(); break;
default: break;
}
} else if (_c == QMetaObject::WriteProperty) {
} else if (_c == QMetaObject::ResetProperty) {
}
#endif // QT_NO_PROPERTIES
Q_UNUSED(_a);
}
const QMetaObject BoardModel::staticMetaObject = {
{ &QAbstractListModel::staticMetaObject, qt_meta_stringdata_BoardModel.data,
qt_meta_data_BoardModel, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *BoardModel::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *BoardModel::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_BoardModel.stringdata0))
return static_cast<void*>(const_cast< BoardModel*>(this));
return QAbstractListModel::qt_metacast(_clname);
}
int BoardModel::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QAbstractListModel::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty || _c == QMetaObject::WriteProperty
|| _c == QMetaObject::ResetProperty || _c == QMetaObject::RegisterPropertyMetaType) {
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyDesignable) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyScriptable) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyStored) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyEditable) {
_id -= 1;
} else if (_c == QMetaObject::QueryPropertyUser) {
_id -= 1;
}
#endif // QT_NO_PROPERTIES
return _id;
}
// SIGNAL 0
void BoardModel::sizeChanged()
{
QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR);
}
QT_END_MOC_NAMESPACE
| [
"mail@email.com"
] | mail@email.com |
0bbf841e761a2e7881cf0cb7336d5e017b0c39b5 | a636c55ab78abd56273ef5c9bf2e9a7bf0b8f20a | /src/sem/depth_multisampled_texture_type.cc | 6f11f1a23772bc82a7938b481526c9540e19c5c0 | [
"Apache-2.0"
] | permissive | sunnyps/tint | 97432995d0829c6e3db900b66918de29f3d4cb79 | 22daca166bbc412345fc60d4f60646d6d2f3ada0 | refs/heads/main | 2023-08-27T17:07:28.621015 | 2021-10-04T14:54:37 | 2021-10-04T14:54:37 | 411,415,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,603 | cc | // Copyright 2021 The Tint Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/sem/depth_multisampled_texture_type.h"
#include "src/program_builder.h"
TINT_INSTANTIATE_TYPEINFO(tint::sem::DepthMultisampledTexture);
namespace tint {
namespace sem {
namespace {
bool IsValidDepthDimension(ast::TextureDimension dim) {
return dim == ast::TextureDimension::k2d;
}
} // namespace
DepthMultisampledTexture::DepthMultisampledTexture(ast::TextureDimension dim)
: Base(dim) {
TINT_ASSERT(Semantic, IsValidDepthDimension(dim));
}
DepthMultisampledTexture::DepthMultisampledTexture(DepthMultisampledTexture&&) =
default;
DepthMultisampledTexture::~DepthMultisampledTexture() = default;
std::string DepthMultisampledTexture::type_name() const {
std::ostringstream out;
out << "__depth_multisampled_texture_" << dim();
return out.str();
}
std::string DepthMultisampledTexture::FriendlyName(const SymbolTable&) const {
std::ostringstream out;
out << "texture_depth_multisampled_" << dim();
return out.str();
}
} // namespace sem
} // namespace tint
| [
"tint-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | tint-scoped@luci-project-accounts.iam.gserviceaccount.com |
ca4a2ad8d7a2616d4153654bf4eeadd06cfa5564 | 69be9b20ec28d319ebac8db566f994fa20650df1 | /src/Encoders.cpp | 4127419dd8150e567630c6f894033b5705eb3649 | [] | no_license | jiezhi320/ADRC-1 | 252b3d554fc85687c5743e4fa3b1d73095dffa11 | e9a32c71fc6b5e98c68213d589df9c296ef62ddf | refs/heads/master | 2021-05-13T12:53:13.550491 | 2015-11-04T02:27:04 | 2015-11-04T02:27:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 804 | cpp | #include "Encoders.h"
#include <fcntl.h>
#include <iostream>
#include <unistd.h>
#include <sys/mman.h>
using namespace std;
Encoders::Encoders() {
m_file = open(MOTOR_DEVICE_NAME, O_RDWR | O_SYNC);
if(m_file == -1) {
cout << "Error: couldn't open the analog device." << endl;
return;
}
m_p_device = (MOTORDATA*)mmap(0, sizeof(MOTORDATA)*vmOUTPUTS,
PROT_READ | PROT_WRITE,
MAP_FILE | MAP_SHARED, m_file, 0);
if(m_p_device == MAP_FAILED) {
cout << "Error: failed to map the analog device." << endl;
}
}
Encoders::~Encoders() {
if(m_file != -1) {
close(m_file);
}
}
int Encoders::ReadCount(const unsigned int port) const {
return m_p_device[port].TachoSensor;
}
int Encoders::ReadSpeed(const unsigned int port) const {
return m_p_device[port].Speed;
}
| [
"psiorx@gmail.com"
] | psiorx@gmail.com |
ccfdb3266ca1b5e8d331fa8defba63d4b57a7aa5 | bcb834d26c7dd8f5e915969cc9783b8360281cc3 | /Test/GoogleTest/ClangSetup/main.cpp | d1c92a41a472389cd90cc07f04bdbb60503a6570 | [] | no_license | alexander190591/funMRI | 00d01b256724e9244ce10a2fdf17569f2b7c7663 | 30094f992c32658074ce2030eedbc01778cacf83 | refs/heads/master | 2022-12-19T00:54:51.056141 | 2020-09-22T20:27:57 | 2020-09-22T20:27:57 | 247,016,091 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 960 | cpp | /****************************************************************************
* Copyright (C) Kamstrup A/S, 2020. All rights reserved.
****************************************************************************/
#ifndef __main_2020__
#define __main_2020__
/**
*
* @file main.cpp
*
* Created:
* @author Nikolaj Emil Sørensen <nikolaj.eriksen@gmail.com>
* @date Wednesday, 15th January 2020 1:06:53
*
*
* Modified:
* mod @author Nikolaj Emil Sørensen <nikolaj.eriksen@gmail.com>
* mod @date Wednesday, 15th January 2020 3:02:29
*
*/
#include "Class.hpp"
#include "MyFile.hpp"
#include <stdbool.h>
#include <string.h>
/**
*
* brief
*
* @param argc
* @param args
* @return int
*/
int main( int argc, char** args )
{
MyClass firstObject;
MyClass secondObject( 10, '2', false );
MyClass thirdObject( std::string( "supz" ) );
}
/****************************************************************************/
#endif // __main.cpp__
| [
"alexander190591@gmail.com"
] | alexander190591@gmail.com |
2ed681d453deb5985daa5da761bbb383d92db22f | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5744014401732608_0/C++/kobebryant24/B.cpp | 96212efd64a7d6e281e355dd7236513a17df4e0e | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,419 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef pair<int,int> pi;
typedef vector<string> vs;
typedef vector<pi> vpi;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define forall(i,a,b) for(int i=a;i<b;++i)
#define max(a,b) ( (a) > (b) ? (a) : (b))
#define min(a,b) ( (a) < (b) ? (a) : (b))
#define mes(a,b) memset(a,b,sizeof a)
#define endl "\n"
#define ll long long
const int oo = 1000000009;
const double eps = 1e-9;
const int mod = 1000000007;
int main(){
int t;cin >> t;
forall(test,0,t){
int b,m;cin >> b >> m;
cout << "Case #" << test+1 << ": ";
if(b==2 && m>1) cout << "IMPOSSIBLE" << endl;
else if(b==2){
cout << "POSSIBLE" << endl;
cout << "01" << endl;
cout << "00" << endl;
}
else{
int ct=0,mat[20][20],y[20];
forall(i,0,20) forall(j,0,20) mat[i][j]=0;
forall(i,0,20) y[i]=0;
y[1]=1;++ct;mat[1][b]=1;
for(int i=2;i<b&&ct<m;++i){
mat[1][i]=1;mat[i][b]=1;
++ct;
y[i]++;
for(int j=i-1;j>1&&ct<m;--j){
if(ct+y[j]<=m) {
mat[i][j]=1;
ct+=y[j];
y[i]+=y[j];
}
}
}
if(m!=ct) cout << "IMPOSSIBLE" << endl;
else{
cout << "POSSIBLE" << endl;
forall(i,1,b+1){
forall(j,1,b+1){
cout << mat[i][j];
}
cout << endl;
}
}
}
}
} | [
"alexandra1.back@gmail.com"
] | alexandra1.back@gmail.com |
005d1e01f5dd184750d598c1477bef73f4128fd0 | 9332aa1506f44d1f7053cc81d02f71140eb7c0f0 | /Brown belt/5 week/Budget professional mobile legacy version/budget_bad_base.cpp | 381d51b75663d78860bdb5c080a7c7b1ec64307e | [] | no_license | arkud/C-plus-plus-modern-development-basics | 39c2d8ef7d3140258ed6d272810a88a769c51f36 | ea324252ab0d0632cfbab5ec17d317773bfd51db | refs/heads/master | 2022-12-18T14:35:33.685055 | 2020-09-27T10:03:22 | 2020-09-27T10:03:22 | 298,999,163 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,813 | cpp | #include <array>
#include <cassert>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string_view>
#include <utility>
using namespace std;
pair<string_view, optional<string_view>> SplitTwoStrict(string_view s, string_view delimiter = " ") {
const size_t pos = s.find(delimiter);
if (pos == s.npos) {
return {s, nullopt};
} else {
return {s.substr(0, pos), s.substr(pos + delimiter.length())};
}
}
pair<string_view, string_view> SplitTwo(string_view s, string_view delimiter = " ") {
const auto[lhs, rhs_opt] = SplitTwoStrict(s, delimiter);
return {lhs, rhs_opt.value_or("")};
}
string_view ReadToken(string_view &s, string_view delimiter = " ") {
const auto[lhs, rhs] = SplitTwo(s, delimiter);
s = rhs;
return lhs;
}
int ConvertToInt(string_view str) {
// use std::from_chars when available to git rid of string copy
size_t pos;
const int result = stoi(string(str), &pos);
if (pos != str.length()) {
std::stringstream error;
error << "string " << str << " contains " << (str.length() - pos) << " trailing chars";
throw invalid_argument(error.str());
}
return result;
}
template<typename Number>
void ValidateBounds(Number number_to_check, Number min_value, Number max_value) {
if (number_to_check < min_value || number_to_check > max_value) {
std::stringstream error;
error << number_to_check << " is out of [" << min_value << ", " << max_value << "]";
throw out_of_range(error.str());
}
}
class Date {
public:
static Date FromString(string_view str) {
const int year = ConvertToInt(ReadToken(str, "-"));
const int month = ConvertToInt(ReadToken(str, "-"));
ValidateBounds(month, 1, 12);
const int day = ConvertToInt(str);
ValidateBounds(day, 1, 31);
return {year, month, day};
}
// Weird legacy, can't wait for std::chrono::year_month_day
time_t AsTimestamp() const {
std::tm t;
t.tm_sec = 0;
t.tm_min = 0;
t.tm_hour = 0;
t.tm_mday = day_;
t.tm_mon = month_ - 1;
t.tm_year = year_ - 1900;
t.tm_isdst = 0;
return mktime(&t);
}
private:
int year_;
int month_;
int day_;
Date(int year, int month, int day)
: year_(year), month_(month), day_(day) {}
};
int ComputeDaysDiff(const Date &date_to, const Date &date_from) {
const time_t timestamp_to = date_to.AsTimestamp();
const time_t timestamp_from = date_from.AsTimestamp();
static constexpr int SECONDS_IN_DAY = 60 * 60 * 24;
return (timestamp_to - timestamp_from) / SECONDS_IN_DAY;
}
static const Date START_DATE = Date::FromString("2000-01-01");
static const Date END_DATE = Date::FromString("2100-01-01");
static const size_t DAY_COUNT = ComputeDaysDiff(END_DATE, START_DATE);
static const size_t DAY_COUNT_P2 = 1 << 16;
static const size_t VERTEX_COUNT = DAY_COUNT_P2 * 2;
size_t ComputeDayIndex(const Date &date) {
return ComputeDaysDiff(date, START_DATE);
}
struct MoneyState{
double earned_ = 0.0;
double spent_ = 0.0;
};
array<double, VERTEX_COUNT> tree_add, tree_factor, tree_spent;
array<MoneyState, VERTEX_COUNT> tree_values;
void Init() {
tree_values.fill({0,0});
tree_add.fill(0);
tree_spent.fill(0);
tree_factor.fill(1);
}
void Push(size_t v, size_t l, size_t r) {
for (size_t w = v * 2; w <= v * 2 + 1; ++w) {
if (w < VERTEX_COUNT) {
tree_factor[w] *= tree_factor[v];
(tree_add[w] *= tree_factor[v]) += tree_add[v];
tree_spent[w] += tree_add[v];
(tree_values[w].earned_ *= tree_factor[v]) += tree_add[v] * (r - l) / 2;
tree_values[w].spent_ += tree_spent[v] * (r - l) / 2;
}
}
tree_factor[v] = 1;
tree_add[v] = 0;
tree_spent[v] = 0;
}
double ComputeSum(size_t v, size_t l, size_t r, size_t ql, size_t qr) {
if (v >= VERTEX_COUNT || qr <= l || r <= ql) {
return 0;
}
Push(v, l, r);
if (ql <= l && r <= qr) {
return tree_values[v].earned_ - tree_values[v].spent_;
}
return ComputeSum(v * 2, l, (l + r) / 2, ql, qr)
+ ComputeSum(v * 2 + 1, (l + r) / 2, r, ql, qr);
}
void Add(size_t v, size_t l, size_t r, size_t ql, size_t qr, double value) {
if (v >= VERTEX_COUNT || qr <= l || r <= ql) {
return;
}
Push(v, l, r);
if (ql <= l && r <= qr) {
tree_add[v] += value;
tree_values[v].earned_ += value * (r - l);
return;
}
Add(v * 2, l, (l + r) / 2, ql, qr, value);
Add(v * 2 + 1, (l + r) / 2, r, ql, qr, value);
tree_values[v].earned_ =
(v * 2 < VERTEX_COUNT ? tree_values[v * 2].earned_ : 0)
+ (v * 2 + 1 < VERTEX_COUNT ? tree_values[v * 2 + 1].earned_ : 0);
}
void Spend(size_t v, size_t l, size_t r, size_t ql, size_t qr, double value) {
if (v >= VERTEX_COUNT || qr <= l || r <= ql) {
return;
}
Push(v, l, r);
if (ql <= l && r <= qr) {
tree_spent[v] += value;
tree_values[v].spent_ += value * (r - l);
return;
}
Spend(v * 2, l, (l + r) / 2, ql, qr, value);
Spend(v * 2 + 1, (l + r) / 2, r, ql, qr, value);
tree_values[v].spent_ =
(v * 2 < VERTEX_COUNT ? tree_values[v * 2].spent_ : 0)
+ (v * 2 + 1 < VERTEX_COUNT ? tree_values[v * 2 + 1].spent_ : 0);
}
void Multiply(size_t v, size_t l, size_t r, size_t ql, size_t qr, int tax_percentage) {
if (v >= VERTEX_COUNT || qr <= l || r <= ql) {
return;
}
Push(v, l, r);
if (ql <= l && r <= qr) {
tree_factor[v] *= 1.0 - tax_percentage / 100.0;
tree_add[v] *= 1.0 - tax_percentage / 100.0;
tree_values[v].earned_ *= 1.0 - tax_percentage / 100.0;
return;
}
Multiply(v * 2, l, (l + r) / 2, ql, qr, tax_percentage);
Multiply(v * 2 + 1, (l + r) / 2, r, ql, qr, tax_percentage);
tree_values[v].earned_ =
(v * 2 < VERTEX_COUNT ? tree_values[v * 2].earned_ : 0)
+ (v * 2 + 1 < VERTEX_COUNT ? tree_values[v * 2 + 1].earned_ : 0);
}
int main() {
cout.precision(25);
assert(DAY_COUNT <= DAY_COUNT_P2 && DAY_COUNT_P2 < DAY_COUNT * 2);
Init();
int q;
cin >> q;
for (int i = 0; i < q; ++i) {
string query_type;
cin >> query_type;
string date_from_str, date_to_str;
cin >> date_from_str >> date_to_str;
auto idx_from = ComputeDayIndex(Date::FromString(date_from_str));
auto idx_to = ComputeDayIndex(Date::FromString(date_to_str)) + 1;
//cerr << query_type << " " << date_from_str << " " << date_to_str << " ";
if (query_type == "ComputeIncome") {
cout << ComputeSum(1, 0, DAY_COUNT_P2, idx_from, idx_to) << endl;
} else if (query_type == "PayTax") {
int tax_percentage;
cin >> tax_percentage;
//cerr << tax_percentage;
Multiply(1, 0, DAY_COUNT_P2, idx_from, idx_to, tax_percentage);
} else if (query_type == "Earn") {
double value;
cin >> value;
//cerr << value;
Add(1, 0, DAY_COUNT_P2, idx_from, idx_to, value / (idx_to - idx_from));
} else if (query_type == "Spend") {
double value;
cin >> value;
//cerr << value;
Spend(1, 0, DAY_COUNT_P2, idx_from, idx_to, value / (idx_to - idx_from));
}
//cerr << endl;
}
return 0;
}
| [
"artyomiius@gmail.com"
] | artyomiius@gmail.com |
ae6476e08c8d8d62d6b6014b829704600cd5780e | af9e53fdbc56abed24f2ba8236103c64032c82eb | /代码/3.cpp | b636a88e8d77e69b83a532fa0bf1c3db56a59a02 | [] | no_license | syj716/CodeSet | 9f271a4fcf647c3c368f0753a38414c189c66e93 | 0695ee0a79438d9760622cf8b0acc232cd1d374a | refs/heads/master | 2022-11-09T09:51:37.481250 | 2020-06-29T04:00:11 | 2020-06-29T04:00:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,358 | cpp | #include<stdio.h>
#include<string.h>
int dates[3002][13][32];
char NameofWeek[7][20] =
{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
int dayOfMonth[13][2] = {
0,0,
31,31,
28,29,
31,31,
30,30,
31,31,
30,30,
31,31,
31,31,
30,30,
31,31,
30,30,
31,31
};
char NameofMonth[13][20] =
{
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
int isleap(int year) {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
return 1;
return 0;
}
struct date {
int year;
int month;
int day;
int cnt;
date(int y, int m, int d, int c) :year(y), month(m), day(d), cnt(c) {}
void nextday() {
int index = isleap(year);
while (year < 3001) {
dates[year][month][day] = cnt;
day++;
cnt++;
if (day > dayOfMonth[month][index]) {
day = 1;
month++;
if (month > 12) {
month = 1;
year++;
index = isleap(year);
}
}
}
}
};
int main() {
date start(1000, 1, 1, 0);
start.nextday();
int year, month, day;
char tmp[10];
scanf("%d %s %d", &day, tmp, &year);
for (int i = 1;i < 13;i++) {
if (strcmp(NameofMonth[i], tmp) == 0) {
month = i;
break;
}
}
int days = dates[2020][1][24] - dates[year][month][day];
printf("%s", NameofWeek[(12-days % 7) % 7]);
return 0;
}
| [
"1523646952@qq.com"
] | 1523646952@qq.com |
f7ebb5c51c5faee6086b93c816be4ea490f3402f | 90047daeb462598a924d76ddf4288e832e86417c | /chrome/browser/ui/page_info/page_info_ui.cc | 401b5cd12f5307c98b44dc619dbf3c8189db364e | [
"BSD-3-Clause"
] | permissive | massbrowser/android | 99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080 | a9c4371682c9443d6e1d66005d4db61a24a9617c | refs/heads/master | 2022-11-04T21:15:50.656802 | 2017-06-08T12:31:39 | 2017-06-08T12:31:39 | 93,747,579 | 2 | 2 | BSD-3-Clause | 2022-10-31T10:34:25 | 2017-06-08T12:36:07 | null | UTF-8 | C++ | false | false | 17,811 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/page_info/page_info_ui.h"
#include <utility>
#include "base/command_line.h"
#include "base/macros.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/permissions/permission_manager.h"
#include "chrome/browser/permissions/permission_result.h"
#include "chrome/browser/permissions/permission_util.h"
#include "chrome/browser/plugins/plugin_utils.h"
#include "chrome/browser/plugins/plugins_field_trial.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/grit/theme_resources.h"
#include "components/strings/grit/components_chromium_strings.h"
#include "components/strings/grit/components_strings.h"
#include "ppapi/features/features.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image.h"
#include "url/gurl.h"
#if defined(OS_ANDROID)
#include "chrome/browser/android/android_theme_resources.h"
#else
#include "chrome/app/vector_icons/vector_icons.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/paint_vector_icon.h"
#endif
namespace {
const int kInvalidResourceID = -1;
// The resource IDs for the strings that are displayed on the permissions
// button if the permission setting is managed by policy.
const int kPermissionButtonTextIDPolicyManaged[] = {
kInvalidResourceID,
IDS_PAGE_INFO_PERMISSION_ALLOWED_BY_POLICY,
IDS_PAGE_INFO_PERMISSION_BLOCKED_BY_POLICY,
IDS_PAGE_INFO_PERMISSION_ASK_BY_POLICY,
kInvalidResourceID,
kInvalidResourceID};
static_assert(arraysize(kPermissionButtonTextIDPolicyManaged) ==
CONTENT_SETTING_NUM_SETTINGS,
"kPermissionButtonTextIDPolicyManaged array size is incorrect");
// The resource IDs for the strings that are displayed on the permissions
// button if the permission setting is managed by an extension.
const int kPermissionButtonTextIDExtensionManaged[] = {
kInvalidResourceID,
IDS_PAGE_INFO_PERMISSION_ALLOWED_BY_EXTENSION,
IDS_PAGE_INFO_PERMISSION_BLOCKED_BY_EXTENSION,
IDS_PAGE_INFO_PERMISSION_ASK_BY_EXTENSION,
kInvalidResourceID,
kInvalidResourceID};
static_assert(arraysize(kPermissionButtonTextIDExtensionManaged) ==
CONTENT_SETTING_NUM_SETTINGS,
"kPermissionButtonTextIDExtensionManaged array size is "
"incorrect");
// The resource IDs for the strings that are displayed on the permissions
// button if the permission setting is managed by the user.
const int kPermissionButtonTextIDUserManaged[] = {
kInvalidResourceID,
IDS_PAGE_INFO_BUTTON_TEXT_ALLOWED_BY_USER,
IDS_PAGE_INFO_BUTTON_TEXT_BLOCKED_BY_USER,
IDS_PAGE_INFO_BUTTON_TEXT_ASK_BY_USER,
kInvalidResourceID,
IDS_PAGE_INFO_BUTTON_TEXT_DETECT_IMPORTANT_CONTENT_BY_USER};
static_assert(arraysize(kPermissionButtonTextIDUserManaged) ==
CONTENT_SETTING_NUM_SETTINGS,
"kPermissionButtonTextIDUserManaged array size is incorrect");
// The resource IDs for the strings that are displayed on the permissions
// button if the permission setting is the global default setting.
const int kPermissionButtonTextIDDefaultSetting[] = {
kInvalidResourceID,
IDS_PAGE_INFO_BUTTON_TEXT_ALLOWED_BY_DEFAULT,
IDS_PAGE_INFO_BUTTON_TEXT_BLOCKED_BY_DEFAULT,
IDS_PAGE_INFO_BUTTON_TEXT_ASK_BY_DEFAULT,
kInvalidResourceID,
IDS_PAGE_INFO_BUTTON_TEXT_DETECT_IMPORTANT_CONTENT_BY_DEFAULT};
static_assert(arraysize(kPermissionButtonTextIDDefaultSetting) ==
CONTENT_SETTING_NUM_SETTINGS,
"kPermissionButtonTextIDDefaultSetting array size is incorrect");
struct PermissionsUIInfo {
ContentSettingsType type;
int string_id;
int blocked_icon_id;
int allowed_icon_id;
};
const PermissionsUIInfo kPermissionsUIInfo[] = {
{CONTENT_SETTINGS_TYPE_COOKIES, 0, IDR_BLOCKED_COOKIES,
IDR_ACCESSED_COOKIES},
{CONTENT_SETTINGS_TYPE_IMAGES, IDS_PAGE_INFO_TYPE_IMAGES,
IDR_BLOCKED_IMAGES, IDR_ALLOWED_IMAGES},
{CONTENT_SETTINGS_TYPE_JAVASCRIPT, IDS_PAGE_INFO_TYPE_JAVASCRIPT,
IDR_BLOCKED_JAVASCRIPT, IDR_ALLOWED_JAVASCRIPT},
{CONTENT_SETTINGS_TYPE_POPUPS, IDS_PAGE_INFO_TYPE_POPUPS,
IDR_BLOCKED_POPUPS, IDR_ALLOWED_POPUPS},
#if BUILDFLAG(ENABLE_PLUGINS)
{CONTENT_SETTINGS_TYPE_PLUGINS, IDS_PAGE_INFO_TYPE_FLASH,
IDR_BLOCKED_PLUGINS, IDR_ALLOWED_PLUGINS},
#endif
{CONTENT_SETTINGS_TYPE_GEOLOCATION, IDS_PAGE_INFO_TYPE_LOCATION,
IDR_BLOCKED_LOCATION, IDR_ALLOWED_LOCATION},
{CONTENT_SETTINGS_TYPE_NOTIFICATIONS, IDS_PAGE_INFO_TYPE_NOTIFICATIONS,
IDR_BLOCKED_NOTIFICATION, IDR_ALLOWED_NOTIFICATION},
{CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC, IDS_PAGE_INFO_TYPE_MIC,
IDR_BLOCKED_MIC, IDR_ALLOWED_MIC},
{CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA, IDS_PAGE_INFO_TYPE_CAMERA,
IDR_BLOCKED_CAMERA, IDR_ALLOWED_CAMERA},
{CONTENT_SETTINGS_TYPE_AUTOMATIC_DOWNLOADS,
IDS_AUTOMATIC_DOWNLOADS_TAB_LABEL, IDR_BLOCKED_DOWNLOADS,
IDR_ALLOWED_DOWNLOADS},
{CONTENT_SETTINGS_TYPE_MIDI_SYSEX, IDS_PAGE_INFO_TYPE_MIDI_SYSEX,
IDR_BLOCKED_MIDI_SYSEX, IDR_ALLOWED_MIDI_SYSEX},
{CONTENT_SETTINGS_TYPE_BACKGROUND_SYNC, IDS_PAGE_INFO_TYPE_BACKGROUND_SYNC,
IDR_BLOCKED_BACKGROUND_SYNC, IDR_ALLOWED_BACKGROUND_SYNC},
// Autoplay is Android-only at the moment, and the Page Info popup on
// Android ignores these block/allow icon pairs, so we can specify 0 there.
{CONTENT_SETTINGS_TYPE_AUTOPLAY, IDS_PAGE_INFO_TYPE_AUTOPLAY, 0, 0},
{CONTENT_SETTINGS_TYPE_SUBRESOURCE_FILTER, IDS_SUBRESOURCE_FILTER_HEADER,
IDR_ALLOWED_SUBRESOURCE_FILTER, IDR_BLOCKED_SUBRESOURCE_FILTER},
};
std::unique_ptr<PageInfoUI::SecurityDescription> CreateSecurityDescription(
int summary_id,
int details_id) {
std::unique_ptr<PageInfoUI::SecurityDescription> security_description(
new PageInfoUI::SecurityDescription());
security_description->summary = l10n_util::GetStringUTF16(summary_id);
security_description->details = l10n_util::GetStringUTF16(details_id);
return security_description;
}
// Gets the actual setting for a ContentSettingType, taking into account what
// the default setting value is and whether Html5ByDefault is enabled.
ContentSetting GetEffectiveSetting(Profile* profile,
ContentSettingsType type,
ContentSetting setting,
ContentSetting default_setting) {
ContentSetting effective_setting = setting;
if (effective_setting == CONTENT_SETTING_DEFAULT)
effective_setting = default_setting;
#if BUILDFLAG(ENABLE_PLUGINS)
HostContentSettingsMap* host_content_settings_map =
HostContentSettingsMapFactory::GetForProfile(profile);
effective_setting = PluginsFieldTrial::EffectiveContentSetting(
host_content_settings_map, type, effective_setting);
// Display the UI string for ASK instead of DETECT for HTML5 by Default.
// TODO(tommycli): Once HTML5 by Default is shipped and the feature flag
// is removed, just migrate the actual content setting to ASK.
if (PluginUtils::ShouldPreferHtmlOverPlugins(host_content_settings_map) &&
effective_setting == CONTENT_SETTING_DETECT_IMPORTANT_CONTENT) {
effective_setting = CONTENT_SETTING_ASK;
}
#endif
return effective_setting;
}
} // namespace
PageInfoUI::CookieInfo::CookieInfo() : allowed(-1), blocked(-1) {}
PageInfoUI::PermissionInfo::PermissionInfo()
: type(CONTENT_SETTINGS_TYPE_DEFAULT),
setting(CONTENT_SETTING_DEFAULT),
default_setting(CONTENT_SETTING_DEFAULT),
source(content_settings::SETTING_SOURCE_NONE),
is_incognito(false) {}
PageInfoUI::ChosenObjectInfo::ChosenObjectInfo(
const PageInfo::ChooserUIInfo& ui_info,
std::unique_ptr<base::DictionaryValue> object)
: ui_info(ui_info), object(std::move(object)) {}
PageInfoUI::ChosenObjectInfo::~ChosenObjectInfo() {}
PageInfoUI::IdentityInfo::IdentityInfo()
: identity_status(PageInfo::SITE_IDENTITY_STATUS_UNKNOWN),
connection_status(PageInfo::SITE_CONNECTION_STATUS_UNKNOWN),
show_ssl_decision_revoke_button(false) {}
PageInfoUI::IdentityInfo::~IdentityInfo() {}
std::unique_ptr<PageInfoUI::SecurityDescription>
PageInfoUI::IdentityInfo::GetSecurityDescription() const {
std::unique_ptr<PageInfoUI::SecurityDescription> security_description(
new PageInfoUI::SecurityDescription());
switch (identity_status) {
case PageInfo::SITE_IDENTITY_STATUS_INTERNAL_PAGE:
#if defined(OS_ANDROID)
// We provide identical summary and detail strings for Android, which
// deduplicates them in the UI code.
return CreateSecurityDescription(IDS_PAGE_INFO_INTERNAL_PAGE,
IDS_PAGE_INFO_INTERNAL_PAGE);
#endif
// Internal pages on desktop have their own UI implementations which
// should never call this function.
NOTREACHED();
case PageInfo::SITE_IDENTITY_STATUS_CERT:
case PageInfo::SITE_IDENTITY_STATUS_EV_CERT:
case PageInfo::SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN:
case PageInfo::SITE_IDENTITY_STATUS_ADMIN_PROVIDED_CERT:
switch (connection_status) {
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_ACTIVE_SUBRESOURCE:
return CreateSecurityDescription(IDS_PAGE_INFO_NOT_SECURE_SUMMARY,
IDS_PAGE_INFO_NOT_SECURE_DETAILS);
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_FORM_ACTION:
return CreateSecurityDescription(IDS_PAGE_INFO_MIXED_CONTENT_SUMMARY,
IDS_PAGE_INFO_NOT_SECURE_DETAILS);
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_PASSIVE_SUBRESOURCE:
return CreateSecurityDescription(IDS_PAGE_INFO_MIXED_CONTENT_SUMMARY,
IDS_PAGE_INFO_MIXED_CONTENT_DETAILS);
default:
return CreateSecurityDescription(IDS_PAGE_INFO_SECURE_SUMMARY,
IDS_PAGE_INFO_SECURE_DETAILS);
}
case PageInfo::SITE_IDENTITY_STATUS_MALWARE:
return CreateSecurityDescription(IDS_PAGE_INFO_MALWARE_SUMMARY,
IDS_PAGE_INFO_MALWARE_DETAILS);
case PageInfo::SITE_IDENTITY_STATUS_SOCIAL_ENGINEERING:
return CreateSecurityDescription(
IDS_PAGE_INFO_SOCIAL_ENGINEERING_SUMMARY,
IDS_PAGE_INFO_SOCIAL_ENGINEERING_DETAILS);
case PageInfo::SITE_IDENTITY_STATUS_UNWANTED_SOFTWARE:
return CreateSecurityDescription(IDS_PAGE_INFO_UNWANTED_SOFTWARE_SUMMARY,
IDS_PAGE_INFO_UNWANTED_SOFTWARE_DETAILS);
case PageInfo::SITE_IDENTITY_STATUS_DEPRECATED_SIGNATURE_ALGORITHM:
case PageInfo::SITE_IDENTITY_STATUS_UNKNOWN:
case PageInfo::SITE_IDENTITY_STATUS_NO_CERT:
default:
return CreateSecurityDescription(IDS_PAGE_INFO_NOT_SECURE_SUMMARY,
IDS_PAGE_INFO_NOT_SECURE_DETAILS);
}
}
PageInfoUI::~PageInfoUI() {}
// static
base::string16 PageInfoUI::PermissionTypeToUIString(ContentSettingsType type) {
for (const PermissionsUIInfo& info : kPermissionsUIInfo) {
if (info.type == type)
return l10n_util::GetStringUTF16(info.string_id);
}
NOTREACHED();
return base::string16();
}
// static
base::string16 PageInfoUI::PermissionActionToUIString(
Profile* profile,
ContentSettingsType type,
ContentSetting setting,
ContentSetting default_setting,
content_settings::SettingSource source) {
ContentSetting effective_setting =
GetEffectiveSetting(profile, type, setting, default_setting);
const int* button_text_ids = NULL;
switch (source) {
case content_settings::SETTING_SOURCE_USER:
if (setting == CONTENT_SETTING_DEFAULT) {
button_text_ids = kPermissionButtonTextIDDefaultSetting;
break;
}
// Fallthrough.
case content_settings::SETTING_SOURCE_POLICY:
case content_settings::SETTING_SOURCE_EXTENSION:
button_text_ids = kPermissionButtonTextIDUserManaged;
break;
case content_settings::SETTING_SOURCE_WHITELIST:
case content_settings::SETTING_SOURCE_NONE:
default:
NOTREACHED();
return base::string16();
}
int button_text_id = button_text_ids[effective_setting];
DCHECK_NE(button_text_id, kInvalidResourceID);
return l10n_util::GetStringUTF16(button_text_id);
}
// static
int PageInfoUI::GetPermissionIconID(ContentSettingsType type,
ContentSetting setting) {
bool use_blocked = (setting == CONTENT_SETTING_BLOCK);
for (const PermissionsUIInfo& info : kPermissionsUIInfo) {
if (info.type == type)
return use_blocked ? info.blocked_icon_id : info.allowed_icon_id;
}
NOTREACHED();
return IDR_INFO;
}
// static
base::string16 PageInfoUI::PermissionDecisionReasonToUIString(
Profile* profile,
const PageInfoUI::PermissionInfo& permission,
const GURL& url) {
ContentSetting effective_setting = GetEffectiveSetting(
profile, permission.type, permission.setting, permission.default_setting);
int message_id = kInvalidResourceID;
switch (permission.source) {
case content_settings::SettingSource::SETTING_SOURCE_POLICY:
message_id = kPermissionButtonTextIDPolicyManaged[effective_setting];
break;
case content_settings::SettingSource::SETTING_SOURCE_EXTENSION:
message_id = kPermissionButtonTextIDExtensionManaged[effective_setting];
break;
default:
break;
}
if (permission.setting == CONTENT_SETTING_BLOCK &&
PermissionUtil::IsPermission(permission.type)) {
PermissionResult permission_result =
PermissionManager::Get(profile)->GetPermissionStatus(permission.type,
url, url);
switch (permission_result.source) {
case PermissionStatusSource::MULTIPLE_DISMISSALS:
case PermissionStatusSource::SAFE_BROWSING_BLACKLIST:
message_id = IDS_PAGE_INFO_PERMISSION_AUTOMATICALLY_BLOCKED;
break;
default:
break;
}
}
if (message_id == kInvalidResourceID)
return base::string16();
return l10n_util::GetStringUTF16(message_id);
}
// static
SkColor PageInfoUI::GetPermissionDecisionTextColor() {
return SK_ColorGRAY;
}
// static
const gfx::Image& PageInfoUI::GetPermissionIcon(const PermissionInfo& info) {
ContentSetting setting = info.setting;
if (setting == CONTENT_SETTING_DEFAULT)
setting = info.default_setting;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
return rb.GetNativeImageNamed(GetPermissionIconID(info.type, setting));
}
// static
base::string16 PageInfoUI::ChosenObjectToUIString(
const ChosenObjectInfo& object) {
base::string16 name;
object.object->GetString(object.ui_info.ui_name_key, &name);
return name;
}
// static
const gfx::Image& PageInfoUI::GetChosenObjectIcon(
const ChosenObjectInfo& object,
bool deleted) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
return rb.GetNativeImageNamed(deleted ? object.ui_info.blocked_icon_id
: object.ui_info.allowed_icon_id);
}
#if defined(OS_ANDROID)
// static
int PageInfoUI::GetIdentityIconID(PageInfo::SiteIdentityStatus status) {
int resource_id = IDR_PAGEINFO_INFO;
switch (status) {
case PageInfo::SITE_IDENTITY_STATUS_UNKNOWN:
case PageInfo::SITE_IDENTITY_STATUS_INTERNAL_PAGE:
break;
case PageInfo::SITE_IDENTITY_STATUS_CERT:
case PageInfo::SITE_IDENTITY_STATUS_EV_CERT:
resource_id = IDR_PAGEINFO_GOOD;
break;
case PageInfo::SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN:
resource_id = IDR_PAGEINFO_WARNING_MINOR;
break;
case PageInfo::SITE_IDENTITY_STATUS_NO_CERT:
resource_id = IDR_PAGEINFO_WARNING_MAJOR;
break;
case PageInfo::SITE_IDENTITY_STATUS_ERROR:
resource_id = IDR_PAGEINFO_BAD;
break;
case PageInfo::SITE_IDENTITY_STATUS_ADMIN_PROVIDED_CERT:
resource_id = IDR_PAGEINFO_ENTERPRISE_MANAGED;
break;
case PageInfo::SITE_IDENTITY_STATUS_DEPRECATED_SIGNATURE_ALGORITHM:
resource_id = IDR_PAGEINFO_WARNING_MINOR;
break;
default:
NOTREACHED();
break;
}
return resource_id;
}
// static
int PageInfoUI::GetConnectionIconID(PageInfo::SiteConnectionStatus status) {
int resource_id = IDR_PAGEINFO_INFO;
switch (status) {
case PageInfo::SITE_CONNECTION_STATUS_UNKNOWN:
case PageInfo::SITE_CONNECTION_STATUS_INTERNAL_PAGE:
break;
case PageInfo::SITE_CONNECTION_STATUS_ENCRYPTED:
resource_id = IDR_PAGEINFO_GOOD;
break;
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_PASSIVE_SUBRESOURCE:
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_FORM_ACTION:
resource_id = IDR_PAGEINFO_WARNING_MINOR;
break;
case PageInfo::SITE_CONNECTION_STATUS_UNENCRYPTED:
resource_id = IDR_PAGEINFO_WARNING_MAJOR;
break;
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_ACTIVE_SUBRESOURCE:
case PageInfo::SITE_CONNECTION_STATUS_ENCRYPTED_ERROR:
resource_id = IDR_PAGEINFO_BAD;
break;
}
return resource_id;
}
#else // !defined(OS_ANDROID)
// static
const gfx::ImageSkia PageInfoUI::GetCertificateIcon() {
return gfx::CreateVectorIcon(kCertificateIcon, 16, gfx::kChromeIconGrey);
}
#endif
// static
bool PageInfoUI::ShouldShowCertificateLink() {
return base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kShowCertLink);
}
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
c67baf25ec6b3caf29664f5384e4bde4bef8dae7 | bd2f117637be64d13d7b94093c537d346ca3257f | /Tests/Core/Text/test.cpp | 9bf1f38555318799c98e9672708fa550e0344a26 | [
"Zlib"
] | permissive | animehunter/clanlib-2.3 | e6d6a09ff58016809d687c101b64ed4da1467562 | 7013c39f4cd1f25b0dad3bedfdb7a5cf593b1bb7 | refs/heads/master | 2016-09-10T12:56:23.015390 | 2011-12-15T20:58:59 | 2011-12-15T20:58:59 | 3,001,221 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,562 | cpp | /*
** ClanLib SDK
** Copyright (c) 1997-2011 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Mark Page
** (if your name is missing here, please add it)
*/
#include "test.h"
int g_bConstructor = 0;
int g_bDestructor = 0;
// This is the Program class that is called by CL_ClanApplication
class Program
{
public:
static int main(const std::vector<CL_String> &args)
{
// Initialize ClanLib base components
CL_SetupCore setup_core;
// Start the Application
TestApp app;
int retval = app.main(args);
return retval;
}
};
// Instantiate CL_ClanApplication, informing it where the Program is located
CL_ClanApplication app(&Program::main);
int TestApp::main(const std::vector<CL_String> &args)
{
// Create a console window for text-output if not available
CL_ConsoleWindow console("Console");
try
{
CL_Console::write_line("ClanLib Test Suite:");
CL_Console::write_line("-------------------");
#ifdef WIN32
CL_Console::write_line("Target: WIN32");
#else
CL_Console::write_line("Target: LINUX");
#endif
CL_Console::write_line("Directory: API/Core/Text");
str = "hello!";
CL_Console::write_line(" - %1", test_stringref());
test_string();
CL_Console::write_line("All Tests Complete");
console.display_close_message();
}
catch(CL_Exception error)
{
CL_Console::write_line("Exception caught:");
CL_Console::write_line(error.message);
console.display_close_message();
return -1;
}
return 0;
}
CL_StringRef TestApp::test_stringref()
{
return str;
}
void TestApp::fail(void)
{
throw CL_Exception("Failed Test");
}
| [
"rombust@cc39f7f4-b520-0410-a30f-b56705a9c917"
] | rombust@cc39f7f4-b520-0410-a30f-b56705a9c917 |
60b4b9e051b95945cdca4e8f2ceda5e560c1163d | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_1/MP+dmb.sy+data-wsi-rfi-addr-[fr-rf].c.cbmc.cpp | 38485c36e024b6bac75ced7496c0bfaadc1b8c75 | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 57,353 | cpp | // 0:vars:3
// 3:atom_1_X0_1:1
// 8:thr1:1
// 9:thr2:1
// 4:atom_1_X5_2:1
// 5:atom_1_X7_0:1
// 6:atom_1_X9_1:1
// 7:thr0:1
#define ADDRSIZE 10
#define NPROC 4
#define NCONTEXT 1
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NPROC*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NPROC*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NPROC*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NPROC*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NPROC*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NPROC*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NPROC*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NPROC*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NPROC*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NPROC];
int cdy[NPROC];
int cds[NPROC];
int cdl[NPROC];
int cisb[NPROC];
int caddr[NPROC];
int cctrl[NPROC];
int cstart[NPROC];
int creturn[NPROC];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
__LOCALS__
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
buff(0,4) = 0;
pw(0,4) = 0;
cr(0,4) = 0;
iw(0,4) = 0;
cw(0,4) = 0;
cx(0,4) = 0;
is(0,4) = 0;
cs(0,4) = 0;
crmax(0,4) = 0;
buff(0,5) = 0;
pw(0,5) = 0;
cr(0,5) = 0;
iw(0,5) = 0;
cw(0,5) = 0;
cx(0,5) = 0;
is(0,5) = 0;
cs(0,5) = 0;
crmax(0,5) = 0;
buff(0,6) = 0;
pw(0,6) = 0;
cr(0,6) = 0;
iw(0,6) = 0;
cw(0,6) = 0;
cx(0,6) = 0;
is(0,6) = 0;
cs(0,6) = 0;
crmax(0,6) = 0;
buff(0,7) = 0;
pw(0,7) = 0;
cr(0,7) = 0;
iw(0,7) = 0;
cw(0,7) = 0;
cx(0,7) = 0;
is(0,7) = 0;
cs(0,7) = 0;
crmax(0,7) = 0;
buff(0,8) = 0;
pw(0,8) = 0;
cr(0,8) = 0;
iw(0,8) = 0;
cw(0,8) = 0;
cx(0,8) = 0;
is(0,8) = 0;
cs(0,8) = 0;
crmax(0,8) = 0;
buff(0,9) = 0;
pw(0,9) = 0;
cr(0,9) = 0;
iw(0,9) = 0;
cw(0,9) = 0;
cx(0,9) = 0;
is(0,9) = 0;
cs(0,9) = 0;
crmax(0,9) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
buff(1,4) = 0;
pw(1,4) = 0;
cr(1,4) = 0;
iw(1,4) = 0;
cw(1,4) = 0;
cx(1,4) = 0;
is(1,4) = 0;
cs(1,4) = 0;
crmax(1,4) = 0;
buff(1,5) = 0;
pw(1,5) = 0;
cr(1,5) = 0;
iw(1,5) = 0;
cw(1,5) = 0;
cx(1,5) = 0;
is(1,5) = 0;
cs(1,5) = 0;
crmax(1,5) = 0;
buff(1,6) = 0;
pw(1,6) = 0;
cr(1,6) = 0;
iw(1,6) = 0;
cw(1,6) = 0;
cx(1,6) = 0;
is(1,6) = 0;
cs(1,6) = 0;
crmax(1,6) = 0;
buff(1,7) = 0;
pw(1,7) = 0;
cr(1,7) = 0;
iw(1,7) = 0;
cw(1,7) = 0;
cx(1,7) = 0;
is(1,7) = 0;
cs(1,7) = 0;
crmax(1,7) = 0;
buff(1,8) = 0;
pw(1,8) = 0;
cr(1,8) = 0;
iw(1,8) = 0;
cw(1,8) = 0;
cx(1,8) = 0;
is(1,8) = 0;
cs(1,8) = 0;
crmax(1,8) = 0;
buff(1,9) = 0;
pw(1,9) = 0;
cr(1,9) = 0;
iw(1,9) = 0;
cw(1,9) = 0;
cx(1,9) = 0;
is(1,9) = 0;
cs(1,9) = 0;
crmax(1,9) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
buff(2,4) = 0;
pw(2,4) = 0;
cr(2,4) = 0;
iw(2,4) = 0;
cw(2,4) = 0;
cx(2,4) = 0;
is(2,4) = 0;
cs(2,4) = 0;
crmax(2,4) = 0;
buff(2,5) = 0;
pw(2,5) = 0;
cr(2,5) = 0;
iw(2,5) = 0;
cw(2,5) = 0;
cx(2,5) = 0;
is(2,5) = 0;
cs(2,5) = 0;
crmax(2,5) = 0;
buff(2,6) = 0;
pw(2,6) = 0;
cr(2,6) = 0;
iw(2,6) = 0;
cw(2,6) = 0;
cx(2,6) = 0;
is(2,6) = 0;
cs(2,6) = 0;
crmax(2,6) = 0;
buff(2,7) = 0;
pw(2,7) = 0;
cr(2,7) = 0;
iw(2,7) = 0;
cw(2,7) = 0;
cx(2,7) = 0;
is(2,7) = 0;
cs(2,7) = 0;
crmax(2,7) = 0;
buff(2,8) = 0;
pw(2,8) = 0;
cr(2,8) = 0;
iw(2,8) = 0;
cw(2,8) = 0;
cx(2,8) = 0;
is(2,8) = 0;
cs(2,8) = 0;
crmax(2,8) = 0;
buff(2,9) = 0;
pw(2,9) = 0;
cr(2,9) = 0;
iw(2,9) = 0;
cw(2,9) = 0;
cx(2,9) = 0;
is(2,9) = 0;
cs(2,9) = 0;
crmax(2,9) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
buff(3,0) = 0;
pw(3,0) = 0;
cr(3,0) = 0;
iw(3,0) = 0;
cw(3,0) = 0;
cx(3,0) = 0;
is(3,0) = 0;
cs(3,0) = 0;
crmax(3,0) = 0;
buff(3,1) = 0;
pw(3,1) = 0;
cr(3,1) = 0;
iw(3,1) = 0;
cw(3,1) = 0;
cx(3,1) = 0;
is(3,1) = 0;
cs(3,1) = 0;
crmax(3,1) = 0;
buff(3,2) = 0;
pw(3,2) = 0;
cr(3,2) = 0;
iw(3,2) = 0;
cw(3,2) = 0;
cx(3,2) = 0;
is(3,2) = 0;
cs(3,2) = 0;
crmax(3,2) = 0;
buff(3,3) = 0;
pw(3,3) = 0;
cr(3,3) = 0;
iw(3,3) = 0;
cw(3,3) = 0;
cx(3,3) = 0;
is(3,3) = 0;
cs(3,3) = 0;
crmax(3,3) = 0;
buff(3,4) = 0;
pw(3,4) = 0;
cr(3,4) = 0;
iw(3,4) = 0;
cw(3,4) = 0;
cx(3,4) = 0;
is(3,4) = 0;
cs(3,4) = 0;
crmax(3,4) = 0;
buff(3,5) = 0;
pw(3,5) = 0;
cr(3,5) = 0;
iw(3,5) = 0;
cw(3,5) = 0;
cx(3,5) = 0;
is(3,5) = 0;
cs(3,5) = 0;
crmax(3,5) = 0;
buff(3,6) = 0;
pw(3,6) = 0;
cr(3,6) = 0;
iw(3,6) = 0;
cw(3,6) = 0;
cx(3,6) = 0;
is(3,6) = 0;
cs(3,6) = 0;
crmax(3,6) = 0;
buff(3,7) = 0;
pw(3,7) = 0;
cr(3,7) = 0;
iw(3,7) = 0;
cw(3,7) = 0;
cx(3,7) = 0;
is(3,7) = 0;
cs(3,7) = 0;
crmax(3,7) = 0;
buff(3,8) = 0;
pw(3,8) = 0;
cr(3,8) = 0;
iw(3,8) = 0;
cw(3,8) = 0;
cx(3,8) = 0;
is(3,8) = 0;
cs(3,8) = 0;
crmax(3,8) = 0;
buff(3,9) = 0;
pw(3,9) = 0;
cr(3,9) = 0;
iw(3,9) = 0;
cw(3,9) = 0;
cx(3,9) = 0;
is(3,9) = 0;
cs(3,9) = 0;
crmax(3,9) = 0;
cl[3] = 0;
cdy[3] = 0;
cds[3] = 0;
cdl[3] = 0;
cisb[3] = 0;
caddr[3] = 0;
cctrl[3] = 0;
cstart[3] = get_rng(0,NCONTEXT-1);
creturn[3] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(0+2,0) = 0;
mem(3+0,0) = 0;
mem(8+0,0) = 0;
mem(9+0,0) = 0;
mem(4+0,0) = 0;
mem(5+0,0) = 0;
mem(6+0,0) = 0;
mem(7+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
co(1,0) = 0;
delta(1,0) = -1;
co(2,0) = 0;
delta(2,0) = -1;
co(3,0) = 0;
delta(3,0) = -1;
co(4,0) = 0;
delta(4,0) = -1;
co(5,0) = 0;
delta(5,0) = -1;
co(6,0) = 0;
delta(6,0) = -1;
co(7,0) = 0;
delta(7,0) = -1;
co(8,0) = 0;
delta(8,0) = -1;
co(9,0) = 0;
delta(9,0) = -1;
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !39, metadata !DIExpression()), !dbg !48
// br label %label_1, !dbg !49
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !47), !dbg !50
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !40, metadata !DIExpression()), !dbg !51
// call void @llvm.dbg.value(metadata i64 2, metadata !43, metadata !DIExpression()), !dbg !51
// store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !52
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 2;
mem(0,cw(1,0)) = 2;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// call void (...) @dmbsy(), !dbg !53
// dumbsy: Guess
old_cdy = cdy[1];
cdy[1] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[1] >= old_cdy);
ASSUME(cdy[1] >= cisb[1]);
ASSUME(cdy[1] >= cdl[1]);
ASSUME(cdy[1] >= cds[1]);
ASSUME(cdy[1] >= cctrl[1]);
ASSUME(cdy[1] >= cw(1,0+0));
ASSUME(cdy[1] >= cw(1,0+1));
ASSUME(cdy[1] >= cw(1,0+2));
ASSUME(cdy[1] >= cw(1,3+0));
ASSUME(cdy[1] >= cw(1,8+0));
ASSUME(cdy[1] >= cw(1,9+0));
ASSUME(cdy[1] >= cw(1,4+0));
ASSUME(cdy[1] >= cw(1,5+0));
ASSUME(cdy[1] >= cw(1,6+0));
ASSUME(cdy[1] >= cw(1,7+0));
ASSUME(cdy[1] >= cr(1,0+0));
ASSUME(cdy[1] >= cr(1,0+1));
ASSUME(cdy[1] >= cr(1,0+2));
ASSUME(cdy[1] >= cr(1,3+0));
ASSUME(cdy[1] >= cr(1,8+0));
ASSUME(cdy[1] >= cr(1,9+0));
ASSUME(cdy[1] >= cr(1,4+0));
ASSUME(cdy[1] >= cr(1,5+0));
ASSUME(cdy[1] >= cr(1,6+0));
ASSUME(cdy[1] >= cr(1,7+0));
ASSUME(creturn[1] >= cdy[1]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !44, metadata !DIExpression()), !dbg !54
// call void @llvm.dbg.value(metadata i64 1, metadata !46, metadata !DIExpression()), !dbg !54
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !55
// ST: Guess
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 1;
mem(0+1*1,cw(1,0+1*1)) = 1;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
ASSUME(creturn[1] >= cw(1,0+1*1));
// ret i8* null, !dbg !56
ret_thread_1 = (- 1);
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !59, metadata !DIExpression()), !dbg !103
// br label %label_2, !dbg !85
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !102), !dbg !105
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !62, metadata !DIExpression()), !dbg !106
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !88
// LD: Guess
old_cr = cr(2,0+1*1);
cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+1*1)] == 2);
ASSUME(cr(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cr(2,0+1*1) >= 0);
ASSUME(cr(2,0+1*1) >= cdy[2]);
ASSUME(cr(2,0+1*1) >= cisb[2]);
ASSUME(cr(2,0+1*1) >= cdl[2]);
ASSUME(cr(2,0+1*1) >= cl[2]);
// Update
creg_r0 = cr(2,0+1*1);
crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+1*1) < cw(2,0+1*1)) {
r0 = buff(2,0+1*1);
} else {
if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) {
ASSUME(cr(2,0+1*1) >= old_cr);
}
pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1));
r0 = mem(0+1*1,cr(2,0+1*1));
}
ASSUME(creturn[2] >= cr(2,0+1*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !64, metadata !DIExpression()), !dbg !106
// %conv = trunc i64 %0 to i32, !dbg !89
// call void @llvm.dbg.value(metadata i32 %conv, metadata !60, metadata !DIExpression()), !dbg !103
// %xor = xor i32 %conv, %conv, !dbg !90
creg_r1 = max(creg_r0,creg_r0);
ASSUME(active[creg_r1] == 2);
r1 = r0 ^ r0;
// call void @llvm.dbg.value(metadata i32 %xor, metadata !65, metadata !DIExpression()), !dbg !103
// %add = add nsw i32 %xor, 1, !dbg !91
creg_r2 = max(creg_r1,0);
ASSUME(active[creg_r2] == 2);
r2 = r1 + 1;
// call void @llvm.dbg.value(metadata i32 %add, metadata !66, metadata !DIExpression()), !dbg !103
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !67, metadata !DIExpression()), !dbg !111
// %conv1 = sext i32 %add to i64, !dbg !93
// call void @llvm.dbg.value(metadata i64 %conv1, metadata !69, metadata !DIExpression()), !dbg !111
// store atomic i64 %conv1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !93
// ST: Guess
iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,0+2*1);
cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,0+2*1)] == 2);
ASSUME(active[cw(2,0+2*1)] == 2);
ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0);
ASSUME(iw(2,0+2*1) >= creg_r2);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(cw(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cw(2,0+2*1) >= old_cw);
ASSUME(cw(2,0+2*1) >= cr(2,0+2*1));
ASSUME(cw(2,0+2*1) >= cl[2]);
ASSUME(cw(2,0+2*1) >= cisb[2]);
ASSUME(cw(2,0+2*1) >= cdy[2]);
ASSUME(cw(2,0+2*1) >= cdl[2]);
ASSUME(cw(2,0+2*1) >= cds[2]);
ASSUME(cw(2,0+2*1) >= cctrl[2]);
ASSUME(cw(2,0+2*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+2*1) = r2;
mem(0+2*1,cw(2,0+2*1)) = r2;
co(0+2*1,cw(2,0+2*1))+=1;
delta(0+2*1,cw(2,0+2*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !70, metadata !DIExpression()), !dbg !113
// call void @llvm.dbg.value(metadata i64 2, metadata !72, metadata !DIExpression()), !dbg !113
// store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !95
// ST: Guess
iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,0+2*1);
cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,0+2*1)] == 2);
ASSUME(active[cw(2,0+2*1)] == 2);
ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(cw(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cw(2,0+2*1) >= old_cw);
ASSUME(cw(2,0+2*1) >= cr(2,0+2*1));
ASSUME(cw(2,0+2*1) >= cl[2]);
ASSUME(cw(2,0+2*1) >= cisb[2]);
ASSUME(cw(2,0+2*1) >= cdy[2]);
ASSUME(cw(2,0+2*1) >= cdl[2]);
ASSUME(cw(2,0+2*1) >= cds[2]);
ASSUME(cw(2,0+2*1) >= cctrl[2]);
ASSUME(cw(2,0+2*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+2*1) = 2;
mem(0+2*1,cw(2,0+2*1)) = 2;
co(0+2*1,cw(2,0+2*1))+=1;
delta(0+2*1,cw(2,0+2*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !74, metadata !DIExpression()), !dbg !115
// %1 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !97
// LD: Guess
old_cr = cr(2,0+2*1);
cr(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+2*1)] == 2);
ASSUME(cr(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cr(2,0+2*1) >= 0);
ASSUME(cr(2,0+2*1) >= cdy[2]);
ASSUME(cr(2,0+2*1) >= cisb[2]);
ASSUME(cr(2,0+2*1) >= cdl[2]);
ASSUME(cr(2,0+2*1) >= cl[2]);
// Update
creg_r3 = cr(2,0+2*1);
crmax(2,0+2*1) = max(crmax(2,0+2*1),cr(2,0+2*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+2*1) < cw(2,0+2*1)) {
r3 = buff(2,0+2*1);
} else {
if(pw(2,0+2*1) != co(0+2*1,cr(2,0+2*1))) {
ASSUME(cr(2,0+2*1) >= old_cr);
}
pw(2,0+2*1) = co(0+2*1,cr(2,0+2*1));
r3 = mem(0+2*1,cr(2,0+2*1));
}
ASSUME(creturn[2] >= cr(2,0+2*1));
// call void @llvm.dbg.value(metadata i64 %1, metadata !76, metadata !DIExpression()), !dbg !115
// %conv7 = trunc i64 %1 to i32, !dbg !98
// call void @llvm.dbg.value(metadata i32 %conv7, metadata !73, metadata !DIExpression()), !dbg !103
// %xor8 = xor i32 %conv7, %conv7, !dbg !99
creg_r4 = max(creg_r3,creg_r3);
ASSUME(active[creg_r4] == 2);
r4 = r3 ^ r3;
// call void @llvm.dbg.value(metadata i32 %xor8, metadata !77, metadata !DIExpression()), !dbg !103
// %add10 = add nsw i32 0, %xor8, !dbg !100
creg_r5 = max(0,creg_r4);
ASSUME(active[creg_r5] == 2);
r5 = 0 + r4;
// %idxprom = sext i32 %add10 to i64, !dbg !100
// %arrayidx = getelementptr inbounds [3 x i64], [3 x i64]* @vars, i64 0, i64 %idxprom, !dbg !100
r6 = 0+r5*1;
ASSUME(creg_r6 >= 0);
ASSUME(creg_r6 >= creg_r5);
ASSUME(active[creg_r6] == 2);
// call void @llvm.dbg.value(metadata i64* %arrayidx, metadata !79, metadata !DIExpression()), !dbg !120
// %2 = load atomic i64, i64* %arrayidx monotonic, align 8, !dbg !100
// LD: Guess
old_cr = cr(2,r6);
cr(2,r6) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,r6)] == 2);
ASSUME(cr(2,r6) >= iw(2,r6));
ASSUME(cr(2,r6) >= creg_r6);
ASSUME(cr(2,r6) >= cdy[2]);
ASSUME(cr(2,r6) >= cisb[2]);
ASSUME(cr(2,r6) >= cdl[2]);
ASSUME(cr(2,r6) >= cl[2]);
// Update
creg_r7 = cr(2,r6);
crmax(2,r6) = max(crmax(2,r6),cr(2,r6));
caddr[2] = max(caddr[2],creg_r6);
if(cr(2,r6) < cw(2,r6)) {
r7 = buff(2,r6);
} else {
if(pw(2,r6) != co(r6,cr(2,r6))) {
ASSUME(cr(2,r6) >= old_cr);
}
pw(2,r6) = co(r6,cr(2,r6));
r7 = mem(r6,cr(2,r6));
}
ASSUME(creturn[2] >= cr(2,r6));
// call void @llvm.dbg.value(metadata i64 %2, metadata !81, metadata !DIExpression()), !dbg !120
// %conv13 = trunc i64 %2 to i32, !dbg !102
// call void @llvm.dbg.value(metadata i32 %conv13, metadata !78, metadata !DIExpression()), !dbg !103
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !83, metadata !DIExpression()), !dbg !122
// %3 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !104
// LD: Guess
old_cr = cr(2,0);
cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0)] == 2);
ASSUME(cr(2,0) >= iw(2,0));
ASSUME(cr(2,0) >= 0);
ASSUME(cr(2,0) >= cdy[2]);
ASSUME(cr(2,0) >= cisb[2]);
ASSUME(cr(2,0) >= cdl[2]);
ASSUME(cr(2,0) >= cl[2]);
// Update
creg_r8 = cr(2,0);
crmax(2,0) = max(crmax(2,0),cr(2,0));
caddr[2] = max(caddr[2],0);
if(cr(2,0) < cw(2,0)) {
r8 = buff(2,0);
} else {
if(pw(2,0) != co(0,cr(2,0))) {
ASSUME(cr(2,0) >= old_cr);
}
pw(2,0) = co(0,cr(2,0));
r8 = mem(0,cr(2,0));
}
ASSUME(creturn[2] >= cr(2,0));
// call void @llvm.dbg.value(metadata i64 %3, metadata !85, metadata !DIExpression()), !dbg !122
// %conv17 = trunc i64 %3 to i32, !dbg !105
// call void @llvm.dbg.value(metadata i32 %conv17, metadata !82, metadata !DIExpression()), !dbg !103
// %cmp = icmp eq i32 %conv, 1, !dbg !106
// %conv18 = zext i1 %cmp to i32, !dbg !106
// call void @llvm.dbg.value(metadata i32 %conv18, metadata !86, metadata !DIExpression()), !dbg !103
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !87, metadata !DIExpression()), !dbg !126
// %4 = zext i32 %conv18 to i64
// call void @llvm.dbg.value(metadata i64 %4, metadata !89, metadata !DIExpression()), !dbg !126
// store atomic i64 %4, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !108
// ST: Guess
iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,3);
cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,3)] == 2);
ASSUME(active[cw(2,3)] == 2);
ASSUME(sforbid(3,cw(2,3))== 0);
ASSUME(iw(2,3) >= max(creg_r0,0));
ASSUME(iw(2,3) >= 0);
ASSUME(cw(2,3) >= iw(2,3));
ASSUME(cw(2,3) >= old_cw);
ASSUME(cw(2,3) >= cr(2,3));
ASSUME(cw(2,3) >= cl[2]);
ASSUME(cw(2,3) >= cisb[2]);
ASSUME(cw(2,3) >= cdy[2]);
ASSUME(cw(2,3) >= cdl[2]);
ASSUME(cw(2,3) >= cds[2]);
ASSUME(cw(2,3) >= cctrl[2]);
ASSUME(cw(2,3) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,3) = (r0==1);
mem(3,cw(2,3)) = (r0==1);
co(3,cw(2,3))+=1;
delta(3,cw(2,3)) = -1;
ASSUME(creturn[2] >= cw(2,3));
// %cmp22 = icmp eq i32 %conv7, 2, !dbg !109
// %conv23 = zext i1 %cmp22 to i32, !dbg !109
// call void @llvm.dbg.value(metadata i32 %conv23, metadata !90, metadata !DIExpression()), !dbg !103
// call void @llvm.dbg.value(metadata i64* @atom_1_X5_2, metadata !91, metadata !DIExpression()), !dbg !129
// %5 = zext i32 %conv23 to i64
// call void @llvm.dbg.value(metadata i64 %5, metadata !93, metadata !DIExpression()), !dbg !129
// store atomic i64 %5, i64* @atom_1_X5_2 seq_cst, align 8, !dbg !111
// ST: Guess
iw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,4);
cw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,4)] == 2);
ASSUME(active[cw(2,4)] == 2);
ASSUME(sforbid(4,cw(2,4))== 0);
ASSUME(iw(2,4) >= max(creg_r3,0));
ASSUME(iw(2,4) >= 0);
ASSUME(cw(2,4) >= iw(2,4));
ASSUME(cw(2,4) >= old_cw);
ASSUME(cw(2,4) >= cr(2,4));
ASSUME(cw(2,4) >= cl[2]);
ASSUME(cw(2,4) >= cisb[2]);
ASSUME(cw(2,4) >= cdy[2]);
ASSUME(cw(2,4) >= cdl[2]);
ASSUME(cw(2,4) >= cds[2]);
ASSUME(cw(2,4) >= cctrl[2]);
ASSUME(cw(2,4) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,4) = (r3==2);
mem(4,cw(2,4)) = (r3==2);
co(4,cw(2,4))+=1;
delta(4,cw(2,4)) = -1;
ASSUME(creturn[2] >= cw(2,4));
// %cmp27 = icmp eq i32 %conv13, 0, !dbg !112
// %conv28 = zext i1 %cmp27 to i32, !dbg !112
// call void @llvm.dbg.value(metadata i32 %conv28, metadata !94, metadata !DIExpression()), !dbg !103
// call void @llvm.dbg.value(metadata i64* @atom_1_X7_0, metadata !95, metadata !DIExpression()), !dbg !132
// %6 = zext i32 %conv28 to i64
// call void @llvm.dbg.value(metadata i64 %6, metadata !97, metadata !DIExpression()), !dbg !132
// store atomic i64 %6, i64* @atom_1_X7_0 seq_cst, align 8, !dbg !114
// ST: Guess
iw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,5);
cw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,5)] == 2);
ASSUME(active[cw(2,5)] == 2);
ASSUME(sforbid(5,cw(2,5))== 0);
ASSUME(iw(2,5) >= max(creg_r7,0));
ASSUME(iw(2,5) >= 0);
ASSUME(cw(2,5) >= iw(2,5));
ASSUME(cw(2,5) >= old_cw);
ASSUME(cw(2,5) >= cr(2,5));
ASSUME(cw(2,5) >= cl[2]);
ASSUME(cw(2,5) >= cisb[2]);
ASSUME(cw(2,5) >= cdy[2]);
ASSUME(cw(2,5) >= cdl[2]);
ASSUME(cw(2,5) >= cds[2]);
ASSUME(cw(2,5) >= cctrl[2]);
ASSUME(cw(2,5) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,5) = (r7==0);
mem(5,cw(2,5)) = (r7==0);
co(5,cw(2,5))+=1;
delta(5,cw(2,5)) = -1;
ASSUME(creturn[2] >= cw(2,5));
// %cmp32 = icmp eq i32 %conv17, 1, !dbg !115
// %conv33 = zext i1 %cmp32 to i32, !dbg !115
// call void @llvm.dbg.value(metadata i32 %conv33, metadata !98, metadata !DIExpression()), !dbg !103
// call void @llvm.dbg.value(metadata i64* @atom_1_X9_1, metadata !99, metadata !DIExpression()), !dbg !135
// %7 = zext i32 %conv33 to i64
// call void @llvm.dbg.value(metadata i64 %7, metadata !101, metadata !DIExpression()), !dbg !135
// store atomic i64 %7, i64* @atom_1_X9_1 seq_cst, align 8, !dbg !117
// ST: Guess
iw(2,6) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,6);
cw(2,6) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,6)] == 2);
ASSUME(active[cw(2,6)] == 2);
ASSUME(sforbid(6,cw(2,6))== 0);
ASSUME(iw(2,6) >= max(creg_r8,0));
ASSUME(iw(2,6) >= 0);
ASSUME(cw(2,6) >= iw(2,6));
ASSUME(cw(2,6) >= old_cw);
ASSUME(cw(2,6) >= cr(2,6));
ASSUME(cw(2,6) >= cl[2]);
ASSUME(cw(2,6) >= cisb[2]);
ASSUME(cw(2,6) >= cdy[2]);
ASSUME(cw(2,6) >= cdl[2]);
ASSUME(cw(2,6) >= cds[2]);
ASSUME(cw(2,6) >= cctrl[2]);
ASSUME(cw(2,6) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,6) = (r8==1);
mem(6,cw(2,6)) = (r8==1);
co(6,cw(2,6))+=1;
delta(6,cw(2,6)) = -1;
ASSUME(creturn[2] >= cw(2,6));
// ret i8* null, !dbg !118
ret_thread_2 = (- 1);
// Dumping thread 3
int ret_thread_3 = 0;
cdy[3] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[3] >= cstart[3]);
T3BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !140, metadata !DIExpression()), !dbg !145
// br label %label_3, !dbg !46
goto T3BLOCK1;
T3BLOCK1:
// call void @llvm.dbg.label(metadata !144), !dbg !147
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !141, metadata !DIExpression()), !dbg !148
// call void @llvm.dbg.value(metadata i64 1, metadata !143, metadata !DIExpression()), !dbg !148
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !49
// ST: Guess
iw(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,0);
cw(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,0)] == 3);
ASSUME(active[cw(3,0)] == 3);
ASSUME(sforbid(0,cw(3,0))== 0);
ASSUME(iw(3,0) >= 0);
ASSUME(iw(3,0) >= 0);
ASSUME(cw(3,0) >= iw(3,0));
ASSUME(cw(3,0) >= old_cw);
ASSUME(cw(3,0) >= cr(3,0));
ASSUME(cw(3,0) >= cl[3]);
ASSUME(cw(3,0) >= cisb[3]);
ASSUME(cw(3,0) >= cdy[3]);
ASSUME(cw(3,0) >= cdl[3]);
ASSUME(cw(3,0) >= cds[3]);
ASSUME(cw(3,0) >= cctrl[3]);
ASSUME(cw(3,0) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,0) = 1;
mem(0,cw(3,0)) = 1;
co(0,cw(3,0))+=1;
delta(0,cw(3,0)) = -1;
ASSUME(creturn[3] >= cw(3,0));
// ret i8* null, !dbg !50
ret_thread_3 = (- 1);
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// %thr2 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !158, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i8** %argv, metadata !159, metadata !DIExpression()), !dbg !224
// %0 = bitcast i64* %thr0 to i8*, !dbg !111
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !111
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !160, metadata !DIExpression()), !dbg !226
// %1 = bitcast i64* %thr1 to i8*, !dbg !113
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !113
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !164, metadata !DIExpression()), !dbg !228
// %2 = bitcast i64* %thr2 to i8*, !dbg !115
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !115
// call void @llvm.dbg.declare(metadata i64* %thr2, metadata !165, metadata !DIExpression()), !dbg !230
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !166, metadata !DIExpression()), !dbg !231
// call void @llvm.dbg.value(metadata i64 0, metadata !168, metadata !DIExpression()), !dbg !231
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !118
// ST: Guess
iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+2*1);
cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+2*1)] == 0);
ASSUME(active[cw(0,0+2*1)] == 0);
ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(cw(0,0+2*1) >= iw(0,0+2*1));
ASSUME(cw(0,0+2*1) >= old_cw);
ASSUME(cw(0,0+2*1) >= cr(0,0+2*1));
ASSUME(cw(0,0+2*1) >= cl[0]);
ASSUME(cw(0,0+2*1) >= cisb[0]);
ASSUME(cw(0,0+2*1) >= cdy[0]);
ASSUME(cw(0,0+2*1) >= cdl[0]);
ASSUME(cw(0,0+2*1) >= cds[0]);
ASSUME(cw(0,0+2*1) >= cctrl[0]);
ASSUME(cw(0,0+2*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+2*1) = 0;
mem(0+2*1,cw(0,0+2*1)) = 0;
co(0+2*1,cw(0,0+2*1))+=1;
delta(0+2*1,cw(0,0+2*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !169, metadata !DIExpression()), !dbg !233
// call void @llvm.dbg.value(metadata i64 0, metadata !171, metadata !DIExpression()), !dbg !233
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !120
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !172, metadata !DIExpression()), !dbg !235
// call void @llvm.dbg.value(metadata i64 0, metadata !174, metadata !DIExpression()), !dbg !235
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !122
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !175, metadata !DIExpression()), !dbg !237
// call void @llvm.dbg.value(metadata i64 0, metadata !177, metadata !DIExpression()), !dbg !237
// store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !124
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// call void @llvm.dbg.value(metadata i64* @atom_1_X5_2, metadata !178, metadata !DIExpression()), !dbg !239
// call void @llvm.dbg.value(metadata i64 0, metadata !180, metadata !DIExpression()), !dbg !239
// store atomic i64 0, i64* @atom_1_X5_2 monotonic, align 8, !dbg !126
// ST: Guess
iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,4);
cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,4)] == 0);
ASSUME(active[cw(0,4)] == 0);
ASSUME(sforbid(4,cw(0,4))== 0);
ASSUME(iw(0,4) >= 0);
ASSUME(iw(0,4) >= 0);
ASSUME(cw(0,4) >= iw(0,4));
ASSUME(cw(0,4) >= old_cw);
ASSUME(cw(0,4) >= cr(0,4));
ASSUME(cw(0,4) >= cl[0]);
ASSUME(cw(0,4) >= cisb[0]);
ASSUME(cw(0,4) >= cdy[0]);
ASSUME(cw(0,4) >= cdl[0]);
ASSUME(cw(0,4) >= cds[0]);
ASSUME(cw(0,4) >= cctrl[0]);
ASSUME(cw(0,4) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,4) = 0;
mem(4,cw(0,4)) = 0;
co(4,cw(0,4))+=1;
delta(4,cw(0,4)) = -1;
ASSUME(creturn[0] >= cw(0,4));
// call void @llvm.dbg.value(metadata i64* @atom_1_X7_0, metadata !181, metadata !DIExpression()), !dbg !241
// call void @llvm.dbg.value(metadata i64 0, metadata !183, metadata !DIExpression()), !dbg !241
// store atomic i64 0, i64* @atom_1_X7_0 monotonic, align 8, !dbg !128
// ST: Guess
iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,5);
cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,5)] == 0);
ASSUME(active[cw(0,5)] == 0);
ASSUME(sforbid(5,cw(0,5))== 0);
ASSUME(iw(0,5) >= 0);
ASSUME(iw(0,5) >= 0);
ASSUME(cw(0,5) >= iw(0,5));
ASSUME(cw(0,5) >= old_cw);
ASSUME(cw(0,5) >= cr(0,5));
ASSUME(cw(0,5) >= cl[0]);
ASSUME(cw(0,5) >= cisb[0]);
ASSUME(cw(0,5) >= cdy[0]);
ASSUME(cw(0,5) >= cdl[0]);
ASSUME(cw(0,5) >= cds[0]);
ASSUME(cw(0,5) >= cctrl[0]);
ASSUME(cw(0,5) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,5) = 0;
mem(5,cw(0,5)) = 0;
co(5,cw(0,5))+=1;
delta(5,cw(0,5)) = -1;
ASSUME(creturn[0] >= cw(0,5));
// call void @llvm.dbg.value(metadata i64* @atom_1_X9_1, metadata !184, metadata !DIExpression()), !dbg !243
// call void @llvm.dbg.value(metadata i64 0, metadata !186, metadata !DIExpression()), !dbg !243
// store atomic i64 0, i64* @atom_1_X9_1 monotonic, align 8, !dbg !130
// ST: Guess
iw(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,6);
cw(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,6)] == 0);
ASSUME(active[cw(0,6)] == 0);
ASSUME(sforbid(6,cw(0,6))== 0);
ASSUME(iw(0,6) >= 0);
ASSUME(iw(0,6) >= 0);
ASSUME(cw(0,6) >= iw(0,6));
ASSUME(cw(0,6) >= old_cw);
ASSUME(cw(0,6) >= cr(0,6));
ASSUME(cw(0,6) >= cl[0]);
ASSUME(cw(0,6) >= cisb[0]);
ASSUME(cw(0,6) >= cdy[0]);
ASSUME(cw(0,6) >= cdl[0]);
ASSUME(cw(0,6) >= cds[0]);
ASSUME(cw(0,6) >= cctrl[0]);
ASSUME(cw(0,6) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,6) = 0;
mem(6,cw(0,6)) = 0;
co(6,cw(0,6))+=1;
delta(6,cw(0,6)) = -1;
ASSUME(creturn[0] >= cw(0,6));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !131
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call13 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !132
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %call14 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !133
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[3] >= cdy[0]);
// %3 = load i64, i64* %thr0, align 8, !dbg !134, !tbaa !135
// LD: Guess
old_cr = cr(0,7);
cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,7)] == 0);
ASSUME(cr(0,7) >= iw(0,7));
ASSUME(cr(0,7) >= 0);
ASSUME(cr(0,7) >= cdy[0]);
ASSUME(cr(0,7) >= cisb[0]);
ASSUME(cr(0,7) >= cdl[0]);
ASSUME(cr(0,7) >= cl[0]);
// Update
creg_r10 = cr(0,7);
crmax(0,7) = max(crmax(0,7),cr(0,7));
caddr[0] = max(caddr[0],0);
if(cr(0,7) < cw(0,7)) {
r10 = buff(0,7);
} else {
if(pw(0,7) != co(7,cr(0,7))) {
ASSUME(cr(0,7) >= old_cr);
}
pw(0,7) = co(7,cr(0,7));
r10 = mem(7,cr(0,7));
}
ASSUME(creturn[0] >= cr(0,7));
// %call15 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !139
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %4 = load i64, i64* %thr1, align 8, !dbg !140, !tbaa !135
// LD: Guess
old_cr = cr(0,8);
cr(0,8) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,8)] == 0);
ASSUME(cr(0,8) >= iw(0,8));
ASSUME(cr(0,8) >= 0);
ASSUME(cr(0,8) >= cdy[0]);
ASSUME(cr(0,8) >= cisb[0]);
ASSUME(cr(0,8) >= cdl[0]);
ASSUME(cr(0,8) >= cl[0]);
// Update
creg_r11 = cr(0,8);
crmax(0,8) = max(crmax(0,8),cr(0,8));
caddr[0] = max(caddr[0],0);
if(cr(0,8) < cw(0,8)) {
r11 = buff(0,8);
} else {
if(pw(0,8) != co(8,cr(0,8))) {
ASSUME(cr(0,8) >= old_cr);
}
pw(0,8) = co(8,cr(0,8));
r11 = mem(8,cr(0,8));
}
ASSUME(creturn[0] >= cr(0,8));
// %call16 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !141
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// %5 = load i64, i64* %thr2, align 8, !dbg !142, !tbaa !135
// LD: Guess
old_cr = cr(0,9);
cr(0,9) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,9)] == 0);
ASSUME(cr(0,9) >= iw(0,9));
ASSUME(cr(0,9) >= 0);
ASSUME(cr(0,9) >= cdy[0]);
ASSUME(cr(0,9) >= cisb[0]);
ASSUME(cr(0,9) >= cdl[0]);
ASSUME(cr(0,9) >= cl[0]);
// Update
creg_r12 = cr(0,9);
crmax(0,9) = max(crmax(0,9),cr(0,9));
caddr[0] = max(caddr[0],0);
if(cr(0,9) < cw(0,9)) {
r12 = buff(0,9);
} else {
if(pw(0,9) != co(9,cr(0,9))) {
ASSUME(cr(0,9) >= old_cr);
}
pw(0,9) = co(9,cr(0,9));
r12 = mem(9,cr(0,9));
}
ASSUME(creturn[0] >= cr(0,9));
// %call17 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !143
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,8+0));
ASSUME(cdy[0] >= cw(0,9+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,8+0));
ASSUME(cdy[0] >= cr(0,9+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[3]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !188, metadata !DIExpression()), !dbg !258
// %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) seq_cst, align 8, !dbg !145
// LD: Guess
old_cr = cr(0,0);
cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,0)] == 0);
ASSUME(cr(0,0) >= iw(0,0));
ASSUME(cr(0,0) >= 0);
ASSUME(cr(0,0) >= cdy[0]);
ASSUME(cr(0,0) >= cisb[0]);
ASSUME(cr(0,0) >= cdl[0]);
ASSUME(cr(0,0) >= cl[0]);
// Update
creg_r13 = cr(0,0);
crmax(0,0) = max(crmax(0,0),cr(0,0));
caddr[0] = max(caddr[0],0);
if(cr(0,0) < cw(0,0)) {
r13 = buff(0,0);
} else {
if(pw(0,0) != co(0,cr(0,0))) {
ASSUME(cr(0,0) >= old_cr);
}
pw(0,0) = co(0,cr(0,0));
r13 = mem(0,cr(0,0));
}
ASSUME(creturn[0] >= cr(0,0));
// call void @llvm.dbg.value(metadata i64 %6, metadata !190, metadata !DIExpression()), !dbg !258
// %conv = trunc i64 %6 to i32, !dbg !146
// call void @llvm.dbg.value(metadata i32 %conv, metadata !187, metadata !DIExpression()), !dbg !224
// %cmp = icmp eq i32 %conv, 2, !dbg !147
// %conv18 = zext i1 %cmp to i32, !dbg !147
// call void @llvm.dbg.value(metadata i32 %conv18, metadata !191, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !193, metadata !DIExpression()), !dbg !262
// %7 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) seq_cst, align 8, !dbg !149
// LD: Guess
old_cr = cr(0,0+1*1);
cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,0+1*1)] == 0);
ASSUME(cr(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cr(0,0+1*1) >= 0);
ASSUME(cr(0,0+1*1) >= cdy[0]);
ASSUME(cr(0,0+1*1) >= cisb[0]);
ASSUME(cr(0,0+1*1) >= cdl[0]);
ASSUME(cr(0,0+1*1) >= cl[0]);
// Update
creg_r14 = cr(0,0+1*1);
crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1));
caddr[0] = max(caddr[0],0);
if(cr(0,0+1*1) < cw(0,0+1*1)) {
r14 = buff(0,0+1*1);
} else {
if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) {
ASSUME(cr(0,0+1*1) >= old_cr);
}
pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1));
r14 = mem(0+1*1,cr(0,0+1*1));
}
ASSUME(creturn[0] >= cr(0,0+1*1));
// call void @llvm.dbg.value(metadata i64 %7, metadata !195, metadata !DIExpression()), !dbg !262
// %conv22 = trunc i64 %7 to i32, !dbg !150
// call void @llvm.dbg.value(metadata i32 %conv22, metadata !192, metadata !DIExpression()), !dbg !224
// %cmp23 = icmp eq i32 %conv22, 1, !dbg !151
// %conv24 = zext i1 %cmp23 to i32, !dbg !151
// call void @llvm.dbg.value(metadata i32 %conv24, metadata !196, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !198, metadata !DIExpression()), !dbg !266
// %8 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) seq_cst, align 8, !dbg !153
// LD: Guess
old_cr = cr(0,0+2*1);
cr(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,0+2*1)] == 0);
ASSUME(cr(0,0+2*1) >= iw(0,0+2*1));
ASSUME(cr(0,0+2*1) >= 0);
ASSUME(cr(0,0+2*1) >= cdy[0]);
ASSUME(cr(0,0+2*1) >= cisb[0]);
ASSUME(cr(0,0+2*1) >= cdl[0]);
ASSUME(cr(0,0+2*1) >= cl[0]);
// Update
creg_r15 = cr(0,0+2*1);
crmax(0,0+2*1) = max(crmax(0,0+2*1),cr(0,0+2*1));
caddr[0] = max(caddr[0],0);
if(cr(0,0+2*1) < cw(0,0+2*1)) {
r15 = buff(0,0+2*1);
} else {
if(pw(0,0+2*1) != co(0+2*1,cr(0,0+2*1))) {
ASSUME(cr(0,0+2*1) >= old_cr);
}
pw(0,0+2*1) = co(0+2*1,cr(0,0+2*1));
r15 = mem(0+2*1,cr(0,0+2*1));
}
ASSUME(creturn[0] >= cr(0,0+2*1));
// call void @llvm.dbg.value(metadata i64 %8, metadata !200, metadata !DIExpression()), !dbg !266
// %conv28 = trunc i64 %8 to i32, !dbg !154
// call void @llvm.dbg.value(metadata i32 %conv28, metadata !197, metadata !DIExpression()), !dbg !224
// %cmp29 = icmp eq i32 %conv28, 2, !dbg !155
// %conv30 = zext i1 %cmp29 to i32, !dbg !155
// call void @llvm.dbg.value(metadata i32 %conv30, metadata !201, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !203, metadata !DIExpression()), !dbg !270
// %9 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !157
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r16 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r16 = buff(0,3);
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r16 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i64 %9, metadata !205, metadata !DIExpression()), !dbg !270
// %conv34 = trunc i64 %9 to i32, !dbg !158
// call void @llvm.dbg.value(metadata i32 %conv34, metadata !202, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i64* @atom_1_X5_2, metadata !207, metadata !DIExpression()), !dbg !273
// %10 = load atomic i64, i64* @atom_1_X5_2 seq_cst, align 8, !dbg !160
// LD: Guess
old_cr = cr(0,4);
cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,4)] == 0);
ASSUME(cr(0,4) >= iw(0,4));
ASSUME(cr(0,4) >= 0);
ASSUME(cr(0,4) >= cdy[0]);
ASSUME(cr(0,4) >= cisb[0]);
ASSUME(cr(0,4) >= cdl[0]);
ASSUME(cr(0,4) >= cl[0]);
// Update
creg_r17 = cr(0,4);
crmax(0,4) = max(crmax(0,4),cr(0,4));
caddr[0] = max(caddr[0],0);
if(cr(0,4) < cw(0,4)) {
r17 = buff(0,4);
} else {
if(pw(0,4) != co(4,cr(0,4))) {
ASSUME(cr(0,4) >= old_cr);
}
pw(0,4) = co(4,cr(0,4));
r17 = mem(4,cr(0,4));
}
ASSUME(creturn[0] >= cr(0,4));
// call void @llvm.dbg.value(metadata i64 %10, metadata !209, metadata !DIExpression()), !dbg !273
// %conv38 = trunc i64 %10 to i32, !dbg !161
// call void @llvm.dbg.value(metadata i32 %conv38, metadata !206, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i64* @atom_1_X7_0, metadata !211, metadata !DIExpression()), !dbg !276
// %11 = load atomic i64, i64* @atom_1_X7_0 seq_cst, align 8, !dbg !163
// LD: Guess
old_cr = cr(0,5);
cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,5)] == 0);
ASSUME(cr(0,5) >= iw(0,5));
ASSUME(cr(0,5) >= 0);
ASSUME(cr(0,5) >= cdy[0]);
ASSUME(cr(0,5) >= cisb[0]);
ASSUME(cr(0,5) >= cdl[0]);
ASSUME(cr(0,5) >= cl[0]);
// Update
creg_r18 = cr(0,5);
crmax(0,5) = max(crmax(0,5),cr(0,5));
caddr[0] = max(caddr[0],0);
if(cr(0,5) < cw(0,5)) {
r18 = buff(0,5);
} else {
if(pw(0,5) != co(5,cr(0,5))) {
ASSUME(cr(0,5) >= old_cr);
}
pw(0,5) = co(5,cr(0,5));
r18 = mem(5,cr(0,5));
}
ASSUME(creturn[0] >= cr(0,5));
// call void @llvm.dbg.value(metadata i64 %11, metadata !213, metadata !DIExpression()), !dbg !276
// %conv42 = trunc i64 %11 to i32, !dbg !164
// call void @llvm.dbg.value(metadata i32 %conv42, metadata !210, metadata !DIExpression()), !dbg !224
// call void @llvm.dbg.value(metadata i64* @atom_1_X9_1, metadata !215, metadata !DIExpression()), !dbg !279
// %12 = load atomic i64, i64* @atom_1_X9_1 seq_cst, align 8, !dbg !166
// LD: Guess
old_cr = cr(0,6);
cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,6)] == 0);
ASSUME(cr(0,6) >= iw(0,6));
ASSUME(cr(0,6) >= 0);
ASSUME(cr(0,6) >= cdy[0]);
ASSUME(cr(0,6) >= cisb[0]);
ASSUME(cr(0,6) >= cdl[0]);
ASSUME(cr(0,6) >= cl[0]);
// Update
creg_r19 = cr(0,6);
crmax(0,6) = max(crmax(0,6),cr(0,6));
caddr[0] = max(caddr[0],0);
if(cr(0,6) < cw(0,6)) {
r19 = buff(0,6);
} else {
if(pw(0,6) != co(6,cr(0,6))) {
ASSUME(cr(0,6) >= old_cr);
}
pw(0,6) = co(6,cr(0,6));
r19 = mem(6,cr(0,6));
}
ASSUME(creturn[0] >= cr(0,6));
// call void @llvm.dbg.value(metadata i64 %12, metadata !217, metadata !DIExpression()), !dbg !279
// %conv46 = trunc i64 %12 to i32, !dbg !167
// call void @llvm.dbg.value(metadata i32 %conv46, metadata !214, metadata !DIExpression()), !dbg !224
// %and = and i32 %conv42, %conv46, !dbg !168
creg_r20 = max(creg_r18,creg_r19);
ASSUME(active[creg_r20] == 0);
r20 = r18 & r19;
// call void @llvm.dbg.value(metadata i32 %and, metadata !218, metadata !DIExpression()), !dbg !224
// %and47 = and i32 %conv38, %and, !dbg !169
creg_r21 = max(creg_r17,creg_r20);
ASSUME(active[creg_r21] == 0);
r21 = r17 & r20;
// call void @llvm.dbg.value(metadata i32 %and47, metadata !219, metadata !DIExpression()), !dbg !224
// %and48 = and i32 %conv34, %and47, !dbg !170
creg_r22 = max(creg_r16,creg_r21);
ASSUME(active[creg_r22] == 0);
r22 = r16 & r21;
// call void @llvm.dbg.value(metadata i32 %and48, metadata !220, metadata !DIExpression()), !dbg !224
// %and49 = and i32 %conv30, %and48, !dbg !171
creg_r23 = max(max(creg_r15,0),creg_r22);
ASSUME(active[creg_r23] == 0);
r23 = (r15==2) & r22;
// call void @llvm.dbg.value(metadata i32 %and49, metadata !221, metadata !DIExpression()), !dbg !224
// %and50 = and i32 %conv24, %and49, !dbg !172
creg_r24 = max(max(creg_r14,0),creg_r23);
ASSUME(active[creg_r24] == 0);
r24 = (r14==1) & r23;
// call void @llvm.dbg.value(metadata i32 %and50, metadata !222, metadata !DIExpression()), !dbg !224
// %and51 = and i32 %conv18, %and50, !dbg !173
creg_r25 = max(max(creg_r13,0),creg_r24);
ASSUME(active[creg_r25] == 0);
r25 = (r13==2) & r24;
// call void @llvm.dbg.value(metadata i32 %and51, metadata !223, metadata !DIExpression()), !dbg !224
// %cmp52 = icmp eq i32 %and51, 1, !dbg !174
// br i1 %cmp52, label %if.then, label %if.end, !dbg !176
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg_r25);
ASSUME(cctrl[0] >= 0);
if((r25==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([120 x i8], [120 x i8]* @.str.1, i64 0, i64 0), i32 noundef 93, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !177
// unreachable, !dbg !177
r26 = 1;
T0BLOCK2:
// %13 = bitcast i64* %thr2 to i8*, !dbg !180
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %13) #7, !dbg !180
// %14 = bitcast i64* %thr1 to i8*, !dbg !180
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %14) #7, !dbg !180
// %15 = bitcast i64* %thr0 to i8*, !dbg !180
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %15) #7, !dbg !180
// ret i32 0, !dbg !181
ret_thread_0 = 0;
ASSERT(r26== 0);
}
| [
"tuan-phong.ngo@it.uu.se"
] | tuan-phong.ngo@it.uu.se |
853f537749c87d144d420d9b6ca44ab6821cce2b | 48e1edbdd9188a8e53dda852248de0e09b8e8e8f | /A350Systems/A350Systems/Waypoint.h | ad77ca4aea3a8bce9727c659d01926ee7405ec1f | [] | no_license | SimJobs/A350 | 1ac6369a2fde6c5e4a02b464ce1a1c7627df95ed | 9462fb665ca16bdc81bb92d0f2a0ef55c25318fd | refs/heads/master | 2021-01-23T04:09:44.137894 | 2014-10-21T16:40:40 | 2014-10-21T16:40:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 947 | h | #ifndef WAYPOINT_H
#define WAYPOINT_H
#include <string>
using namespace std;
namespace Backend
{
struct Waypoint
{
private:
//location
float longitude;
float latitude;
//name
string name;
//data for waypoint
int altitude;
int speed;
public:
Waypoint(float latitude, float longitude, string name, int altitude = 0, int speed = 0);
float getLongitude()
{
return longitude;
}
void setLongitude(float longitude)
{
this->longitude = longitude;
}
float getLatitude()
{
return latitude;
}
void setLatitude(float latitude)
{
this->latitude = latitude;
}
string getName()
{
return name;
}
void setName(string name)
{
this->name = name;
}
int getAltitude()
{
return altitude;
}
void setAltitude(int altitude)
{
this->altitude = altitude;
}
int getSpeed()
{
return speed;
}
void setSpeed(int speed)
{
this->speed = speed;
}
};
}
#endif | [
"simjobsinc@gmail.com"
] | simjobsinc@gmail.com |
37376ef68df587ce1671bf3921841995bf8fe21d | dde6e0373d64418ceac8da010144cc921d33eec7 | /HTest1/src/GOffAxisCamera.h | c7a1be2597c9969e0494079456eb0309962c1e2a | [] | no_license | fengxiuyaun/OgreHavokTest | 25eb1e9f7eba0712e12e51bc6e8233223a314ebd | 7bac456c4bc5513ccbe0ae0695e9fa28f7c4316b | refs/heads/master | 2020-04-05T23:34:01.993161 | 2011-08-01T03:54:47 | 2011-08-01T03:54:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,512 | h | #ifndef __GOFFAXKIS_HEADER__
#define __GOFFAXKIS_HEADER__
#include "Singleton.h"
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include "ExampleApplication.h"
#pragma once
#define NUMBER_OF_DISPLAYS 4
class GOffAxisCamera : public HK::Singleton<GOffAxisCamera> {
friend class HK::Singleton<GOffAxisCamera>;
protected:
GOffAxisCamera();
~GOffAxisCamera();
public:
Ogre::SceneNode *GetUberNode(){return _uberNode;}
bool LoadIni(char *file);
void Start(){_bStart = true;}
void EnableOffAxisProjection(Ogre::Camera *camera);
void MoveCamera(Ogre::Vector3 rot, Ogre::Vector3 trans);
void SetPosition(Ogre::Vector3 pos){
_uberNode->setPosition(pos); //Update uber node
_dummyCam->setPosition(pos); //Update dummy camera
};
Ogre::Vector3 GetPosition(){return _uberNode->getPosition();}
void SetOrientation(Ogre::Quaternion o){_uberNode->setOrientation(o);}
Ogre::Quaternion GetOrientation(){return _uberNode->getOrientation();}
Ogre::Quaternion GetRealCameraOrientation(){return _dummyCam->getRealOrientation();}
void SetMatrix(Ogre::Matrix4 m){_offAxis = m;}
void SetCamera(Ogre::Camera *c){
_camera = c;
_uberNode->attachObject(_camera);
}
void Update();
private:
double _dFOVLeft,_dFOVRight,_dFOVTop,_dFOVBottom;
double _dCaveRoll, _dCavePitch, _dCaveYaw;
double _dCaveFOV;
bool _bStart;
int _nDisplays;
Ogre::Matrix4 _offAxis;
Ogre::Camera *_camera;
Ogre::SceneNode *_uberNode;
Ogre::Camera *_dummyCam;
};
#endif // __GDEBUGGER_HEADER__ | [
"jerdak@gmail.com"
] | jerdak@gmail.com |
5c717326a2aa0618c3f91c7d2a007ecd4bf1de79 | 41b8c46b39698d8642df8d3b947384996e6d2167 | /src/trajectory_optimizer/cubic_bezier_curve.cpp | cb4ac4561d65970e617825e117e0c1a1b974f789 | [] | no_license | ColleyLi/TrajectoryOptimizer | dbe579258bfcfb71e06b91100aad2ffd9d7659cb | e38cd47041d3c47285db3e881a611c71b8df7d2e | refs/heads/master | 2023-04-21T21:39:30.620452 | 2021-05-19T06:02:55 | 2021-05-19T06:02:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,587 | cpp | /******************************************************************************
* Copyright 2020 The zhejiang lab Authors. All Rights Reserved.
*****************************************************************************/
/**
* @file cubic_bezier_curve.cc
**/
#include "cubic_bezier_curve.h"
namespace localPlanner
{
CubicBezierCurve::CubicBezierCurve(){}
CubicBezierTrajectory CubicBezierCurve::GetCubicBezierTrajectory(const Pointxy& p0, const Pointxy& p1, const Pointxy& p2, const Pointxy& p3, const double dt)
{
CubicBezierTrajectory trajectory;
p0_ = p0;
p1_ = p1;
p2_ = p2;
p3_ = p3;
trajectory.p0 = p0;
trajectory.p1 = p1;
trajectory.p2 = p2;
trajectory.p3 = p3;
CubicBezierCurveInterpolation(dt);
trajectory.poses = poses_;
trajectory.maxk = GetMaxCurvature();
trajectory.k0 = GetCurvatureatInitPoint();
return trajectory;
}
Pointxy CubicBezierCurve::Evaluate(const int order, const double t)
{
Pointxy point;
switch (order)
{
case 0: {
point.x = (1-t)*(1-t)*(1-t)*p0_.x+3*(1-t)*(1-t)*t*p1_.x+3*(1-t)*t*t*p2_.x+t*t*t*p3_.x;
point.y = (1-t)*(1-t)*(1-t)*p0_.y+3*(1-t)*(1-t)*t*p1_.y+3*(1-t)*t*t*p2_.y+t*t*t*p3_.y;
break;
}
case 1: {
point.x = 3*(1-t)*(1-t)*(p1_.x-p0_.x)+6*(1-t)*t*(p2_.x-p1_.x)+3*t*t*(p3_.x-p2_.x);
point.y = 3*(1-t)*(1-t)*(p1_.y-p0_.y)+6*(1-t)*t*(p2_.y-p1_.y)+3*t*t*(p3_.y-p2_.y);
break;
}
case 2: {
point.x = 6*(1-t)*(p2_.x-2*p1_.x+p0_.x)+6*t*(p3_.x-2*p2_.x+p1_.x);
point.y = 6*(1-t)*(p2_.y-2*p1_.y+p0_.y)+6*t*(p3_.y-2*p2_.y+p1_.y);
break;
}
case 3: {
point.x = -6*p0_.x+18*p1_.x-18*p2_.x+6*p3_.x;
point.y = -6*p0_.y+18*p1_.y-18*p2_.y+6*p3_.y;
break;
}
default:
point.x = 0.0;
point.y = 0.0;
}
return point;
}
double CubicBezierCurve::GetCurvatureatInitPoint(){return k0_;}
double CubicBezierCurve::GetMaxCurvature()
{
auto maxPosition = std::max_element(abscurvatures_.begin(), abscurvatures_.end());
return *maxPosition;
}
double CubicBezierCurve::GetMinCurvature()
{
auto minPosition = std::min_element(abscurvatures_.begin(), abscurvatures_.end());
return *minPosition;
}
std::vector<Pose> CubicBezierCurve::GetTrajectoryPoses()
{
return poses_;
}
std::vector<double> CubicBezierCurve::GetAllCurvatures()
{
return abscurvatures_;
}
void CubicBezierCurve::CubicBezierCurveInterpolation(const double dt)
{
poses_.clear();
abscurvatures_.clear();
double t = 0.0;
while (t <= 1.0)
{
Pose pose;
Pointxy p = Evaluate(0, t);
Pointxy dp = Evaluate(1, t);
Pointxy ddp = Evaluate(2, t);
pose.x = p.x;
pose.y = p.y;
pose.theta = std::atan2(dp.y, dp.x);
pose.kappa = (dp.x * ddp.y - dp.y * ddp.x) / pow(dp.x * dp.x + dp.y * dp.y, 1.5);
poses_.push_back(std::move(pose));
abscurvatures_.push_back(fabs((dp.x*ddp.y-dp.y*ddp.x)/pow(dp.x*dp.x+dp.y*dp.y ,1.5)));
if (t == 0.0)
{
k0_ = (dp.x*ddp.y-dp.y*ddp.x)/pow(dp.x*dp.x+dp.y*dp.y ,1.5);
}
t += dt;
}
}
} // localPlanner
| [
"shenzheng@zhejianglab.com"
] | shenzheng@zhejianglab.com |
c761e1f520b94b81eff95a74b7d9b842d6d9b048 | cf36b5f820198a5807f1c6343fd3c8c61de034e7 | /include/spmCalculator/spmCalculator.hpp | f1a9c89c87678edb36f595bb3952197848c7c24b | [] | no_license | kunaljathal/Simple-SPM | df72a128be1138f7123880050e38b2c1d1044365 | fd35e7f253dcf6f465a52fee38d97c237400b4f9 | refs/heads/master | 2016-09-16T03:05:18.496028 | 2015-08-11T17:40:37 | 2015-08-11T17:40:37 | 40,556,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | hpp | #ifndef SPMCALCULATOR_H
#define SPMCALCULATOR_H
class spmCalculator
{
public:
static int spmCalculate(double *xAccValues, double *yAccValues, double *zAccValues, unsigned int samplingRate, unsigned int windowSizeInSeconds);
private:
static double singleAxisEstimate(double *accValues, const unsigned int windowSizeSamples, const unsigned int samplesPerMinute);
};
#endif
| [
"Kunal@Kunals-MacBook-Air.local"
] | Kunal@Kunals-MacBook-Air.local |
ddcf1238306684ac13e6444bab63473d9bc0d6a2 | 470385354ed332fc9f700c2fc46ebc28e7918512 | /listas/lista_1/h_squats.cpp | 9014923261175e33fd292091de6db3d50ef3e2de | [] | no_license | sconetto/ppc | 3a97c092d4b235989bb92250c191aeb1258f88c3 | bfd70be6722a358b8488bdcdfb6316707458c755 | refs/heads/master | 2020-07-04T23:44:57.254823 | 2019-11-25T00:51:57 | 2019-11-25T00:51:57 | 202,459,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 917 | cpp | #include <iostream>
#include <string>
using namespace std;
int main(int argc, char const *argv[]) {
int n, su = 0, sd = 0, mins = 0;
char aux;
string hams;
cin >> n;
if (n < 2 || n > 200 || (n % 2) != 0) {
exit(1);
}
for (size_t i = 0; i < n; i++) {
cin >> aux;
hams.push_back(aux);
if (aux == 'x') {
sd++;
} else if (aux == 'X') {
su++;
}
}
while(true) {
if (su > sd) {
mins++;
su--;
sd++;
for (size_t i = 0; i < hams.size(); i++) {
if (hams[i] == 'X') {
hams[i] = 'x';
break;
}
}
} else if (sd > su) {
mins++;
sd--;
su++;
for (size_t i = 0; i < hams.size(); i++) {
if (hams[i] == 'x') {
hams[i] = 'X';
break;
}
}
} else if (sd == su) {
break;
}
}
cout << mins << endl << hams << endl;
return 0;
}
| [
"sconetto.joao@gmail.com"
] | sconetto.joao@gmail.com |
1d46dc09a5b43581107715c6e9d18cff9409bda4 | c2757b08e4a3a27438141423e669adcae6594ccc | /FG_Course9_cpp_group_asteroids/FG_Course9_cpp_group_asteroids/src/ResourceManager.cpp | 6c7c23a034e4b72a622a8b866b9ed42aff4c7eb1 | [] | no_license | TinyKenny/FG_Course9_cpp_group | f59ddaf4b6d2bf779ac0a4bae14c54648331e4ed | 17fbd9f21d403fd29c81b093bb524046c0199e0e | refs/heads/main | 2023-03-22T17:23:45.326030 | 2021-03-12T10:42:50 | 2021-03-12T10:42:50 | 343,375,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 743 | cpp | #include "ResourceManager.h"
ResourceManager::ResourceManager()
{
loadedFonts["default"] = TTF_OpenFont("res/comic.ttf", 20);
loadedSounds["shot"] = Mix_LoadWAV("res/shot.wav");
loadedSounds["hit"] = Mix_LoadWAV("res/hit.wav");
}
ResourceManager::~ResourceManager()
{
for (auto const& x : loadedSounds)
{
Mix_FreeChunk(x.second);
}
}
TTF_Font* ResourceManager::getFont(const std::string& name)
{
auto font = loadedFonts.find(name);
if (font == loadedFonts.end())
{
return nullptr;
}
else
{
return font->second;
}
}
Mix_Chunk* ResourceManager::getSoundClip(const std::string& name)
{
auto chunk = loadedSounds.find(name);
if (chunk == loadedSounds.end())
{
return nullptr;
}
else
{
return chunk->second;
}
} | [
"37851342+TeoC00l@users.noreply.github.com"
] | 37851342+TeoC00l@users.noreply.github.com |
58937a7cc330d6119d46923904850fce73d25a3f | 378969fa995f5f4d479ec7af87d7fb7e42332be2 | /lib/shader.hpp | c883f47988581fd97cf577cec07eadc4dab79b5d | [
"Unlicense"
] | permissive | mewbak/ying | b995551f132e91a1d1fd319a72921d5b632ba505 | 8daccccc2de5a2dbf2430146adbbbf67c26551d9 | refs/heads/master | 2020-04-16T07:54:54.530756 | 2019-01-12T17:13:10 | 2019-01-12T17:13:10 | 165,403,759 | 0 | 0 | null | 2019-01-12T15:33:58 | 2019-01-12T15:33:57 | null | UTF-8 | C++ | false | false | 5,329 | hpp | #ifndef SHADER_H
#define SHADER_H
// System Headers
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
class Shader {
public:
// The program id
unsigned int ID;
// Constructor reads and builds the Shader
Shader(const char* vertexPath, const char* fragmentPath) {
// 1. Retrieve the vertex/fragment source code from filePath
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;
// ensure ifstream objects can throw exceptions:
vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);
try {
// Open files
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
std::stringstream vShaderStream, fShaderStream;
// Read file's buffer contents intro streams
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
// Close file handlers
vShaderFile.close();
fShaderFile.close();
// Convert stream into string
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
} catch (std::ifstream::failure e) {
throw std::runtime_error("SHADER::FILE_NOT_SUCCESSFULLY_READ: " + e.code().message());
}
const char* vShaderCode = vertexCode.c_str();
const char* fShaderCode = fragmentCode.c_str();
// 2. Compile shaders
unsigned int vertex, fragment;
// Vertex shader
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, nullptr);
glCompileShader(vertex);
checkCompileErrors(vertex, "VERTEX");
// Fragment shader
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, nullptr);
glCompileShader(fragment);
checkCompileErrors(fragment, "FRAGMENT");
// Shader Program
ID = glCreateProgram();
glAttachShader(ID, vertex);
glAttachShader(ID, fragment);
glLinkProgram(ID);
checkCompileErrors(ID, "PROGRAM");
// Delete the shaders as they're linked into our program now and no longer necessary
glDeleteShader(vertex);
glDeleteShader(fragment);
}
// Use/activate the Shader
void use() {
glUseProgram(ID);
}
// Utility uniform functions
void setBool(const std::string &name, bool value) const {
glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value);
}
void setInt(const std::string &name, int value) const {
glUniform1i(glGetUniformLocation(ID, name.c_str()), value);
}
void setFloat(const std::string &name, float value) const {
glUniform1f(glGetUniformLocation(ID, name.c_str()), value);
}
void setVec2(const std::string &name, const glm::vec2 &value) const {
glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void setVec2(const std::string &name, float x, float y) const {
glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y);
}
void setVec3(const std::string &name, const glm::vec3 &value) const {
glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void setVec3(const std::string &name, float x, float y, float z) const {
glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z);
}
void setVec4(const std::string &name, const glm::vec4 &value) const {
glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
}
void setVec4(const std::string &name, float x, float y, float z, float w) const {
glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w);
}
void setMat2(const std::string &name, const glm::mat2 &mat) const {
glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
void setMat3(const std::string &name, const glm::mat3 &mat) const {
glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
void setMat4(const std::string &name, const glm::mat4 &mat) const {
glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
private:
// Utility function for checking shader compilation/linking errors.
void checkCompileErrors(unsigned int shader, std::string type) {
int success;
char infoLog[1024];
if (type != "PROGRAM") {
// Print compile errors if any
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (success) {
return;
}
glGetShaderInfoLog(shader, 1024, nullptr, infoLog);
throw std::runtime_error("VERTEX::COMPILATION_ERROR of type: " + type + " " + std::string(infoLog));
} else {
glGetProgramiv(shader, GL_LINK_STATUS, &success);
if (success) {
return;
}
glGetProgramInfoLog(shader, 1024, nullptr, infoLog);
throw std::runtime_error("PROGRAM_LINKING_ERROR of type: " + type + " " + std::string(infoLog));
}
}
};
#endif
| [
"henry@karlek.io"
] | henry@karlek.io |
0a58fbb9a48c2b5e1e8fc809c41766235669852c | 629a05d73fcccc21003b43d7733e5afc37b214c1 | /src/robotX/utils/TimeUtils.cpp | fb7d4d03a87321ee92373685e4f3e4103df9b6bb | [] | no_license | glee0413/robotX | 4179872b9f90194dc9dcdd9ebf344a38a526c556 | a8c9fd0b27c31ef7907248350ff4e1ef0c85e146 | refs/heads/master | 2021-01-17T19:23:51.397200 | 2017-02-14T13:43:09 | 2017-02-14T13:43:09 | 59,926,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,273 | cpp | /*
* TimeUtils.cpp
*
* Created on: 2016年5月11日
* Author: light
*/
#include <sys/time.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
#include <utils/TimeUtils.h>
namespace Utils {
TimeUtils::TimeUtils() {
// TODO Auto-generated constructor stub
gettimeofday(&this->m_current,NULL);
}
TimeUtils::~TimeUtils() {
// TODO Auto-generated destructor stub
}
const char* TimeUtils::getLocalTime(char* time_str) {
//TODO:线程不安全,time_str,需要保存足够的长度
time_t now;
struct tm *timenow;
time(&now);
timenow = localtime(&now);
strcpy(time_str, asctime(timenow));
time_str[strlen(time_str)-1] = 0;
return time_str;
}
const char* TimeUtils::getTimeOfDay(char* time_str) {
time_t now;
struct tm *timenow;
struct timeval tv;
gettimeofday(&tv,NULL);
time(&now);
timenow = localtime(&now);
sprintf(time_str,"%02d:%02d:%02d.%06ld",timenow->tm_hour,timenow->tm_min,timenow->tm_sec,tv.tv_usec);
return time_str;
}
int TimeUtils::getDiff() {
int diff = 0;
gettimeofday(&this->m_diff, NULL);
diff = (m_diff.tv_sec - m_current.tv_sec) * 1000
+ (m_diff.tv_usec - m_current.tv_usec);
memcpy(&m_current, &m_diff, sizeof(m_current));
return diff;
}
} /* namespace Utils */
| [
"glee-0413@163.com"
] | glee-0413@163.com |
a3f34c3f5a895122ef39e8e644b5fea22ffd2043 | ba732d80d942509dcd3f305ec8b0d95834e79808 | /ref_book/01_cpp_games/ch14/05_queue.cpp | e27ec171730f0ba43ffb1e029b240164fbefaee3 | [] | no_license | minsa97/lecture_cpp | 198e0c55a72f2c4edfcfa264995a5c18c77c9eb5 | efa53e033af7014ef73156673d273f93c5a215ce | refs/heads/main | 2023-05-11T13:12:40.584750 | 2021-05-31T09:21:16 | 2021-05-31T09:21:16 | 343,638,422 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | cpp | // 05_queue.cpp
#include <iostream>
#include <queue>
using namespace std;
int main(){
queue<int> que;
int count;
cout << "피보나치 수의 개수를 입력하세요: ";
cin >> count;
cout << "피보나치 수열 = ";
que.push(0);
que.push(1);
for (int i = 0; i < count; i++) {
int x = que.front();
que.pop();
cout << x << " ";
que.push(x + que.front());
}
cout << endl;
return 0;
} | [
"minsa97@naver.com"
] | minsa97@naver.com |
3eb45ce17fdc3f412c3ba5d21c490254f36407ed | d077e40e376f16c9420f32001decf946a34a6e71 | /NumCore/HypreGMRESsolver.h | 75f51ed9a15f506a626c6bfec34cda62c70ee4e5 | [
"MIT"
] | permissive | jnbrunet/febio2 | 43196e79f8c54a5c92f3f592aa7437fd3b3fe842 | fdbedae97c7d2ecad3dc89d25c8343cfbdeb195a | refs/heads/master | 2021-07-21T01:04:58.828864 | 2020-05-19T06:47:31 | 2020-05-19T06:47:31 | 203,228,954 | 0 | 0 | null | 2019-08-19T18:38:29 | 2019-08-19T18:38:28 | null | UTF-8 | C++ | false | false | 2,212 | h | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2019 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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.*/
#pragma once
#include <FECore/LinearSolver.h>
#include "CompactUnSymmMatrix.h"
//-----------------------------------------------------------------------------
// This class implements the HYPRE GMRES solver
class HypreGMRESsolver : public LinearSolver
{
class Implementation;
public:
HypreGMRESsolver();
~HypreGMRESsolver();
void SetPrintLevel(int n);
void SetMaxIterations(int n);
void SetConvergencTolerance(double tol);
public:
// allocate storage
bool PreProcess();
//! Factor the matrix (for iterative solvers, this can be used for creating pre-conditioner)
bool Factor();
//! Calculate the solution of RHS b and store solution in x
bool BackSolve(vector<double>& x, vector<double>& b);
//! Return a sparse matrix compatible with this solver
SparseMatrix* CreateSparseMatrix(Matrix_Type ntype);
//! set the sparse matrix
bool SetSparseMatrix(SparseMatrix* A) override;
private:
Implementation* imp;
};
| [
"mherron@omen.sci.utah.edu"
] | mherron@omen.sci.utah.edu |
56e08704d4831c92de58b97105790bc4df04ad6d | 7a2e4fb0ef75367e88112160713f94b1eee06eea | /src/NodeRpcProxy/NodeRpcProxy.h | eefd98e042d28ec5adf867488b3ace0ca1874bad | [] | no_license | rainmanp7/digitalnote45 | 0ba02600369f19c729841c736f5809893bc45034 | c64310a220f12b6d4e7f4820c8014026a4266a02 | refs/heads/master | 2020-03-17T16:02:22.867091 | 2018-05-17T01:33:53 | 2018-05-17T01:33:53 | 133,733,725 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,447 | h | // Copyright (c) 2011-2016 The Cryptonote developers
// Copyright (c) 2014-2017 XDN-project developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_set>
#include "Common/ObserverManager.h"
#include "INode.h"
namespace System {
class ContextGroup;
class Dispatcher;
class Event;
}
namespace CryptoNote {
class HttpClient;
class INodeRpcProxyObserver {
public:
virtual ~INodeRpcProxyObserver() {}
virtual void connectionStatusUpdated(bool connected) {}
};
class NodeRpcProxy : public CryptoNote::INode {
public:
NodeRpcProxy(const std::string& nodeHost, unsigned short nodePort);
virtual ~NodeRpcProxy();
virtual bool addObserver(CryptoNote::INodeObserver* observer) override;
virtual bool removeObserver(CryptoNote::INodeObserver* observer) override;
virtual bool addObserver(CryptoNote::INodeRpcProxyObserver* observer);
virtual bool removeObserver(CryptoNote::INodeRpcProxyObserver* observer);
virtual void init(const Callback& callback) override;
virtual bool shutdown() override;
virtual size_t getPeerCount() const override;
virtual uint32_t getLastLocalBlockHeight() const override;
virtual uint32_t getLastKnownBlockHeight() const override;
virtual uint32_t getLocalBlockCount() const override;
virtual uint32_t getKnownBlockCount() const override;
virtual uint64_t getLastLocalBlockTimestamp() const override;
virtual void relayTransaction(const CryptoNote::Transaction& transaction, const Callback& callback) override;
virtual void getRandomOutsByAmounts(std::vector<uint64_t>&& amounts, uint64_t outsCount, std::vector<COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount>& result, const Callback& callback) override;
virtual void getNewBlocks(std::vector<Crypto::Hash>&& knownBlockIds, std::vector<CryptoNote::block_complete_entry>& newBlocks, uint32_t& startHeight, const Callback& callback) override;
virtual void getTransactionOutsGlobalIndices(const Crypto::Hash& transactionHash, std::vector<uint32_t>& outsGlobalIndices, const Callback& callback) override;
virtual void queryBlocks(std::vector<Crypto::Hash>&& knownBlockIds, uint64_t timestamp, std::vector<BlockShortEntry>& newBlocks, uint32_t& startHeight, const Callback& callback) override;
virtual void getPoolSymmetricDifference(std::vector<Crypto::Hash>&& knownPoolTxIds, Crypto::Hash knownBlockId, bool& isBcActual,
std::vector<std::unique_ptr<ITransactionReader>>& newTxs, std::vector<Crypto::Hash>& deletedTxIds, const Callback& callback) override;
virtual void getMultisignatureOutputByGlobalIndex(uint64_t amount, uint32_t gindex, MultisignatureOutput& out, const Callback& callback) override;
virtual void getBlocks(const std::vector<uint32_t>& blockHeights, std::vector<std::vector<BlockDetails>>& blocks, const Callback& callback) override;
virtual void getBlocks(const std::vector<Crypto::Hash>& blockHashes, std::vector<BlockDetails>& blocks, const Callback& callback) override;
virtual void getBlocks(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t blocksNumberLimit, std::vector<BlockDetails>& blocks, uint32_t& blocksNumberWithinTimestamps, const Callback& callback) override;
virtual void getTransactions(const std::vector<Crypto::Hash>& transactionHashes, std::vector<TransactionDetails>& transactions, const Callback& callback) override;
virtual void getTransactionsByPaymentId(const Crypto::Hash& paymentId, std::vector<TransactionDetails>& transactions, const Callback& callback) override;
virtual void getPoolTransactions(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t transactionsNumberLimit, std::vector<TransactionDetails>& transactions, uint64_t& transactionsNumberWithinTimestamps, const Callback& callback) override;
virtual void isSynchronized(bool& syncStatus, const Callback& callback) override;
unsigned int rpcTimeout() const { return m_rpcTimeout; }
void rpcTimeout(unsigned int val) { m_rpcTimeout = val; }
private:
void resetInternalState();
void workerThread(const Callback& initialized_callback);
std::vector<Crypto::Hash> getKnownTxsVector() const;
void pullNodeStatusAndScheduleTheNext();
void updateNodeStatus();
void updateBlockchainStatus();
bool updatePoolStatus();
void updatePeerCount(size_t peerCount);
void updatePoolState(const std::vector<std::unique_ptr<ITransactionReader>>& addedTxs, const std::vector<Crypto::Hash>& deletedTxsIds);
std::error_code doRelayTransaction(const CryptoNote::Transaction& transaction);
std::error_code doGetRandomOutsByAmounts(std::vector<uint64_t>& amounts, uint64_t outsCount,
std::vector<COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount>& result);
std::error_code doGetNewBlocks(std::vector<Crypto::Hash>& knownBlockIds,
std::vector<CryptoNote::block_complete_entry>& newBlocks, uint32_t& startHeight);
std::error_code doGetTransactionOutsGlobalIndices(const Crypto::Hash& transactionHash,
std::vector<uint32_t>& outsGlobalIndices);
std::error_code doQueryBlocksLite(const std::vector<Crypto::Hash>& knownBlockIds, uint64_t timestamp,
std::vector<CryptoNote::BlockShortEntry>& newBlocks, uint32_t& startHeight);
std::error_code doGetPoolSymmetricDifference(std::vector<Crypto::Hash>&& knownPoolTxIds, Crypto::Hash knownBlockId, bool& isBcActual,
std::vector<std::unique_ptr<ITransactionReader>>& newTxs, std::vector<Crypto::Hash>& deletedTxIds);
void scheduleRequest(std::function<std::error_code()>&& procedure, const Callback& callback);
template <typename Request, typename Response>
std::error_code binaryCommand(const std::string& url, const Request& req, Response& res);
template <typename Request, typename Response>
std::error_code jsonCommand(const std::string& url, const Request& req, Response& res);
template <typename Request, typename Response>
std::error_code jsonRpcCommand(const std::string& method, const Request& req, Response& res);
enum State {
STATE_NOT_INITIALIZED,
STATE_INITIALIZING,
STATE_INITIALIZED
};
private:
State m_state = STATE_NOT_INITIALIZED;
std::mutex m_mutex;
std::condition_variable m_cv_initialized;
std::thread m_workerThread;
System::Dispatcher* m_dispatcher = nullptr;
System::ContextGroup* m_context_group = nullptr;
Tools::ObserverManager<CryptoNote::INodeObserver> m_observerManager;
Tools::ObserverManager<CryptoNote::INodeRpcProxyObserver> m_rpcProxyObserverManager;
const std::string m_nodeHost;
const unsigned short m_nodePort;
unsigned int m_rpcTimeout;
HttpClient* m_httpClient = nullptr;
System::Event* m_httpEvent = nullptr;
uint64_t m_pullInterval;
// Internal state
bool m_stop = false;
std::atomic<size_t> m_peerCount;
std::atomic<uint32_t> m_nodeHeight;
std::atomic<uint32_t> m_networkHeight;
//protect it with mutex if decided to add worker threads
Crypto::Hash m_lastKnowHash;
std::atomic<uint64_t> m_lastLocalBlockTimestamp;
std::unordered_set<Crypto::Hash> m_knownTxs;
bool m_connected;
};
}
| [
"muslimsoap@gmail.com"
] | muslimsoap@gmail.com |
8b657049df30665f18183ef0822ec2455a1e3abf | 3028bcee07ca7b245a9e134fd70e9c791a2d75f8 | /Lab3_Event/Lab3_Event/main.cpp | cbe218910b1ec36a72fae3f885e0bdc1ea08346a | [] | no_license | Smartkin/os-labs | 49d48592b17f580abd06de9d74002db5c3d680d6 | 5cb91048a161db38456c85f4edfc571ee317b256 | refs/heads/master | 2020-03-28T09:53:16.456288 | 2018-12-24T00:40:16 | 2018-12-24T00:40:16 | 148,067,022 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | cpp | #include <Windows.h>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
//Helper for Lab_3
//Emulates chat between 2 processes
int main(int argc, char** argv)
{
HANDLE event = 0x0;
std::string ev_name;
std::string search_str;
std::cout << "Enter event name: ";
std::cin >> ev_name; std::cin.ignore();
std::cout << "Enter string to find: ";
std::cin >> search_str; std::cin.ignore();
std::ofstream task_f("..//..//event.txt", std::ofstream::out);
task_f << search_str;
task_f.close();
std::cout << "Waiting for opened event...\n";
while (event == 0x0)
{
event = OpenEvent(SYNCHRONIZE, TRUE, ev_name.c_str());
}
WaitForSingleObject(event, INFINITE);
std::ifstream file("..//..//event.txt", std::ifstream::in);
std::stringstream res;
res << file.rdbuf();
std::cout << res.str() << std::endl;
file.close();
system("pause");
return 0;
} | [
"vladislav5019@gmail.com"
] | vladislav5019@gmail.com |
355fb36ac25fb1c5292dbfe146a98a4acb94e1a2 | 8b59552ce92fab023f5efb462a12a3616bb44464 | /RemoteControl/RemoteControlView.cpp | 1949468eef60359b2b8b83019c5c91e0e38378ca | [] | no_license | 0x6666/RemoteControl | bbdb8a7f7507bbf305ee5d439f0926ad6f89adba | 08d9330534a1d8fa73d7f98209ceb681db374a6e | refs/heads/master | 2021-06-12T15:29:59.614740 | 2015-05-03T14:13:43 | 2015-05-03T14:13:43 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,434 | cpp | ///////////////////////////////////////////////////////////////
//
// FileName : RemoteControlView.cpp
// Creator : 杨松
// Date : 2013年2月27日, 20:10:26
// Comment : 远控控制服务器文档视图结构中的视图类的实现
//
//////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "RemoteControl.h"
#include "RemoteControlDoc.h"
#include "RemoteControlView.h"
#include "clientItemView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CRemoteControlView
IMPLEMENT_DYNCREATE(CRemoteControlView, CView)
BEGIN_MESSAGE_MAP(CRemoteControlView, CView)
ON_WM_SIZE()
ON_MESSAGE(WM_ITEM_VIEW_SBCLICK , OnItemViewDBClick)
ON_MESSAGE(WM_FULLS_CREEN , OnFullScreen)
ON_MESSAGE(WM_MONITORINT_CLIENT , OnStopMonitoringClient)
ON_WM_NCCALCSIZE()
ON_WM_VSCROLL()
ON_WM_MOVE()
END_MESSAGE_MAP()
// CRemoteControlView 构造/析构
CRemoteControlView::CRemoteControlView()
/*_APS_NEXT_CONTROL_VALUE是编译器生成的下一个控件的ID
因为客户端视图是动态创建,需要ID且不能重复,所以在这里
将m_iLastClientID设置为_APS_NEXT_CONTROL_VALUE的值(动
态设置,每次添加或者删除了控件后手动设置)
*/
: m_iLastClientID(1037)
, m_pFullViewItem(NULL)
, m_curRowIndex(0)
, m_iRowCount(2) //2
, m_iColumnCount(3) //3
{
// TODO: 在此处添加构造代码
}
CRemoteControlView::~CRemoteControlView()
{
}
BOOL CRemoteControlView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return CView::PreCreateWindow(cs);
}
// CRemoteControlView 绘制
void CRemoteControlView::OnDraw(CDC* /*pDC*/)
{
CRemoteControlDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 在此处为本机数据添加绘制代码
}
// CRemoteControlView 诊断
#ifdef _DEBUG
void CRemoteControlView::AssertValid() const
{
CView::AssertValid();
}
void CRemoteControlView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CRemoteControlDoc* CRemoteControlView::GetDocument() const // 非调试版本是内联的
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CRemoteControlDoc)));
return (CRemoteControlDoc*)m_pDocument;
}
#endif //_DEBUG
BOOL CRemoteControlView::AddNewClient( PClientDescripter clientDes )
{
if (NULL == clientDes)
return FALSE;//貌似参数有问题
for (ClientViewList::iterator it = m_lstClient.begin()
; it != m_lstClient.end() ; ++it)
{
if ((*it)->GetClientIP() == clientDes->mIP)//客户端已经存在了
return FALSE;
}
ClientItemView* item = new ClientItemView( clientDes/*name , strIP , port */, GetDocument());
if(FALSE == item->Create( this , ++m_iLastClientID ))
{//创建失败
delete item;
--m_iLastClientID;
return FALSE;
}
else
{//创建成功
m_lstClient.push_back(item);
AdjustItemViewPosition(FALSE);
//调整滚动条的滚动范围
AdjustScrollSize();
}
return TRUE;
}
// CRemoteControlView 消息处理程序
void CRemoteControlView::OnSize(UINT nType, int cx, int cy)
{
CView::OnSize(nType, cx, cy);
AdjustItemViewPosition();
}
void CRemoteControlView::DispatchMsg( const CString& ip, USHORT port, const void* msg )
{
//将消息派送派送到指定的客户端视图
ClientViewList::iterator it = m_lstClient.begin();
for ( ; it != m_lstClient.end() ; ++it )
{
if ((*it)->GetClientIP() == ip)
{
(*it)->OnRcMessage( port, msg );
return ;
}
}
}
LRESULT CRemoteControlView::OnItemViewDBClick( WPARAM wParam , LPARAM lParam )
{
ASSERT(wParam != NULL);
CString ip = *((CString*)wParam);
if(!IsWindow(m_pFullViewItem->GetSafeHwnd()))
m_pFullViewItem = NULL;
if ((NULL != m_pFullViewItem) && (m_pFullViewItem->GetClientIP() == ip))
{//已经是full view了,那就重新排列
m_pFullViewItem->SetDrawEdge(TRUE);
m_pFullViewItem = NULL;
AdjustItemViewPosition(FALSE);
}else
{//设置full view
for ( ClientViewList::iterator it = m_lstClient.begin() ;
it != m_lstClient.end() ; ++it )
{
if ((*it)->GetClientIP() == ip)
{
m_pFullViewItem = *it;
m_pFullViewItem->SetDrawEdge(FALSE);
CRect rc;
GetClientRect(&rc);
m_pFullViewItem->MoveWindow(0 , 0 , rc.Width() , rc.Height() , TRUE);
m_pFullViewItem->ShowWindow(SW_SHOW);
//m_pFullViewItem->SetWindowPos(NULL , 0 , 0 , rc.Width() , rc.Height() , SWP_SHOWWINDOW);
}else{
(*it)->ShowWindow(SW_HIDE);
}
}
}
//调整滚动范围
AdjustScrollSize();
Invalidate(TRUE);
return 0;
}
void CRemoteControlView::AdjustItemViewPosition(BOOL keepFull /*= TRUE*/)
{
if (keepFull && m_pFullViewItem)
{//保持原有的fullView
//先调整滚动范围
AdjustScrollSize();
CRect rc;
GetClientRect(&rc);
m_pFullViewItem->SetWindowPos(NULL , 0 , 0 , rc.Width() , rc.Height() , SWP_SHOWWINDOW);
}
else
{//不需要保持原有的fullView
if (NULL != m_pFullViewItem)
{//原来就是全屏的
m_pFullViewItem->SetDrawEdge(TRUE);
m_pFullViewItem = NULL;
}
ClientViewList::iterator it = m_lstClient.begin();
int height = 0;
int width = 0;
GetItenSize( width , height);
int i = 0;
//先跳过前面隐藏的
for ( i = 0 ; it != m_lstClient.end() &&
(i < m_curRowIndex * m_iColumnCount) ; ++it , ++i)
{//可以显示的就调整一下位置
(*it)->ShowWindow(SW_HIDE);
}
for ( i = 0 ; it != m_lstClient.end() &&
(i != (m_iRowCount * m_iColumnCount)) ;
++it , ++i )
{//可以显示的就调整一下位置
(*it)->MoveWindow((i % m_iColumnCount) * width ,
(/*(*/i / m_iColumnCount/*) / m_iRowCount*/) * height ,
width , height ,TRUE);
(*it)->ShowWindow(SW_SHOW);
}
//后面的也不需要显示了
for ( ; it != m_lstClient.end() ; ++it )
{//可以显示的就调整一下位置
(*it)->ShowWindow(SW_HIDE);
}
//先调整滚动范围
AdjustScrollSize();
}
}
void CRemoteControlView::DestroyView()
{
for (ClientViewList::iterator it = m_lstClient.begin() ; it != m_lstClient.end() ; ++it)
{
ClientItemView* pView = *it;
pView->DestroyWindow();
delete pView;
// it = m_lstClient.begin();
}
m_lstClient.clear();
}
void CRemoteControlView::ClientDropped( const CString& ip )
{
for(ClientViewList::iterator it = m_lstClient.begin() ; it != m_lstClient.end() ; ++it)
{
if ((*it)->GetClientIP() == ip)
{//找到了制定的客户端视图
(*it)->Dropped();
break;
}
}
}
LRESULT CRemoteControlView::OnStopMonitoringClient( WPARAM wParam , LPARAM lParam )
{
CString strIP = *((CString*)wParam);
CRemoteControlDoc* pDoc = GetDocument();
pDoc->StopMonitoring(strIP);
//从客户端视图链表中删除指定的客户端
for(ClientViewList::iterator it = m_lstClient.begin() ; it != m_lstClient.end() ; ++it)
{
if ((*it)->GetClientIP() == strIP)
{//找到了制定的客户端视图
ClientItemView* view = *it;
if (m_pFullViewItem == view)
{//是全屏的
m_pFullViewItem = NULL;
}
view->DestroyWindow();
delete view;
m_lstClient.remove(view);
break;
}
}
if ((0 != m_curRowIndex) && (GetRowCount() - m_curRowIndex) < m_iRowCount)
{//有隐藏但是当前显示区域没有填满
--m_curRowIndex;
SetScrollPos(SB_VERT , m_curRowIndex , TRUE);
}
//调整各个视图的位置
AdjustItemViewPosition(FALSE);
return 0;
}
LRESULT CRemoteControlView::OnFullScreen( WPARAM wParam , LPARAM lParam )
{
ASSERT(wParam != NULL);
CString ip = *((CString*)wParam);
if ((NULL != m_pFullViewItem) && (m_pFullViewItem->GetClientIP() == ip))
{//已经是full view了
return 0;
}else
{//设置full view
for ( ClientViewList::iterator it = m_lstClient.begin() ;
it != m_lstClient.end() ; ++it )
{
if ((*it)->GetClientIP() == ip)
{
m_pFullViewItem = *it;
m_pFullViewItem->SetDrawEdge(FALSE);
CRect rc;
GetClientRect(&rc);
m_pFullViewItem->MoveWindow(0 , 0 , rc.Width() , rc.Height() , TRUE);
m_pFullViewItem->ShowWindow(SW_SHOW);
//m_pFullViewItem->SetWindowPos(NULL , 0 , 0 , rc.Width() , rc.Height() , SWP_SHOWWINDOW);
}
else
{//其他的不需要显示的都隐藏
(*it)->ShowWindow(SW_HIDE);
}
}
}
Invalidate(TRUE);
return 0;
}
void CRemoteControlView::OnInitialUpdate()
{
CView::OnInitialUpdate();
SCROLLINFO si = {0};
si.cbSize = sizeof(SCROLLINFO);
si.fMask = SIF_PAGE ;
si.nPage = 1;
SetScrollInfo(SB_VERT , &si , TRUE);
}
void CRemoteControlView::AdjustScrollSize()
{
if (NULL != m_pFullViewItem)
{//全屏时需要隐藏滚动条
ShowScrollBar(SB_VERT , FALSE);
}
else
{//非全屏
if((int)m_lstClient.size() > (m_iRowCount * m_iColumnCount))
{//需要显示滚动条
//计算滚动区域的大小
int rCnt = GetRowCount();
rCnt -= (m_iRowCount - 1);
SetScrollRange(SB_VERT , 0 , rCnt-1);
ShowScrollBar(SB_VERT , TRUE);
}
else
{//不需要显示滚动条
ShowScrollBar(SB_VERT , FALSE);
}
}
}
void CRemoteControlView::GetItenSize( int& w , int& h )
{
CRect rc;
GetClientRect(&rc);
h = rc.Height() / m_iRowCount;
w = rc.Width() / m_iColumnCount;
}
void CRemoteControlView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
switch (nSBCode)
{
case SB_BOTTOM:
case SB_TOP:
case SB_ENDSCROLL:
break;
case SB_LINEDOWN:
case SB_PAGEDOWN:
{
int rCnt = GetRowCount();//行数
if (rCnt > m_curRowIndex + 1)
{//还可以下滚
++m_curRowIndex;
AdjustItemViewPosition(TRUE);
SetScrollPos(SB_VERT , m_curRowIndex , TRUE);
}
}
break;
case SB_LINEUP:
case SB_PAGEUP:
{
if (0 < m_curRowIndex )
{//还可以下滚
--m_curRowIndex;
AdjustItemViewPosition(TRUE);
SetScrollPos(SB_VERT , m_curRowIndex , TRUE);
}
}
break;
case SB_THUMBPOSITION:
break;
case SB_THUMBTRACK:
{//拖动到制定位置
if (m_curRowIndex != nPos)
{//位置有调整
m_curRowIndex = nPos;
AdjustItemViewPosition(TRUE);
SetScrollPos(SB_VERT , m_curRowIndex , TRUE);
}
}
break;
default:
ASSERT(FALSE);
}
CView::OnVScroll(nSBCode, nPos, pScrollBar);
}
int CRemoteControlView::GetRowCount()
{
int rCnt = m_lstClient.size();
rCnt = (rCnt / m_iRowCount) + ((rCnt % m_iRowCount)? 1 : 0);
return rCnt;
}
void CRemoteControlView::OnMove(int x, int y)
{
CView::OnMove(x, y);
for (ClientViewList::iterator it = m_lstClient.begin() ; it != m_lstClient.end(); ++it)
{
(*it)->PostMessage(WM_MOVE , 0 , 0);
}
}
| [
"yangsongfwd@sina.com"
] | yangsongfwd@sina.com |
1b43d695bb39c699a7e2dea6a30fb26f9029cea6 | 6d4bb1fd018e732e190c3967c8738313340e9b0a | /src/Wrapper/HK/include/HK/DVRStatementImpl.h | b01fe1980b73ffdd8ac6df2911ed5f8fbef68b34 | [] | no_license | anyboo/Phoenix | 5c14f39bce905b2cc26e037973e28012dcb9da34 | 13b9608e402e5f3ce2feabb4bad5a0e7c862699a | refs/heads/RefireCode | 2020-04-12T03:05:30.351331 | 2016-09-28T10:12:47 | 2016-09-28T10:12:47 | 62,291,017 | 3 | 5 | null | 2016-09-28T10:12:47 | 2016-06-30T07:48:54 | C | UTF-8 | C++ | false | false | 1,200 | h | #pragma once
#include "HKLite.h"
#include "DVR/DVRStatementImpl.h"
#include "HK/Utility.h"
namespace DVR {
namespace HKLite {
class HKLite_API DVRStatementImpl : public DVR::DVRStatementImpl
{
public:
DVRStatementImpl(DVR::DVRSessionImpl& rSession, Utility::HANDLE pDvr);
~DVRStatementImpl();
long donwloadByName(const RecordFile& rf, const std::string& filename);
void downloadByTime(const Poco::DateTime& time);
int getdownloadPos(const long handle);
int playByName(const RecordFile& filename, HWND& hwnd);
void playByTime(const Poco::DateTime& time);
void stopPlayback(const int playhandle);
void setplayPos(const int playhandle, const int proValue);
int getplayPos(const int playhandle);
void list(const Poco::DateTime& beginTime, const Poco::DateTime& endTime, const std::vector<int>& channels, std::vector<RecordFile>& files);
bool canDownloadByName();
bool canPlayByName();
typedef void (*ProcessCallbackType)(long lPlayHandle, long lTotalSize, long lDownLoadSize, long dwUser);
private:
Utility::HANDLE _handle;
int _state;
};
inline bool DVRStatementImpl::canDownloadByName()
{
return true;
}
inline bool DVRStatementImpl::canPlayByName()
{
return true;
}
}}
| [
"zyf079@gmail.com"
] | zyf079@gmail.com |
e8cd26d509386423936089f2dc8fd0cf831da3f7 | 828ba76e1e18870bee0cc3be87a81a2f6a9ce5ea | /metUnit4NANO-bmp280/metUnit4NANO-bmp280.ino | 385aecd766867caf824d5a60096e1ca68b1103dc | [
"LicenseRef-scancode-other-permissive"
] | permissive | filipecebr1980/arduMet | 12c1148944bb42d33c0bb6b70e3d1d126c6965d2 | fb9f9dadfb38a8fa11b6b606abab0f44f22ac435 | refs/heads/master | 2022-12-25T16:23:51.818524 | 2020-10-03T23:32:32 | 2020-10-03T23:32:32 | 291,845,840 | 0 | 0 | null | 2020-10-03T23:32:33 | 2020-08-31T23:21:21 | C++ | UTF-8 | C++ | false | false | 4,794 | ino | /* Meteorological Unit - Temp, Umid and Pressure and Air Density
* V 1.2.0 - Air density enabled
*Created by Filipe Brandao Using
*Sparkfun GY-BME280 Library
*SMS0408E2 Library
*Using examples from Adafruit and Sparkfun Libraries.
*
The GY-BME280 is using address 0x76 (jumper closed)
Hardware connections:
BME280 -> Arduino
GND -> GND
3.3 -> 3.3
SDA -> A4
SCL -> A5
SUNMAN SMS0408E2
LCD -> Arduino
VDD -> 12
DI -> 11
VSS -> 10
CLK -> 9
REQUIRES the following Arduino libraries:
- https://github.com/sparkfun/SparkFun_BME280_Arduino_Library
- Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor
- SUNMAN SMS0408E2 LDC 7 Segments display: https://github.com/filipecebr1980/Sunman-SMS0408E2
*/
#include <Adafruit_Sensor.h>
#include <Sms0408.h>
#include <Wire.h>
#include "SparkFunBME280.h"
uint32_t delayMS=2000;
int VDD_PIN=12;
int DI_PIN=11;
int VSS_PIN=10;
int CLK_PIN=9;
int BLA_PIN=8;
int BLK_PIN=7;
//create an LCD object
Sms0408 myLCD(DI_PIN,CLK_PIN,BLK_PIN);
//create sensor object
BME280 mySensor;
void setup() {
//Configure Pins as OUTPUT
pinMode(VSS_PIN,OUTPUT);
pinMode(VDD_PIN,OUTPUT);
pinMode(CLK_PIN,OUTPUT);
pinMode(DI_PIN,OUTPUT);
pinMode(BLA_PIN,OUTPUT);
pinMode(BLK_PIN,OUTPUT);
//powers up SUNMAN SMS0408
digitalWrite(VDD_PIN, HIGH);
digitalWrite(VSS_PIN, LOW);
digitalWrite(BLA_PIN, HIGH);
digitalWrite(BLK_PIN, LOW);
Serial.begin(9600);
Serial.println("System started");
Wire.begin();
mySensor.setI2CAddress(0x76); //Connect to sensor
if(mySensor.beginI2C() == false) {
Serial.println("Sensor B connect failed!");
myLCD.displayError();
myLCD.adjust();
while(1){}
}
Serial.println("Sensor conection OK!");
//tests lcd (all segments ON for 1 second
testLcd();
delay(delayMS);
}
void loop() {
//shows temperature in C°
//displayTemp(-10.0);
displayTemp(mySensor.readTempC());
delay(delayMS);
sendSerial();
//shows humidity in %
displayHumid(mySensor.readFloatHumidity());
delay(delayMS);
sendSerial();
//shows pressure in hPa (millibar)
displayPressure(mySensor.readFloatPressure()/100.0);
delay(delayMS);
sendSerial();
//shows air density in kg/m³
displayPressure(airDensity());
delay(delayMS);
sendSerial();
}
void displayTemp(float temp){
//shows temperature in C°
if (temp>=0.0){
myLCD.clearLCD();
myLCD.displayInt((int)temp);
myLCD.codig(18,0);
myLCD.adjust();
}
else {
//for negative temperature
myLCD.clearLCD();
myLCD.codig(19,0);
myLCD.displayInt((int)(abs(temp)));
myLCD.codig(18,0);
myLCD.adjust();
}
}
void displayHumid(float humid){
//shows relative humidity, not more than 99%
if (humid >=100.0){
humid=99.0;
}
myLCD.clearLCD();
myLCD.showColumn();
myLCD.codig(17,0);
myLCD.codig(16,0);
myLCD.displayInt((int)humid);
myLCD.adjust();
}
void displayPressure(float pressure){
myLCD.clearLCD();
if(pressure < 1000.0){
myLCD.displayFloatAuto(pressure);
}
else
{
myLCD.displayInt((int)pressure);
}
myLCD.adjust();
}
void displayAirDensity(){
myLCD.clearLCD();
myLCD.displayFloatAuto(airDensity());
myLCD.adjust();
}
void testLcd(){
//fills LCD (all segments on- good to test if has any
//bad segment
myLCD.fillLCD();
delay(1000);
myLCD.clearLCD();
}
/*This funcion calculates air density as funcion of Temp, Press and Rel.Humidity
* Uses the methodology of defining dry air pressure and water vapor pressure
* as well as using the universal constants for ideal gases for both water vapor and dry air.
* For more detail about this calculation, visit: https://www.omnicalculator.com/physics/air-density
*/
float airDensity(){
double t,p,rh,p1,pv,pd,Rd,Rv,density;
//Specific gas constant for dry air: 287.058 J/(Kg.K)
Rd=287.058;
//Specific gas constant for water vapor 461.495 J/(Kg.K)
Rv=461.495;
//reads temp in C°
t=(double)mySensor.readTempC();
//read pressure in Pa
p=(double)mySensor.readFloatPressure();
//reads rel humidity
rh=(double)mySensor.readFloatHumidity();
//calculates the saturation vapor pressure, temperature converted to Kelvin
p1=6.1078*pow(10,7.5*t/(t+237.3));
//actual vapor pressure in function of relative humidity and temperature
pv=p1*rh;
//actual dry air pressure
pd=p-pv;
//temperatute in kelvin:
t=t+273.15;
//calculates air density:
density = (pd/(Rd*t))+(pv/(Rv*t));
return (float)density;
}
void sendSerial(){
Serial.print((String)mySensor.readTempC()+" " + (String)mySensor.readFloatHumidity()+ " " + (String)mySensor.readFloatPressure()+" ");
Serial.println(airDensity(),3);
}
| [
"filipecebr@gmail.com"
] | filipecebr@gmail.com |
becb7aa59ae134fdb492ff13cf50f0376bfb18e6 | 7873fa1647bab7ecac2bc5a98367aa96f32fb94a | /AFS.cpp | 47446ceba569bb9b1bd8e1c09fd19202c8e52d7f | [] | no_license | pegasus1/SPOJ | 81158badc827e978db0e9c429dc34181f0bfe1ee | eff901d039b63b6a337148dfbe37c1536918bbf8 | refs/heads/master | 2021-01-10T05:32:37.535098 | 2015-06-05T18:20:38 | 2015-06-05T18:20:38 | 36,937,530 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 765 | cpp | #include<iostream>
using namespace std;
#include<stdio.h>
int main()
{
int t;
unsigned long long n,st,lt,i,sum,p,s1;
scanf("%d",&t);
while(t--)
{
sum = 0;
scanf("%llu",&n);
if(n<=3)
printf("%d\n",n-1);
else
{
for(i=2;i*i<=n;i++)
{
p = n/i;
sum+=(p-1)*i;
st = p+1;
lt = n/(i-1);
s1 = ((lt-st+1)*(st+lt))/2;
s1 = s1 * (i-2);
sum = sum+s1;
}
for(;i<st;i++)
{
p = n/i;
sum = sum + (p-1)*i;
}
sum+=n-1;
printf("%llu\n",sum);
}
}
return 0;
}
| [
"ayush.rajoria@outlook.com"
] | ayush.rajoria@outlook.com |
60bc4cc438b1fb32b7356bb403af21e2fac0dd37 | a49ad8d5b41bd36f7d4f7b96c7770e7a39bfdba1 | /BSc (H) Sem 18-94033-45/serious stuff/CALC.cpp | 383c32251e4ad5a0fe87220be0f7db2ce2849b4d | [] | no_license | Legedith/1st-sem | 7fd10a58d9b80fa5668f9a38966f8452569f7f12 | ed99f573c5132be1047b774bc9e12268ccbae7a9 | refs/heads/master | 2020-06-29T23:18:06.147719 | 2019-10-23T00:59:40 | 2019-10-23T00:59:40 | 200,653,230 | 0 | 1 | null | 2019-10-23T00:59:41 | 2019-08-05T12:42:05 | C++ | UTF-8 | C++ | false | false | 4,128 | cpp | #include <iostream>
#include <conio.h>
using namespace std;
void HomePage(float []);
void menu(float []);
void Switch(char, float []);
void ca();
float add( float [] );
float sub( float [] );
float multiply( float [] );
float div( float [] );
int mod( float [] );
int limit;
float result;
string choice;
int main()
{
ca();
return 0;
}
void HomePage(float array[])
{
while (choice!="Exit" && choice!="exit" && choice!= "EXIT" && choice!="2")
{
cout<<" *************************************************"<<endl;
cout<<" * WELCOME *"<<endl;
cout<<" * ------- *"<<endl;
cout<<" * 1.Menu *"<<endl;
cout<<" * 2.Exit *"<<endl;
cout<<" * *"<<endl;
cout<<" *************************************************"<<endl;
cout<<"Enter your choice - ";
cin>>choice;
cout<<endl<<endl<<endl;
if (choice=="Exit" || choice=="exit" || choice== "EXIT" || choice=="2")
{
break;
}
else if( choice=="Menu" || choice=="menu" || choice == "MENU" || choice == "1")
{
menu(array);
break;
}
else
cout<<"\nWrong choice entered\n\n\n\n\n";
}
}
void menu(float array[])
{
char ch,en='y';
while(en=='y' || en=='Y')
{
cout<<" #**************************#"<<endl;
cout<<" * Menu *"<<endl;
cout<<" * ______ *"<<endl;
cout<<" * A.Addition *"<<endl;
cout<<" * B.Subtraction *"<<endl;
cout<<" * C.Multiplication *"<<endl;
cout<<" * D.Division *"<<endl;
cout<<" * E.Modulus *"<<endl;
cout<<" * F.Go Back *"<<endl;
cout<<" #**************************#"<<endl;
cout<<" CAUTION - Precision will be lost in case of modulo function.\n";
cout<<" (Decimals will be converted to integers)\n\n\n ";
cout<<" Select an operation - ";
cin>>ch;
cout<<endl<<endl;
Switch(ch, array);
cout<<" Do you want to continue\n (Reply y or Y to continue) - ";
cin>>en;
}
}
void Switch(char ch, float array[])
{
switch(ch)
{
case 'a':
case 'A':
case '1': result= add(array);
cout<<"The sum of the numbers is "<<result<<endl<<endl;
break;
case 'b':
case 'B':
case '2':result=sub(array);
cout<<"The difference of the numbers is "<<result<<endl<<endl;
break;
case 'c':
case 'C':
case '3':result= multiply(array);
cout<<"The product of the numbers is "<<result<<endl<<endl;
break;
case 'd':
case 'D':
case '4':result=div(array);
cout<<"The result is "<<result<<endl<<endl;
break;
case 'e':
case 'E':
case '5':result=mod(array);
cout<<"The result is "<<result<<endl<<endl;
break;
case 'f':
case 'F':
case '6': HomePage(array);
choice="exit";
break;
default:
cout<<"You have entered wrong input\n\n\n\n";
menu(array);
}
}
float add( float array[] )
{
float sum=0;
for(int i=0; i<limit; i++ )
sum = sum + array[i];
return sum;
}
float multiply( float array[] )
{
float pro=1;
for(int i=0; i<limit; i++ )
pro = pro * array[i];
return pro;
}
float sub( float array[] )
{
int n1,n2;
cout<<"Select element 1 - ";
cin>>n1;
cout<<"Select element 2 - ";
cin>>n2;
n1--;
n2--;
result = array[n1]-array[n2];
return result;
}
float div( float array[] )
{
int n1,n2;
cout<<"Select element 1 - ";
cin>>n1;
cout<<"Select element 2 - ";
cin>>n2;
n1--;
n2--;
result = array[n1]/array[n2];
return result;
}
int mod( float array[] )
{
int n1,n2;
cout<<"Select element 1 - ";
cin>>n1;
cout<<"Select element 2 - ";
cin>>n2;
n1--;
n2--;
int num1= static_cast<int>(array[n1]);
int num2= array[n2];
cout<<num1<<"Is num1 and \n"<<endl<<num2<<" is num2";
result = num1%num2;
cout<<endl<<result<<endl;
return result;
}
void ca()
{
cout<<"On how many numbers would you like to perform the calculations - ";
cin>>limit;
cout<<endl;
float array[ limit ];
for (int i=0,j=1; i<limit;i++,j++)
{
cout<<"Enter number "<<j <<" - "<<"\n";
cin>>array[i];
}
HomePage(array);
}
| [
"jatindehmiwal@gmail.com"
] | jatindehmiwal@gmail.com |
326290c4ecf7545c941af67142c603da0505e157 | 63daf225819636397fda6ef7e52783331c27f295 | /python-call-so/testLib.cpp | bbf6a8f55cc42027b4cbcec402ee07baefe0a278 | [] | no_license | cash2one/language-Python | e332ecfb4e9321a11407b29987ee64d44e552b15 | 8adb4f2fd2f023f9cc89b4edce1da5f71a3332ab | refs/heads/master | 2021-06-16T15:15:08.346420 | 2017-04-20T02:44:16 | 2017-04-20T02:44:16 | 112,173,361 | 1 | 0 | null | 2017-11-27T09:08:57 | 2017-11-27T09:08:57 | null | UTF-8 | C++ | false | false | 345 | cpp | #include <stdio.h>
#include "testLib.h"
CTestLib::CTestLib()
{
}
CTestLib::~CTestLib()
{
}
int CTestLib::sum(int a, int b)
{
int result = a + b;
show(result);
return result;
}
void CTestLib::show(int value)
{
printf("[class] result: %d\n", value);
}
extern "C" {
CTestLib obj;
int sum(int a, int b)
{
return obj.sum(a, b);
}
}
| [
"finetang@gmail.com"
] | finetang@gmail.com |
0296c1524210d3ace54d4184939eaf0e1675ea76 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_4711_git-2.1.4.cpp | 008446ce15498fee9b8a68b786ccba945a3be1d3 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 872 | cpp | static int git_clean_config(const char *var, const char *value, void *cb)
{
if (starts_with(var, "column."))
return git_column_config(var, value, "clean", &colopts);
/* honors the color.interactive* config variables which also
applied in git-add--interactive and git-stash */
if (!strcmp(var, "color.interactive")) {
clean_use_color = git_config_colorbool(var, value);
return 0;
}
if (starts_with(var, "color.interactive.")) {
int slot = parse_clean_color_slot(var +
strlen("color.interactive."));
if (slot < 0)
return 0;
if (!value)
return config_error_nonbool(var);
color_parse(value, var, clean_colors[slot]);
return 0;
}
if (!strcmp(var, "clean.requireforce")) {
force = !git_config_bool(var, value);
return 0;
}
/* inspect the color.ui config variable and others */
return git_color_default_config(var, value, cb);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
4ae5b93d68c44d5c4f9a9fbcb01c3f8459b2b053 | 2694b5757220afebf0a07cc2c14e487c81219654 | /450-DSA-Cracker/String/count-and-say.cpp | 8c760b8c4ff31c92c16bf56db01947ebdd7d06f6 | [] | no_license | sumitrathawani1810/Data-Structure-Algorithm | 64254e3116aad331b7e3019b5eebadf885bf9dc5 | 7ad452368e721c970f4b0ca9cde39d436bba2533 | refs/heads/main | 2023-08-31T20:26:23.648931 | 2021-10-23T04:07:39 | 2021-10-23T04:07:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,191 | cpp | #include<bits/stdc++.h>
using namespace std;
class Solution{
public:
string countAndSay(int n){
// We will check for 1 and 2 individually,
if(n==1)
return "1";
if(n==2)
return "11";
// Now for any entry greater than 2, we will :
string s="11";
for(int i =3;i<n;i++){
string t = "";
int c =1 ;
s = s + '&'; // This is a Delimiter
int len = s.length();
for(int j=1;j<len;j++)
{
if(s[j]!=s[j-1])
{
// If they're not equall,
// convert count to string n and add to t, n ewset count to 1
t=t+to_string(c);
t=t+s[j-1];
c=1;
}
else
// Count to see the number of characters aresmae
c++;
}
s=t;
}return s;
}
}asy;
int main(void)
{
int n;
cin >>n;
cout<<asy.countAndSay(n);
} | [
"iamlucif3r@localhost.localdomain"
] | iamlucif3r@localhost.localdomain |
dfb6247e47d201d3c3565423dbd3be55c844fb0c | cda270bdbce3f32e7e764acb8657466bb3a90044 | /src/data_types.cpp | 53b6021d74fcd4bf8d76d4666063511950a08688 | [] | no_license | make-j64/focus-stacking | 6e177d8bddc6729e07be035d01479601f275dc7d | d0e46e3904a3f4f0323adfea32c01bfd9aae394c | refs/heads/master | 2022-03-10T21:51:28.985736 | 2019-11-26T10:11:49 | 2019-11-26T10:11:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 150 | cpp | #include "data_types.h"
std::ostream& operator << (std::ostream& os, coordinate &c)
{
os << "(" << c.x << ", " << c.y << ")";
return os;
}
| [
"markosloizou@hotmail.com"
] | markosloizou@hotmail.com |
80e08b81a41f4c07118a85f3a3eca02143564dca | b794490c0e89db4a3a4daabe91b2f057a32878f0 | /Hook/Hook_Ring3/KeboardHook/KeboardHook.cpp | f3da580ad465121fa1c2f64a311fd1c5958d21d6 | [] | no_license | FusixGit/hf-2011 | 8ad747ee208183a194d0ce818f07d312899a44d2 | e0f1d9743238d75ea81f1c8d0a3ea1b5a2320a16 | refs/heads/master | 2021-01-10T17:31:14.137939 | 2012-11-05T12:43:24 | 2012-11-05T12:43:24 | 50,957,230 | 3 | 8 | null | null | null | null | GB18030 | C++ | false | false | 95 | cpp | // KeboardHook.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
| [
"hongfu830202@gmail.com"
] | hongfu830202@gmail.com |
9f953dc461d6c19379e00b4d9a19d6be83c45cb7 | 85d8b496ba390a8890c023f20ffa41e32cadc1b3 | /nekBone/setup.cpp | 2f565b2106a65c684ef71edced193d5ddcae3d2c | [
"BSD-3-Clause"
] | permissive | luspi/nekBench | 8570a25ec546381247b28f3edc440359f196913c | 7363779d6696aca1e786fe5671d6d7c350b5a180 | refs/heads/master | 2023-01-02T13:46:46.340135 | 2020-06-16T09:09:12 | 2020-06-16T09:09:12 | 273,134,966 | 0 | 0 | NOASSERTION | 2020-08-02T02:15:51 | 2020-06-18T03:42:45 | null | UTF-8 | C++ | false | false | 13,626 | cpp | /*
The MIT License (MIT)
Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <unistd.h>
#include "BP.hpp"
#include "../axhelm/kernelHelper.cpp"
void reportMemoryUsage(occa::device &device, const char *mess);
BP_t *setup(mesh_t *mesh, dfloat lambda1, occa::properties &kernelInfo, setupAide &options){
BP_t *BP = new BP_t();
BP->BPid = 5;
BP->Nfields = 1;
//options.getArgs("NUMBER OF FIELDS", BP->Nfields);
if(BP->Nfields > 1) BP->BPid = 6;
options.getArgs("MESH DIMENSION", BP->dim);
options.getArgs("ELEMENT TYPE", BP->elementType);
BP->mesh = mesh;
BP->options = options;
solveSetup(BP, lambda1, kernelInfo);
const dlong Ndof = mesh->Np*(mesh->Nelements+mesh->totalHaloPairs);
BP->fieldOffset = Ndof;
const dlong Nall = BP->Nfields*Ndof;
BP->r = (dfloat*) calloc(Nall, sizeof(dfloat));
BP->x = (dfloat*) calloc(Nall, sizeof(dfloat));
BP->q = (dfloat*) calloc(Nall, sizeof(dfloat));
// setup RHS
for(dlong e=0;e<mesh->Nelements;++e){
for(int n=0;n<mesh->Np;++n){
dfloat JW = mesh->ggeo[mesh->Np*(e*mesh->Nggeo + GWJID) + n];
dlong id = n+e*mesh->Np;
dfloat xn = mesh->x[id];
dfloat yn = mesh->y[id];
dfloat zn = mesh->z[id];
dfloat mode = 1;
for(int fld=0;fld<BP->Nfields;++fld){
dlong fldid = id + fld*Ndof;
// mass projection rhs
BP->r[fldid] =
(3.*M_PI*M_PI*mode*mode+lambda1)*JW*cos(mode*M_PI*xn)*cos(mode*M_PI*yn)*cos(mode*M_PI*zn);
BP->x[fldid] = 0;
}
}
}
BP->o_r = mesh->device.malloc(Nall*sizeof(dfloat), BP->r);
BP->o_x = mesh->device.malloc(Nall*sizeof(dfloat), BP->x);
BP->lambda = (dfloat*) calloc(2*Nall, sizeof(dfloat));
for(int i=0; i<BP->fieldOffset; i++) {
BP->lambda[i] = 1.0;
BP->lambda[i+BP->fieldOffset] = lambda1;
}
BP->o_lambda = mesh->device.malloc(2*Nall*sizeof(dfloat), BP->lambda);
char *suffix = strdup("Hex3D");
if(options.compareArgs("DISCRETIZATION","CONTINUOUS"))
ogsGatherScatterMany(BP->o_r, BP->Nfields, Ndof, ogsDfloat, ogsAdd, mesh->ogs);
if (mesh->rank==0)
reportMemoryUsage(mesh->device, "setup done");
return BP;
}
void solveSetup(BP_t *BP, dfloat lambda1, occa::properties &kernelInfo){
mesh_t *mesh = BP->mesh;
setupAide options = BP->options;
int knlId = 0;
options.getArgs("KERNEL ID", knlId);
BP->knlId = knlId;
dlong Ntotal = mesh->Np*mesh->Nelements;
dlong Nhalo = mesh->Np*mesh->totalHaloPairs;
dlong Nall = (Ntotal + Nhalo)*BP->Nfields;
dlong Nblock = mymax(1,(Ntotal+blockSize-1)/blockSize);
dlong Nblock2 = mymax(1,(Nblock+blockSize-1)/blockSize);
dlong NthreadsUpdatePCG = 256;
//dlong NblocksUpdatePCG = mymin((Ntotal+NthreadsUpdatePCG-1)/NthreadsUpdatePCG, 32);
dlong NblocksUpdatePCG = (Ntotal+NthreadsUpdatePCG-1)/NthreadsUpdatePCG;
BP->NthreadsUpdatePCG = NthreadsUpdatePCG;
BP->NblocksUpdatePCG = NblocksUpdatePCG;
BP->NsolveWorkspace = 4;
BP->offsetSolveWorkspace = Nall;
/*
const int PAGESIZE = 512; // in bytes
const int pageW = PAGESIZE/sizeof(dfloat);
if (BP->offsetSolveWorkspace%pageW) BP->offsetSolveWorkspace = (BP->offsetSolveWorkspace + 1)*pageW;
dfloat *scratch = (dfloat*) calloc(BP->offsetSolveWorkspace*BP->NsolveWorkspace, sizeof(dfloat));
occa::memory o_scratch = mesh->device.malloc(BP->offsetSolveWorkspace*BP->NsolveWorkspace*sizeof(dfloat), scratch);
*/
BP->o_solveWorkspace = new occa::memory[BP->NsolveWorkspace];
for(int wk=0;wk<BP->NsolveWorkspace;++wk) {
BP->o_solveWorkspace[wk] = mesh->device.malloc(Nall*sizeof(dfloat), BP->solveWorkspace);
//BP->o_solveWorkspace[wk] = o_scratch.slice(wk*BP->offsetSolveWorkspace*sizeof(dfloat));
}
if(options.compareArgs("PRECONDITIONER", "JACOBI")){
BP->o_invDiagA = mesh->device.malloc(Nall*sizeof(dfloat));
int *mapB = (int*) calloc(Nall, sizeof(int));
BP->o_mapB = mesh->device.malloc(Nall*sizeof(int), mapB);
free(mapB);
}
BP->tmp = (dfloat*) calloc(Nblock, sizeof(dfloat));
// BP->tmp2 = (dfloat*) calloc(Nblock2, sizeof(dfloat));
BP->o_tmp = mesh->device.malloc(Nblock*sizeof(dfloat), BP->tmp);
BP->o_tmp2 = mesh->device.malloc(Nblock2*sizeof(dfloat), BP->tmp);
BP->tmpNormr = (dfloat*) calloc(BP->NblocksUpdatePCG,sizeof(dfloat));
BP->o_tmpNormr = mesh->device.malloc(BP->NblocksUpdatePCG*sizeof(dfloat), BP->tmpNormr);
BP->tmpAtomic = (dfloat*) calloc(1,sizeof(dfloat));
BP->o_tmpAtomic = mesh->device.malloc(1*sizeof(dfloat), BP->tmpAtomic);
BP->o_zeroAtomic = mesh->device.malloc(1*sizeof(dfloat), BP->tmpAtomic);
//setup async halo stream
BP->defaultStream = mesh->defaultStream;
BP->dataStream = mesh->dataStream;
dlong Nbytes = BP->Nfields*mesh->totalHaloPairs*mesh->Np*sizeof(dfloat);
if(Nbytes>0){
BP->sendBuffer =
(dfloat*) occaHostMallocPinned(mesh->device, Nbytes, NULL, BP->o_sendBuffer, BP->h_sendBuffer);
BP->recvBuffer =
(dfloat*) occaHostMallocPinned(mesh->device, Nbytes, NULL, BP->o_recvBuffer, BP->h_recvBuffer);
}else{
BP->sendBuffer = NULL;
BP->recvBuffer = NULL;
}
mesh->device.setStream(BP->defaultStream);
BP->type = strdup(dfloatString);
BP->Nblock = Nblock;
BP->Nblock2 = Nblock2;
// count total number of elements
hlong NelementsLocal = mesh->Nelements;
hlong NelementsGlobal = 0;
MPI_Allreduce(&NelementsLocal, &NelementsGlobal, 1, MPI_HLONG, MPI_SUM, mesh->comm);
BP->NelementsGlobal = NelementsGlobal;
//check all the bounaries for a Dirichlet
bool allNeumann = (lambda1==0) ? true :false;
BP->allNeumannPenalty = 1.;
hlong localElements = (hlong) mesh->Nelements;
hlong totalElements = 0;
MPI_Allreduce(&localElements, &totalElements, 1, MPI_HLONG, MPI_SUM, mesh->comm);
BP->allNeumannScale = 1./sqrt((dfloat)mesh->Np*totalElements);
BP->EToB = (int *) calloc(mesh->Nelements*mesh->Nfaces,sizeof(int));
int lallNeumann, gallNeumann;
lallNeumann = allNeumann ? 0:1;
MPI_Allreduce(&lallNeumann, &gallNeumann, 1, MPI_INT, MPI_SUM, mesh->comm);
BP->allNeumann = (gallNeumann>0) ? false: true;
//printf("allNeumann = %d \n", BP->allNeumann);
//copy boundary flags
BP->o_EToB = mesh->device.malloc(mesh->Nelements*mesh->Nfaces*sizeof(int), BP->EToB);
//setup an unmasked gs handle
meshParallelGatherScatterSetup(mesh, Ntotal, mesh->globalIds, mesh->comm, 0);
//make a masked version of the global id numbering
mesh->maskedGlobalIds = (hlong *) calloc(Ntotal,sizeof(hlong));
memcpy(mesh->maskedGlobalIds, mesh->globalIds, Ntotal*sizeof(hlong));
//use the masked ids to make another gs handle
BP->ogs = ogsSetup(Ntotal, mesh->maskedGlobalIds, mesh->comm, 1, mesh->device);
BP->o_invDegree = BP->ogs->o_invDegree;
kernelInfo["defines/p_Nalign"] = USE_OCCA_MEM_BYTE_ALIGN;
kernelInfo["defines/" "p_blockSize"]= blockSize;
kernelInfo["defines/" "p_Nfields"]= BP->Nfields;
string threadModel;
options.getArgs("THREAD MODEL", threadModel);
string arch = "VOLTA";
options.getArgs("ARCH", arch);
int bpid = BP->BPid;
for (int r=0;r<2;r++){
if ((r==0 && mesh->rank==0) || (r==1 && mesh->rank>0)) {
mesh->addScalarKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl",
"addScalar",
kernelInfo);
mesh->maskKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl",
"mask",
kernelInfo);
mesh->sumKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl",
"sum",
kernelInfo);
BP->innerProductKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "innerProduct", kernelInfo);
BP->weightedNorm2Kernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "weightedNorm2", kernelInfo);
BP->weightedMultipleNorm2Kernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "weightedMultipleNorm2", kernelInfo);
BP->scaledAddKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "scaledAdd", kernelInfo);
BP->dotMultiplyKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "dotMultiply", kernelInfo);
BP->vecCopyKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "vecCopy", kernelInfo);
BP->vecInvKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "vecInv", kernelInfo);
BP->vecScaleKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "vecScale", kernelInfo);
BP->updateJacobiKernel =
mesh->device.buildKernel(DBP "/kernel/updateJacobi.okl", "updateJacobi", kernelInfo);
/*
BP->vecAtomicGatherKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "vecAtomicGather", kernelInfo);
BP->vecAtomicMultipleGatherKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "vecAtomicMultipleGather", kernelInfo);
BP->vecAtomicInnerProductKernel =
mesh->device.buildKernel(DBP "/kernel/utils.okl", "vecAtomicInnerProduct", kernelInfo);
*/
// add custom defines
kernelInfo["defines/" "p_NpTet"]= mesh->Np;
kernelInfo["defines/" "p_NpP"]= (mesh->Np+mesh->Nfp*mesh->Nfaces);
kernelInfo["defines/" "p_Nverts"]= mesh->Nverts;
int Nmax = mymax(mesh->Np, mesh->Nfaces*mesh->Nfp);
int maxNodes = mymax(mesh->Np, (mesh->Nfp*mesh->Nfaces));
int NblockV = mymax(1,maxNthreads/mesh->Np); // works for CUDA
int NnodesV = 1; //hard coded for now
int NblockS = mymax(1,maxNthreads/maxNodes); // works for CUDA
int NblockP = mymax(1,maxNthreads/(4*mesh->Np)); // get close to maxNthreads threads
int NblockG;
if(mesh->Np<=32) NblockG = ( 32/mesh->Np );
else NblockG = maxNthreads/mesh->Np;
kernelInfo["defines/" "p_Nmax"]= Nmax;
kernelInfo["defines/" "p_maxNodes"]= maxNodes;
kernelInfo["defines/" "p_NblockV"]= NblockV;
kernelInfo["defines/" "p_NnodesV"]= NnodesV;
kernelInfo["defines/" "p_NblockS"]= NblockS;
kernelInfo["defines/" "p_NblockP"]= NblockP;
kernelInfo["defines/" "p_NblockG"]= NblockG;
kernelInfo["defines/" "p_halfC"]= (int)((mesh->cubNq+1)/2);
kernelInfo["defines/" "p_halfN"]= (int)((mesh->Nq+1)/2);
kernelInfo["defines/" "p_NthreadsUpdatePCG"] = (int) NthreadsUpdatePCG; // WARNING SHOULD BE MULTIPLE OF 32
kernelInfo["defines/" "p_NwarpsUpdatePCG"] = (int) (NthreadsUpdatePCG/32); // WARNING: CUDA SPECIFIC
BP->BPKernel = (occa::kernel*) new occa::kernel[20];
int combineDot = 0;
combineDot = 0; //options.compareArgs("COMBINE DOT PRODUCT", "TRUE");
occa::properties props = kernelInfo;
if(strstr(threadModel.c_str(), "NATIVE")) props["okl/enabled"] = false;
string fileName = DBP "/kernel/" + arch + "/updatePCG.okl";
if(strstr(threadModel.c_str(), "NATIVE+SERIAL") || strstr(threadModel.c_str(), "NATIVE+OPENMP"))
fileName = "kernel/" + arch + "/updatePCG.c";
BP->updatePCGKernel =
mesh->device.buildKernel(fileName.c_str(), "BPUpdatePCG", props);
BP->updateMultiplePCGKernel =
mesh->device.buildKernel(fileName.c_str(), "BPMultipleUpdatePCG", props);
fileName = DBP "/kernel/utils.okl";
if(strstr(threadModel.c_str(), "NATIVE+SERIAL") || strstr(threadModel.c_str(), "NATIVE+OPENMP"))
fileName = "kernel/" + arch + "/weightedInnerProduct.c";
BP->weightedInnerProduct2Kernel =
mesh->device.buildKernel(fileName.c_str(), "weightedInnerProduct2", props);
BP->weightedMultipleInnerProduct2Kernel =
mesh->device.buildKernel(fileName.c_str(), "weightedMultipleInnerProduct2", props);
occa::kernel nothingKernel = mesh->device.buildKernel(DBP "/kernel/utils.okl", "nothingKernel", kernelInfo);
nothingKernel();
}
MPI_Barrier(mesh->comm);
}
string kernelName = "axhelm";
if(BP->Nfields > 1) kernelName += "_n" + std::to_string(BP->Nfields);
kernelName += "_v" + std::to_string(knlId);
BP->BPKernel[bpid] = loadAxKernel(mesh->device, threadModel, arch, kernelName, mesh->N, mesh->Nelements);
// WARNING C0 appropriate only
mesh->sumKernel(mesh->Nelements*mesh->Np, BP->o_invDegree, BP->o_tmp);
BP->o_tmp.copyTo(BP->tmp);
dfloat nullProjectWeightLocal = 0;
dfloat nullProjectWeightGlobal = 0;
for(dlong n=0;n<BP->Nblock;++n)
nullProjectWeightLocal += BP->tmp[n];
MPI_Allreduce(&nullProjectWeightLocal, &nullProjectWeightGlobal, 1, MPI_DFLOAT, MPI_SUM, mesh->comm);
BP->nullProjectWeightGlobal = 1./nullProjectWeightGlobal;
}
| [
"stefanke@gpu03.ftm.alcf.anl.gov"
] | stefanke@gpu03.ftm.alcf.anl.gov |
7eb155845bd7602ff96c60bfbf4e3f5a8af43255 | c5fb286e9adb0132f87ffecd0091f71a9907c197 | /ext/aip/src/lib/aptl/memory/BaseArena.h | c1e3125a2e0086761afeb9e5ca9973867ef2695f | [
"Apache-2.0"
] | permissive | sovaai/sova-engine | 2dc00ca554fd464cc2fd693c02c8de4acb4dcc5c | 783b04072bb243891bc332fcb0f61e938e456f4f | refs/heads/master | 2022-12-31T20:32:14.158432 | 2020-10-28T19:07:39 | 2020-10-28T19:07:39 | 289,885,115 | 50 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,581 | h | #ifndef _BASEARENA_H_
#define _BASEARENA_H_
#include <assert.h>
#include <stdlib.h>
#include <_include/cc_compat.h>
#include <_include/_string.h>
namespace Arena
{
struct DefaultPolicy
{
static const size_t defaultBlockSize = 8UL * 1024 * 1024;
};
template< typename MemberType >
struct BaseSetMember : public MemberType
{
BaseSetMember() : MemberType() { }
BaseSetMember *next;
BaseSetMember **pPrev;
};
template< typename Policy, typename MemberType >
class BaseSet
{
typedef typename Policy::StatusType StatusType;
public:
BaseSet() : first( 0 ) { }
StatusType initialize() { first = 0; return Policy::statusSuccess; }
StatusType add( MemberType &item )
{
item.next = first;
if ( !isEmpty() )
first->pPrev = &item.next;
first = &item;
item.pPrev = &first;
return Policy::statusSuccess;
}
MemberType *getFirst() { return first; }
MemberType *getNext( MemberType *item ) { return item->next; }
void remove( MemberType &item )
{
if ( item.next != 0 )
item.next->pPrev = item.pPrev;
*item.pPrev = item.next;
}
bool isEmpty() const { return first == 0; }
protected:
MemberType *first;
};
struct Block
{
volatile uint8_t *area;
};
template< typename Policy, typename BlockType, typename BlocksSetType >
class BaseAreaEngine
{
typedef typename Policy::StatusType StatusType;
public:
typedef BlockType AreaBlockType;
public:
BaseAreaEngine() : blockSize( Policy::defaultBlockSize ) { }
StatusType create( size_t blockSize, BlocksSetType &/* blocks */ )
{
this->blockSize = blockSize;
return Policy::statusSuccess;
}
bool notEnoughSpace( size_t offset, size_t amount ) { return offset + amount > blockSize; }
StatusType allocBlock( BlockType *&block )
{
size_t sizeToAlloc = ( blockSize + sizeof( BlockType ) + 0xF ) & ( ~(static_cast<size_t>( 0xF )) );
block = reinterpret_cast<BlockType *>( ::malloc( sizeToAlloc ) );
if ( unlikely(block == 0) )
return Policy::statusErrorAlloc;
block->area = reinterpret_cast<uint8_t *>( block ) + sizeToAlloc - blockSize;
return Policy::statusSuccess;
}
StatusType allocInBlock( BlockType *activeBlock, uint8_t *&area, size_t &offset, size_t amount )
{
area = (uint8_t *)( activeBlock->area ) + offset;
offset += amount;
return Policy::statusSuccess;
}
StatusType shrink( BlocksSetType &set, size_t &offset, uint8_t *area, size_t areaSize, size_t shrinkAreaSize )
{
if ( areaSize == shrinkAreaSize )
return Policy::statusSuccess;
if ( unlikely(set.isEmpty() || ( areaSize < shrinkAreaSize )) )
return Policy::statusErrorInvalidArg;
BlockType *activeBlock = set.getFirst();
if ( unlikely(( area + areaSize ) != ( activeBlock->area + offset )) )
return Policy::statusErrorInvalidArg;
offset -= ( areaSize - shrinkAreaSize );
return Policy::statusSuccess;
}
StatusType addBlockToSet( BlockType &block, BlocksSetType &set ) { return set.add( block ); }
StatusType destroyBlock( BlockType *block )
{
::free( block );
return Policy::statusSuccess;
}
StatusType freeBlock( BlockType *block, BlocksSetType &set )
{
set.remove( *block );
return destroyBlock( block, set );
}
StatusType rewind( size_t &offset )
{
offset = 0;
return Policy::statusSuccess;
}
static size_t allocationCostBytes() { return 0; }
protected:
size_t blockSize;
};
template< typename Policy, typename BlockType, typename BlocksSetType >
class BaseAreaEngineWithReuse : public BaseAreaEngine< Policy, BlockType, BlocksSetType >
{
typedef BaseAreaEngine< Policy, BlockType, BlocksSetType > Base;
typedef typename Policy::StatusType StatusType;
public:
BaseAreaEngineWithReuse() : Base(), freeBlocks() { }
~BaseAreaEngineWithReuse()
{
while ( !freeBlocks.isEmpty() )
{
BlockType *block = freeBlocks.getFirst();
freeBlocks.remove( *block );
Base::destroyBlock( block );
}
}
StatusType create( size_t blockSize, BlocksSetType &blocks )
{
StatusType status = Base::create( blockSize, blocks );
if ( unlikely(status != Policy::statusSuccess) )
return status;
return freeBlocks.initialize();
}
StatusType allocBlock( BlockType *&block )
{
if ( freeBlocks.isEmpty() )
return Base::allocBlock( block );
block = freeBlocks.getFirst();
freeBlocks.remove( *block );
return Policy::statusSuccess;
}
StatusType freeBlock( BlockType *block, BlocksSetType &set )
{
set.remove( *block );
return freeBlocks.add( *block );
}
protected:
BlocksSetType freeBlocks;
};
template< typename Policy, typename BlockType, typename BlocksSetType, typename AreaEngine >
class BaseArea : public AreaEngine
{
typedef typename Policy::StatusType StatusType;
public:
BaseArea() :
AreaEngine(),
blocks(),
offset( 0 )
{
}
~BaseArea()
{
while ( !blocks.isEmpty() )
{
BlockType *block = blocks.getFirst();
blocks.remove( *block );
AreaEngine::destroyBlock( block );
}
}
StatusType create( size_t blockSize )
{
StatusType status = AreaEngine::create( blockSize, blocks );
if ( unlikely(status != Policy::statusSuccess) )
return status;
offset = 0;
return blocks.initialize();
}
static size_t allocationCostBytes() { return AreaEngine::allocationCostBytes(); }
template< typename T >
StatusType alloc( T *&ptr, size_t amount = sizeof( T ) )
{
uint8_t *tmpArea;
StatusType status = allocGeneric( tmpArea, amount );
if ( unlikely(status != Policy::statusSuccess) )
return status;
ptr = reinterpret_cast<T *>( tmpArea );
return Policy::statusSuccess;
}
StatusType allocGeneric( uint8_t *&area, size_t amount )
{
if ( unlikely(amount > AreaEngine::blockSize) )
return Policy::statusErrorSmallBlock;
area = 0;
if ( blocks.isEmpty() || AreaEngine::notEnoughSpace( offset, amount ) )
{
BlockType *block;
StatusType status = AreaEngine::allocBlock( block );
if ( unlikely(status != Policy::statusSuccess) )
return status;
status = AreaEngine::addBlockToSet( *block, blocks );
if ( unlikely(status != Policy::statusSuccess) )
return status;
status = AreaEngine::rewind( offset );
if ( unlikely(status != Policy::statusSuccess) )
return status;
}
return AreaEngine::allocInBlock( blocks.getFirst(), area, offset, amount );
}
StatusType freeAll()
{
while ( !blocks.isEmpty() )
{
StatusType status = AreaEngine::freeBlock( blocks.getFirst(), blocks );
if ( unlikely(status != Policy::statusSuccess) )
return status;
}
return Policy::statusSuccess;
}
StatusType shrink( uint8_t *area, size_t areaSize, size_t shrinkAreaSize )
{
return AreaEngine::shrink( blocks, offset, area, areaSize, shrinkAreaSize );
}
StatusType rewind() { return AreaEngine::rewind( offset ); }
protected:
BlocksSetType blocks;
size_t offset;
};
template< typename Policy, typename AreaType, typename AreasSetType >
class BaseArenaEngine
{
typedef typename Policy::StatusType StatusType;
public:
StatusType create() { return Policy::statusSuccess; }
StatusType allocArea( AreaType *&area )
{
area = new AreaType;
if ( unlikely(area == 0) )
return Policy::statusErrorAlloc;
return Policy::statusSuccess;
}
StatusType freeArea( AreaType *area )
{
delete area;
return Policy::statusSuccess;
}
};
template< typename Policy, typename AreaType, typename AreasSetType, typename ArenaEngine >
class BaseArena : public ArenaEngine
{
typedef typename Policy::StatusType StatusType;
public:
typedef AreaType Area;
public:
BaseArena() :
ArenaEngine(),
areas(),
isCreated( false )
{
}
~BaseArena()
{
while ( !areas.isEmpty() )
{
Area *area = areas.getFirst();
areas.remove( *area );
ArenaEngine::freeArea( area );
}
}
StatusType create()
{
if ( unlikely(isCreated) )
return Policy::statusErrorAlreadyCreated;
StatusType status = areas.initialize();
if ( unlikely(status != Policy::statusSuccess) )
return status;
status = ArenaEngine::create();
if ( unlikely(status != Policy::statusSuccess) )
return status;
isCreated = true;
return Policy::statusSuccess;
}
StatusType makeArea( Area *&area, size_t blockSize = Policy::defaultBlockSize )
{
if ( unlikely(!isCreated) )
return Policy::statusErrorNotCreated;
StatusType status = ArenaEngine::allocArea( area );
if ( unlikely(status != Policy::statusSuccess) )
return status;
status = area->create( blockSize );
if ( unlikely(status != Policy::statusSuccess) )
{
ArenaEngine::freeArea( area );
return status;
}
status = areas.add( *area );
if ( unlikely(status != Policy::statusSuccess) )
{
ArenaEngine::freeArea( area );
return status;
}
return Policy::statusSuccess;
}
protected:
AreasSetType areas;
bool isCreated;
};
}
#endif /* _BASEARENA_H_ */
| [
"fedor.zorky@gmail.com"
] | fedor.zorky@gmail.com |
a68c239156ad1cd518b926b9a23b210b8310e418 | 6bcd0eb0cf8a2ecf4fb60f1a354424ad3e8ce5e7 | /DeviceEnumeration/cpp/BackgroundDeviceWatcherTaskCpp/BackgroundDeviceWatcherTaskCpp.h | d2a78cd21f10e7bdbc54c24b56ab108f0873a12a | [
"MIT"
] | permissive | mhdubose/Windows-universal-samples | 8e0fa492ca624b96f60a28913753066eac8e09f4 | 7c3abf2bc631dccdd19c1a55fc16109c3d3e78d5 | refs/heads/master | 2021-01-14T12:35:20.616148 | 2015-08-27T23:11:19 | 2015-08-27T23:15:06 | 38,263,630 | 0 | 0 | null | 2015-06-29T18:27:38 | 2015-06-29T18:27:37 | null | UTF-8 | C++ | false | false | 409 | h | // Copyright (c) Microsoft Corporation. All rights reserved.
#pragma once
using namespace Windows::ApplicationModel::Background;
namespace BackgroundDeviceWatcherTaskCpp
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class BackgroundDeviceWatcher sealed : public IBackgroundTask
{
public:
BackgroundDeviceWatcher() {}
virtual void Run(IBackgroundTaskInstance^ taskInstance);
};
}
| [
"IrinVoso@users.noreply.github.com"
] | IrinVoso@users.noreply.github.com |
998f09f75e090e68113e7c20f007c1f8c7be75da | 49b05e95d9003b7f1f4f66620c3e051a27648d91 | /Applications/Terminal/Terminal.h | 82d13a546f8d70bff9c4f449119dfd16727b8972 | [
"BSD-2-Clause"
] | permissive | ygorko/serenity | 8f1d25b8d48465c9353c585b64e4e089c3434bbf | ccc6e69a294edacf7bec77cb2c2640ada7fe1f77 | refs/heads/master | 2020-05-31T03:40:53.063797 | 2019-06-03T17:52:31 | 2019-06-03T19:17:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,652 | h | #pragma once
#include <AK/AKString.h>
#include <AK/Types.h>
#include <AK/Vector.h>
#include <LibCore/CConfigFile.h>
#include <LibCore/CNotifier.h>
#include <LibCore/CTimer.h>
#include <LibGUI/GFrame.h>
#include <SharedGraphics/GraphicsBitmap.h>
#include <SharedGraphics/Rect.h>
class Font;
class Terminal final : public GFrame {
public:
explicit Terminal(int ptm_fd, RetainPtr<CConfigFile> config);
virtual ~Terminal() override;
void create_window();
void on_char(byte);
void flush_dirty_lines();
void force_repaint();
void apply_size_increments_to_window(GWindow&);
void set_opacity(float);
float opacity() { return m_opacity; };
bool should_beep() { return m_should_beep; }
void set_should_beep(bool sb) { m_should_beep = sb; };
RetainPtr<CConfigFile> config() const { return m_config; }
private:
typedef Vector<unsigned, 4> ParamVector;
virtual void event(CEvent&) override;
virtual void paint_event(GPaintEvent&) override;
virtual void resize_event(GResizeEvent&) override;
virtual void keydown_event(GKeyEvent&) override;
virtual const char* class_name() const override { return "Terminal"; }
void scroll_up();
void scroll_down();
void newline();
void set_cursor(unsigned row, unsigned column);
void put_character_at(unsigned row, unsigned column, byte ch);
void invalidate_cursor();
void set_window_title(const String&);
void inject_string(const String&);
void unimplemented_escape();
void unimplemented_xterm_escape();
void escape$A(const ParamVector&);
void escape$B(const ParamVector&);
void escape$C(const ParamVector&);
void escape$D(const ParamVector&);
void escape$H(const ParamVector&);
void escape$J(const ParamVector&);
void escape$K(const ParamVector&);
void escape$M(const ParamVector&);
void escape$G(const ParamVector&);
void escape$X(const ParamVector&);
void escape$d(const ParamVector&);
void escape$m(const ParamVector&);
void escape$s(const ParamVector&);
void escape$u(const ParamVector&);
void escape$t(const ParamVector&);
void escape$r(const ParamVector&);
void escape$S(const ParamVector&);
void escape$T(const ParamVector&);
void escape$L(const ParamVector&);
void escape$h_l(bool, bool, const ParamVector&);
void clear();
void set_size(word columns, word rows);
word columns() const { return m_columns; }
word rows() const { return m_rows; }
Rect glyph_rect(word row, word column);
Rect row_rect(word row);
void update_cursor();
struct Attribute {
Attribute() { reset(); }
static byte default_foreground_color;
static byte default_background_color;
void reset()
{
foreground_color = default_foreground_color;
background_color = default_background_color;
flags = Flags::NoAttributes;
}
byte foreground_color;
byte background_color;
enum Flags
{
NoAttributes = 0x00,
Bold = 0x01,
Italic = 0x02,
Underline = 0x04,
Negative = 0x08,
Blink = 0x10,
};
// TODO: it would be really nice if we had a helper for enums that
// exposed bit ops for class enums...
int flags = Flags::NoAttributes;
bool operator==(const Attribute& other) const
{
return foreground_color == other.foreground_color && background_color == other.background_color && flags == other.flags;
}
bool operator!=(const Attribute& other) const
{
return !(*this == other);
}
};
struct Line {
explicit Line(word columns);
~Line();
void clear(Attribute);
bool has_only_one_background_color() const;
byte* characters { nullptr };
Attribute* attributes { nullptr };
bool dirty { false };
word length { 0 };
};
Line& line(size_t index)
{
ASSERT(index < m_rows);
return *m_lines[index];
}
Vector<OwnPtr<Line>> m_lines;
int m_scroll_region_top { 0 };
int m_scroll_region_bottom { 0 };
word m_columns { 0 };
word m_rows { 0 };
byte m_cursor_row { 0 };
byte m_cursor_column { 0 };
byte m_saved_cursor_row { 0 };
byte m_saved_cursor_column { 0 };
bool m_stomp { false };
bool m_should_beep { false };
Attribute m_current_attribute;
void execute_escape_sequence(byte final);
void execute_xterm_command();
enum EscapeState
{
Normal,
ExpectBracket,
ExpectParameter,
ExpectIntermediate,
ExpectFinal,
ExpectXtermParameter1,
ExpectXtermParameter2,
ExpectXtermFinal,
};
EscapeState m_escape_state { Normal };
Vector<byte> m_parameters;
Vector<byte> m_intermediates;
Vector<byte> m_xterm_param1;
Vector<byte> m_xterm_param2;
byte m_final { 0 };
byte* m_horizontal_tabs { nullptr };
bool m_belling { false };
int m_pixel_width { 0 };
int m_pixel_height { 0 };
int m_inset { 2 };
int m_line_spacing { 4 };
int m_line_height { 0 };
int m_ptm_fd { -1 };
bool m_swallow_current { false };
bool m_in_active_window { false };
bool m_need_full_flush { false };
CNotifier m_notifier;
float m_opacity { 1 };
bool m_needs_background_fill { true };
bool m_cursor_blink_state { true };
int m_glyph_width { 0 };
CTimer m_cursor_blink_timer;
CTimer m_visual_beep_timer;
RetainPtr<CConfigFile> m_config;
};
| [
"awesomekling@gmail.com"
] | awesomekling@gmail.com |
03132ecf0ea8c074928ddfedc34853f11d17826a | 78f38f9968e1b8d31e1969c26f7b5588118ec085 | /AdventOfCode2016/AdventOfCode2016/AOC_23/AOC_23.cpp | a8b83bbd30f30b0221369c1001ff09dc502c6529 | [] | no_license | RTwTools/AdventOfCode | dfb5368b9dc08a59f225f0707f39ea66cb4515de | 9f8bb65e2e973cc664995781d6d409c158c6c655 | refs/heads/master | 2020-06-12T22:13:36.175924 | 2018-12-23T18:50:09 | 2018-12-23T18:50:09 | 75,435,362 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,617 | cpp | #include "AOC_23.h"
AOC_23::AOC_23(std::string fileName) :
passReg(4, 0),
line(0)
{
//open input file
std::string input = readFile(fileName);
if (input == "") return;
//split string at '\n', split commands at ' '
std::vector<std::string> lines = splitString(input, '\n');
for (int i = 0; i < (int)lines.size(); i++)
commands.push_back(splitString(lines[i], ' '));
//execute commands
passReg[0] = 7;
for (;;)
{
if (line >= (int)commands.size()) break;
line += executeCommand(commands[line]);
}
std::cout << "--- Challenge 23 A ---" << std::endl;
std::cout << "The value in reg A is [" << passReg[0] << "]." << std::endl;
//reset all values for part B
passReg[1] = passReg[2] = passReg[3] = line = 0;
passReg[0] = 12;
//re-read commands because the new command 'tgl' changes the initial values
commands.clear();
for (int i = 0; i < (int)lines.size(); i++)
commands.push_back(splitString(lines[i], ' '));
for (;;)
{
if (line >= (int)commands.size()) break;
line += executeCommand(commands[line]);
}
std::cout << "--- Challenge 23 B ---" << std::endl;
std::cout << "The value in reg A is [" << passReg[0] << "]." << std::endl;
std::cout << std::endl;
}
int AOC_23::executeCommand(std::vector<std::string> command)
{
//optimization for my specific input
if (line == 4)
{
passReg[0] = passReg[1] * passReg[3];
passReg[2] = passReg[3] = 0;
line = 10;
return 0;
}
if (command[0] == "cpy")
{
if (isRegister(command[2]))
passReg[getRegIndex(command[2])] = getValue(command[1]);
}
else if (command[0] == "inc")
passReg[getRegIndex(command[1])] += 1;
else if (command[0] == "dec")
passReg[getRegIndex(command[1])] -= 1;
else if (command[0] == "jnz")
{
int value = getValue(command[1]);
if (value != 0)
return (getValue(command[2]));
}
else if (command[0] == "tgl")
{
int commandID = getValue(command[1]) + line;
if (commandID >= 0 && commandID < (int)commands.size())
{
if (commands[commandID].size() == ONE_ARGUMENT)
commands[commandID][0] = (commands[commandID][0] == "inc") ? "dec" : "inc";
else if (commands[commandID].size() == TWO_ARGUMENTS)
commands[commandID][0] = (commands[commandID][0] == "jnz") ? "cpy" : "jnz";
}
}
else
std::cout << "invalid command: [" << command[0] << "]." << std::endl;
return 1;
}
int AOC_23::getValue(std::string str)
{
if (isRegister(str))
return passReg[getRegIndex(str)];
else
return std::stoi(str);
}
bool AOC_23::isRegister(std::string str)
{
return (str[0] >= 'a' && str[0] <= 'd');
}
int AOC_23::getRegIndex(std::string reg)
{
return (int)reg[0] - (int)'a';
} | [
"JeroenJacobs@Outlook.com"
] | JeroenJacobs@Outlook.com |
62a79fc795b079f4d7ff06235ddc99dcd0b42430 | b28305dab0be0e03765c62b97bcd7f49a4f8073d | /ash/wallpaper/wallpaper_widget_controller.cc | 809500b80b531cd952e9dd2552a2039a139b46f8 | [
"BSD-3-Clause"
] | permissive | svarvel/browser-android-tabs | 9e5e27e0a6e302a12fe784ca06123e5ce090ced5 | bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f | refs/heads/base-72.0.3626.105 | 2020-04-24T12:16:31.442851 | 2019-08-02T19:15:36 | 2019-08-02T19:15:36 | 171,950,555 | 1 | 2 | NOASSERTION | 2019-08-02T19:15:37 | 2019-02-21T21:47:44 | null | UTF-8 | C++ | false | false | 8,191 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/wallpaper/wallpaper_widget_controller.h"
#include <utility>
#include "ash/ash_export.h"
#include "ash/root_window_controller.h"
#include "ash/shell.h"
#include "ash/wallpaper/wallpaper_controller.h"
#include "base/scoped_observer.h"
#include "ui/aura/window.h"
#include "ui/aura/window_observer.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
namespace ash {
// Observes a wallpaper widget state, and notifies WallpaperWidgetController
// about relevant widget changes:
// * when widget is being destroyed
// * when the widgets implicit animations finish.
// Additionally, provides methods to manage wallpaper widget state - e.g. to
// show widget, reparent widget, or change the widget blur.
class WallpaperWidgetController::WidgetHandler
: public ui::ImplicitAnimationObserver,
public views::WidgetObserver,
public aura::WindowObserver {
public:
WidgetHandler(WallpaperWidgetController* controller, views::Widget* widget)
: controller_(controller),
widget_(widget),
parent_window_(widget->GetNativeWindow()->parent()),
widget_observer_(this),
window_observer_(this) {
DCHECK(controller_);
DCHECK(widget_);
widget_observer_.Add(widget_);
window_observer_.Add(parent_window_);
}
~WidgetHandler() override { Reset(true /*close*/); }
views::Widget* widget() { return widget_; }
// ui::ImplicitAnimationObserver:
void OnImplicitAnimationsCompleted() override {
observing_implicit_animations_ = false;
StopObservingImplicitAnimations();
controller_->WidgetFinishedAnimating(this);
}
// views::WidgetObserver:
void OnWidgetDestroying(views::Widget* widget) override {
Reset(false /*close*/);
// NOTE: Do not use |this| past this point - |controller_| will delete this
// instance.
controller_->WidgetHandlerReset(this);
}
// aura::WindowObserver:
void OnWindowBoundsChanged(aura::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds,
ui::PropertyChangeReason reason) override {
widget_->SetBounds(new_bounds);
}
void Show() {
ui::ScopedLayerAnimationSettings settings(
widget_->GetLayer()->GetAnimator());
observing_implicit_animations_ = true;
settings.AddObserver(this);
// When |widget_| shows, AnimateShowWindowCommon() is called to do the
// animation. Sets transition duration to 0 to avoid animating to the
// show animation's initial values.
settings.SetTransitionDuration(base::TimeDelta());
widget_->Show();
}
bool Reparent(aura::Window* new_parent) {
if (parent_window_ == new_parent)
return false;
window_observer_.Remove(parent_window_);
if (has_blur_cache_)
parent_window_->layer()->RemoveCacheRenderSurfaceRequest();
new_parent->AddChild(widget_->GetNativeWindow());
parent_window_ = widget_->GetNativeWindow()->parent();
window_observer_.Add(parent_window_);
has_blur_cache_ = widget_->GetLayer()->layer_blur() > 0.0f;
if (has_blur_cache_)
parent_window_->layer()->AddCacheRenderSurfaceRequest();
return true;
}
void SetBlur(float blur_sigma) {
widget_->GetLayer()->SetLayerBlur(blur_sigma);
const bool old_has_blur_cache = has_blur_cache_;
has_blur_cache_ = blur_sigma > 0.0f;
if (!old_has_blur_cache && has_blur_cache_) {
parent_window_->layer()->AddCacheRenderSurfaceRequest();
} else if (old_has_blur_cache && !has_blur_cache_) {
parent_window_->layer()->RemoveCacheRenderSurfaceRequest();
}
}
void StopAnimating() { widget_->GetLayer()->GetAnimator()->StopAnimating(); }
private:
void Reset(bool close) {
if (reset_)
return;
reset_ = true;
window_observer_.RemoveAll();
widget_observer_.RemoveAll();
if (observing_implicit_animations_) {
observing_implicit_animations_ = false;
StopObservingImplicitAnimations();
}
if (has_blur_cache_)
parent_window_->layer()->RemoveCacheRenderSurfaceRequest();
parent_window_ = nullptr;
if (close)
widget_->CloseNow();
widget_ = nullptr;
}
WallpaperWidgetController* controller_;
views::Widget* widget_;
aura::Window* parent_window_;
bool reset_ = false;
bool has_blur_cache_ = false;
bool observing_implicit_animations_ = false;
ScopedObserver<views::Widget, WidgetHandler> widget_observer_;
ScopedObserver<aura::Window, WidgetHandler> window_observer_;
DISALLOW_COPY_AND_ASSIGN(WidgetHandler);
};
WallpaperWidgetController::WallpaperWidgetController(
base::OnceClosure wallpaper_set_callback)
: wallpaper_set_callback_(std::move(wallpaper_set_callback)) {}
WallpaperWidgetController::~WallpaperWidgetController() = default;
views::Widget* WallpaperWidgetController::GetWidget() {
if (!active_widget_)
return nullptr;
return active_widget_->widget();
}
views::Widget* WallpaperWidgetController::GetAnimatingWidget() {
if (!animating_widget_)
return nullptr;
return animating_widget_->widget();
}
bool WallpaperWidgetController::IsAnimating() const {
return animating_widget_.get();
}
void WallpaperWidgetController::EndPendingAnimation() {
if (!IsAnimating())
return;
animating_widget_->StopAnimating();
}
void WallpaperWidgetController::AddAnimationEndCallback(
base::OnceClosure callback) {
animation_end_callbacks_.emplace_back(std::move(callback));
}
void WallpaperWidgetController::SetWallpaperWidget(views::Widget* widget,
float blur_sigma) {
DCHECK(widget);
// If there is a widget currently being shown, finish the animation and set it
// as the primary widget, before starting transition to the new wallpaper.
if (animating_widget_) {
SetAnimatingWidgetAsActive();
active_widget_->StopAnimating();
}
animating_widget_ = std::make_unique<WidgetHandler>(this, widget);
animating_widget_->SetBlur(blur_sigma);
animating_widget_->Show();
}
bool WallpaperWidgetController::Reparent(aura::Window* root_window,
int container) {
aura::Window* new_parent = root_window->GetChildById(container);
bool moved_widget = active_widget_ && active_widget_->Reparent(new_parent);
bool moved_animating_widget =
animating_widget_ && animating_widget_->Reparent(new_parent);
return moved_widget || moved_animating_widget;
}
void WallpaperWidgetController::SetWallpaperBlur(float blur_sigma) {
if (animating_widget_)
animating_widget_->SetBlur(blur_sigma);
if (active_widget_)
active_widget_->SetBlur(blur_sigma);
}
void WallpaperWidgetController::ResetWidgetsForTesting() {
animating_widget_.reset();
active_widget_.reset();
}
void WallpaperWidgetController::WidgetHandlerReset(WidgetHandler* widget) {
if (widget == active_widget_.get()) {
SetAnimatingWidgetAsActive();
if (active_widget_)
active_widget_->StopAnimating();
} else if (widget == animating_widget_.get()) {
animating_widget_.reset();
}
}
void WallpaperWidgetController::WidgetFinishedAnimating(WidgetHandler* widget) {
if (widget != animating_widget_.get())
return;
SetAnimatingWidgetAsActive();
}
void WallpaperWidgetController::SetAnimatingWidgetAsActive() {
active_widget_ = std::move(animating_widget_);
if (!active_widget_)
return;
if (wallpaper_set_callback_)
std::move(wallpaper_set_callback_).Run();
// Notify observers that animation finished.
RunAnimationEndCallbacks();
Shell::Get()->wallpaper_controller()->OnWallpaperAnimationFinished();
}
void WallpaperWidgetController::RunAnimationEndCallbacks() {
std::list<base::OnceClosure> callbacks;
animation_end_callbacks_.swap(callbacks);
for (auto& callback : callbacks)
std::move(callback).Run();
}
} // namespace ash
| [
"artem@brave.com"
] | artem@brave.com |
282cb6bc3252bcbb409f65049f47506d495e82c5 | e08b2ee4b3c34fc9ef03fbdda7fffa8ec9ef1077 | /sim/program.h | bf74e989853f3021577814c5e71db46f7bd2f7bf | [] | no_license | trnila/ledcube | d1c04f80629e51474f44f9b6a7c3f49ee250fafd | 3dd814b2ac0cec53c8656cc33416a6d3bbbda1a7 | refs/heads/master | 2020-03-22T16:31:27.790283 | 2018-07-09T19:23:20 | 2018-07-09T19:23:20 | 140,332,313 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | h | #pragma once
#include <glm/glm.hpp>
class Program {
public:
Program(const char *vertex, const char *fragment);
void setUniform(const char *attr, glm::mat4 coord);
void setUniform(const char *attr, glm::vec3 vec);
void activate();
void configureCoord();
private:
GLuint program;
GLint getUniformHandle(const char *attribute_name);
GLint getAttributeHandle(const char *attribute_name);
GLuint createShader(const char *filename, GLenum type);
};
| [
"daniel.trnka@gmail.com"
] | daniel.trnka@gmail.com |
fdff192bbe4c7dda9e0d42dfeeef939d4304a3d1 | 52896a1d66e157f966105bee46cf8a7e48c26df2 | /src/renderer.h | 41718bdb6c8da498e335cb7fba120b9f1f8826b8 | [] | no_license | AntonHakansson/c_physics | 9b86027263a1d3c2900806069308e7ecc5ca4c5b | fc8a71f7ba04287c9f69010af633ecfc1a995602 | refs/heads/main | 2023-08-19T10:08:41.625908 | 2021-09-23T16:34:48 | 2021-09-23T16:40:52 | 349,856,320 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,122 | h | #pragma once
#include <raylib.h>
#include "language_layer.h"
constexpr u32 MAX_DRAW_CALLS = 1024;
enum RENDER_COMMAND_TYPE {
FILLED_RECT,
SCALED_TEX_RECT,
CIRCLE,
LINE,
TEXT,
MAX_RENDER_COMMANDS,
};
struct RenderCommand {
RENDER_COMMAND_TYPE type;
u8 flags;
union {
// NOTE(anton) : render command RECT
struct {
v2 pos;
v2 size;
Color c;
f32 angle;
} rect;
// NOTE(anton) : render command RECT
struct {
v2 pos;
v2 size;
Texture2D texture;
Color tint;
f32 angle;
} texture;
// NOTE(anton) : render command CIRCLE
struct {
v2 pos;
f32 radius;
Color c;
} circle;
// NOTE(anton) : render command LINE
struct {
v2 start_pos;
v2 end_pos;
Color c;
} line;
// NOTE(anton) : render command TEXT
struct {
v2 pos;
Color c;
f32 font_scale;
const char *text;
} text;
};
};
struct Renderer {
RenderCommand render_commands[MAX_DRAW_CALLS];
u32 render_commands_count;
Camera2D world_camera;
u32 left, right, top, bottom;
};
| [
"anton.hakansson98@gmail.com"
] | anton.hakansson98@gmail.com |
cc140bfb72092d443e89dcb5eda7761848b64fce | 2b45998c5472e30ea7058603bca3a77700b86b70 | /실패작 개똥벌레.cpp | e563801434de367dbf8c850235ef3f149f04619e | [] | no_license | forybm/CodeMountain | c6b5e404bc5947f2a41df76331bb1ba078dcbe41 | 7a3c8bc76db7f57ad68638f800513d0ea0a7c5a2 | refs/heads/master | 2021-06-21T15:05:30.653346 | 2017-07-27T06:03:55 | 2017-07-27T06:03:55 | 98,499,311 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 788 | cpp | #include <stdio.h>
#include <algorithm>
using namespace std;
int H[500000]={0};
int main()
{
int length,high; //동굴의 길이, 동굴의 높이
int n[200000]; //종유석 갯
scanf("%d%d",&length,&high);
for(int i=1;i<=length;i++)
{
scanf("%d",&n[i]);
}
for(int i=1;i<=length;i++)
{
if(i%2==0) //짝수번째 종유석은 위세어 아래로
{
for(int j=high;j>=1;j--)
{
H[j]++;
n[i]--;
if(n[i]==0) break;
}
}
else if(i%2==1) //홀수번째 종유석은 아래에서 위
{
for(int j=1;j<=high;j++)
{
H[j]++;
n[i]--;
if(n[i]==0) break;
}
}
}
int count=0;
sort(H+1,H+high+1);
for(int i=1;i<=high;i++)
{
if(H[1]==H[i]) count++;
else if(H[i]>H[1]) break;
}
printf("%d %d",H[1],count);
}
| [
"forybm1@naver.com"
] | forybm1@naver.com |
7bbf92a4274078f823e2d125ce8cb7ce20f510bf | 4882847af716e5342f437569970795fe1fc9a853 | /Code/MUD/Implementations/mud/Game/Areas/Room.hpp | a3f558a1bd16a783961c3c5342a60dc91ec37cc6 | [] | no_license | Aslai/MUD | 059a40976cbd501265a5097e08a70ec8773bab01 | 86b3828fe343ee787f799d59b1d9f6ad2226a614 | refs/heads/master | 2020-06-06T15:46:33.822555 | 2014-10-13T02:06:07 | 2014-10-13T02:06:07 | 18,485,230 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | hpp | //Be sure that Realm is defined in the case of a circular reference
#ifndef MUD_GAME_AREAS_ROOM_DEFINED
#define MUD_GAME_AREAS_ROOM_DEFINED
namespace MUD{
namespace Game{
class Room;
}
}
#endif // MUD_GAME_AREAS_REALM_DEFINED
#ifndef MUD_GAME_AREAS_ROOM_HPP
#define MUD_GAME_AREAS_ROOM_HPP
#include "Game/Areas/Zone.hpp"
#include "Game/Areas/Room.hpp"
#include "Lua/Lua.hpp"
#include "Game/Actors/Actor.hpp"
#include "Memory/RefCounter.hpp"
namespace MUD{
namespace Game{
class Room{
Zone& MyZone;
Lua::Value Properties;
std::string id;
std::vector<RefCounter<Actor>> Actors;
Lua::Script RoomScript;
public:
enum class Exit{
North = 0,
East,
South,
West,
Up,
Down,
NotAnExit
};
static Room& GetRoomByID( std::string RealmID, std::string ZoneID, std::string RoomID );
};
}
}
#endif
| [
"kaslai@kaslai.com"
] | kaslai@kaslai.com |
fe20a07562f747220d02cd166472b964841d9ab1 | 33b567f6828bbb06c22a6fdf903448bbe3b78a4f | /opencascade/TColgp_HArray1OfPnt2d.hxx | ff851b63fc00c2db908b1562e14bede163b46782 | [
"Apache-2.0"
] | permissive | CadQuery/OCP | fbee9663df7ae2c948af66a650808079575112b5 | b5cb181491c9900a40de86368006c73f169c0340 | refs/heads/master | 2023-07-10T18:35:44.225848 | 2023-06-12T18:09:07 | 2023-06-12T18:09:07 | 228,692,262 | 64 | 28 | Apache-2.0 | 2023-09-11T12:40:09 | 2019-12-17T20:02:11 | C++ | UTF-8 | C++ | false | false | 997 | hxx | // Created on: 1993-03-10
// Created by: Philippe DAUTRY
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef TColgp_HArray1OfPnt2d_HeaderFile
#define TColgp_HArray1OfPnt2d_HeaderFile
#include <gp_Pnt2d.hxx>
#include <TColgp_Array1OfPnt2d.hxx>
#include <NCollection_DefineHArray1.hxx>
DEFINE_HARRAY1(TColgp_HArray1OfPnt2d, TColgp_Array1OfPnt2d)
#endif
| [
"adam.jan.urbanczyk@gmail.com"
] | adam.jan.urbanczyk@gmail.com |
8819e6252b12de94972dc95f5c918bfe01856186 | 37bd9a94cddce57c8699a1ddc037b531c82eaa51 | /src/wallet/message_store.cpp | d0ca8dca8d31db5a31844257d3d718927f6e3cb3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | Vireonidae/vireo | 607366c8f97c6878bc72721e79a04601e50b80fb | 750e16bf5c242b864acb7b37b8c10652929e5f3f | refs/heads/master | 2022-11-12T10:24:09.275176 | 2020-06-29T22:13:28 | 2020-06-29T22:38:26 | 271,019,442 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 51,319 | cpp | // Copyright (c) 2018, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 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 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 "message_store.h"
#include <boost/archive/portable_binary_oarchive.hpp>
#include <boost/archive/portable_binary_iarchive.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <sstream>
#include "file_io_utils.h"
#include "storages/http_abstract_invoke.h"
#include "wallet_errors.h"
#include "serialization/binary_utils.h"
#include "common/base58.h"
#include "common/util.h"
#include "string_tools.h"
#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "wallet.mms"
namespace mms
{
message_store::message_store(std::unique_ptr<epee::net_utils::http::abstract_http_client> http_client) : m_transporter(std::move(http_client))
{
m_active = false;
m_auto_send = false;
m_next_message_id = 1;
m_num_authorized_signers = 0;
m_num_required_signers = 0;
m_nettype = cryptonote::network_type::UNDEFINED;
m_run = true;
}
namespace
{
// MMS options handling mirrors what "wallet2" is doing for its options, on-demand init and all
// It's not very clean to initialize Bitmessage-specific options here, but going one level further
// down still into "message_transporter" for that is a little bit too much
struct options
{
const command_line::arg_descriptor<std::string> bitmessage_address = {"bitmessage-address", mms::message_store::tr("Use PyBitmessage instance at URL <arg>"), "http://localhost:8442/"};
const command_line::arg_descriptor<std::string> bitmessage_login = {"bitmessage-login", mms::message_store::tr("Specify <arg> as username:password for PyBitmessage API"), "username:password"};
};
}
void message_store::init_options(boost::program_options::options_description& desc_params)
{
const options opts{};
command_line::add_arg(desc_params, opts.bitmessage_address);
command_line::add_arg(desc_params, opts.bitmessage_login);
}
void message_store::init(const multisig_wallet_state &state, const std::string &own_label,
const std::string &own_transport_address, uint32_t num_authorized_signers, uint32_t num_required_signers)
{
m_num_authorized_signers = num_authorized_signers;
m_num_required_signers = num_required_signers;
m_signers.clear();
m_messages.clear();
m_next_message_id = 1;
// The vector "m_signers" gets here once the required number of elements, one for each authorized signer,
// and is never changed again. The rest of the code relies on "size(m_signers) == m_num_authorized_signers"
// without further checks.
authorized_signer signer;
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
signer.me = signer.index == 0; // Strict convention: The very first signer is fixed as / must be "me"
m_signers.push_back(signer);
signer.index++;
}
set_signer(state, 0, own_label, own_transport_address, state.address);
m_nettype = state.nettype;
set_active(true);
m_filename = state.mms_file;
save(state);
}
void message_store::set_options(const boost::program_options::variables_map& vm)
{
const options opts{};
std::string bitmessage_address = command_line::get_arg(vm, opts.bitmessage_address);
epee::wipeable_string bitmessage_login = command_line::get_arg(vm, opts.bitmessage_login);
set_options(bitmessage_address, bitmessage_login);
}
void message_store::set_options(const std::string &bitmessage_address, const epee::wipeable_string &bitmessage_login)
{
m_transporter.set_options(bitmessage_address, bitmessage_login);
}
void message_store::set_signer(const multisig_wallet_state &state,
uint32_t index,
const boost::optional<std::string> &label,
const boost::optional<std::string> &transport_address,
const boost::optional<cryptonote::account_public_address> monero_address)
{
THROW_WALLET_EXCEPTION_IF(index >= m_num_authorized_signers, tools::error::wallet_internal_error, "Invalid signer index " + std::to_string(index));
authorized_signer &m = m_signers[index];
if (label)
{
m.label = label.get();
}
if (transport_address)
{
m.transport_address = transport_address.get();
}
if (monero_address)
{
m.monero_address_known = true;
m.monero_address = monero_address.get();
}
// Save to minimize the chance to loose that info (at least while in beta)
save(state);
}
const authorized_signer &message_store::get_signer(uint32_t index) const
{
THROW_WALLET_EXCEPTION_IF(index >= m_num_authorized_signers, tools::error::wallet_internal_error, "Invalid signer index " + std::to_string(index));
return m_signers[index];
}
bool message_store::signer_config_complete() const
{
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = m_signers[i];
if (m.label.empty() || m.transport_address.empty() || !m.monero_address_known)
{
return false;
}
}
return true;
}
// Check if all signers have a label set (as it's a requirement for starting auto-config
// by the "manager")
bool message_store::signer_labels_complete() const
{
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = m_signers[i];
if (m.label.empty())
{
return false;
}
}
return true;
}
void message_store::get_signer_config(std::string &signer_config)
{
std::stringstream oss;
boost::archive::portable_binary_oarchive ar(oss);
ar << m_signers;
signer_config = oss.str();
}
void message_store::unpack_signer_config(const multisig_wallet_state &state, const std::string &signer_config,
std::vector<authorized_signer> &signers)
{
try
{
std::stringstream iss;
iss << signer_config;
boost::archive::portable_binary_iarchive ar(iss);
ar >> signers;
}
catch (...)
{
THROW_WALLET_EXCEPTION_IF(true, tools::error::wallet_internal_error, "Invalid structure of signer config");
}
uint32_t num_signers = (uint32_t)signers.size();
THROW_WALLET_EXCEPTION_IF(num_signers != m_num_authorized_signers, tools::error::wallet_internal_error, "Wrong number of signers in config: " + std::to_string(num_signers));
}
void message_store::process_signer_config(const multisig_wallet_state &state, const std::string &signer_config)
{
// The signers in "signer_config" and the resident wallet signers are matched not by label, but
// by Monero address, and ALL labels will be set from "signer_config", even the "me" label.
// In the auto-config process as implemented now the auto-config manager is responsible for defining
// the labels, and right at the end of the process ALL wallets use the SAME labels. The idea behind this
// is preventing problems like duplicate labels and confusion (Bob choosing a label "IamAliceHonest").
// (Of course signers are free to re-define any labels they don't like AFTER auto-config.)
//
// Usually this method will be called with only the "me" signer defined in the wallet, and may
// produce unexpected behaviour if that wallet contains additional signers that have nothing to do with
// those arriving in "signer_config".
std::vector<authorized_signer> signers;
unpack_signer_config(state, signer_config, signers);
uint32_t new_index = 1;
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = signers[i];
uint32_t index;
uint32_t take_index;
bool found = get_signer_index_by_monero_address(m.monero_address, index);
if (found)
{
// Redefine existing (probably "me", under usual circumstances)
take_index = index;
}
else
{
// Add new; neglect that we may erroneously overwrite already defined signers
// (but protect "me")
take_index = new_index;
if ((new_index + 1) < m_num_authorized_signers)
{
new_index++;
}
}
authorized_signer &modify = m_signers[take_index];
modify.label = m.label; // ALWAYS set label, see comments above
if (!modify.me)
{
modify.transport_address = m.transport_address;
modify.monero_address_known = m.monero_address_known;
if (m.monero_address_known)
{
modify.monero_address = m.monero_address;
}
}
}
save(state);
}
void message_store::start_auto_config(const multisig_wallet_state &state)
{
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
authorized_signer &m = m_signers[i];
if (!m.me)
{
setup_signer_for_auto_config(i, create_auto_config_token(), true);
}
m.auto_config_running = true;
}
save(state);
}
// Check auto-config token string and convert to standardized form;
// Try to make it as foolproof as possible, with built-in tolerance to make up for
// errors in transmission that still leave the token recognizable.
bool message_store::check_auto_config_token(const std::string &raw_token,
std::string &adjusted_token) const
{
std::string prefix(AUTO_CONFIG_TOKEN_PREFIX);
uint32_t num_hex_digits = (AUTO_CONFIG_TOKEN_BYTES + 1) * 2;
uint32_t full_length = num_hex_digits + prefix.length();
uint32_t raw_length = raw_token.length();
std::string hex_digits;
if (raw_length == full_length)
{
// Prefix must be there; accept it in any casing
std::string raw_prefix(raw_token.substr(0, 3));
boost::algorithm::to_lower(raw_prefix);
if (raw_prefix != prefix)
{
return false;
}
hex_digits = raw_token.substr(3);
}
else if (raw_length == num_hex_digits)
{
// Accept the token without the prefix if it's otherwise ok
hex_digits = raw_token;
}
else
{
return false;
}
// Convert to strict lowercase and correct any common misspellings
boost::algorithm::to_lower(hex_digits);
std::replace(hex_digits.begin(), hex_digits.end(), 'o', '0');
std::replace(hex_digits.begin(), hex_digits.end(), 'i', '1');
std::replace(hex_digits.begin(), hex_digits.end(), 'l', '1');
// Now it must be correct hex with correct checksum, no further tolerance possible
std::string token_bytes;
if (!epee::string_tools::parse_hexstr_to_binbuff(hex_digits, token_bytes))
{
return false;
}
const crypto::hash &hash = crypto::cn_fast_hash(token_bytes.data(), token_bytes.size() - 1);
if (token_bytes[AUTO_CONFIG_TOKEN_BYTES] != hash.data[0])
{
return false;
}
adjusted_token = prefix + hex_digits;
return true;
}
// Create a new auto-config token with prefix, random 8-hex digits plus 2 checksum digits
std::string message_store::create_auto_config_token()
{
unsigned char random[AUTO_CONFIG_TOKEN_BYTES];
crypto::rand(AUTO_CONFIG_TOKEN_BYTES, random);
std::string token_bytes;
token_bytes.append((char *)random, AUTO_CONFIG_TOKEN_BYTES);
// Add a checksum because technically ANY four bytes are a valid token, and without a checksum we would send
// auto-config messages "to nowhere" after the slightest typo without knowing it
const crypto::hash &hash = crypto::cn_fast_hash(token_bytes.data(), token_bytes.size());
token_bytes += hash.data[0];
std::string prefix(AUTO_CONFIG_TOKEN_PREFIX);
return prefix + epee::string_tools::buff_to_hex_nodelimer(token_bytes);
}
// Add a message for sending "me" address data to the auto-config transport address
// that can be derived from the token and activate auto-config
size_t message_store::add_auto_config_data_message(const multisig_wallet_state &state,
const std::string &auto_config_token)
{
authorized_signer &me = m_signers[0];
me.auto_config_token = auto_config_token;
setup_signer_for_auto_config(0, auto_config_token, false);
me.auto_config_running = true;
auto_config_data data;
data.label = me.label;
data.transport_address = me.transport_address;
data.monero_address = me.monero_address;
std::stringstream oss;
boost::archive::portable_binary_oarchive ar(oss);
ar << data;
return add_message(state, 0, message_type::auto_config_data, message_direction::out, oss.str());
}
// Process a single message with auto-config data, destined for "message.signer_index"
void message_store::process_auto_config_data_message(uint32_t id)
{
// "auto_config_data" contains the label that the auto-config data sender uses for "me", but that's
// more for completeness' sake, and right now it's not used. In general, the auto-config manager
// decides/defines the labels, and right after completing auto-config ALL wallets use the SAME labels.
const message &m = get_message_ref_by_id(id);
auto_config_data data;
try
{
std::stringstream iss;
iss << m.content;
boost::archive::portable_binary_iarchive ar(iss);
ar >> data;
}
catch (...)
{
THROW_WALLET_EXCEPTION_IF(true, tools::error::wallet_internal_error, "Invalid structure of auto config data");
}
authorized_signer &signer = m_signers[m.signer_index];
// "signer.label" does NOT change, see comment above
signer.transport_address = data.transport_address;
signer.monero_address_known = true;
signer.monero_address = data.monero_address;
signer.auto_config_running = false;
}
void message_store::stop_auto_config()
{
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
authorized_signer &m = m_signers[i];
if (!m.auto_config_transport_address.empty())
{
// Try to delete the chan that was used for auto-config
m_transporter.delete_transport_address(m.auto_config_transport_address);
}
m.auto_config_token.clear();
m.auto_config_public_key = crypto::null_pkey;
m.auto_config_secret_key = crypto::null_skey;
m.auto_config_transport_address.clear();
m.auto_config_running = false;
}
}
void message_store::setup_signer_for_auto_config(uint32_t index, const std::string token, bool receiving)
{
// It may be a little strange to hash the textual hex digits of the auto config token into
// 32 bytes and turn that into a Monero public/secret key pair, instead of doing something
// much less complicated like directly using the underlying random 40 bits as key for a
// symmetric cipher, but everything is there already for encrypting and decrypting messages
// with such key pairs, and furthermore it would be trivial to use tokens with a different
// number of bytes.
//
// In the wallet of the auto-config manager each signer except "me" gets set its own
// auto-config parameters. In the wallet of somebody using the token to send auto-config
// data the auto-config parameters are stored in the "me" signer and taken from there
// to send that data.
THROW_WALLET_EXCEPTION_IF(index >= m_num_authorized_signers, tools::error::wallet_internal_error, "Invalid signer index " + std::to_string(index));
authorized_signer &m = m_signers[index];
m.auto_config_token = token;
crypto::hash_to_scalar(token.data(), token.size(), m.auto_config_secret_key);
crypto::secret_key_to_public_key(m.auto_config_secret_key, m.auto_config_public_key);
m.auto_config_transport_address = m_transporter.derive_transport_address(m.auto_config_token);
}
bool message_store::get_signer_index_by_monero_address(const cryptonote::account_public_address &monero_address, uint32_t &index) const
{
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = m_signers[i];
if (m.monero_address == monero_address)
{
index = m.index;
return true;
}
}
MWARNING("No authorized signer with Vireo address " << account_address_to_string(monero_address));
return false;
}
bool message_store::get_signer_index_by_label(const std::string label, uint32_t &index) const
{
for (uint32_t i = 0; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = m_signers[i];
if (m.label == label)
{
index = m.index;
return true;
}
}
MWARNING("No authorized signer with label " << label);
return false;
}
void message_store::process_wallet_created_data(const multisig_wallet_state &state, message_type type, const std::string &content)
{
switch(type)
{
case message_type::key_set:
// Result of a "prepare_multisig" command in the wallet
// Send the key set to all other signers
case message_type::additional_key_set:
// Result of a "make_multisig" command or a "exchange_multisig_keys" in the wallet in case of M/N multisig
// Send the additional key set to all other signers
case message_type::multisig_sync_data:
// Result of a "export_multisig_info" command in the wallet
// Send the sync data to all other signers
for (uint32_t i = 1; i < m_num_authorized_signers; ++i)
{
add_message(state, i, type, message_direction::out, content);
}
break;
case message_type::partially_signed_tx:
// Result of a "transfer" command in the wallet, or a "sign_multisig" command
// that did not yet result in the minimum number of signatures required
// Create a message "from me to me" as a container for the tx data
if (m_num_required_signers == 1)
{
// Probably rare, but possible: The 1 signature is already enough, correct the type
// Easier to correct here than asking all callers to detect this rare special case
type = message_type::fully_signed_tx;
}
add_message(state, 0, type, message_direction::in, content);
break;
case message_type::fully_signed_tx:
add_message(state, 0, type, message_direction::in, content);
break;
default:
THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, "Illegal message type " + std::to_string((uint32_t)type));
break;
}
}
size_t message_store::add_message(const multisig_wallet_state &state,
uint32_t signer_index, message_type type, message_direction direction,
const std::string &content)
{
message m;
m.id = m_next_message_id++;
m.type = type;
m.direction = direction;
m.content = content;
m.created = (uint64_t)time(NULL);
m.modified = m.created;
m.sent = 0;
m.signer_index = signer_index;
if (direction == message_direction::out)
{
m.state = message_state::ready_to_send;
}
else
{
m.state = message_state::waiting;
};
m.wallet_height = (uint32_t)state.num_transfer_details;
if (m.type == message_type::additional_key_set)
{
m.round = state.multisig_rounds_passed;
}
else
{
m.round = 0;
}
m.signature_count = 0; // Future expansion for signature counting when signing txs
m.hash = crypto::null_hash;
m_messages.push_back(m);
// Save for every new message right away (at least while in beta)
save(state);
MINFO(boost::format("Added %s message %s for signer %s of type %s")
% message_direction_to_string(direction) % m.id % signer_index % message_type_to_string(type));
return m_messages.size() - 1;
}
// Get the index of the message with id "id", return false if not found
bool message_store::get_message_index_by_id(uint32_t id, size_t &index) const
{
for (size_t i = 0; i < m_messages.size(); ++i)
{
if (m_messages[i].id == id)
{
index = i;
return true;
}
}
MWARNING("No message found with an id of " << id);
return false;
}
// Get the index of the message with id "id" that must exist
size_t message_store::get_message_index_by_id(uint32_t id) const
{
size_t index;
bool found = get_message_index_by_id(id, index);
THROW_WALLET_EXCEPTION_IF(!found, tools::error::wallet_internal_error, "Invalid message id " + std::to_string(id));
return index;
}
// Get the modifiable message with id "id" that must exist; private/internal use!
message& message_store::get_message_ref_by_id(uint32_t id)
{
return m_messages[get_message_index_by_id(id)];
}
// Get the message with id "id", return false if not found
// This version of the method allows to check whether id is valid without triggering an error
bool message_store::get_message_by_id(uint32_t id, message &m) const
{
size_t index;
bool found = get_message_index_by_id(id, index);
if (found)
{
m = m_messages[index];
}
return found;
}
// Get the message with id "id" that must exist
message message_store::get_message_by_id(uint32_t id) const
{
message m;
bool found = get_message_by_id(id, m);
THROW_WALLET_EXCEPTION_IF(!found, tools::error::wallet_internal_error, "Invalid message id " + std::to_string(id));
return m;
}
bool message_store::any_message_of_type(message_type type, message_direction direction) const
{
for (size_t i = 0; i < m_messages.size(); ++i)
{
if ((m_messages[i].type == type) && (m_messages[i].direction == direction))
{
return true;
}
}
return false;
}
bool message_store::any_message_with_hash(const crypto::hash &hash) const
{
for (size_t i = 0; i < m_messages.size(); ++i)
{
if (m_messages[i].hash == hash)
{
return true;
}
}
return false;
}
// Count the ids in the vector that are set i.e. not 0, while ignoring index 0
// Mostly used to check whether we have a message for each authorized signer except me,
// with the signer index used as index into 'ids'; the element at index 0, for me,
// is ignored, to make constant subtractions of 1 for indices when filling the
// vector unnecessary
size_t message_store::get_other_signers_id_count(const std::vector<uint32_t> &ids) const
{
size_t count = 0;
for (size_t i = 1 /* and not 0 */; i < ids.size(); ++i)
{
if (ids[i] != 0)
{
count++;
}
}
return count;
}
// Is in every element of vector 'ids' (except at index 0) a message id i.e. not 0?
bool message_store::message_ids_complete(const std::vector<uint32_t> &ids) const
{
return get_other_signers_id_count(ids) == (ids.size() - 1);
}
void message_store::delete_message(uint32_t id)
{
delete_transport_message(id);
size_t index = get_message_index_by_id(id);
m_messages.erase(m_messages.begin() + index);
}
void message_store::delete_all_messages()
{
for (size_t i = 0; i < m_messages.size(); ++i)
{
delete_transport_message(m_messages[i].id);
}
m_messages.clear();
}
// Make a message text, which is "attacker controlled data", reasonably safe to display
// This is mostly geared towards the safe display of notes sent by "mms note" with a "mms show" command
void message_store::get_sanitized_message_text(const message &m, std::string &sanitized_text) const
{
sanitized_text.clear();
// Restrict the size to fend of DOS-style attacks with heaps of data
size_t length = std::min(m.content.length(), (size_t)1000);
for (size_t i = 0; i < length; ++i)
{
char c = m.content[i];
if ((int)c < 32)
{
// Strip out any controls, especially ESC for getting rid of potentially dangerous
// ANSI escape sequences that a console window might interpret
c = ' ';
}
else if ((c == '<') || (c == '>'))
{
// Make XML or HTML impossible that e.g. might contain scripts that Qt might execute
// when displayed in the GUI wallet
c = ' ';
}
sanitized_text += c;
}
}
void message_store::write_to_file(const multisig_wallet_state &state, const std::string &filename)
{
std::stringstream oss;
boost::archive::portable_binary_oarchive ar(oss);
ar << *this;
std::string buf = oss.str();
crypto::chacha_key key;
crypto::generate_chacha_key(&state.view_secret_key, sizeof(crypto::secret_key), key, 1);
file_data write_file_data = {};
write_file_data.magic_string = "MMS";
write_file_data.file_version = 0;
write_file_data.iv = crypto::rand<crypto::chacha_iv>();
std::string encrypted_data;
encrypted_data.resize(buf.size());
crypto::chacha20(buf.data(), buf.size(), key, write_file_data.iv, &encrypted_data[0]);
write_file_data.encrypted_data = encrypted_data;
std::stringstream file_oss;
boost::archive::portable_binary_oarchive file_ar(file_oss);
file_ar << write_file_data;
bool success = epee::file_io_utils::save_string_to_file(filename, file_oss.str());
THROW_WALLET_EXCEPTION_IF(!success, tools::error::file_save_error, filename);
}
void message_store::read_from_file(const multisig_wallet_state &state, const std::string &filename)
{
boost::system::error_code ignored_ec;
bool file_exists = boost::filesystem::exists(filename, ignored_ec);
if (!file_exists)
{
// Simply do nothing if the file is not there; allows e.g. easy recovery
// from problems with the MMS by deleting the file
MINFO("No message store file found: " << filename);
return;
}
std::string buf;
bool success = epee::file_io_utils::load_file_to_string(filename, buf);
THROW_WALLET_EXCEPTION_IF(!success, tools::error::file_read_error, filename);
file_data read_file_data;
try
{
std::stringstream iss;
iss << buf;
boost::archive::portable_binary_iarchive ar(iss);
ar >> read_file_data;
}
catch (const std::exception &e)
{
MERROR("MMS file " << filename << " has bad structure <iv,encrypted_data>: " << e.what());
THROW_WALLET_EXCEPTION_IF(true, tools::error::file_read_error, filename);
}
crypto::chacha_key key;
crypto::generate_chacha_key(&state.view_secret_key, sizeof(crypto::secret_key), key, 1);
std::string decrypted_data;
decrypted_data.resize(read_file_data.encrypted_data.size());
crypto::chacha20(read_file_data.encrypted_data.data(), read_file_data.encrypted_data.size(), key, read_file_data.iv, &decrypted_data[0]);
try
{
std::stringstream iss;
iss << decrypted_data;
boost::archive::portable_binary_iarchive ar(iss);
ar >> *this;
}
catch (const std::exception &e)
{
MERROR("MMS file " << filename << " has bad structure: " << e.what());
THROW_WALLET_EXCEPTION_IF(true, tools::error::file_read_error, filename);
}
m_filename = filename;
}
// Save to the same file this message store was loaded from
// Called after changes deemed "important", to make it less probable to lose messages in case of
// a crash; a better and long-term solution would of course be to use LMDB ...
void message_store::save(const multisig_wallet_state &state)
{
if (!m_filename.empty())
{
write_to_file(state, m_filename);
}
}
bool message_store::get_processable_messages(const multisig_wallet_state &state,
bool force_sync, std::vector<processing_data> &data_list, std::string &wait_reason)
{
uint32_t wallet_height = (uint32_t)state.num_transfer_details;
data_list.clear();
wait_reason.clear();
// In all scans over all messages looking for complete sets (1 message for each signer),
// if there are duplicates, the OLDEST of them is taken. This may not play a role with
// any of the current message types, but may with future ones, and it's probably a good
// idea to have a clear and somewhat defensive strategy.
std::vector<uint32_t> auto_config_messages(m_num_authorized_signers, 0);
bool any_auto_config = false;
for (size_t i = 0; i < m_messages.size(); ++i)
{
message &m = m_messages[i];
if ((m.type == message_type::auto_config_data) && (m.state == message_state::waiting))
{
if (auto_config_messages[m.signer_index] == 0)
{
auto_config_messages[m.signer_index] = m.id;
any_auto_config = true;
}
// else duplicate auto config data, ignore
}
}
if (any_auto_config)
{
bool auto_config_complete = message_ids_complete(auto_config_messages);
if (auto_config_complete)
{
processing_data data;
data.processing = message_processing::process_auto_config_data;
data.message_ids = auto_config_messages;
data.message_ids.erase(data.message_ids.begin());
data_list.push_back(data);
return true;
}
else
{
wait_reason = tr("Auto-config cannot proceed because auto config data from other signers is not complete");
return false;
// With ANY auto config data present but not complete refuse to check for any
// other processing. Manually delete those messages to abort such an auto config
// phase if needed.
}
}
// Any signer config that arrived will be processed right away, regardless of other things that may wait
for (size_t i = 0; i < m_messages.size(); ++i)
{
message &m = m_messages[i];
if ((m.type == message_type::signer_config) && (m.state == message_state::waiting))
{
processing_data data;
data.processing = message_processing::process_signer_config;
data.message_ids.push_back(m.id);
data_list.push_back(data);
return true;
}
}
// ALL of the following processings depend on the signer info being complete
if (!signer_config_complete())
{
wait_reason = tr("The signer config is not complete.");
return false;
}
if (!state.multisig)
{
if (!any_message_of_type(message_type::key_set, message_direction::out))
{
// With the own key set not yet ready we must do "prepare_multisig" first;
// Key sets from other signers may be here already, but if we process them now
// the wallet will go multisig too early: we can't produce our own key set any more!
processing_data data;
data.processing = message_processing::prepare_multisig;
data_list.push_back(data);
return true;
}
// Ids of key set messages per signer index, to check completeness
// Naturally, does not care about the order of the messages and is trivial to secure against
// key sets that were received more than once
// With full M/N multisig now possible consider only key sets of the right round, i.e.
// with not yet multisig the only possible round 0
std::vector<uint32_t> key_set_messages(m_num_authorized_signers, 0);
for (size_t i = 0; i < m_messages.size(); ++i)
{
message &m = m_messages[i];
if ((m.type == message_type::key_set) && (m.state == message_state::waiting)
&& (m.round == 0))
{
if (key_set_messages[m.signer_index] == 0)
{
key_set_messages[m.signer_index] = m.id;
}
// else duplicate key set, ignore
}
}
bool key_sets_complete = message_ids_complete(key_set_messages);
if (key_sets_complete)
{
// Nothing else can be ready to process earlier than this, ignore everything else and give back
processing_data data;
data.processing = message_processing::make_multisig;
data.message_ids = key_set_messages;
data.message_ids.erase(data.message_ids.begin());
data_list.push_back(data);
return true;
}
else
{
wait_reason = tr("Wallet can't go multisig because key sets from other signers are missing or not complete.");
return false;
}
}
if (state.multisig && !state.multisig_is_ready)
{
// In the case of M/N multisig the call 'wallet2::multisig' returns already true
// after "make_multisig" but with calls to "exchange_multisig_keys" still needed, and
// sets the parameter 'ready' to false to document this particular "in-between" state.
// So what may be possible here, with all necessary messages present, is a call to
// "exchange_multisig_keys".
// Consider only messages belonging to the next round to do, which has the number
// "state.multisig_rounds_passed".
std::vector<uint32_t> additional_key_set_messages(m_num_authorized_signers, 0);
for (size_t i = 0; i < m_messages.size(); ++i)
{
message &m = m_messages[i];
if ((m.type == message_type::additional_key_set) && (m.state == message_state::waiting)
&& (m.round == state.multisig_rounds_passed))
{
if (additional_key_set_messages[m.signer_index] == 0)
{
additional_key_set_messages[m.signer_index] = m.id;
}
// else duplicate key set, ignore
}
}
bool key_sets_complete = message_ids_complete(additional_key_set_messages);
if (key_sets_complete)
{
processing_data data;
data.processing = message_processing::exchange_multisig_keys;
data.message_ids = additional_key_set_messages;
data.message_ids.erase(data.message_ids.begin());
data_list.push_back(data);
return true;
}
else
{
wait_reason = tr("Wallet can't start another key exchange round because key sets from other signers are missing or not complete.");
return false;
}
}
// Properly exchanging multisig sync data is easiest and most transparent
// for the user if a wallet sends its own data first and processes any received
// sync data afterwards so that's the order that the MMS enforces here.
// (Technically, it seems to work also the other way round.)
//
// To check whether a NEW round of syncing is necessary the MMS works with a
// "wallet state": new state means new syncing needed.
//
// The MMS monitors the "wallet state" by recording "wallet heights" as
// numbers of transfers present in a wallet at the time of message creation. While
// not watertight, this quite simple scheme should already suffice to trigger
// and orchestrate a sensible exchange of sync data.
if (state.has_multisig_partial_key_images || force_sync)
{
// Sync is necessary and not yet completed: Processing of transactions
// will only be possible again once properly synced
// Check first whether we generated already OUR sync info; take note of
// any processable sync info from other signers on the way in case we need it
bool own_sync_data_created = false;
std::vector<uint32_t> sync_messages(m_num_authorized_signers, 0);
for (size_t i = 0; i < m_messages.size(); ++i)
{
message &m = m_messages[i];
if ((m.type == message_type::multisig_sync_data) && (force_sync || (m.wallet_height == wallet_height)))
// It's data for the same "round" of syncing, on the same "wallet height", therefore relevant
// With "force_sync" take ANY waiting sync data, maybe it will work out
{
if (m.direction == message_direction::out)
{
own_sync_data_created = true;
// Ignore whether sent already or not, and assume as complete if several other signers there
}
else if ((m.direction == message_direction::in) && (m.state == message_state::waiting))
{
if (sync_messages[m.signer_index] == 0)
{
sync_messages[m.signer_index] = m.id;
}
// else duplicate sync message, ignore
}
}
}
if (!own_sync_data_created)
{
// As explained above, creating sync data BEFORE processing such data from
// other signers reliably works, so insist on that here
processing_data data;
data.processing = message_processing::create_sync_data;
data_list.push_back(data);
return true;
}
uint32_t id_count = (uint32_t)get_other_signers_id_count(sync_messages);
// Do we have sync data from ALL other signers?
bool all_sync_data = id_count == (m_num_authorized_signers - 1);
// Do we have just ENOUGH sync data to have a minimal viable sync set?
// In cases like 2/3 multisig we don't need messages from ALL other signers, only
// from enough of them i.e. num_required_signers minus 1 messages
bool enough_sync_data = id_count >= (m_num_required_signers - 1);
bool sync = false;
wait_reason = tr("Syncing not done because multisig sync data from other signers are missing or not complete.");
if (all_sync_data)
{
sync = true;
}
else if (enough_sync_data)
{
if (force_sync)
{
sync = true;
}
else
{
// Don't sync, but give a hint how this minimal set COULD be synced if really wanted
wait_reason += (boost::format("\nUse \"mms next sync\" if you want to sync with just %s out of %s authorized signers and transact just with them")
% (m_num_required_signers - 1) % (m_num_authorized_signers - 1)).str();
}
}
if (sync)
{
processing_data data;
data.processing = message_processing::process_sync_data;
for (size_t i = 0; i < sync_messages.size(); ++i)
{
uint32_t id = sync_messages[i];
if (id != 0)
{
data.message_ids.push_back(id);
}
}
data_list.push_back(data);
return true;
}
else
{
// We can't proceed to any transactions until we have synced; "wait_reason" already set above
return false;
}
}
bool waiting_found = false;
bool note_found = false;
bool sync_data_found = false;
for (size_t i = 0; i < m_messages.size(); ++i)
{
message &m = m_messages[i];
if (m.state == message_state::waiting)
{
waiting_found = true;
switch (m.type)
{
case message_type::fully_signed_tx:
{
// We can either submit it ourselves, or send it to any other signer for submission
processing_data data;
data.processing = message_processing::submit_tx;
data.message_ids.push_back(m.id);
data_list.push_back(data);
data.processing = message_processing::send_tx;
for (uint32_t j = 1; j < m_num_authorized_signers; ++j)
{
data.receiving_signer_index = j;
data_list.push_back(data);
}
return true;
}
case message_type::partially_signed_tx:
{
if (m.signer_index == 0)
{
// We started this ourselves, or signed it but with still signatures missing:
// We can send it to any other signer for signing / further signing
// In principle it does not make sense to send it back to somebody who
// already signed, but the MMS does not / not yet keep track of that,
// because that would be somewhat complicated.
processing_data data;
data.processing = message_processing::send_tx;
data.message_ids.push_back(m.id);
for (uint32_t j = 1; j < m_num_authorized_signers; ++j)
{
data.receiving_signer_index = j;
data_list.push_back(data);
}
return true;
}
else
{
// Somebody else sent this to us: We can sign it
// It would be possible to just pass it on, but that's not directly supported here
processing_data data;
data.processing = message_processing::sign_tx;
data.message_ids.push_back(m.id);
data_list.push_back(data);
return true;
}
}
case message_type::note:
note_found = true;
break;
case message_type::multisig_sync_data:
sync_data_found = true;
break;
default:
break;
}
}
}
if (waiting_found)
{
wait_reason = tr("There are waiting messages, but nothing is ready to process under normal circumstances");
if (sync_data_found)
{
wait_reason += tr("\nUse \"mms next sync\" if you want to force processing of the waiting sync data");
}
if (note_found)
{
wait_reason += tr("\nUse \"mms note\" to display the waiting notes");
}
}
else
{
wait_reason = tr("There are no messages waiting to be processed.");
}
return false;
}
void message_store::set_messages_processed(const processing_data &data)
{
for (size_t i = 0; i < data.message_ids.size(); ++i)
{
set_message_processed_or_sent(data.message_ids[i]);
}
}
void message_store::set_message_processed_or_sent(uint32_t id)
{
message &m = get_message_ref_by_id(id);
if (m.state == message_state::waiting)
{
// So far a fairly cautious and conservative strategy: Only delete from Bitmessage
// when fully processed (and e.g. not already after reception and writing into
// the message store file)
delete_transport_message(id);
m.state = message_state::processed;
}
else if (m.state == message_state::ready_to_send)
{
m.state = message_state::sent;
}
m.modified = (uint64_t)time(NULL);
}
void message_store::encrypt(crypto::public_key public_key, const std::string &plaintext,
std::string &ciphertext, crypto::public_key &encryption_public_key, crypto::chacha_iv &iv)
{
crypto::secret_key encryption_secret_key;
crypto::generate_keys(encryption_public_key, encryption_secret_key);
crypto::key_derivation derivation;
bool success = crypto::generate_key_derivation(public_key, encryption_secret_key, derivation);
THROW_WALLET_EXCEPTION_IF(!success, tools::error::wallet_internal_error, "Failed to generate key derivation for message encryption");
crypto::chacha_key chacha_key;
crypto::generate_chacha_key(&derivation, sizeof(derivation), chacha_key, 1);
iv = crypto::rand<crypto::chacha_iv>();
ciphertext.resize(plaintext.size());
crypto::chacha20(plaintext.data(), plaintext.size(), chacha_key, iv, &ciphertext[0]);
}
void message_store::decrypt(const std::string &ciphertext, const crypto::public_key &encryption_public_key, const crypto::chacha_iv &iv,
const crypto::secret_key &view_secret_key, std::string &plaintext)
{
crypto::key_derivation derivation;
bool success = crypto::generate_key_derivation(encryption_public_key, view_secret_key, derivation);
THROW_WALLET_EXCEPTION_IF(!success, tools::error::wallet_internal_error, "Failed to generate key derivation for message decryption");
crypto::chacha_key chacha_key;
crypto::generate_chacha_key(&derivation, sizeof(derivation), chacha_key, 1);
plaintext.resize(ciphertext.size());
crypto::chacha20(ciphertext.data(), ciphertext.size(), chacha_key, iv, &plaintext[0]);
}
void message_store::send_message(const multisig_wallet_state &state, uint32_t id)
{
message &m = get_message_ref_by_id(id);
const authorized_signer &me = m_signers[0];
const authorized_signer &receiver = m_signers[m.signer_index];
transport_message dm;
crypto::public_key public_key;
dm.timestamp = (uint64_t)time(NULL);
dm.subject = "MMS V0 " + tools::get_human_readable_timestamp(dm.timestamp);
dm.source_transport_address = me.transport_address;
dm.source_monero_address = me.monero_address;
if (m.type == message_type::auto_config_data)
{
// Encrypt with the public key derived from the auto-config token, and send to the
// transport address likewise derived from that token
public_key = me.auto_config_public_key;
dm.destination_transport_address = me.auto_config_transport_address;
// The destination Monero address is not yet known
memset(&dm.destination_monero_address, 0, sizeof(cryptonote::account_public_address));
}
else
{
// Encrypt with the receiver's view public key
public_key = receiver.monero_address.m_view_public_key;
const authorized_signer &receiver = m_signers[m.signer_index];
dm.destination_monero_address = receiver.monero_address;
dm.destination_transport_address = receiver.transport_address;
}
encrypt(public_key, m.content, dm.content, dm.encryption_public_key, dm.iv);
dm.type = (uint32_t)m.type;
dm.hash = crypto::cn_fast_hash(dm.content.data(), dm.content.size());
dm.round = m.round;
crypto::generate_signature(dm.hash, me.monero_address.m_view_public_key, state.view_secret_key, dm.signature);
m_transporter.send_message(dm);
m.state=message_state::sent;
m.sent= (uint64_t)time(NULL);
}
bool message_store::check_for_messages(const multisig_wallet_state &state, std::vector<message> &messages)
{
m_run.store(true, std::memory_order_relaxed);
const authorized_signer &me = m_signers[0];
std::vector<std::string> destinations;
destinations.push_back(me.transport_address);
for (uint32_t i = 1; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = m_signers[i];
if (m.auto_config_running)
{
destinations.push_back(m.auto_config_transport_address);
}
}
std::vector<transport_message> transport_messages;
bool r = m_transporter.receive_messages(destinations, transport_messages);
if (!m_run.load(std::memory_order_relaxed))
{
// Stop was called, don't waste time processing the messages
// (but once started processing them, don't react to stop request anymore, avoid receiving them "partially)"
return false;
}
bool new_messages = false;
for (size_t i = 0; i < transport_messages.size(); ++i)
{
transport_message &rm = transport_messages[i];
if (any_message_with_hash(rm.hash))
{
// Already seen, do not take again
}
else
{
uint32_t sender_index;
bool take = false;
message_type type = static_cast<message_type>(rm.type);
crypto::secret_key decrypt_key = state.view_secret_key;
if (type == message_type::auto_config_data)
{
// Find out which signer sent it by checking which auto config transport address
// the message was sent to
for (uint32_t i = 1; i < m_num_authorized_signers; ++i)
{
const authorized_signer &m = m_signers[i];
if (m.auto_config_transport_address == rm.destination_transport_address)
{
take = true;
sender_index = i;
decrypt_key = m.auto_config_secret_key;
break;
}
}
}
else if (type == message_type::signer_config)
{
// Typically we can't check yet whether we know the sender, so take from any
// and pretend it's from "me" because we might have nothing else yet
take = true;
sender_index = 0;
}
else
{
// Only accept from senders that are known as signer here, otherwise just ignore
take = get_signer_index_by_monero_address(rm.source_monero_address, sender_index);
}
if (take && (type != message_type::auto_config_data))
{
// If the destination address is known, check it as well; this additional filter
// allows using the same transport address for multiple signers
take = rm.destination_monero_address == me.monero_address;
}
if (take)
{
crypto::hash actual_hash = crypto::cn_fast_hash(rm.content.data(), rm.content.size());
THROW_WALLET_EXCEPTION_IF(actual_hash != rm.hash, tools::error::wallet_internal_error, "Message hash mismatch");
bool signature_valid = crypto::check_signature(actual_hash, rm.source_monero_address.m_view_public_key, rm.signature);
THROW_WALLET_EXCEPTION_IF(!signature_valid, tools::error::wallet_internal_error, "Message signature not valid");
std::string plaintext;
decrypt(rm.content, rm.encryption_public_key, rm.iv, decrypt_key, plaintext);
size_t index = add_message(state, sender_index, (message_type)rm.type, message_direction::in, plaintext);
message &m = m_messages[index];
m.hash = rm.hash;
m.transport_id = rm.transport_id;
m.sent = rm.timestamp;
m.round = rm.round;
m.signature_count = rm.signature_count;
messages.push_back(m);
new_messages = true;
}
}
}
return new_messages;
}
void message_store::delete_transport_message(uint32_t id)
{
const message &m = get_message_by_id(id);
if (!m.transport_id.empty())
{
m_transporter.delete_message(m.transport_id);
}
}
std::string message_store::account_address_to_string(const cryptonote::account_public_address &account_address) const
{
return get_account_address_as_str(m_nettype, false, account_address);
}
const char* message_store::message_type_to_string(message_type type)
{
switch (type)
{
case message_type::key_set:
return tr("key set");
case message_type::additional_key_set:
return tr("additional key set");
case message_type::multisig_sync_data:
return tr("multisig sync data");
case message_type::partially_signed_tx:
return tr("partially signed tx");
case message_type::fully_signed_tx:
return tr("fully signed tx");
case message_type::note:
return tr("note");
case message_type::signer_config:
return tr("signer config");
case message_type::auto_config_data:
return tr("auto-config data");
default:
return tr("unknown message type");
}
}
const char* message_store::message_direction_to_string(message_direction direction)
{
switch (direction)
{
case message_direction::in:
return tr("in");
case message_direction::out:
return tr("out");
default:
return tr("unknown message direction");
}
}
const char* message_store::message_state_to_string(message_state state)
{
switch (state)
{
case message_state::ready_to_send:
return tr("ready to send");
case message_state::sent:
return tr("sent");
case message_state::waiting:
return tr("waiting");
case message_state::processed:
return tr("processed");
case message_state::cancelled:
return tr("cancelled");
default:
return tr("unknown message state");
}
}
// Convert a signer to string suitable for a column in a list, with 'max_width'
// Format: label: transport_address
std::string message_store::signer_to_string(const authorized_signer &signer, uint32_t max_width)
{
std::string s = "";
s.reserve(max_width);
uint32_t avail = max_width;
uint32_t label_len = signer.label.length();
if (label_len > avail)
{
s.append(signer.label.substr(0, avail - 2));
s.append("..");
return s;
}
s.append(signer.label);
avail -= label_len;
uint32_t transport_addr_len = signer.transport_address.length();
if ((transport_addr_len > 0) && (avail > 10))
{
s.append(": ");
avail -= 2;
if (transport_addr_len <= avail)
{
s.append(signer.transport_address);
}
else
{
s.append(signer.transport_address.substr(0, avail-2));
s.append("..");
}
}
return s;
}
}
| [
"cam@camthegeek.net"
] | cam@camthegeek.net |
0e6e560bb8cda7980ff82d974bce9815e29788dd | 40cdb94b52db41bb7b06f0b304a554247a8c9754 | /Gpu_Rvd/header/cuda/cuda_polygon.h | 63e90237b8359ce810f8b2d05a1dde11b75610a6 | [
"MIT"
] | permissive | stormHan/gpu_rvd | adb86de5e2d236ac63476c8d598d4021deb9b2d5 | 4029bfa604117c723c712445b42842b4aa499db2 | refs/heads/master | 2020-06-23T03:13:14.648566 | 2017-03-29T12:40:34 | 2017-03-29T12:40:34 | 74,668,863 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 542 | h | /*
*
*/
#ifndef CUDA_POLYGON_H
#define CUDA_POLYGON_H
namespace Gpu_Rvd{
/*
* \brief Cuda polygon vertex.
* \detials x, y, z is the spatial position of a vertxt.
* w is the weight of a vextex. neigh_s is the nearby seed
* of the current point.
*/
struct CudaVertex
{
double x;
double y;
double z;
double w;
int neigh_s = -1;
};
/*
* \brief Cuda polygon. A smart data stuction to store the clipped triangle.
*/
struct CudaPolygon
{
CudaVertex vertex[15];
index_t vertex_nb;
};
}
#endif /* CUDA_POLYGON_H */ | [
"stormhan1205@gmail.com"
] | stormhan1205@gmail.com |
9418324f5f67691190bb0ff12b9a7e48c993f21a | 350db570521d3fc43f07df645addb9d6e648c17e | /0155_Min_Stack/solution.cpp | 5f0290ad67573f5fcc955ab398e5f2eb808a06c6 | [] | no_license | benjaminhuanghuang/ben-leetcode | 2efcc9185459a1dd881c6e2ded96c42c5715560a | a2cd0dc5e098080df87c4fb57d16877d21ca47a3 | refs/heads/master | 2022-12-10T02:30:06.744566 | 2022-11-27T04:06:52 | 2022-11-27T04:06:52 | 236,252,145 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 943 | cpp | /*
155. Min Stack
Level: Easy
https://leetcode.com/problems/min-stack
*/
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
#include "common/ListNode.h"
#include "common/TreeNode.h"
using namespace std;
/*
Solution:
*/
class MinStack
{
private:
stack<int> valStack;
stack<int> minStack;
public:
/** initialize your data structure here. */
MinStack()
{
}
void push(int x)
{
valStack.push(x);
if (minStack.empty())
{
minStack.push(x);
}
else
{
minStack.push(min(x, minStack.top()));
}
}
void pop()
{
valStack.pop();
minStack.pop();
}
int top()
{
return valStack.top();
}
int getMin()
{
return minStack.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/ | [
"bhuang@rms.com"
] | bhuang@rms.com |
e44cba589706d446a3f2fd25f4643f5074c0e6f6 | 3f435b73e0fd7701828ea7e569e0586d38f98edb | /Begginers/sumodd.cpp | 50a727297bd3a748b063bd9867ec42f74de48e84 | [] | no_license | lhpdev/URIJudgeExercises | 44adb7912c5abf4ac623e2053c041099950ec429 | 87293f5ab12f2a92dce3fb9dc02c403ad9a0e60f | refs/heads/master | 2021-09-22T09:06:09.539693 | 2018-09-06T21:15:00 | 2018-09-06T21:15:00 | 93,896,132 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,317 | cpp | #include <stdio.h>
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int X,Y,i,sum,sumX,sumY,auxX, auxY;
scanf("%d" , &X);
scanf("%d" , &Y);
sum = 0;
sumX = 0;
sumY= 0;
if (( X < 0) && (Y < 0)){ // OK
auxX = -X;
auxY = -Y;
if( auxX > auxY){
for (int i = (auxY + 1); i < auxX; ++i)
{
if ( i%2 != 0){
sum = sum + i;
}
}
}else{
for (int i = (auxX + 1); i < auxY; ++i)
{
if ( i%2 != 0){
sum = sum + i;
}
}
}
printf("%d\n",-sum);
}
if ((X > 0) && (Y >0)){ // OK
if( X > Y){
for (int i = (Y + 1); i < X; ++i)
{
if ( i%2 != 0){
sum = sum + i;
}
}
}else{
for (int i = (X + 1); i < Y; ++i)
{
if ( i%2 != 0){
sum = sum + i;
}
}
}
printf("%d\n",sum);
}
if ((X > 0) && (Y < 0)){
auxY = -Y;
for (int i = 0; i < X; ++i)
{
if ( i%2 != 0){
sumX = sumX + i;
}
}
for (int i = 0; i < auxY; ++i)
{
if ( i%2 != 0){
sumY = sumY + i;
}
}
printf("%d\n",sumX -sumY);
}
if ((X < 0) && (Y > 0)){
auxX = -X;
for (int i = 0; i < auxX; ++i)
{
if ( i%2 != 0){
sumX = sumX + i;
}
}
for (int i = 0; i < Y; ++i)
{
if ( i%2 != 0){
sumY = sumY + i;
}
}
printf("%d\n",sumY - sumX);
}
return 0;
} | [
"lucass.hauptmann@gmail.com"
] | lucass.hauptmann@gmail.com |
5caae901f14254a8128f9b5cd9b6ccd98a037612 | 4255fcba4718c888eb32e4530b736ef037882d28 | /APIs_Drivers/DigitalOut_ex_1/main.cpp | 6ddc38d6f7c0a63b167b6b048932d80350173bf6 | [
"Apache-2.0"
] | permissive | ARMmbed/mbed-os-examples-docs_only | e2fb92478a847c2578c7950a510ae2730b3eccc4 | d955550449cc6ac7d1151550f2a058803a2986ee | refs/heads/master | 2023-07-05T06:05:59.974508 | 2021-09-19T22:47:14 | 2021-09-19T22:47:14 | 152,603,832 | 6 | 28 | Apache-2.0 | 2021-09-19T22:47:15 | 2018-10-11T14:19:44 | C++ | UTF-8 | C++ | false | false | 643 | cpp | /*
* Copyright (c) 2006-2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
DigitalOut myled(LED1);
int main()
{
// check that myled object is initialized and connected to a pin
if (myled.is_connected()) {
printf("myled is initialized and connected!\n\r");
}
// Blink LED
while (1) {
myled = 1; // set LED1 pin to high
printf("myled = %d \n\r", (uint8_t)myled);
ThisThread::sleep_for(500);
myled.write(0); // set LED1 pin to low
printf("myled = %d \n\r", myled.read());
ThisThread::sleep_for(500);
}
}
| [
"maciej.bocianski@gmail.com"
] | maciej.bocianski@gmail.com |
e086d8de5a7d3349357bb1d7a885c19b1e96e908 | 7292da3fcac24ba18579466b44b4b8e053464eb6 | /Server/recomandare.cpp | 947c016670f227fd8a3510b5732e18d787f22634 | [] | no_license | raresmihai/readsprofiler | 16b12e2c58703094fe5280ead5ce0945088eed65 | c32315322675727fe9c41437224b2d8d84f8ca80 | refs/heads/master | 2021-01-19T03:13:46.835065 | 2016-07-23T19:13:45 | 2016-07-23T19:13:45 | 48,611,239 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,829 | cpp | #include "recomandare.h"
void recomandare_carti(int client_descriptor)
{
int caz_recomandare;
if(read(client_descriptor,&caz_recomandare,4)<0)
{
perror("Eroare la citirea cazului de recomandare.\n");
}
char username[50];
if(read(client_descriptor,&username,50)<0)
{
perror("Eroare la citirea usernameului pentru recomandare.\n");
}
char isbn[20];
if(caz_recomandare == 2)
{
if(read(client_descriptor,&isbn,20)<0)
{
perror("Eroare la citirea isbn-ului pentru recomandare.\n");
}
}
switch(caz_recomandare)
{
case 1:
recomanda_top_5_carti(client_descriptor);
break;
case 2:
recomandari_similare(client_descriptor,isbn);
break;
case 3:
recomandari_dupa_istoric(client_descriptor,username);
break;
}
}
void recomandari_dupa_istoric(int client_descriptor, char *username)
{
SugestieCarte recomandariCarti[1000];
bzero(&recomandariCarti,sizeof(recomandariCarti));
Tabela tabele[3];
strcpy(tabele[0].denumire_tabela,"cautari_utilizatori");
tabele[0].importanta_tabela = 1;
strcpy(tabele[1].denumire_tabela,"accesari_utilizatori");
tabele[1].importanta_tabela = 2;
strcpy(tabele[2].denumire_tabela,"descarcari_utilizatori");
tabele[2].importanta_tabela = 3;
char interogare[1000];
QSqlQuery query_tabelaPrincipala;
char isbn[20];
for(int i=0;i<3;i++)
{
sprintf(interogare,"SELECT isbn FROM %s WHERE username = '%s'",tabele[i].denumire_tabela,username);
if(!query_tabelaPrincipala.exec(interogare)){
qDebug() << "Eroare la selectarea isbnurilor de baza in recomandare:\n" << query_tabelaPrincipala.lastError();
}
while(query_tabelaPrincipala.next())
{
strcpy(isbn,query_tabelaPrincipala.value(0).toString().toStdString().c_str());
adauga_recomandari(recomandariCarti,tabele[i].importanta_tabela,isbn,username);
}
}
int nr_recomandari = sortare_dupa_grad(recomandariCarti);
int caz_recomandare_client = 3;
if(nr_recomandari < 5)
{
if(nr_recomandari == 0)
{
caz_recomandare_client = 1;
write(client_descriptor,&caz_recomandare_client,4);
recomanda_top_5_carti(client_descriptor);
}
else
{
write(client_descriptor,&caz_recomandare_client,4);
SugestieCarte topCarti[1000];
bzero(&topCarti,sizeof(topCarti));
int nr_top_recomandari = top_carti_dupa_rating(topCarti);
int i=0;
while(nr_recomandari<5 && i<nr_top_recomandari)
{
if(cartea_nu_a_fost_deja_adaugata(recomandariCarti,topCarti[i].isbn))
{
recomandariCarti[nr_recomandari] = topCarti[i];
nr_recomandari++;
}
i++;
}
trimite_recomandarile_clientului(client_descriptor,recomandariCarti);
}
}
else
{
write(client_descriptor,&caz_recomandare_client,4);
trimite_recomandarile_clientului(client_descriptor,recomandariCarti);
}
}
void adauga_recomandari(SugestieCarte *recomandariCarti, int importanta_tabela, char *isbn, char *username)
{
char interogare[1000];
QSqlQuery query;
//selectare rating
sprintf(interogare,"SELECT rating_acordat FROM rating_utilizatori WHERE isbn = '%s' AND username = '%s'",isbn,username);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea ratingului de baza in recomandare:\n" << query.lastError();
}
int rating_carte_de_baza = 0;
if(query.size()>0){
query.first();
rating_carte_de_baza = query.value(0).toInt();
}
//selectare id_autor
sprintf(interogare,"SELECT id_autor FROM carti WHERE isbn = '%s'",isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea autorului in recomandare:\n" << query.lastError();
}
query.first();
int id_autor = query.value(0).toInt();
//selectare an_aparitie
sprintf(interogare,"SELECT an_aparitie FROM carti WHERE isbn = '%s'",isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea anului in recomandare:\n" << query.lastError();
}
query.first();
int an_aparitie = query.value(0).toInt();
//selectare genuri
sprintf(interogare,"SELECT id_gen FROM genuri_carte WHERE isbn = '%s'",isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea genurilor in recomandare:\n" << query.lastError();
}
int nr_genuri = query.size();
int genuri[nr_genuri];
int k=0;
while(query.next())
{
genuri[k]=query.value(0).toInt();
k++;
}
//selectare subgenuri
sprintf(interogare,"SELECT id_subgen FROM subgenuri_carte WHERE isbn = '%s'",isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea subgenurilor in recomandare:\n" << query.lastError();
}
int nr_subgenuri = query.size();
int subgenuri[nr_subgenuri];
k=0;
while(query.next())
{
subgenuri[k]=query.value(0).toInt();
k++;
}
//setare campuri pentru interogari
int nr_interogari = 2 + nr_genuri + nr_subgenuri;
InterogareDinamica interogari[nr_interogari];
strcpy(interogari[0].nume_tabela,"carti");
strcpy(interogari[0].nume_camp,"id_autor");
interogari[0].valoare_camp = id_autor;
interogari[0].importanta_camp = 3;
strcpy(interogari[1].nume_tabela,"carti");
strcpy(interogari[1].nume_camp,"an_aparitie");
interogari[1].valoare_camp = an_aparitie;
interogari[1].importanta_camp = 2;
for(int i=2;i<2+nr_genuri;i++)
{
strcpy(interogari[i].nume_tabela,"genuri_carte");
strcpy(interogari[i].nume_camp,"id_gen");
interogari[i].valoare_camp = genuri[i-2];
interogari[i].importanta_camp = 5;
}
for(int i=2+nr_genuri;i<nr_interogari;i++)
{
strcpy(interogari[i].nume_tabela,"subgenuri_carte");
strcpy(interogari[i].nume_camp,"id_subgen");
interogari[i].valoare_camp = subgenuri[i-2-nr_genuri];
interogari[i].importanta_camp = 4;
}
//INTEROGARI
char isbn_sugestie[20];
for(int i=0;i<nr_interogari;i++)
{
sprintf(interogare,"SELECT isbn FROM %s WHERE isbn != '%s' AND %s = %d",interogari[i].nume_tabela,isbn,interogari[i].nume_camp,interogari[i].valoare_camp);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea isbnului recomandarii:\n" << query.lastError();
}
while(query.next())
{
strcpy(isbn_sugestie,query.value(0).toString().toStdString().c_str());
if(user_nu_a_mai_accesat_cartea(username,isbn_sugestie))
{
double rating_carte_sugestie = rating_carte(isbn_sugestie);
double grad_recomandare = calculare_grad_recomandare(importanta_tabela,interogari[i].importanta_camp,rating_carte_de_baza,rating_carte_sugestie);
adauga_sugestie_noua(recomandariCarti,isbn_sugestie,grad_recomandare);
}
}
}
}
void adauga_sugestie_noua(SugestieCarte *recomandariCarti, char *isbn_sugestie, double grad_recomandare)
{
bool sugestieGasita = false;
int lungime = 0;
while(recomandariCarti[lungime].grad_recomandare>0)
{
if(strcmp(recomandariCarti[lungime].isbn,isbn_sugestie)==0)
{
recomandariCarti[lungime].grad_recomandare+=grad_recomandare;
sugestieGasita = true;
break;
}
lungime++;
}
if(sugestieGasita==false)
{
recomandariCarti[lungime].grad_recomandare=grad_recomandare;
strcpy(recomandariCarti[lungime].isbn,isbn_sugestie);
}
}
double calculare_grad_recomandare(int importanta_tabela, int importanta_camp, int rating_carte_de_baza, double rating_carte_sugestie)
{
return (double)(importanta_tabela * importanta_tabela * (3*rating_carte_sugestie + 2*importanta_camp + rating_carte_de_baza));
}
int sortare_dupa_grad(SugestieCarte *recomandariCarti)
{
int lungime = 0;
while(recomandariCarti[lungime].grad_recomandare>0) lungime++;
SugestieCarte aux;
for(int i = 0;i<lungime-1;i++)
{
for(int j = i+1; j<lungime;j++)
{
if(recomandariCarti[i].grad_recomandare<recomandariCarti[j].grad_recomandare)
{
aux = recomandariCarti[i];
recomandariCarti[i]=recomandariCarti[j];
recomandariCarti[j]=aux;
}
}
}
return lungime;
}
int top_carti_dupa_rating(SugestieCarte *topCarti)
{
QSqlQuery query;
if(!query.exec("SELECT isbn,valoare/nr_voturi FROM rating WHERE nr_voturi > 3 ORDER BY valoare/nr_voturi DESC")){
qDebug() << "Eroare la selectarea TOP recomandari:\n" << query.lastError();
}
int nr_top_carti = 0;
while(query.next()&&nr_top_carti<30)
{
strcpy(topCarti[nr_top_carti].isbn,query.value(0).toString().toStdString().c_str());
topCarti[nr_top_carti].grad_recomandare = query.value(1).toDouble();
nr_top_carti++;
}
return nr_top_carti;
}
double rating_carte(char *isbn)
{
char interogare[1000];
QSqlQuery query;
sprintf(interogare,"SELECT IFNULL(valoare/nr_voturi,2.5) FROM rating WHERE isbn = '%s'",isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea ratingului cartii sugestie in recomandare:\n" << query.lastError();
}
query.first();
double rating = query.value(0).toDouble();
return rating;
}
bool user_nu_a_mai_accesat_cartea(char *username, char *isbn)
{
char interogare[1000];
QSqlQuery query;
sprintf(interogare,"SELECT id FROM accesari_utilizatori WHERE username = '%s' AND isbn = '%s'",username,isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la verificare accesare in recomandare:\n" << query.lastError();
}
if(query.size()==0)
{
return true;
}
return false;
}
void recomanda_top_5_carti(int client_descriptor)
{
QSqlQuery query;
if(!query.exec("SELECT isbn FROM rating WHERE nr_voturi > 3 ORDER BY valoare/nr_voturi DESC LIMIT 5")){
qDebug() << "Eroare la top 5 recomandari:\n" << query.lastError();
}
SugestieCarte top5[5];
int index = 0;
while(query.next())
{
strcpy(top5[index].isbn,query.value(0).toString().toStdString().c_str());
index++;
}
trimite_recomandarile_clientului(client_descriptor,top5);
}
bool cartea_nu_a_fost_deja_adaugata(SugestieCarte *recomandari, char *isbn)
{
int i = 0;
while(recomandari[i].grad_recomandare>0)
{
if(strcmp(recomandari[i].isbn,isbn)==0)
{
return false;
}
i++;
}
return true;
}
void recomandari_similare(int client_descriptor,char *isbn)
{
SugestieCarte recomandariSimilare[1000];
bzero(&recomandariSimilare,sizeof(recomandariSimilare));
char interogare[1000];
char username_similar[50];
char isbn_sugestie[20];
int nr_voturi;
QSqlQuery query;
QSqlQuery query_nrVoturi;
QSqlQuery query_isbn;
sprintf(interogare,"SELECT username FROM rating_utilizatori WHERE isbn = '%s'",isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la select usernames in recomandare:\n" << query.lastError();
}
while(query.next())
{
strcpy(username_similar,query.value(0).toString().toStdString().c_str());
sprintf(interogare,"SELECT isbn FROM rating_utilizatori WHERE username = '%s' AND isbn != '%s'",username_similar,isbn);
if(!query_isbn.exec(interogare)){
qDebug() << "Eroare la selectarea isbnurilor recomandarilor similare:\n" << query.lastError();
}
while(query_isbn.next())
{
strcpy(isbn_sugestie,query_isbn.value(0).toString().toStdString().c_str());
sprintf(interogare,"SELECT nr_voturi FROM rating WHERE isbn = '%s'",isbn_sugestie);
if(!query_nrVoturi.exec(interogare)){
qDebug() << "Eroare la selectarea isbnurilor recomandarilor similare:\n" << query.lastError();
}
query_nrVoturi.first();
nr_voturi = query_nrVoturi.value(0).toInt();
adauga_sugestie_noua(recomandariSimilare,isbn_sugestie,(double)nr_voturi);
}
}
int nr_recomandari = sortare_dupa_grad(recomandariSimilare);
int caz_recomandare_client = 2;
if(nr_recomandari < 5)
{
if(nr_recomandari == 0)
{
caz_recomandare_client = 1;
write(client_descriptor,&caz_recomandare_client,4);
recomanda_top_5_carti(client_descriptor);
}
else
{
write(client_descriptor,&caz_recomandare_client,4);
SugestieCarte topCarti[1000];
bzero(&topCarti,sizeof(topCarti));
int nr_top_recomandari = top_carti_dupa_rating(topCarti);
int i=0;
while(nr_recomandari<5 && i<nr_top_recomandari)
{
if(cartea_nu_a_fost_deja_adaugata(recomandariSimilare,topCarti[i].isbn))
{
recomandariSimilare[nr_recomandari] = topCarti[i];
nr_recomandari++;
}
i++;
}
trimite_recomandarile_clientului(client_descriptor,recomandariSimilare);
}
}
else
{
write(client_descriptor,&caz_recomandare_client,4);
trimite_recomandarile_clientului(client_descriptor,recomandariSimilare);
}
}
void trimite_recomandarile_clientului(int client_descriptor, SugestieCarte *recomandari)
{
QSqlQuery query;
char interogare[1000];
for(int i=0;i<5;i++)
{
if(write(client_descriptor,&recomandari[i].isbn,20)<=0){
perror("Eroare la scrierea isbnului in recomandare.\n");
}
sprintf(interogare,"SELECT coperta FROM carti WHERE isbn = '%s'",recomandari[i].isbn);
if(!query.exec(interogare)){
qDebug() << "Eroare la selectarea copertii cartii in recomandare:\n" << query.lastError();
}
query.first();
QByteArray outByteArray = query.value(0).toByteArray();
int dimens = (int)outByteArray.size();
if(write(client_descriptor,&dimens,4)<=0){
perror("Eroare la scrierea dimensiunii copertii in recomandare.\n");
}
char img_data[dimens];
for(int i=0;i<dimens;i++)
{
img_data[i]=outByteArray[i];
}
if(write(client_descriptor,&img_data,dimens)!=dimens){
perror("Eroare la scrierea copertii in recomandare.\n");
}
}
}
| [
"raresbabuta@gmail.com"
] | raresbabuta@gmail.com |
d4dcd077dcd08cdf5c50423f2e3b60ad7d724d90 | 2f85ea1b415b0a5b14c3f67a43bc7c8266c2d1b3 | /Bitmanipulation/clearallbit.cpp | 60d17ef0ab26b050bf191ab92ace6446566c6fe2 | [] | no_license | ratankumar19/Competitive-Programming | 960c565fcbf91c282bcfb0d8141ed85335985310 | d19f1678f4695b8057d619651a8c05310f212c5c | refs/heads/master | 2022-11-13T22:06:59.396406 | 2020-07-11T13:16:08 | 2020-07-11T13:16:08 | 278,863,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 287 | cpp | int clearAllBits(int n, int i){
/* Don't write main().
* Don't read input, it is passed as function argument.
* Return output and don't print it.
* Taking input and printing output is handled automatically.
*/
int mask= (1<<i)-1;
n=n&mask;
return n;
}
| [
"ratankumar086@gmail.com"
] | ratankumar086@gmail.com |
6094c04c1b4f7ff3716e230b238a20611bc1e4c7 | 9e882dab9db411cc1c24f3dc82c4eb734c956130 | /src/ParticlePhysics/MuonTomography/Hit.h | a5b071a15019092fc356cc541701379b5e16be93 | [] | no_license | OpenCMT/uLib | 8d4a2541fb60e596c07c139a151ae5cc2eb97931 | b7c775ee3510296b7cc1a29de3f5443ce518a68d | refs/heads/master | 2023-04-09T14:04:22.232237 | 2023-02-22T10:20:56 | 2023-02-22T10:20:56 | 36,926,725 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,630 | h | /*//////////////////////////////////////////////////////////////////////////////
// CMT Cosmic Muon Tomography project //////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
Copyright (c) 2014, Universita' degli Studi di Padova, INFN sez. di Padova
All rights reserved
Authors: Andrea Rigoni Garola < andrea.rigoni@pd.infn.it >
------------------------------------------------------------------
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.
//////////////////////////////////////////////////////////////////////////////*/
#ifndef U_PPMUTOM_HIT_H
#define U_PPMUTOM_HIT_H
#include <Core/Types.h>
#include <Math/Dense.h>
namespace uLib {
template <typename Type, typename Code>
class Hit {
Code m_Code;
Type m_DriftTime;
};
class HitMC {
public:
virtual Id_t GetChamber() = 0;
virtual Vector3f GetPosition() = 0;
virtual Scalarf GetDritfTime() = 0;
protected:
virtual ~HitMC() {}
};
} // uLib
#endif // HIT_H
| [
"andrea.rigoni@pd.infn.it"
] | andrea.rigoni@pd.infn.it |
cc6946f0915aa96352d543d8ceac5e5067e33945 | 4feaaccdbd7359309f348a066ade183c2994449f | /strategy/strategy.cpp | 6d3bcce7c5bd78c5c7153a42443d6556bc1d637b | [] | no_license | sirjofri/patterns | 8c0d07fb0750c09008853f0c9093c087fe1411a2 | be0908a9ce0c0709ec844fd4a346e04d7d8e5aae | refs/heads/master | 2020-03-08T09:22:49.373068 | 2018-04-04T11:22:51 | 2018-04-04T11:22:51 | 128,045,716 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,206 | cpp | #include "strategy.h"
#include <iostream>
#include <sstream>
std::string Strategy::getStr(std::string in)
{
return "No Strategy!";
}
int Strategy::str()
{
return -1;
}
std::string AStrategy::getStr(std::string in)
{
std::ostringstream ret;
ret << "Strategy A: " << in << ":";
return ret.str();
}
int AStrategy::str()
{
return 1;
}
std::string BStrategy::getStr(std::string in)
{
std::ostringstream ret;
ret << "Strategy B: " << in << ":";
return ret.str();
}
int BStrategy::str()
{
return 2;
}
Entity::Entity(Strategy *s)
: strategy(s)
{}
std::string Entity::getStrategy()
{
std::ostringstream ret;
ret << "Current Strategy: " << strategy->getStr("Test String");
return ret.str();
}
int Entity::str()
{
return strategy->str();
}
int main(int argc, char **argv)
{
Strategy *a_str = new AStrategy();
Strategy *b_str = new BStrategy();
Entity *e_a = new Entity(a_str);
Entity *e_b = new Entity(b_str);
std::cout << "Entity with Strategy A:\n\t" << e_a->getStrategy() << std::endl;
std::cout << "Entity with Strategy B:\n\t" << e_b->getStrategy() << std::endl;
int e_a_str = e_a->str();
int e_b_str = e_b->str();
if(e_a_str != 1 && e_b_str != 2)
return 1;
return 0;
}
| [
"sirjofri@gmx.de"
] | sirjofri@gmx.de |
3df6c4edd068d49ee25386a20c261446f8034967 | f3a316a2f25b37793e1741295d7e932e3d8e7c09 | /source/common/simpleformatter.cpp | ae17a0500518a892e7588f2ee3299c664cb9c56b | [
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"NAIST-2003",
"BSD-3-Clause",
"LicenseRef-scancode-unicode",
"ICU",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | CdTCzech/ICU | 3cb59891b9efcbcfa5fb6e75d394d666561650a3 | 4c9b8dfefd9a26096f7642c556fa3b4bd887317e | refs/heads/master | 2023-03-01T19:23:09.347544 | 2021-02-09T13:01:11 | 2021-02-09T13:01:11 | 257,857,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,246 | cpp | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
******************************************************************************
* Copyright (C) 2014-2016, International Business Machines
* Corporation and others. All Rights Reserved.
******************************************************************************
* simpleformatter.cpp
*/
#include "unicode/utypes.h"
#include "unicode/simpleformatter.h"
#include "unicode/unistr.h"
#include "uassert.h"
U_NAMESPACE_BEGIN
namespace {
/**
* Argument numbers must be smaller than this limit.
* Text segment lengths are offset by this much.
* This is currently the only unused char value in compiled patterns,
* except it is the maximum value of the first unit (max arg +1).
*/
const int32_t ARG_NUM_LIMIT = 0x100;
/**
* Initial and maximum char/UChar value set for a text segment.
* Segment length char values are from ARG_NUM_LIMIT+1 to this value here.
* Normally 0xffff, but can be as small as ARG_NUM_LIMIT+1 for testing.
*/
const UChar SEGMENT_LENGTH_PLACEHOLDER_CHAR = 0xffff;
/**
* Maximum length of a text segment. Longer segments are split into shorter ones.
*/
const int32_t MAX_SEGMENT_LENGTH = SEGMENT_LENGTH_PLACEHOLDER_CHAR - ARG_NUM_LIMIT;
enum {
APOS = 0x27,
DIGIT_ZERO = 0x30,
DIGIT_ONE = 0x31,
DIGIT_NINE = 0x39,
OPEN_BRACE = 0x7b,
CLOSE_BRACE = 0x7d
};
inline UBool isInvalidArray(const void *array, int32_t length) {
return (length < 0 || (array == NULL && length != 0));
}
} // namespace
SimpleFormatter &SimpleFormatter::operator=(const SimpleFormatter& other) {
if (this == &other) {
return *this;
}
compiledPattern = other.compiledPattern;
return *this;
}
SimpleFormatter::~SimpleFormatter() {}
UBool SimpleFormatter::applyPatternMinMaxArguments(
const UnicodeString &pattern,
int32_t min, int32_t max,
UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) {
return FALSE;
}
// Parse consistent with MessagePattern, but
// - support only simple numbered arguments
// - build a simple binary structure into the result string
const UChar *patternBuffer = pattern.getBuffer();
int32_t patternLength = pattern.length();
// Reserve the first char for the number of arguments.
compiledPattern.setTo((UChar)0);
int32_t textLength = 0;
int32_t maxArg = -1;
UBool inQuote = FALSE;
for (int32_t i = 0; i < patternLength;) {
UChar c = patternBuffer[i++];
if (c == APOS) {
if (i < patternLength && (c = patternBuffer[i]) == APOS) {
// double apostrophe, skip the second one
++i;
} else if (inQuote) {
// skip the quote-ending apostrophe
inQuote = FALSE;
continue;
} else if (c == OPEN_BRACE || c == CLOSE_BRACE) {
// Skip the quote-starting apostrophe, find the end of the quoted literal text.
++i;
inQuote = TRUE;
} else {
// The apostrophe is part of literal text.
c = APOS;
}
} else if (!inQuote && c == OPEN_BRACE) {
if (textLength > 0) {
compiledPattern.setCharAt(compiledPattern.length() - textLength - 1,
(UChar)(ARG_NUM_LIMIT + textLength));
textLength = 0;
}
int32_t argNumber;
if ((i + 1) < patternLength &&
0 <= (argNumber = patternBuffer[i] - DIGIT_ZERO) && argNumber <= 9 &&
patternBuffer[i + 1] == CLOSE_BRACE) {
i += 2;
} else {
// Multi-digit argument number (no leading zero) or syntax error.
// MessagePattern permits PatternProps.skipWhiteSpace(pattern, index)
// around the number, but this class does not.
argNumber = -1;
if (i < patternLength && DIGIT_ONE <= (c = patternBuffer[i++]) && c <= DIGIT_NINE) {
argNumber = c - DIGIT_ZERO;
while (i < patternLength &&
DIGIT_ZERO <= (c = patternBuffer[i++]) && c <= DIGIT_NINE) {
argNumber = argNumber * 10 + (c - DIGIT_ZERO);
if (argNumber >= ARG_NUM_LIMIT) {
break;
}
}
}
if (argNumber < 0 || c != CLOSE_BRACE) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return FALSE;
}
}
if (argNumber > maxArg) {
maxArg = argNumber;
}
compiledPattern.append((UChar)argNumber);
continue;
} // else: c is part of literal text
// Append c and track the literal-text segment length.
if (textLength == 0) {
// Reserve a char for the length of a new text segment, preset the maximum length.
compiledPattern.append(SEGMENT_LENGTH_PLACEHOLDER_CHAR);
}
compiledPattern.append(c);
if (++textLength == MAX_SEGMENT_LENGTH) {
textLength = 0;
}
}
if (textLength > 0) {
compiledPattern.setCharAt(compiledPattern.length() - textLength - 1,
(UChar)(ARG_NUM_LIMIT + textLength));
}
int32_t argCount = maxArg + 1;
if (argCount < min || max < argCount) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return FALSE;
}
compiledPattern.setCharAt(0, (UChar)argCount);
return TRUE;
}
UnicodeString& SimpleFormatter::format(
const UnicodeString &value0,
UnicodeString &appendTo, UErrorCode &errorCode) const {
const UnicodeString *values[] = { &value0 };
return formatAndAppend(values, 1, appendTo, NULL, 0, errorCode);
}
UnicodeString& SimpleFormatter::format(
const UnicodeString &value0,
const UnicodeString &value1,
UnicodeString &appendTo, UErrorCode &errorCode) const {
const UnicodeString *values[] = { &value0, &value1 };
return formatAndAppend(values, 2, appendTo, NULL, 0, errorCode);
}
UnicodeString& SimpleFormatter::format(
const UnicodeString &value0,
const UnicodeString &value1,
const UnicodeString &value2,
UnicodeString &appendTo, UErrorCode &errorCode) const {
const UnicodeString *values[] = { &value0, &value1, &value2 };
return formatAndAppend(values, 3, appendTo, NULL, 0, errorCode);
}
UnicodeString& SimpleFormatter::formatAndAppend(
const UnicodeString *const *values, int32_t valuesLength,
UnicodeString &appendTo,
int32_t *offsets, int32_t offsetsLength, UErrorCode &errorCode) const {
if (U_FAILURE(errorCode)) {
return appendTo;
}
if (isInvalidArray(values, valuesLength) || isInvalidArray(offsets, offsetsLength) ||
valuesLength < getArgumentLimit()) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return appendTo;
}
return format(compiledPattern.getBuffer(), compiledPattern.length(), values,
appendTo, NULL, TRUE,
offsets, offsetsLength, errorCode);
}
UnicodeString &SimpleFormatter::formatAndReplace(
const UnicodeString *const *values, int32_t valuesLength,
UnicodeString &result,
int32_t *offsets, int32_t offsetsLength, UErrorCode &errorCode) const {
if (U_FAILURE(errorCode)) {
return result;
}
if (isInvalidArray(values, valuesLength) || isInvalidArray(offsets, offsetsLength)) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return result;
}
const UChar *cp = compiledPattern.getBuffer();
int32_t cpLength = compiledPattern.length();
if (valuesLength < getArgumentLimit(cp, cpLength)) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return result;
}
// If the pattern starts with an argument whose value is the same object
// as the result, then we keep the result contents and append to it.
// Otherwise we replace its contents.
int32_t firstArg = -1;
// If any non-initial argument value is the same object as the result,
// then we first copy its contents and use that instead while formatting.
UnicodeString resultCopy;
if (getArgumentLimit(cp, cpLength) > 0) {
for (int32_t i = 1; i < cpLength;) {
int32_t n = cp[i++];
if (n < ARG_NUM_LIMIT) {
if (values[n] == &result) {
if (i == 2) {
firstArg = n;
} else if (resultCopy.isEmpty() && !result.isEmpty()) {
resultCopy = result;
}
}
} else {
i += n - ARG_NUM_LIMIT;
}
}
}
if (firstArg < 0) {
result.remove();
}
return format(cp, cpLength, values,
result, &resultCopy, FALSE,
offsets, offsetsLength, errorCode);
}
UnicodeString SimpleFormatter::getTextWithNoArguments(
const UChar *compiledPattern,
int32_t compiledPatternLength,
int32_t* offsets,
int32_t offsetsLength) {
for (int32_t i = 0; i < offsetsLength; i++) {
offsets[i] = -1;
}
int32_t capacity = compiledPatternLength - 1 -
getArgumentLimit(compiledPattern, compiledPatternLength);
UnicodeString sb(capacity, 0, 0); // Java: StringBuilder
for (int32_t i = 1; i < compiledPatternLength;) {
int32_t n = compiledPattern[i++];
if (n > ARG_NUM_LIMIT) {
n -= ARG_NUM_LIMIT;
sb.append(compiledPattern + i, n);
i += n;
} else if (n < offsetsLength) {
// TODO(ICU-20406): This does not distinguish between "{0}{1}" and "{1}{0}".
// Consider removing this function and replacing it with an iterator interface.
offsets[n] = sb.length();
}
}
return sb;
}
UnicodeString &SimpleFormatter::format(
const UChar *compiledPattern, int32_t compiledPatternLength,
const UnicodeString *const *values,
UnicodeString &result, const UnicodeString *resultCopy, UBool forbidResultAsValue,
int32_t *offsets, int32_t offsetsLength,
UErrorCode &errorCode) {
if (U_FAILURE(errorCode)) {
return result;
}
for (int32_t i = 0; i < offsetsLength; i++) {
offsets[i] = -1;
}
for (int32_t i = 1; i < compiledPatternLength;) {
int32_t n = compiledPattern[i++];
if (n < ARG_NUM_LIMIT) {
const UnicodeString *value = values[n];
if (value == NULL) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return result;
}
if (value == &result) {
if (forbidResultAsValue) {
errorCode = U_ILLEGAL_ARGUMENT_ERROR;
return result;
}
if (i == 2) {
// We are appending to result which is also the first value object.
if (n < offsetsLength) {
offsets[n] = 0;
}
} else {
if (n < offsetsLength) {
offsets[n] = result.length();
}
result.append(*resultCopy);
}
} else {
if (n < offsetsLength) {
offsets[n] = result.length();
}
result.append(*value);
}
} else {
int32_t length = n - ARG_NUM_LIMIT;
result.append(compiledPattern + i, length);
i += length;
}
}
return result;
}
U_NAMESPACE_END
| [
"hrncirmirek@outlook.com"
] | hrncirmirek@outlook.com |
bd24e1838c561918013176d649610cc4092098e0 | edff53877fe160f6f5176c32c40fd42a08e7fb95 | /d01/ex06/HumanB.hpp | 49bce3795a25ac69d2c9b842c9b3d91e4fb1ee96 | [] | no_license | brockcheese/piscine_cpp | 52ceb30dce80dc83d503a29a31fc979fe071085e | 056877decab3606c61018ae9ada39e77b56a7bf4 | refs/heads/master | 2023-01-13T22:04:29.159560 | 2020-11-09T02:53:07 | 2020-11-09T02:53:07 | 295,583,532 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 176 | hpp | #include "HumanA.hpp"
class HumanB {
std::string _name;
Weapon* _weapon;
public:
HumanB(std::string name);
~HumanB();
void setWeapon(Weapon& weapon);
void attack();
};
| [
"bpace@e1z1r3p21.42.us.org"
] | bpace@e1z1r3p21.42.us.org |
7f33e43d78ed28a2063adc7bda8920f31b67abb2 | 31d6eddaa5c6b62a7591fe29578ceb537cd7d40f | /pub/Publisher.cpp | 7347dd0fec0cab4bb11541a2d02d0f01c252be85 | [] | no_license | StudyforLife/MyIce | 091a66ccddcb37a3967f3a87e276ad263e2cf34f | 7e848afad5cafd2c220ecac27cb3ec656325d0eb | refs/heads/master | 2020-04-11T02:51:38.891815 | 2018-12-16T10:48:01 | 2018-12-16T10:48:01 | 161,458,988 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,541 | cpp | #include<iostream>
#include<IceStorm/IceStorm.h>
#include<Ice/Ice.h>
#include<sstream>
#include<vector>
#include<time.h>
#include<cstdio>
#include<sys/types.h>
#include<sys/stat.h>
#include"Station.h"
using namespace std;
using namespace StationDemo;
myTopicList create_topic()
{
myTopicList m;
int size=100;
stringstream ss;
m.reserve(size);
for(int i=1;i<=size;i++)
{
ss<<i;
string s="主题"+ss.str();
m.push_back(s);
ss.clear();
ss.str("");
}
return m;
}
vector<int> create_Data(myTopicList m)
{
vector<int> v;
int sum=0;
for(int i=1;i<=m.size();i++)
{
sum+=i;
v.push_back(sum);
}
return v;
}
int main(int argc,char* argv[])
{
myTopicList m=create_topic();
Ice::CommunicatorPtr ic;
//读取配置文件
Ice::InitializationData initData;
initData.properties=Ice::createProperties();
initData.properties->load("Config/config.client");
ic=Ice::initialize(initData);
Ice::ObjectPrx obj=ic->propertyToProxy("client.proxy");
/*
//直接初始化
ic=Ice::initialize();
Ice::ObjectPrx obj=ic->stringToProxy("StationTest/TopicManager:default -h localhost -p 9999");*/
IceStorm::TopicManagerPrx topicManager=IceStorm::TopicManagerPrx::checkedCast(obj);
//存储主题代理
IceStorm::TopicPrx TopicList[m.size()];
for(int i=0;i<m.size();i++)
{
try{
TopicList[i]=topicManager->retrieve(m[i]);
}catch(const IceStorm::NoSuchTopic&){
try{
TopicList[i]=topicManager->create(m[i]);
}catch(const IceStorm::TopicExists&){
//error
}
}
}
StationMessagePrx station[m.size()];
for(int j=0;j<m.size();j++)
{
Ice::ObjectPrx pub=TopicList[j]->getPublisher();
station[j]=StationMessagePrx::uncheckedCast(pub);
}
//操作调用
time_t t;
char str[255]={};
vector<int> v1=create_Data(m);
Message msg;
stringstream ss;
msg.flag=0;
while(true)
{
msg.flag+=1;
for(int i=0;i<m.size();i++)
{
time(&t);
tm* p=localtime(&t);
sprintf(str,"%4d/%d/%d-%d:%d:%d",p->tm_year+1900,\
p->tm_mon+1,p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);
string message="江陵路-近江-远江-边疆-新疆-下沙-上沙-中沙-自定义消息";
msg.tpName=m[i];
ss<<v1[i];
msg.data=ss.str()+": "+message;
ss.clear();
ss.str("");
msg.time=str;
int size1=msg.data.length()+msg.tpName.length()+msg.time.length();
cout<<"数据大小:"<<size1<<endl;
station[i]->getMsg(msg);
usleep(30000);
//sleep(5);
}
cout<<"flag: "<<msg.flag<<endl;
while(msg.flag>=1000)
{
msg.flag=0;
}
}
if(ic)
ic->destroy();
}
| [
"840431307@qq.com"
] | 840431307@qq.com |
b2ba115e0b7acba4127081a54a81adb38a0192c9 | e431a1685ace7e541da641d9005195db89cb1b6f | /10_v1.cpp | 33f34f5c670deef562caddedaf2e1ba5ced688ed | [] | no_license | jianminchen/LeetCode-17 | 7f82230be3510fdfb60847bcee521e6796b33ea9 | 68080d07819bf81823a0c9d25ec84f2a19d422a6 | refs/heads/master | 2021-01-19T07:07:30.481800 | 2016-07-17T08:08:56 | 2016-07-17T08:08:56 | 67,087,459 | 1 | 0 | null | 2016-09-01T01:35:35 | 2016-09-01T01:35:34 | null | UTF-8 | C++ | false | false | 1,343 | cpp | /*
10_v1.cpp
Regular Expression Matching
My first submission got WA because I forgot to initialize the f array as
false. I don't quite understand why my second submission got WA since I
believe bool f[lenS + 1][lenP + 1] = {false} should have already initialized
all values of f.
Turns out this is incorrect. Basically "int f[100] = {0}" would zero out the
whole array but "int f[n] = {0}" would not. In fact VS cannot even compile
this.
*/
class Solution {
bool isCharMatch(char s, char p) { return s == p || p == '.'; }
public:
bool isMatch(string s, string p) {
int lenS = s.size(), lenP = p.size();
bool f[lenS + 1][lenP + 1] = {false};
f[0][0] = true;
bool flag = true;
for (int i = 1; i <= lenP; i++) {
if (p[i - 1] != '*' && (i < lenP && p[i] != '*')) flag = false;
if (flag && p[i - 1] == '*')
f[0][i] = true;
else
f[0][i] = false;
}
for (int i = 1; i <= lenS; i++) {
for (int j = 1; j <= lenP; j++) {
char sc = s[i - 1], sp = p[j - 1];
if (sp != '*') {
if (isCharMatch(sc, sp))
f[i][j] = f[i - 1][j - 1];
else
f[i][j] = false;
} else {
f[i][j] = f[i][j - 2] || (f[i - 1][j] && isCharMatch(sc, p[j - 2]));
}
}
}
return f[lenS][lenP];
}
}; | [
"phoenixinter@gmail.com"
] | phoenixinter@gmail.com |
85668a7d828245ac86bc3f22ba7d15e298300ba1 | 539bff0ab3912fc0b570ff09a94562f3815079ba | /board.cpp | f97af3a845ea354e7a81ed5cc2d5613bdd218bd6 | [
"Apache-2.0"
] | permissive | volkertb/4steps | 78cea28a3435c21973457cb875305f1be29f0817 | ce3c04790a15847783130e7340f0f1c2b57991a7 | refs/heads/master | 2022-04-26T14:28:00.822943 | 2022-01-05T01:10:09 | 2022-01-05T01:12:15 | 120,374,551 | 0 | 0 | null | 2018-02-05T23:18:51 | 2018-02-05T23:18:51 | null | UTF-8 | C++ | false | false | 35,664 | cpp | #include <QMouseEvent>
#include <QToolTip>
#include <QPainter>
#include "board.hpp"
#include "globals.hpp"
#include "messagebox.hpp"
#include "io.hpp"
#include "palette.hpp"
Board::Board(Globals& globals_,NodePtr currentNode_,const bool explore_,const Side viewpoint,const bool soundOn,const std::array<bool,NUM_SIDES>& controllableSides_,const TurnState* const customSetup_,QWidget* const parent,const Qt::WindowFlags f) :
QWidget(parent,f),
explore(explore_),
southIsUp(viewpoint==SECOND_SIDE),
currentNode(currentNode_),
globals(globals_),
potentialSetup(customSetup_==nullptr ? GameState() : GameState(*customSetup_)),
controllableSides(controllableSides_),
autoRotate(false),
drag{NO_SQUARE,NO_SQUARE},
colorKeys{"regular",
"goal_south",
"goal_north",
"trap_south",
"trap_north",
"highlight_light",
"highlight_dark",
"highlight_mild_light",
"highlight_mild_dark",
"alternative",
"goal_south_alternative",
"goal_north_alternative",
"trap_south_alternative",
"trap_north_alternative",
"highlight_light_alternative",
"highlight_dark_alternative",
"highlight_mild_light_alternative",
"highlight_mild_dark_alternative"}
{
fill(customColors,REGULAR);
setContextMenuPolicy(Qt::NoContextMenu);
qMediaPlayer.setPlaylist(&qMediaPlaylist);
toggleSound(soundOn);
if (!customSetup())
initSetup();
globals.settings.beginGroup("Board");
const auto stepMode=globals.settings.value("step_mode").toBool();
const auto iconSet=static_cast<PieceIcons::Set>(globals.settings.value("icon_set",PieceIcons::VECTOR).toInt());
const auto coordinateDisplay=static_cast<CoordinateDisplay>(globals.settings.value("coordinate_display",TRAPS_ONLY).toInt());
const auto animate=globals.settings.value("animate",true).toBool();
const auto animationDelay=globals.settings.value("animation_delay",375).toInt();
const auto volume=globals.settings.value("volume",100).toInt();
const auto confirm=globals.settings.value("confirm",true).toBool();
globals.settings.endGroup();
globals.settings.beginGroup("Colors");
const QString defaultMainColors[2]={"#89657B","#C92D0C"};
const QString defaultTrapColors[NUM_SIDES]={"#F66610","#4200F2"};
const QString defaultHighLightColors[NUM_SIDES]={"#FFFFFF","#000000"};
const QString defaultMildHighLightColors[NUM_SIDES]={"#C9C9C9","#232323"};
const QString defaultColors[NUM_SQUARE_COLORS]={
defaultMainColors[0],
defaultMainColors[0],
defaultMainColors[0],
defaultTrapColors[FIRST_SIDE],
defaultTrapColors[SECOND_SIDE],
defaultHighLightColors[FIRST_SIDE],
defaultHighLightColors[SECOND_SIDE],
defaultMildHighLightColors[FIRST_SIDE],
defaultMildHighLightColors[SECOND_SIDE],
defaultMainColors[1],
defaultMainColors[1],
defaultMainColors[1],
defaultTrapColors[FIRST_SIDE],
defaultTrapColors[SECOND_SIDE],
defaultHighLightColors[FIRST_SIDE],
defaultHighLightColors[SECOND_SIDE],
defaultMildHighLightColors[FIRST_SIDE],
defaultMildHighLightColors[SECOND_SIDE],
};
QColor colors[NUM_SQUARE_COLORS];
for (unsigned int colorIndex=0;colorIndex<Board::NUM_SQUARE_COLORS;++colorIndex)
colors[colorIndex]=globals.settings.value(colorKeys[colorIndex],defaultColors[colorIndex]).toString();
globals.settings.endGroup();
setStepMode(stepMode);
setIconSet(iconSet);
setCoordinateDisplay(coordinateDisplay);
setAnimate(animate);
setAnimationDelay(animationDelay);
setVolume(volume);
setConfirm(confirm);
for (unsigned int colorIndex=0;colorIndex<Board::NUM_SQUARE_COLORS;++colorIndex)
setColor(colorIndex,colors[colorIndex]);
connect(this,&Board::boardChanged,this,[this](const bool refresh) {
if (refresh)
refreshHighlights(true);
});
connect(this,&Board::boardChanged,this,static_cast<void (Board::*)()>(&Board::update));
connect(&animationTimer,&QTimer::timeout,this,&Board::animateNextStep);
}
bool Board::customSetup() const
{
return currentNode.get()==nullptr;
}
bool Board::setupPhase() const
{
return customSetup() || currentNode->inSetup();
}
bool Board::setupPlacementPhase() const
{
return !customSetup() && currentNode->inSetup() && currentSetupPiece>FIRST_PIECE_TYPE;
}
Side Board::sideToMove() const
{
return customSetup() ? potentialSetup.sideToMove : currentNode->gameState.sideToMove;
}
const GameState& Board::gameState() const
{
return setupPhase() ? potentialSetup :
(potentialMove.get().empty() ? currentNode->gameState : std::get<RESULTING_STATE>(potentialMove.get().back()));
}
const GameState& Board::displayedGameState() const
{
if (isAnimating()) {
const auto& previousNode=currentNode->previousNode;
assert(previousNode!=nullptr);
const auto& previousMove=currentNode->move;
if (nextAnimatedStep==previousMove.begin())
return previousNode->gameState;
else
return std::get<RESULTING_STATE>(*--decltype(nextAnimatedStep)(nextAnimatedStep));
}
else
return gameState();
}
Placements Board::currentPlacements() const
{
return gameState().placements(sideToMove());
}
std::pair<Placements,ExtendedSteps> Board::tentativeMove() const
{
std::pair<Placements,ExtendedSteps> result;
if (setupPhase())
result.first=currentPlacements();
else
result.second=potentialMove.get().current();
return result;
}
std::string Board::tentativeMoveString() const
{
if (setupPhase())
return toString(currentPlacements());
else
return toString(potentialMove.get().current());
}
bool Board::gameEnd() const
{
return !customSetup() && currentNode->result.endCondition!=NO_END;
}
bool Board::playable() const
{
return !gameEnd() && (explore || controllableSides[sideToMove()]);
}
bool Board::setNode(NodePtr newNode,const bool silent,bool keepState)
{
keepState&=(newNode==currentNode.get());
const bool transition=(newNode->previousNode==currentNode.get() && potentialMove.data.empty());
currentNode=std::move(newNode);
if (!keepState || !silent)
disableAnimation();
if (!silent && currentNode->previousNode!=nullptr) {
if (currentNode->previousNode->inSetup())
playSound("qrc:/finished-setup.wav");
else if (animate)
animateMove(!transition);
else
playStepSounds(currentNode->move,true);
}
if (!keepState) {
endDrag();
if (setupPhase())
initSetup();
else
potentialMove.data.clear();
}
if (autoRotate)
setViewpoint(sideToMove());
emit boardChanged();
return !keepState;
}
void Board::playMoveSounds(const Node& node)
{
if (node.previousNode!=nullptr) {
if (node.previousNode->inSetup())
playSound("qrc:/finished-setup.wav");
else
playStepSounds(node.move,true);
}
}
void Board::proposeMove(const Node& child,const unsigned int playedOutSteps)
{
if (currentNode->inSetup())
proposeSetup(child);
else {
const auto& move=child.move;
doSteps(move,false,move.size()-playedOutSteps);
}
}
void Board::proposeCustomSetup(const TurnState& turnState)
{
assert(customSetup());
endDrag();
potentialSetup.sideToMove=turnState.sideToMove;
potentialSetup.squarePieces=turnState.squarePieces;
emit boardChanged();
}
bool Board::proposeSetup(const Placements& placements)
{
if (playable()) {
endDrag();
if (!customSetup())
clearSetup();
potentialSetup.add(placements);
if (customSetup() || !nextSetupPiece(false))
emit boardChanged();
return true;
}
else
return false;
}
void Board::proposeSetup(const Node& child)
{
if (proposeSetup(child.playedPlacements())) {
assert(potentialSetup.sideToMove!=child.gameState.sideToMove);
assert(potentialSetup.squarePieces==child.gameState.squarePieces);
}
}
void Board::doSteps(const ExtendedSteps& steps,const bool sound,const int undoneSteps)
{
const bool updated=(int(steps.size())!=undoneSteps);
if (!steps.empty() && (playable() || !updated)) {
potentialMove.data.append(steps);
potentialMove.data.shiftEnd(-undoneSteps);
if (sound && !explore)
playStepSounds(steps,false);
if (updated)
endDrag();
if (!autoFinalize(true) && updated)
emit boardChanged();
}
}
void Board::undoSteps(const bool all)
{
bool updated=potentialMove.data.shiftEnd(false,all);
if (explore && !updated && currentNode->previousNode!=nullptr) {
const auto oldNode=currentNode;
setNode(currentNode->previousNode);
if (!all) {
if (currentNode->inSetup())
proposeSetup(*oldNode.get());
else {
const auto& move=oldNode->move;
doSteps(move,false,move.size()==MAX_STEPS_PER_MOVE ? 1 : 0);
}
}
updated=true;
}
if (updated) {
endDrag();
emit boardChanged();
}
}
void Board::redoSteps(const bool all)
{
if (playable()) {
const bool updated=potentialMove.data.shiftEnd(true,all);
if (updated)
endDrag();
if (!autoFinalize(updated) && updated)
emit boardChanged();
}
}
void Board::redoSteps(const ExtendedSteps& steps)
{
if (playable()) {
potentialMove.data.set(steps,steps.size());
endDrag();
if (!autoFinalize(true))
emit boardChanged();
}
}
void Board::animateMove(const bool showStart)
{
if (customSetup() || currentNode->isGameStart())
return;
else if (currentNode->move.empty())
playSound("qrc:/finished-setup.wav");
else {
qMediaPlaylist.clear();
const auto& previousMove=currentNode->move;
nextAnimatedStep=previousMove.begin();
assert(nextAnimatedStep!=previousMove.end());
if (showStart) {
animationTimer.start();
update();
}
else
animateNextStep();
}
}
void Board::rotate()
{
southIsUp=!southIsUp;
refreshHighlights(false);
update();
emit boardRotated(southIsUp);
}
void Board::setViewpoint(const Side side)
{
if ((side==SECOND_SIDE)!=southIsUp)
rotate();
}
void Board::setAutoRotate(const bool on)
{
if (on) {
autoRotate=true;
setViewpoint(sideToMove());
}
else
autoRotate=false;
}
void Board::toggleSound(const bool soundOn_)
{
soundOn=soundOn_;
if (!soundOn)
qMediaPlayer.stop();
}
void Board::setStepMode(const bool newStepMode)
{
setSetting(stepMode,newStepMode,"step_mode");
setMouseTracking(stepMode);
if (refreshHighlights(true))
update();
}
void Board::setIconSet(const PieceIcons::Set newIconSet)
{
if (setSetting(iconSet,newIconSet,"icon_set"))
update();
}
void Board::setCoordinateDisplay(const CoordinateDisplay newCoordinateDisplay)
{
if (setSetting(coordinateDisplay,newCoordinateDisplay,"coordinate_display"))
update();
}
void Board::setAnimate(const bool newAnimate)
{
setSetting(animate,newAnimate,"animate");
}
void Board::setAnimationDelay(const int newAnimationDelay)
{
if (setSetting(animationDelay,newAnimationDelay,"animation_delay"))
animationTimer.setInterval(animationDelay);
}
void Board::setVolume(const int newVolume)
{
if (setSetting(volume,newVolume,"volume"))
qMediaPlayer.setVolume(newVolume);
}
void Board::setConfirm(const bool newConfirm)
{
setSetting(confirm,newConfirm,"confirm");
}
void Board::setColor(const unsigned int colorIndex,const QColor& newColor)
{
auto& currentColor=colors[colorIndex];
if (newColor!=currentColor.data) {
currentColor=newColor;
globals.settings.beginGroup("Colors");
globals.settings.setValue(colorKeys[colorIndex],newColor.name());
globals.settings.endGroup();
update();
}
}
void Board::playSound(const QString& soundFile,const bool override)
{
if (soundOn || override) {
qMediaPlaylist.clear();
qMediaPlaylist.addMedia(QUrl(soundFile));
qMediaPlayer.play();
}
}
void Board::setExploration(const bool on)
{
explore=on;
if (on)
autoFinalize(false);
else if (!playable()) {
endDrag();
undoSteps(true);
}
update();
}
void Board::setControllable(const std::array<bool,NUM_SIDES>& controllableSides_)
{
controllableSides=controllableSides_;
if (playable())
update();
else
endDrag();
}
int Board::squareWidth() const
{
return width()/NUM_FILES;
}
int Board::squareHeight() const
{
return height()/NUM_RANKS;
}
void Board::normalizeOrientation(unsigned int& file,unsigned int& rank) const
{
if (southIsUp)
file=NUM_FILES-1-file;
else
rank=NUM_RANKS-1-rank;
}
QRect Board::visualRectangle(unsigned int file,unsigned int rank) const
{
normalizeOrientation(file,rank);
return QRect(file*squareWidth(),rank*squareHeight(),squareWidth(),squareHeight());
}
SquareIndex Board::orientedSquare(unsigned int file,unsigned int rank) const
{
if (isValidSquare(file,rank)) {
normalizeOrientation(file,rank);
return toSquare(file,rank);
}
else
return NO_SQUARE;
}
SquareIndex Board::positionToSquare(const QPoint& position) const
{
const int file=floorDiv(position.x(),squareWidth());
const int rank=floorDiv(position.y(),squareHeight());
return orientedSquare(file,rank);
}
int Board::closestAxisDirection(unsigned int value,const unsigned int size)
{
value*=2;
if (value<size)
return -1;
else if (value>size)
return 1;
else
return 0;
}
SquareIndex Board::closestAdjacentSquare(const QPoint& position) const
{
const int file=floorDiv(position.x(),squareWidth());
const int rank=floorDiv(position.y(),squareHeight());
const int localX=position.x()%squareWidth();
const int localY=position.y()%squareHeight();
const int widthDirection=(file==0 ? 1 : (file==NUM_FILES-1 ? -1 : closestAxisDirection(localX,squareWidth())));
const int heightDirection=(rank==0 ? 1 : (rank==NUM_RANKS-1 ? -1 : closestAxisDirection(localY,squareHeight())));
const int distanceX=( widthDirection==1) ? squareWidth() -localX : localX;
const int distanceY=(heightDirection==1) ? squareHeight()-localY : localY;
const int diffDistance=distanceX*squareHeight()-distanceY*squareWidth();
if (diffDistance<0) {
if (widthDirection!=0)
return orientedSquare(file+widthDirection,rank);
}
else if (diffDistance>0)
if (heightDirection!=0)
return orientedSquare(file,rank+heightDirection);
return NO_SQUARE;
}
bool Board::isSetupSquare(const Side side,const SquareIndex square) const
{
return customSetup() ? square!=NO_SQUARE : ::isSetupSquare(side,square);
}
bool Board::validDrop() const
{
return setupPhase() ? (isSetupSquare(sideToMove(),drag[DESTINATION]) && drag[ORIGIN]!=drag[DESTINATION]) : !dragSteps.empty();
}
bool Board::isAnimating() const
{
return animationTimer.isActive();
}
template<class Type>
bool Board::setSetting(readonly<Board,Type>& currentValue,const Type newValue,const QString& key)
{
if (currentValue==newValue)
return false;
else {
currentValue=newValue;
globals.settings.beginGroup("Board");
globals.settings.setValue(key,currentValue.get());
globals.settings.endGroup();
return true;
}
}
void Board::clearSetup()
{
potentialSetup=currentNode->gameState;
for (SquareIndex square=FIRST_SQUARE;square<NUM_SQUARES;increment(square))
if (isSetupSquare(sideToMove(),square))
potentialSetup.squarePieces[square]=NO_PIECE;
}
void Board::initSetup()
{
clearSetup();
nextSetupPiece();
}
bool Board::nextSetupPiece(const bool finalize)
{
std::array<unsigned int,NUM_PIECE_TYPES> numPiecesPerType=numStartingPiecesPerType;
for (SquareIndex square=FIRST_SQUARE;square<NUM_SQUARES;increment(square)) {
const PieceTypeAndSide squarePiece=potentialSetup.squarePieces[square];
if (squarePiece!=NO_PIECE && isSetupSquare(sideToMove(),square)) {
assert(isSide(squarePiece,sideToMove()));
--numPiecesPerType[toPieceType(squarePiece)];
}
}
currentSetupPiece=static_cast<PieceType>(NUM_PIECE_TYPES-1);
for (auto numPiecesIter=numPiecesPerType.crbegin();numPiecesIter!=numPiecesPerType.crend();++numPiecesIter,decrement(currentSetupPiece))
if (currentSetupPiece==FIRST_PIECE_TYPE) {
// Fill remaining squares with most numerous piece type.
const PieceTypeAndSide piece=toPieceTypeAndSide(FIRST_PIECE_TYPE,sideToMove());
for (SquareIndex square=FIRST_SQUARE;square<NUM_SQUARES;increment(square)) {
PieceTypeAndSide& squarePiece=potentialSetup.squarePieces[square];
if (squarePiece==NO_PIECE && isSetupSquare(sideToMove(),square))
squarePiece=piece;
}
if (finalize)
autoFinalize(true);
emit boardChanged();
return true;
}
else if (*numPiecesIter>0)
break;
return false;
}
bool Board::setUpPiece(const SquareIndex destination)
{
if (isSetupSquare(sideToMove(),destination)) {
auto& squarePieces=potentialSetup.squarePieces;
if (std::all_of(squarePieces.begin(),squarePieces.end(),[](const PieceTypeAndSide& piece){return piece==NO_PIECE;}))
emit gameStarted();
squarePieces[destination]=toPieceTypeAndSide(currentSetupPiece,sideToMove());
emit boardChanged();
nextSetupPiece();
return true;
}
else
return false;
}
bool Board::refreshHighlights(const bool clearSelected)
{
if (stepMode && !setupPlacementPhase())
return updateStepHighlights();
else {
bool change=(highlighted[DESTINATION]!=NO_SQUARE);
highlighted[DESTINATION]=NO_SQUARE;
if (clearSelected) {
change|=(highlighted[ORIGIN]!=NO_SQUARE);
highlighted[ORIGIN]=NO_SQUARE;
}
return change;
}
}
bool Board::updateStepHighlights()
{
return updateStepHighlights(mapFromGlobal(QCursor::pos()));
}
bool Board::updateStepHighlights(const QPoint& mousePosition)
{
const std::array<SquareIndex,2> oldSelected=highlighted;
highlighted[ORIGIN]=positionToSquare(mousePosition);
highlighted[DESTINATION]=closestAdjacentSquare(mousePosition);
if (setupPhase()) {
if (!isSetupSquare(sideToMove(),highlighted[ORIGIN]) || potentialSetup.squarePieces[highlighted[ORIGIN]]==NO_PIECE)
fill(highlighted,NO_SQUARE);
else if (!isSetupSquare(sideToMove(),highlighted[DESTINATION]))
highlighted[DESTINATION]=NO_SQUARE;
}
else {
Squares legalDestinations=gameState().legalDestinations(highlighted[ORIGIN]);
if (legalDestinations.empty()) {
legalDestinations=gameState().legalDestinations(highlighted[DESTINATION]);
if (legalDestinations.empty())
fill(highlighted,NO_SQUARE);
else
std::swap(highlighted[ORIGIN],highlighted[DESTINATION]);
}
if (!found(legalDestinations,highlighted[DESTINATION]))
highlighted[DESTINATION]=NO_SQUARE;
}
return oldSelected!=highlighted;
}
bool Board::singleSquareAction(const SquareIndex square)
{
if (square==NO_SQUARE)
return false;
else if (setupPlacementPhase()) {
if (setUpPiece(square)) {
refreshHighlights(true);
return true;
}
}
else if (stepMode)
return doubleSquareAction(highlighted[ORIGIN],highlighted[DESTINATION]);
else {
if (highlighted[ORIGIN]==NO_SQUARE) {
if (setupPhase() ? (isSetupSquare(sideToMove(),square) && potentialSetup.squarePieces[square]!=NO_PIECE) : gameState().legalOrigin(square)) {
highlighted[ORIGIN]=square;
return true;
}
}
else if (highlighted[ORIGIN]==square) {
highlighted[ORIGIN]=NO_SQUARE;
return true;
}
else
return doubleSquareAction(highlighted[ORIGIN],square);
}
return false;
}
bool Board::doubleSquareAction(const SquareIndex origin,const SquareIndex destination)
{
if (origin==NO_SQUARE || destination==NO_SQUARE)
return false;
else if (setupPhase())
return doubleSquareSetupAction(origin,destination);
else {
const ExtendedSteps route=gameState().preferredRoute(origin,destination);
if (!route.empty()) {
doSteps(route,true);
return true;
}
}
return false;
}
bool Board::doubleSquareSetupAction(const SquareIndex origin,const SquareIndex destination)
{
if (destination==NO_SQUARE) {
potentialSetup.squarePieces[origin]=NO_PIECE;
if (!customSetup())
nextSetupPiece();
emit boardChanged();
return true;
}
else if (isSetupSquare(sideToMove(),destination)) {
auto& squarePieces=potentialSetup.squarePieces;
if (customSetup()) {
squarePieces[destination]=squarePieces[origin];
squarePieces[origin]=NO_PIECE;
}
else
std::swap(squarePieces[origin],squarePieces[destination]);
emit boardChanged();
return true;
}
else
return false;
}
void Board::finalizeSetup(const Placements& placements)
{
const auto newNode=Node::addSetup(currentNode,placements,explore);
currentNode=std::move(newNode);
if (sideToMove()==SECOND_SIDE)
initSetup();
else
potentialMove.data.clear();
emit boardChanged();
emit sendNodeChange(newNode,currentNode);
if (autoRotate)
setViewpoint(sideToMove());
}
void Board::finalizeMove(const ExtendedSteps& move)
{
const auto newNode=Node::makeMove(currentNode,move,explore);
currentNode=std::move(newNode);
potentialMove.data.clear();
emit boardChanged();
emit sendNodeChange(newNode,currentNode);
if (autoRotate && currentNode->result.endCondition==NO_END)
setViewpoint(sideToMove());
}
void Board::endDrag()
{
drag[ORIGIN]=NO_SQUARE;
dragSteps.clear();
update();
}
bool Board::autoFinalize(const bool stepsTaken)
{
if (!customSetup() && explore) {
if (currentNode->inSetup()) {
if (currentSetupPiece<=FIRST_PIECE_TYPE)
finalizeSetup(currentPlacements());
else if (const auto& child=currentNode->findPartialMatchingChild(currentPlacements()).first) {
proposeSetup(*child.get());
return true;
}
else
return false;
}
else {
const auto& currentSteps=potentialMove.get().current();
if (gameState().stepsAvailable==0 || (!stepsTaken && currentNode->findMatchingChild(currentSteps).first!=nullptr)) {
if (currentNode->legalMove(gameState())==MoveLegality::LEGAL)
finalizeMove(currentSteps);
else
return false;
}
else {
if (const auto& child=currentNode->findPartialMatchingChild(potentialMove.get().all()).first)
potentialMove.data.set(child->move,currentSteps.size());
return false;
}
}
if (const auto& child=currentNode->child(0))
proposeMove(*child.get(),0);
return true;
}
else
return false;
}
bool Board::confirmMove()
{
if (confirm && !explore && found(controllableSides,false))
return MessageBox(QMessageBox::Question,tr("Confirm move"),tr("Do you want to submit this move?"),QMessageBox::Yes|QMessageBox::No,this).exec()==QMessageBox::Yes;
else
return true;
}
bool Board::event(QEvent* event)
{
if (event->type()==QEvent::ToolTip) {
const auto helpEvent=static_cast<QHelpEvent*>(event);
const auto squareIndex=positionToSquare(helpEvent->pos());
if (squareIndex!=NO_SQUARE) {
QToolTip::showText(helpEvent->globalPos(),toCoordinates(squareIndex).data());
return true;
}
}
return QWidget::event(event);
}
void Board::mousePressEvent(QMouseEvent* event)
{
disableAnimation();
const SquareIndex square=positionToSquare(event->pos());
switch (event->button()) {
case Qt::LeftButton:
if (square!=NO_SQUARE && playable()) {
const PieceTypeAndSide currentPiece=gameState().squarePieces[square];
if (customSetup() ? currentPiece!=NO_PIECE : (currentNode->inSetup() ? isSide(currentPiece,sideToMove()) : gameState().legalOrigin(square))) {
fill(drag,square);
dragSteps.clear();
update();
}
}
break;
case Qt::RightButton:
if (playable()) {
if (drag[ORIGIN]!=NO_SQUARE) {
endDrag();
break;
}
else if (!stepMode && highlighted[ORIGIN]!=NO_SQUARE) {
highlighted[ORIGIN]=NO_SQUARE;
update();
break;
}
else if (customSetup()) {
if (square!=NO_SQUARE)
new Palette(*this,square);
break;
}
}
emit customContextMenuRequested(event->pos());
break;
case Qt::BackButton:
if (!customSetup())
undoSteps(false);
break;
case Qt::ForwardButton:
if (!customSetup())
redoSteps(false);
break;
default:
event->ignore();
return;
break;
}
event->accept();
}
void Board::mouseMoveEvent(QMouseEvent* event)
{
if (!playable()) {
event->ignore();
return;
}
event->accept();
if ((event->buttons()&Qt::LeftButton)!=0) {
disableAnimation();
if (drag[ORIGIN]!=NO_SQUARE) {
const SquareIndex square=positionToSquare(event->pos());
if (drag[DESTINATION]!=square) {
drag[DESTINATION]=square;
if (square==NO_SQUARE || drag[ORIGIN]==drag[DESTINATION])
dragSteps.clear();
else if (!setupPhase())
dragSteps=gameState().preferredRoute(drag[ORIGIN],drag[DESTINATION],dragSteps);
}
update();
}
}
if (refreshHighlights(false))
update();
}
void Board::mouseReleaseEvent(QMouseEvent* event)
{
switch (event->button()) {
case Qt::LeftButton:
disableAnimation();
if (playable()) {
const SquareIndex eventSquare=positionToSquare(event->pos());
if (drag[ORIGIN]!=NO_SQUARE) {
assert(eventSquare==drag[DESTINATION]);
if (drag[ORIGIN]==eventSquare)
singleSquareAction(eventSquare);
else if (setupPhase())
doubleSquareSetupAction(drag[ORIGIN],eventSquare);
else
doSteps(dragSteps,true);
endDrag();
}
else if (singleSquareAction(eventSquare))
update();
}
break;
case Qt::MidButton:
break;
default:
disableAnimation();
event->ignore();
return;
break;
}
event->accept();
}
void Board::mouseDoubleClickEvent(QMouseEvent* event)
{
if (!playable()) {
event->ignore();
return;
}
switch (event->button()) {
case Qt::LeftButton: {
disableAnimation();
const SquareIndex eventSquare=positionToSquare(event->pos());
if ((eventSquare==NO_SQUARE || gameState().squarePieces[eventSquare]==NO_PIECE) && (!stepMode || found(highlighted,NO_SQUARE))) {
if (customSetup()) {
if (potentialSetup.hasFloatingPieces())
MessageBox(QMessageBox::Critical,tr("Illegal position"),tr("Unprotected piece on trap."),QMessageBox::NoButton,this).exec();
else {
const auto node=std::make_shared<Node>(nullptr,ExtendedSteps(),potentialSetup);
if (!node->inSetup() && node->result.endCondition==NO_END) {
emit sendNodeChange(node,currentNode);
currentNode=std::move(node);
if (autoRotate)
setViewpoint(sideToMove());
emit boardChanged();
}
else
MessageBox(QMessageBox::Critical,tr("Terminal position"),tr("Game already finished in this position."),QMessageBox::NoButton,this).exec();
}
}
else if (currentNode->inSetup()) {
if (currentSetupPiece<=FIRST_PIECE_TYPE && confirmMove()) {
if (!explore)
playSound("qrc:/finished-setup.wav");
finalizeSetup(currentPlacements());
}
}
else {
const auto& playedMove=potentialMove.get().current();
switch (currentNode->legalMove(gameState())) {
case MoveLegality::LEGAL:
if (confirmMove()) {
if (!explore)
playSound("qrc:/loud-step.wav");
finalizeMove(playedMove);
}
break;
case MoveLegality::ILLEGAL_PUSH_INCOMPLETION:
playSound("qrc:/illegal-move.wav");
MessageBox(QMessageBox::Critical,tr("Incomplete push"),tr("Push was not completed."),QMessageBox::NoButton,this).exec();
break;
case MoveLegality::ILLEGAL_PASS:
playSound("qrc:/illegal-move.wav");
if (!playedMove.empty())
MessageBox(QMessageBox::Critical,tr("Illegal pass"),tr("Move did not change board."),QMessageBox::NoButton,this).exec();
break;
case MoveLegality::ILLEGAL_REPETITION:
playSound("qrc:/illegal-move.wav");
MessageBox(QMessageBox::Critical,tr("Illegal repetition"),tr("Move would repeat board and side to move too often."),QMessageBox::NoButton,this).exec();
break;
}
}
}
}
break;
case Qt::RightButton:
disableAnimation();
break;
case Qt::BackButton:
if (!customSetup()) {
disableAnimation();
undoSteps(true);
}
break;
case Qt::ForwardButton:
if (!customSetup()) {
disableAnimation();
redoSteps(true);
}
break;
default:
event->ignore();
return;
break;
}
event->accept();
}
void Board::wheelEvent(QWheelEvent* event)
{
if (!customSetup()) {
disableAnimation();
if (event->angleDelta().y()<0)
undoSteps(false);
else
redoSteps(false);
}
event->accept();
}
void Board::focusOutEvent(QFocusEvent*)
{
endDrag();
}
void Board::paintEvent(QPaintEvent*)
{
QPainter qPainter(this);
if (coordinateDisplay!=NONE) {
qreal factor=squareHeight()/static_cast<qreal>(qPainter.fontMetrics().height());
for (SquareIndex square=FIRST_SQUARE;square<NUM_SQUARES;increment(square))
if (coordinateDisplay==ALL || isTrap(square))
factor=std::min(factor,squareWidth()/static_cast<qreal>(qPainter.fontMetrics().horizontalAdvance(toCoordinates(square,'A').data())));
if (factor>0) {
QFont qFont(qPainter.font());
qFont.setPointSizeF(qFont.pointSizeF()*factor);
qPainter.setFont(qFont);
}
}
const GameState& gameState_=displayedGameState();
const auto previousPieces=(customSetup() || currentNode->move.empty() ? nullptr : ¤tNode->previousNode->gameState.squarePieces);
QPen qPen(Qt::SolidPattern,1);
const QPoint mousePosition=mapFromGlobal(QCursor::pos());
const bool alternativeColoring=(explore && found(controllableSides,false));
const auto startingColor=&colors[alternativeColoring ? ALTERNATIVE : REGULAR];
for (unsigned int pass=0;pass<2;++pass)
for (SquareIndex square=FIRST_SQUARE;square<NUM_SQUARES;increment(square)) {
const unsigned int file=toFile(square);
const unsigned int rank=toRank(square);
const bool isTrapSquare=isTrap(file,rank);
if (!isAnimating() && (drag[ORIGIN]==NO_SQUARE ? found(highlighted,square) || (gameState_.inPush && square==gameState_.followupDestination)
: square==drag[DESTINATION] && validDrop())) {
if (pass==0)
continue;
else {
qPainter.setBrush((startingColor+HIGHLIGHT+sideToMove())->data);
qPen.setColor(*(startingColor+HIGHLIGHT+otherSide(sideToMove())));
}
}
else if (pass==1)
continue;
else {
if (!isAnimating() && !setupPhase() && (square==drag[ORIGIN] || found<ORIGIN>(dragSteps,square)))
qPainter.setBrush((startingColor+HIGHLIGHT_MILD+sideToMove())->data);
else if (setupPhase() ? !customSetup() && playable() && isSetupRank(sideToMove(),rank)
: (isAnimating() || gameState_.stepsAvailable==MAX_STEPS_PER_MOVE) &&
previousPieces!=nullptr && (*previousPieces)[square]!=gameState_.squarePieces[square])
qPainter.setBrush((startingColor+HIGHLIGHT+otherSide(sideToMove()))->data);
else {
const auto customColor=customColors[square];
if (customColor!=REGULAR)
qPainter.setBrush((startingColor+customColor)->data);
else {
if (customSetup())
qPainter.setBrush((startingColor+HIGHLIGHT_MILD+sideToMove())->data);
else
qPainter.setBrush((startingColor+REGULAR)->data);
if (isTrapSquare) {
const QColor trapColors[NUM_SIDES]={(startingColor+TRAP+ FIRST_SIDE)->data,
(startingColor+TRAP+SECOND_SIDE)->data};
if (!customSetup() || trapColors[FIRST_SIDE]!=trapColors[SECOND_SIDE])
qPainter.setBrush(trapColors[rank<NUM_RANKS/2 ? FIRST_SIDE : SECOND_SIDE]);
}
else {
const QColor goalColors[NUM_SIDES]={(startingColor+GOAL+SECOND_SIDE)->data,
(startingColor+GOAL+ FIRST_SIDE)->data};
if (!customSetup() || goalColors[FIRST_SIDE]!=goalColors[SECOND_SIDE])
for (Side side=FIRST_SIDE;side<NUM_SIDES;increment(side))
if (isGoal(square,side)) {
qPainter.setBrush(goalColors[side]);
break;
}
}
}
}
qPen.setColor(*(startingColor+HIGHLIGHT+sideToMove()));
}
qPainter.setPen(qPen);
const QRect qRect=visualRectangle(file,rank);
qPainter.drawRect(qRect);
if (coordinateDisplay==ALL || (coordinateDisplay==TRAPS_ONLY && isTrapSquare)) {
if (gameEnd())
qPainter.setPen(colors[alternativeColoring ? REGULAR : ALTERNATIVE]);
qPainter.drawText(qRect,Qt::AlignCenter,toCoordinates(file,rank,'A').data());
}
if (square!=drag[ORIGIN] || isAnimating()) {
const PieceTypeAndSide pieceOnSquare=gameState_.squarePieces[square];
if (pieceOnSquare!=NO_PIECE)
globals.pieceIcons.drawPiece(qPainter,iconSet,pieceOnSquare,qRect);
}
}
if (playable() && setupPlacementPhase())
globals.pieceIcons.drawPiece(qPainter,iconSet,toPieceTypeAndSide(currentSetupPiece,sideToMove()),QRect((NUM_FILES-1)/2.0*squareWidth(),(NUM_RANKS-1)/2.0*squareHeight(),squareWidth(),squareHeight()));
if (drag[ORIGIN]!=NO_SQUARE && !isAnimating())
globals.pieceIcons.drawPiece(qPainter,iconSet,gameState_.squarePieces[drag[ORIGIN]],QRect(mousePosition.x()-squareWidth()/2,mousePosition.y()-squareHeight()/2,squareWidth(),squareHeight()));
qPainter.end();
}
void Board::animateNextStep()
{
const auto lastStep=currentNode->move.end();
if (soundOn) {
if (qMediaPlayer.state()==QMediaPlayer::StoppedState)
qMediaPlaylist.clear();
if (!playCaptureSound(*nextAnimatedStep++))
qMediaPlaylist.addMedia(QUrl(nextAnimatedStep==lastStep ? "qrc:/loud-step.wav" : "qrc:/soft-step.wav"));
qMediaPlayer.play();
}
else
++nextAnimatedStep;
if (nextAnimatedStep==lastStep)
animationTimer.stop();
else
animationTimer.start();
update();
}
void Board::disableAnimation()
{
if (isAnimating()) {
animationTimer.stop();
update();
}
}
void Board::playStepSounds(const ExtendedSteps& steps,const bool emphasize)
{
if (soundOn) {
qMediaPlaylist.clear();
for (const auto& step:steps)
playCaptureSound(step);
if (qMediaPlaylist.isEmpty())
qMediaPlaylist.addMedia(QUrl(emphasize ? "qrc:/loud-step.wav" : "qrc:/soft-step.wav"));
qMediaPlayer.play();
}
}
bool Board::playCaptureSound(const ExtendedStep& step)
{
assert(soundOn);
const auto trappedPiece=std::get<TRAPPED_PIECE>(step);
if (trappedPiece==NO_PIECE)
return false;
else {
if (toSide(trappedPiece)==std::get<RESULTING_STATE>(step).sideToMove)
qMediaPlaylist.addMedia(QUrl("qrc:/dropped-piece.wav"));
else
qMediaPlaylist.addMedia(QUrl("qrc:/captured-piece.wav"));
return true;
}
}
| [
"TFiFiE@users.noreply.github.com"
] | TFiFiE@users.noreply.github.com |
8d965163a077fc792ce77f58e3589df276f10484 | 8242d218808b8cc5734a27ec50dbf1a7a7a4987a | /Intermediate/Build/Win64/Netshoot/Development/Engine/Module.Engine.3_of_48.cpp | dacb31bff1153bc4ff4e73098305b0e3cc53439c | [] | no_license | whyhhr/homework2 | a2e75b494a962eab4fb0a740f83dc8dc27f8f6ee | 9808107fcc983c998d8601920aba26f96762918c | refs/heads/main | 2023-08-29T08:14:39.581638 | 2021-10-22T16:47:11 | 2021-10-22T16:47:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,327 | cpp | // This file is automatically generated at compile-time to include some subset of the user-created cpp files.
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimCompress_RemoveEverySecondKey.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimCompress_RemoveLinearKeys.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimCompress_RemoveTrivialKeys.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimCompressionDerivedData.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimCompressionTypes.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimCurveCompressionCodec.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimCurveCompressionCodec_CompressedRichCurve.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimCurveCompressionCodec_UniformIndexable.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimCurveCompressionCodec_UniformlySampled.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimCurveCompressionSettings.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimCurveTypes.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimData.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimEncoding.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimEncoding_ConstantKeyLerp.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimEncoding_PerTrackCompression.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimEncoding_VariableKeyLerp.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimInstance.cpp"
#include "F:/UE4Source/UnrealEngine-release/Engine/Source/Runtime/Engine/Private/Animation/AnimInstanceProxy.cpp"
| [
"49893309+whyhhr@users.noreply.github.com"
] | 49893309+whyhhr@users.noreply.github.com |
1e2b5e7193f95d59054ec19ef1aeed89ec11660a | 5bae8b53fed74f9e093f2fdedc08485182aa8d47 | /src/MG5_aMCNLO/Commons/read_slha_MEKD.cc | 39568adbde5c02086a008755783c3c5af76d7834 | [] | no_license | odysei/MEKD | eac098ea7241f287dde1fb625aaaeb7138823d8b | 1614a2192a1e7725cc96e3cb773b02f62ac3c52b | refs/heads/master | 2020-12-25T17:14:26.875430 | 2018-12-01T19:31:44 | 2018-12-01T19:31:44 | 10,505,338 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,302 | cc | #ifndef READ_SLHA_MEKD_CC
#define READ_SLHA_MEKD_CC
#include <algorithm>
#include <iostream>
#include <fstream>
#include "read_slha_MEKD.h"
using namespace std;
void SLHABlock_MEKD::set_entry(vector<int> indices, complex<double> value)
{
if (_entries.size() == 0)
_indices = indices.size();
else if (indices.size() != _indices)
throw "Wrong number of indices in set_entry";
_entries[indices] = value;
}
complex<double> SLHABlock_MEKD::get_entry(vector<int> indices,
complex<double> def_val)
{
if (_entries.find(indices) == _entries.end()) {
cout << "Warning: No such entry in " << _name
<< ", using default value " << def_val << endl;
return def_val;
}
return _entries[indices];
}
void SLHAReader_MEKD::read_slha_file(string file_name)
{
ifstream param_card;
param_card.open(file_name.c_str(), ifstream::in);
if (!param_card.good()) {
cerr << "Error while opening param card\n"; /// Old-school warning
throw "Error while opening param card";
}
// cout << "Opened slha file " << file_name << " for reading" << endl;
char buf[200];
string line;
string block("");
while (param_card.good()) {
param_card.getline(buf, 200);
line = buf;
// Change to lowercase
transform(line.begin(), line.end(), line.begin(),
(int (*)(int))tolower);
if (line != "" && line[0] != '#') {
if (block != "") {
// Look for double index blocks
double dindex1, dindex2;
complex<double> value;
stringstream linestr2(line);
if (linestr2 >> dindex1 >> dindex2 >> value &&
dindex1 == int(dindex1) and dindex2 == int(dindex2)) {
vector<int> indices;
indices.push_back(int(dindex1));
indices.push_back(int(dindex2));
set_block_entry(block, indices, value);
// Done with this line, read next
continue;
}
stringstream linestr1(line);
// Look for single index blocks
if (linestr1 >> dindex1 >> value && dindex1 == int(dindex1)) {
vector<int> indices;
indices.push_back(int(dindex1));
set_block_entry(block, indices, value);
// Done with this line, read next
continue;
}
}
// Look for block
if (line.find("block ") != line.npos) {
line = line.substr(6);
// Get rid of spaces between block and block name
while (line[0] == ' ')
line = line.substr(1);
// Now find end of block name
size_t space_pos = line.find(' ');
if (space_pos != line.npos)
line = line.substr(0, space_pos);
block = line;
continue;
}
// Look for decay
if (line.find("decay ") == 0) {
line = line.substr(6);
block = "";
stringstream linestr(line);
int pdg_code;
complex<double> value;
if (linestr >> pdg_code >> value)
set_block_entry("decay", pdg_code, value);
else
cout << "Warning: Wrong format for decay block " << line
<< endl;
continue;
}
}
}
if (_blocks.size() == 0)
throw "No information read from SLHA card";
param_card.close();
}
complex<double> SLHAReader_MEKD::get_block_entry(string block_name,
vector<int> indices,
complex<double> def_val)
{
if (_blocks.find(block_name) == _blocks.end()) {
cout << "No such block " << block_name << ", using default value "
<< def_val << endl;
return def_val;
}
return _blocks[block_name].get_entry(indices);
}
complex<double> SLHAReader_MEKD::get_block_entry(string block_name, int index,
complex<double> def_val)
{
vector<int> indices;
indices.push_back(index);
return get_block_entry(block_name, indices, def_val);
}
void SLHAReader_MEKD::set_block_entry(string block_name, vector<int> indices,
complex<double> value)
{
if (_blocks.find(block_name) == _blocks.end()) {
SLHABlock_MEKD block(block_name);
_blocks[block_name] = block;
}
_blocks[block_name].set_entry(indices, value);
/* cout << "Set block " << block_name << " entry ";
for (int i=0;i < indices.size();i++)
cout << indices[i] << " ";
cout << "to " << _blocks[block_name].get_entry(indices) << endl;*/
}
void SLHAReader_MEKD::set_block_entry(string block_name, int index,
complex<double> value)
{
vector<int> indices;
indices.push_back(index);
set_block_entry(block_name, indices, value);
}
#endif
| [
"odysei@gmail.com"
] | odysei@gmail.com |
49f69bb0ea5eb1d6d2a98e9d8f8e81f0e4001f8d | 09175c20d82ad4a6da112bc9df3c52821c7a3165 | /linux/my_application.cc | c889043a925f0aa186ee111f0afe337f65e0712d | [] | no_license | eyouyou/flutter-router-example | 8cfc833120503af82be194207d811ffdb6668f44 | 890b9a1c593946cfbac82c9551fde63dfee5395c | refs/heads/master | 2023-04-09T22:59:43.332427 | 2021-04-20T08:08:46 | 2021-04-20T08:08:46 | 359,735,575 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,678 | cc | #include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
// Use a header bar when running in GNOME as this is the common style used
// by applications and is the setup most users will be using (e.g. Ubuntu
// desktop).
// If running on X and not using GNOME then just use a traditional title bar
// in case the window manager does more exotic layout, e.g. tiling.
// If running on Wayland assume the header bar will work (may need changing
// if future cases occur).
gboolean use_header_bar = TRUE;
#ifdef GDK_WINDOWING_X11
GdkScreen *screen = gtk_window_get_screen(window);
if (GDK_IS_X11_SCREEN(screen)) {
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
use_header_bar = FALSE;
}
}
#endif
if (use_header_bar) {
GtkHeaderBar *header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "flutter_router_template");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
}
else {
gtk_window_set_title(window, "flutter_router_template");
}
gtk_window_set_default_size(window, 1280, 720);
gtk_widget_show(GTK_WIDGET(window));
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application, gchar ***arguments, int *exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GObject::dispose.
static void my_application_dispose(GObject *object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID,
nullptr));
}
| [
"393370459@QQ.COM"
] | 393370459@QQ.COM |
2c407ee7b13fc60f72838b69a8f4d4ba091cd204 | f88b70a6dfa6c495a9c2dc0ae19ff1daef3a0147 | /Solution/solution.h | b595d4d0bc00d7aa23e24bf6a870bd5be62a8bc7 | [] | no_license | hongsezuie/Solutions | 4490f6ddbb8a541047fe1c04b5ad78e34177a5aa | e95bc4b4911aa6ccb7d10375cc6a8fd3625cf719 | refs/heads/master | 2021-01-25T10:17:10.268601 | 2015-04-03T00:12:24 | 2015-04-03T00:12:24 | 33,083,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,059 | h | #ifndef SOLUTION_H
#define SOLUTION_H
#include <vector>
#include <string>
#include <set>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <math.h>
#include <unordered_map>
#include <stack>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
Solution();
~Solution();
std::vector<std::string> findRepeatedDnaSequences(std::string s);
std::vector<std::vector<int> > generate(int numRows);
int compareVersion(std::string version1, std::string version2);
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB);
bool isPalindrome(std::string s);
bool isPalindrome_2(std::string s);
bool isPalindrome_3(std::string s);
std::vector<int> getRow(int rowIndex);
bool hasPathSum(TreeNode *root, int sum);
public:
long double combination(int InputA, int InputB);
};
#endif // SOLUTION_H
| [
"ccxinfosec@gmail.com"
] | ccxinfosec@gmail.com |
6e01a71d125d05a9514200080186ec69ff8a507a | 34aadfb024f98b6de7441f17b4796c39af168b93 | /lookup/src/LookupInterface.cpp | fb47a0797de31f167a1d33d1945ba6751a2f4ee7 | [] | no_license | cbuchxrn/argus_utils | 5a393014ed9a6dd977995d176fe8ca5f3eea81fc | d19be5bdd54e324d1bb23e10625462bf2c6bd5e0 | refs/heads/master | 2022-01-12T14:17:12.322705 | 2018-04-10T17:57:32 | 2018-04-10T17:57:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,949 | cpp | #include "lookup/LookupInterface.h"
#include <boost/thread/thread.hpp>
namespace argus
{
LookupInterface::LookupInterface()
: nodeHandle(), lookupNamespace( "/lookup/" ) {}
LookupInterface::LookupInterface( const ros::NodeHandle& nh )
: nodeHandle( nh ), lookupNamespace( "/lookup/" ) {}
void LookupInterface::SetLookupNamespace( const std::string& ns )
{
lookupNamespace = ns;
if( lookupNamespace.back() != '/' ) { lookupNamespace += "/"; }
}
void LookupInterface::WriteNamespace( const std::string& targetName, const std::string& ns )
{
std::string resolvedNamespace = CleanPath( nodeHandle.resolveName( ns ) );
std::string lookupPath = FormLookupPath( targetName );
ROS_INFO_STREAM( "Registering target (" << targetName
<< ") with fully resolved namespace (" << resolvedNamespace
<< ") at lookup path (" << lookupPath << ")" );
nodeHandle.setParam( lookupPath, resolvedNamespace );
}
bool LookupInterface::ReadNamespace( const std::string& targetName,
std::string& resolvedNamespace,
const ros::Duration& timeout )
{
std::string path = FormLookupPath( targetName );
if( nodeHandle.getParam( path, resolvedNamespace ) ) { return true; }
else if( timeout.toSec() == 0.0 ) { return false; }
ros::Time start = ros::Time::now();
do
{
boost::this_thread::sleep( boost::posix_time::milliseconds(500) );
// ros::Duration( 0.5 ).sleep();
if( nodeHandle.getParam( path, resolvedNamespace ) ) { return true; }
} while( ros::Time::now() < start + timeout );
return false;
}
std::string LookupInterface::CleanPath( const std::string& path )
{
std::string p = path;
if( p.back() != '/' ) { p += "/"; }
return p;
}
std::string LookupInterface::FormLookupPath( const std::string& key ) const
{
std::string lookupPath = CleanPath( lookupNamespace + key );
//lookupPath += "namespace";
return lookupPath;
}
} // end namespace lookup
| [
"humhu@cmu.edu"
] | humhu@cmu.edu |
7bac4654b45a46a942871fc56268171fb10f8b66 | e6652252222ce9e4ff0664e539bf450bc9799c50 | /d0706/7.6/source/DL24-dsh/ah.cpp | 163f7d7e74a04db442b62dbb67750505565a04a5 | [] | no_license | cjsoft/inasdfz | db0cea1cf19cf6b753353eda38d62f1b783b8f76 | 3690e76404b9189e4dd52de3770d59716c81a4df | refs/heads/master | 2021-01-17T23:13:51.000569 | 2016-07-12T07:21:19 | 2016-07-12T07:21:19 | 62,596,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 224 | cpp | #include<iostream>
#include<cstdio>
using namespace std;
int T;
int main(){
freopen ("ah.in","r",stdin);
freopen ("ah.out","w",stdout);
cin>>T;
for (int i=1;i<=T;i++) cout<<"0"<<endl;
return 0;
}
| [
"egwcyh@qq.com"
] | egwcyh@qq.com |
fbebc41338f515d657c2ce930ba11491b423a151 | 210dd9fd19c280b0930ce7eb318af1b009c6df27 | /min_max_array.cpp | f7211806e7eee3b549c907fda083cae68c73c3a1 | [] | no_license | GK884/DSA_C | 06ffc8f15f057ad74c7c94da9bc48a1bf3ca03a6 | 351dbe8235ee2f71c7b5863bee8212bbf9eaff7c | refs/heads/main | 2023-06-19T10:10:20.725249 | 2021-07-10T18:54:27 | 2021-07-10T18:54:27 | 380,975,421 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 731 | cpp | /******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <iostream>
#include<climits>
using namespace std;
int main()
{
int n;
cin>>n;
int maxno = INT_MIN, minno = INT_MAX;
int a[n];
for(int i= 0; i< n; i++)
cin>>a[i];
for(int i = 0;i < n; i++)
{
maxno = max(a[i],maxno);
minno = min(a[i], minno);
}
cout<<maxno<<"\n"<<minno;
return 0;
}
| [
"gk765813@gmail.com"
] | gk765813@gmail.com |
135b88a2c4f61c0f69bc263e9b1b31283f055ee7 | 60470ca9f67acf563a80e7d11c4a86bae0f7902c | /src/crypto/rfc6979_hmac_sha256.h | 5080d317bbc0817be839c4d8b5bab4cbbe2fa98c | [
"MIT"
] | permissive | peterfillmore/duckcoin | ad266463fdb649c6c98ae7185f721795cc5456f3 | b2127d7a6654bcb60633230fe3922794ba55bf2f | refs/heads/master | 2021-01-13T09:27:20.526141 | 2016-11-24T05:48:33 | 2016-11-24T05:48:33 | 72,105,032 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 981 | h | // Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITBREADCRUMB_RFC6979_HMAC_SHA256_H
#define BITBREADCRUMB_RFC6979_HMAC_SHA256_H
#include "crypto/hmac_sha256.h"
#include <stdint.h>
#include <stdlib.h>
/** The RFC 6979 PRNG using HMAC-SHA256. */
class RFC6979_HMAC_SHA256
{
private:
unsigned char V[CHMAC_SHA256::OUTPUT_SIZE];
unsigned char K[CHMAC_SHA256::OUTPUT_SIZE];
bool retry;
public:
/**
* Construct a new RFC6979 PRNG, using the given key and message.
* The message is assumed to be already hashed.
*/
RFC6979_HMAC_SHA256(const unsigned char* key, size_t keylen, const unsigned char* msg, size_t msglen);
/**
* Generate a byte array.
*/
void Generate(unsigned char* output, size_t outputlen);
~RFC6979_HMAC_SHA256();
};
#endif // BITBREADCRUMB_RFC6979_HMAC_SHA256_H
| [
"pfillmor@internode.on.net"
] | pfillmor@internode.on.net |
7bbeb7fa849d18319876dc16d1cb205919a6ff4b | 66c655a05d79ecfbc104b9b40a147c90b9efe242 | /Client/Store.cpp | 591ee9b431b701213d49fa686e8ae09e8a941545 | [] | no_license | a110b1110/MapleStory | 244cdb3a98aed43244341b1b815b86cd1b0c0f15 | 03d627fad6224ac41ac9d92a2243d1caa05a6b35 | refs/heads/master | 2021-01-01T06:29:04.838321 | 2017-08-15T09:10:24 | 2017-08-15T09:10:24 | 97,435,142 | 0 | 0 | null | 2017-07-17T04:26:52 | 2017-07-17T04:26:52 | null | UHC | C++ | false | false | 12,311 | cpp | #include "stdafx.h"
#include "Store.h"
#include "BitMapMgr.h"
#include "BitMap.h"
#include "ObjMgr.h"
#include "Mouse.h"
#include "KeyMgr.h"
//Item----------------------------
#include "Npc.h"
#include "Item.h"
#include "Armor.h"
#include "Glove.h"
#include "Accessory.h"
#include "Helmet.h"
#include "Shoes.h"
#include "Potion.h"
#include "Weapon.h"
//--------------------------------
typedef list<CItem*>::iterator ITEMITER;
CStore::CStore(void)
{
m_eUiType = UI_STORE;
ZeroMemory(&m_tEscButton_Rect, sizeof(RECT));
ZeroMemory(&m_tEscButton_Info, sizeof(INFO));
ZeroMemory(&m_tScroll_Rect, sizeof(RECT));
ZeroMemory(&m_tScroll_Info, sizeof(INFO));
m_pStore_Npc = NULL;
}
CStore::~CStore(void)
{
Release();
}
void CStore::Initialize(void)
{
m_tInfo.fx = 200.f;
m_tInfo.fy = 100.f;
m_tInfo.fcx = 508.f;
m_tInfo.fcy = 505.f;
//Esc Button
m_tEscButton_Info.fx = m_tInfo.fx + m_tInfo.fcx / 2.f;
m_tEscButton_Info.fy = m_tInfo.fy + 10.f;
m_tEscButton_Info.fcx = 9.f;
m_tEscButton_Info.fcy = 9.f;
//Scroll
m_tScroll_Info.fx = m_tInfo.fx + 258.f;
m_tScroll_Info.fy = m_tInfo.fy + 134.f;
m_tScroll_Info.fcx = 9.f;
m_tScroll_Info.fcy = 26.f;
#pragma region Item List
//Store Item
//----------------------------------------------------------------------------------
//Armor (Armor, Armor1)
CItem* pArmor = new CArmor(L"Armor");
((CArmor*)pArmor)->Initialize();
((CArmor*)pArmor)->SetArmor_Data(5, 5, 5, 5, 10, 5, 1000, 0);
pArmor->SetItemDescription(L"기본 갑옷");
m_Store_ItemList.push_back(pArmor);
pArmor = new CArmor(L"Armor1");
((CArmor*)pArmor)->Initialize();
((CArmor*)pArmor)->SetArmor_Data(10, 10, 10, 10, 15, 10, 2000, 1);
pArmor->SetItemDescription(L"고급 갑옷");
m_Store_ItemList.push_back(pArmor);
//----------------------------------------------------------------------------------
//Weapon (Weapon, Weapon1)
CItem* pWeapon = new CWeapon(L"Weapon");
((CWeapon*)pWeapon)->Initialize();
((CWeapon*)pWeapon)->SetWeapon_Data(10, 2, 2, 2, 0, 0, 1000, 2);
pWeapon->SetItemDescription(L"기본 무기");
m_Store_ItemList.push_back(pWeapon);
pWeapon = new CWeapon(L"Weapon1");
((CWeapon*)pWeapon)->Initialize();
((CWeapon*)pWeapon)->SetWeapon_Data(20, 4, 4, 4, 0, 0, 2000, 3);
pWeapon->SetItemDescription(L"고급 무기");
m_Store_ItemList.push_back(pWeapon);
//----------------------------------------------------------------------------------
//Glove (Glove, Glove1)
CItem* pGlove = new CGlove(L"Glove");
((CGlove*)pGlove)->Initialize();
((CGlove*)pGlove)->SetGlove_Data(2, 2, 2, 2, 5, 0, 500, 4);
pGlove->SetItemDescription(L"기본 장갑");
m_Store_ItemList.push_back(pGlove);
pGlove = new CGlove(L"Glove1");
((CGlove*)pGlove)->Initialize();
((CGlove*)pGlove)->SetGlove_Data(4, 4, 4, 4, 10, 0, 1000, 5);
pGlove->SetItemDescription(L"고급 장갑");
m_Store_ItemList.push_back(pGlove);
//----------------------------------------------------------------------------------
//Helmet
CItem* pHelmet = new CHelmet(L"Helmet");
((CHelmet*)pHelmet)->Initialize();
((CHelmet*)pHelmet)->SetHelmet_Data(4, 4, 4, 4, 5, 5, 500, 6);
pHelmet->SetItemDescription(L"투구");
m_Store_ItemList.push_back(pHelmet);
//----------------------------------------------------------------------------------
//Accessory
CItem* pAcs = new CAccessory(L"Accessory", ITEM_RING);
((CAccessory*)pAcs)->Initialize();
((CAccessory*)pAcs)->SetAccessory_Data(2, 2, 2, 2, 3, 3, 500, 7);
pAcs->SetItemDescription(L"메이플 반지");
m_Store_ItemList.push_back(pAcs);
pAcs = new CAccessory(L"Accessory1", ITEM_RING);
((CAccessory*)pAcs)->Initialize();
((CAccessory*)pAcs)->SetAccessory_Data(4, 4, 4, 4, 6, 6, 1000, 8);
pAcs->SetItemDescription(L"고급 반지");
m_Store_ItemList.push_back(pAcs);
//----------------------------------------------------------------------------------
//Shoes
CItem* pShoes = new CShoes(L"Shoes");
((CShoes*)pShoes)->Initialize();
((CShoes*)pShoes)->SetShoes_Data(2, 2, 2, 2, 0, 0, 500, 9);
pShoes->SetItemDescription(L"기본 신발");
m_Store_ItemList.push_back(pShoes);
pShoes = new CShoes(L"Shoes1");
((CShoes*)pShoes)->Initialize();
((CShoes*)pShoes)->SetShoes_Data(4, 4, 4, 4, 2, 2, 1000, 10);
pShoes->SetItemDescription(L"고급 신발");
m_Store_ItemList.push_back(pShoes);
//----------------------------------------------------------------------------------
//Potion
CItem* pPotion = new CPotion(L"Hp_Potion", ITEM_HP_POTION);
((CPotion*)pPotion)->Initialize();
((CPotion*)pPotion)->SetPotion_Data(0, 0, 0, 0, 1000, 0, 100, 11);
pPotion->SetItemDescription(L"생명력 포션");
m_Store_ItemList.push_back(pPotion);
pPotion = new CPotion(L"Mp_Potion", ITEM_MP_POTION);
((CPotion*)pPotion)->Initialize();
((CPotion*)pPotion)->SetPotion_Data(0, 0, 0, 0, 0, 1000, 100, 12);
pPotion->SetItemDescription(L"마나 포션");
m_Store_ItemList.push_back(pPotion);
//----------------------------------------------------------------------------------
float fx = 10.f;
float fy = 125.f;
int iIndex = 0;
ITEMITER iter = m_Store_ItemList.begin();
for (iter; iter != m_Store_ItemList.end(); ++iter, ++iIndex)
{
(*iter)->SetPos(m_tInfo.fx + fx, m_tInfo.fy + fy + (42.5f * iIndex));
}
#pragma endregion
m_eRenderType = RENDER_UI;
}
int CStore::Update(void)
{
//Button Rect
m_tEscButton_Rect.left = long(m_tEscButton_Info.fx + (m_tEscButton_Info.fcx / 2.f) - m_tEscButton_Info.fcx / 2);
m_tEscButton_Rect.right = long(m_tEscButton_Info.fx + (m_tEscButton_Info.fcx / 2.f) + m_tEscButton_Info.fcx / 2);
m_tEscButton_Rect.top = long(m_tEscButton_Info.fy + (m_tEscButton_Info.fcy / 2.f) - m_tEscButton_Info.fcy / 2);
m_tEscButton_Rect.bottom = long(m_tEscButton_Info.fy + (m_tEscButton_Info.fcy / 2.f) + m_tEscButton_Info.fcy / 2);
//Scroll Rect
m_tScroll_Rect.left = long(m_tScroll_Info.fx + (m_tScroll_Info.fcx / 2.f) - m_tScroll_Info.fcx / 2);
m_tScroll_Rect.right = long(m_tScroll_Info.fx + (m_tScroll_Info.fcx / 2.f) + m_tScroll_Info.fcx / 2);
m_tScroll_Rect.top = long(m_tScroll_Info.fy + (m_tScroll_Info.fcy / 2.f) - m_tScroll_Info.fcy / 2);
m_tScroll_Rect.bottom = long(m_tScroll_Info.fy + (m_tScroll_Info.fcy / 2.f) + m_tScroll_Info.fcy / 2);
if (m_bVisible == true)
{
Scroll_Move();
Item_View_Control();
}
return 0;
}
void CStore::Render(HDC _dc)
{
if (m_bVisible == true)
{
TransparentBlt(_dc,
int(m_tInfo.fx), int(m_tInfo.fy),
int(m_tInfo.fcx), int(m_tInfo.fcy),
GETS(CBitMapMgr)->FindImage(L"Store")->GetMemDC(),
0, 0,
int(m_tInfo.fcx), int(m_tInfo.fcy),
RGB(0, 0, 0));
TransparentBlt(_dc,
int(m_tEscButton_Info.fx), int(m_tEscButton_Info.fy),
int(m_tEscButton_Info.fcx), int(m_tEscButton_Info.fcy),
GETS(CBitMapMgr)->FindImage(L"Button_Esc")->GetMemDC(),
0, 0,
int(m_tEscButton_Info.fcx), int(m_tEscButton_Info.fcy),
RGB(1, 1, 1));
TransparentBlt(_dc,
int(m_tScroll_Info.fx), int(m_tScroll_Info.fy),
int(m_tScroll_Info.fcx), int(m_tScroll_Info.fcy),
GETS(CBitMapMgr)->FindImage(L"UI_Scroll")->GetMemDC(),
0, 0,
int(m_tScroll_Info.fcx), int(m_tScroll_Info.fcy),
RGB(0, 0, 0));
/*
Rectangle(_dc,
m_tEscButton_Rect.left,
m_tEscButton_Rect.top,
m_tEscButton_Rect.right,
m_tEscButton_Rect.bottom);
Rectangle(_dc,
m_tScroll_Rect.left,
m_tScroll_Rect.top,
m_tScroll_Rect.right,
m_tScroll_Rect.bottom);
*/
ITEMITER iter = m_Store_ItemList.begin();
float fx = 10.f;
float fy = 125.f;
int iIndex = 0;
for (iter; iter != m_Store_ItemList.end(); ++iter, ++iIndex)
{
if (iIndex < 9)
{
(*iter)->Render(_dc);
(*iter)->SetPos(m_tInfo.fx + fx, m_tInfo.fy + fy + (42.5f * iIndex));
(*iter)->SetItemDescription_Render(_dc, m_tInfo.fx + 50.f, m_tInfo.fy + 125.f + (42.5f * iIndex));
}
}
}
}
void CStore::Release(void)
{
ITEMITER iter_Item = m_Store_ItemList.begin();
ITEMITER iter_Item_End = m_Store_ItemList.end();
for (iter_Item; iter_Item != iter_Item_End; ++iter_Item)
{
delete *iter_Item;
}
m_Store_ItemList.clear();
}
void CStore::Scroll_Move(void)
{
//마우스로 클릭하고 밑으로 내릴때 스크롤 바가 움직이게 한다.
static bool bMove = false;
POINT pt;
pt = CMouse::GetPos();
if (PtInRect(&m_tScroll_Rect, pt) && GETS(CKeyMgr)->GetKeyState(VK_LBUTTON))
bMove = true;
if (!GETS(CKeyMgr)->GetKeyState(VK_LBUTTON) && bMove == true)
bMove = false;
if (bMove == true)
{
if (m_tScroll_Info.fy < m_tInfo.fy + 134.f)
{
m_tScroll_Info.fy = m_tInfo.fy + 134.f;
return;
}
if (m_tScroll_Info.fy > 559.f)
{
m_tScroll_Info.fy = 559.f;
return;
}
//Scroll Move
m_tScroll_Info.fy = pt.y - m_tScroll_Info.fcx / 2.f;
}
}
void CStore::Item_View_Control(void)
{
/*
아이템 리스트에서 스크롤이 될 경우에 리스트의 맨 앞에 있는 것이 빠지고
그 밑에 있는 것들이 위로 올라오는 식으로 보여 주어야 한다.
지금 상태는 미리 13개 아이템을 다 넣어논 상태이고 지금 13개 다 보여주고 있다.
기준은 스크롤 바의 좌표 값을 기준으로 잡아보자.
*/
static bool bMoveUp = false;
if (m_tScroll_Info.fy < m_tInfo.fy + 134.f)
{
bMoveUp = false;
return;
}
else if (m_tScroll_Info.fy > m_tInfo.fy + 134.f && m_tScroll_Info.fy < 559.f)
{
ITEMITER iter = m_Store_ItemList.begin();
ITEMITER iter_End = m_Store_ItemList.end();
float fx = 10.f;
float fy = 125.f;
int iIndex = 0;
//스크롤바를 밑으로 내릴시에
if (bMoveUp == false)
{
if (m_tScroll_Info.fy >= 315 && m_tScroll_Info.fy < 396)
{
for (iter; iter != iter_End;)
{
if ((*iter)->GetItemData()->m_dwOption == 0)
{
m_Store_ItemList.erase(iter);
iter = m_Store_ItemList.begin();
iter_End = m_Store_ItemList.end();
}
else
++iter;
}
}
else if (m_tScroll_Info.fy >= 396 && m_tScroll_Info.fy < 477)
{
for (iter; iter != iter_End;)
{
if ((*iter)->GetItemData()->m_dwOption == 1)
{
m_Store_ItemList.erase(iter);
iter = m_Store_ItemList.begin();
iter_End = m_Store_ItemList.end();
}
else
++iter;
}
}
else if (m_tScroll_Info.fy >= 477 && m_tScroll_Info.fy < 558)
{
for (iter; iter != iter_End;)
{
if ((*iter)->GetItemData()->m_dwOption == 2)
{
m_Store_ItemList.erase(iter);
iter = m_Store_ItemList.begin();
iter_End = m_Store_ItemList.end();
}
else
++iter;
}
}
else if (m_tScroll_Info.fy >= 558 && m_tScroll_Info.fy < 559)
{
for (iter; iter != iter_End;)
{
if ((*iter)->GetItemData()->m_dwOption == 3)
{
m_Store_ItemList.erase(iter);
iter = m_Store_ItemList.begin();
iter_End = m_Store_ItemList.end();
}
else
++iter;
}
}
}
//스크롤 바를 위로 올릴시에
if (bMoveUp == true)
{
if (m_tScroll_Info.fy <= 315 && m_tScroll_Info.fy > 234)
{
CItem* pArmor = new CArmor(L"Armor");
((CArmor*)pArmor)->Initialize();
((CArmor*)pArmor)->SetArmor_Data(5, 5, 5, 5, 10, 5, 1000, 0);
pArmor->SetItemDescription(L"기본 갑옷");
m_Store_ItemList.push_front(pArmor);
}
else if (m_tScroll_Info.fy <= 396 && m_tScroll_Info.fy > 315)
{
CItem* pArmor = new CArmor(L"Armor1");
((CArmor*)pArmor)->Initialize();
((CArmor*)pArmor)->SetArmor_Data(10, 10, 10, 10, 15, 10, 2000, 1);
pArmor->SetItemDescription(L"고급 갑옷");
m_Store_ItemList.push_front(pArmor);
}
else if (m_tScroll_Info.fy <= 477 && m_tScroll_Info.fy > 396)
{
CItem* pWeapon = new CWeapon(L"Weapon");
((CWeapon*)pWeapon)->Initialize();
((CWeapon*)pWeapon)->SetWeapon_Data(10, 2, 2, 2, 0, 0, 1000, 2);
pWeapon->SetItemDescription(L"기본 무기");
m_Store_ItemList.push_front(pWeapon);
}
else if (m_tScroll_Info.fy <= 558 && m_tScroll_Info.fy > 477)
{
CItem* pWeapon = new CWeapon(L"Weapon1");
((CWeapon*)pWeapon)->Initialize();
((CWeapon*)pWeapon)->SetWeapon_Data(20, 4, 4, 4, 0, 0, 2000, 3);
pWeapon->SetItemDescription(L"고급 무기");
m_Store_ItemList.push_front(pWeapon);
}
}
/*
system("cls");
cout << m_tScroll_Info.fy << endl;
cout << m_tScroll_Rect.top << endl;
cout << m_tScroll_Rect.bottom << endl;
*/
}
}
| [
"ygchoi2001@naver.com"
] | ygchoi2001@naver.com |
416898df56d0412e5c0adad54b07ce3dc83ead70 | 8b01178a3b58043681ee138961ed366db46fb749 | /src/coincontrol.h | ecceb0bf6ce746ea7c8a69c672620ad3c905d823 | [
"MIT"
] | permissive | awardprj/AwardCoin | a574c3475bf6a69fa544257c5d5e80d424d9a461 | 5c3703129c716f177da3a1d7ef0421778abef62e | refs/heads/master | 2020-05-21T21:57:52.593996 | 2019-05-12T16:49:58 | 2019-05-12T16:49:58 | 186,162,973 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,240 | h | // Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2014-2016 The Dash developers
// Copyright (c) 2017-2018 The PIVX developers
// Copyright (c) 2019 The AwardCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_COINCONTROL_H
#define BITCOIN_COINCONTROL_H
#include "primitives/transaction.h"
#include "script/standard.h"
/** Coin Control Features. */
class CCoinControl
{
public:
CTxDestination destChange;
bool useObfuScation;
bool useSwiftTX;
bool fSplitBlock;
int nSplitBlock;
//! If false, allows unselected inputs, but requires all selected inputs be used
bool fAllowOtherInputs;
//! Includes watch only addresses which match the ISMINE_WATCH_SOLVABLE criteria
bool fAllowWatchOnly;
//! Minimum absolute fee (not per kilobyte)
CAmount nMinimumTotalFee;
CCoinControl()
{
SetNull();
}
void SetNull()
{
destChange = CNoDestination();
setSelected.clear();
useSwiftTX = false;
useObfuScation = false;
fAllowOtherInputs = false;
fAllowWatchOnly = true;
nMinimumTotalFee = 0;
fSplitBlock = false;
nSplitBlock = 1;
}
bool HasSelected() const
{
return (setSelected.size() > 0);
}
bool IsSelected(const uint256& hash, unsigned int n) const
{
COutPoint outpt(hash, n);
return (setSelected.count(outpt) > 0);
}
void Select(const COutPoint& output)
{
setSelected.insert(output);
}
void UnSelect(const COutPoint& output)
{
setSelected.erase(output);
}
void UnSelectAll()
{
setSelected.clear();
}
void ListSelected(std::vector<COutPoint>& vOutpoints)
{
vOutpoints.assign(setSelected.begin(), setSelected.end());
}
unsigned int QuantitySelected()
{
return setSelected.size();
}
void SetSelection(std::set<COutPoint> setSelected)
{
this->setSelected.clear();
this->setSelected = setSelected;
}
private:
std::set<COutPoint> setSelected;
};
#endif // BITCOIN_COINCONTROL_H
| [
"root@ubuntu16.local"
] | root@ubuntu16.local |
38f7b7eed402c1a1e013b6eb40fb65d237a8d7a2 | 5a076617e29016fe75d6421d235f22cc79f8f157 | /FBReader修改epub快速加载/FBReader/jni/NativeFormats/util/AndroidLog.h | 64200d073a1dd26903973d510187ba80891782ba | [] | no_license | dddddttttt/androidsourcecodes | 516b8c79cae7f4fa71b97a2a470eab52844e1334 | 3d13ab72163bbeed2ef226a476e29ca79766ea0b | refs/heads/master | 2020-08-17T01:38:54.095515 | 2018-04-08T15:17:24 | 2018-04-08T15:17:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,225 | h | /*
* Copyright (C) 2011 Geometer Plus <contact@geometerplus.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#ifndef __ANDROIDLOG_H__
#define __ANDROIDLOG_H__
#include <jni.h>
#include <cstdarg>
#include <cstdio>
#include <string>
#include <AndroidUtil.h>
class AndroidLog {
public:
AndroidLog();
~AndroidLog();
private:
void extractLogClass();
void extractLClass();
void extractSystemErr();
void prepareBuffer();
public:
void w(const std::string &tag, const std::string &message);
void lStartTime(const std::string &start);
void lEndTime(const std::string &end);
void errln(const std::string &message);
void errln(jobject object);
void errln(int value);
void err(const std::string &message);
void err(jobject object);
void err(int value);
void wf(const std::string &tag, const std::string &format, ...);
void errlnf(const std::string &format, ...);
void errf(const std::string &format, ...);
private:
JNIEnv *myEnv;
jclass myLogClass;
jclass myLClass;
jobject mySystemErr;
jclass myPrintStreamClass;
char *myBuffer;
};
inline AndroidLog::AndroidLog() {
myEnv = AndroidUtil::getEnv();
myLogClass = 0;
myLClass=0;
mySystemErr = 0;
myPrintStreamClass = 0;
myBuffer = 0;
}
inline AndroidLog::~AndroidLog() {
if (myBuffer != 0) {
delete[] myBuffer;
}
myEnv->DeleteLocalRef(myLogClass);
myEnv->DeleteLocalRef(myLClass);
myEnv->DeleteLocalRef(mySystemErr);
myEnv->DeleteLocalRef(myPrintStreamClass);
}
inline void AndroidLog::extractLogClass() {
if (myLogClass == 0) {
myLogClass = myEnv->FindClass("android/util/Log");
}
}
inline void AndroidLog::extractLClass()
{
if(myLClass==0)
{
myLClass=myEnv->FindClass("com/nil/util/L");
}
}
inline void AndroidLog::extractSystemErr() {
if (mySystemErr == 0) {
jclass systemClass = myEnv->FindClass("java/lang/System");
jfieldID systemErr = myEnv->GetStaticFieldID(systemClass, "err", "Ljava/io/PrintStream;");
mySystemErr = myEnv->GetStaticObjectField(systemClass, systemErr);
myEnv->DeleteLocalRef(systemClass);
}
if (myPrintStreamClass == 0) {
myPrintStreamClass = myEnv->FindClass("java/io/PrintStream");
}
}
inline void AndroidLog::w(const std::string &tag, const std::string &message) {
extractLogClass();
jmethodID logW = myEnv->GetStaticMethodID(myLogClass, "w", "(Ljava/lang/String;Ljava/lang/String;)I");
jstring javaTag = myEnv->NewStringUTF(tag.c_str());
jstring javaMessage = myEnv->NewStringUTF(message.c_str());
myEnv->CallStaticIntMethod(myLogClass, logW, javaTag, javaMessage);
myEnv->DeleteLocalRef(javaTag);
myEnv->DeleteLocalRef(javaMessage);
}
inline void AndroidLog::lStartTime(const std::string & start)
{
extractLClass();
jmethodID l=myEnv->GetStaticMethodID(myLClass,"startTime","(Ljava/lang/String;)V");
jstring startString=myEnv->NewStringUTF(start.c_str());
myEnv->CallStaticVoidMethod(myLClass,l,startString);
myEnv->DeleteLocalRef(startString);
}
inline void AndroidLog::lEndTime(const std::string &end)
{
extractLClass();
jmethodID l=myEnv->GetStaticMethodID(myLClass,"endTime","(Ljava/lang/String;)V");
jstring endString=myEnv->NewStringUTF(end.c_str());
myEnv->CallStaticVoidMethod(myLClass,l,endString);
myEnv->DeleteLocalRef(endString);
}
inline void AndroidLog::errln(const std::string &message) {
extractSystemErr();
jmethodID println = myEnv->GetMethodID(myPrintStreamClass, "println", "(Ljava/lang/String;)V");
jstring javaMessage = myEnv->NewStringUTF(message.c_str());
myEnv->CallVoidMethod(mySystemErr, println, javaMessage);
myEnv->DeleteLocalRef(javaMessage);
}
inline void AndroidLog::errln(jobject object) {
extractSystemErr();
jmethodID println = myEnv->GetMethodID(myPrintStreamClass, "println", "(Ljava/lang/Object;)V");
myEnv->CallVoidMethod(mySystemErr, println, object);
}
inline void AndroidLog::errln(int value) {
extractSystemErr();
jmethodID println = myEnv->GetMethodID(myPrintStreamClass, "println", "(I)V");
myEnv->CallVoidMethod(mySystemErr, println, (jint)value);
}
inline void AndroidLog::err(const std::string &message) {
extractSystemErr();
jmethodID println = myEnv->GetMethodID(myPrintStreamClass, "print", "(Ljava/lang/String;)V");
jstring javaMessage = myEnv->NewStringUTF(message.c_str());
myEnv->CallVoidMethod(mySystemErr, println, javaMessage);
myEnv->DeleteLocalRef(javaMessage);
}
inline void AndroidLog::err(jobject object) {
extractSystemErr();
jmethodID println = myEnv->GetMethodID(myPrintStreamClass, "print", "(Ljava/lang/Object;)V");
myEnv->CallVoidMethod(mySystemErr, println, object);
}
inline void AndroidLog::err(int value) {
extractSystemErr();
jmethodID println = myEnv->GetMethodID(myPrintStreamClass, "print", "(I)V");
myEnv->CallVoidMethod(mySystemErr, println, (jint)value);
}
inline void AndroidLog::prepareBuffer() {
if (myBuffer == 0) {
myBuffer = new char[8192];
}
myBuffer[0] = '\0';
}
inline void AndroidLog::wf(const std::string &tag, const std::string &format, ...) {
prepareBuffer();
va_list args;
va_start(args, format);
vsprintf(myBuffer, format.c_str(), args);
va_end(args);
w(tag, myBuffer);
}
inline void AndroidLog::errlnf(const std::string &format, ...) {
prepareBuffer();
va_list args;
va_start(args, format);
vsprintf(myBuffer, format.c_str(), args);
va_end(args);
errln(myBuffer);
}
inline void AndroidLog::errf(const std::string &format, ...) {
prepareBuffer();
va_list args;
va_start(args, format);
vsprintf(myBuffer, format.c_str(), args);
va_end(args);
err(myBuffer);
}
#endif /* __ANDROIDLOG_H__ */
| [
"harry.han@gmail.com"
] | harry.han@gmail.com |
a5a88c366ed8c8fcb22e55c81639475020d8ea4e | 09e7e5a0df4945291ade308e02dad3955f447156 | /src/Netmon/plugins/statistics/StatisticsView.cpp | 11b0a2b258a0aee231e172fab1b0ec6d6121c23a | [] | no_license | poiuytr92/win32-netmon | 5833eebb62ec389eccea8f87225447ac9e03bb48 | 9bd14a134f20187eadeab2c5f372ef8727b24a17 | refs/heads/master | 2021-02-07T03:44:45.019642 | 2015-09-25T15:06:31 | 2015-09-25T15:06:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,600 | cpp | // Copyright (C) 2012-2014 F32 (feng32tc@gmail.com)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as
// published by the Free Software Foundation;
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "stdafx.h"
#include "StatisticsView.h"
#include "../../utils/Utils.h"
#include "GdiWidget/GwPieChart.h"
#include "GdiWidget/GwHistogram.h"
#include "GdiWidget/GwLogHistogram.h"
#include "GdiWidget/GwGroupbox.h"
#include "GdiWidget/GwLabel.h"
#pragma region Members of StatisticsView
// GDI Objects
HDC StatisticsView::_hdcTarget;
HDC StatisticsView::_hdcBuf;
HBITMAP StatisticsView::_hbmpBuf;
// Window Handle
HWND StatisticsView::_hWnd;
// Model Object
StatisticsModel *StatisticsView::_model;
#pragma endregion
StatisticsView::StatisticsView(StatisticsModel *model)
{
_process = PROCESS_ALL;
_model = model;
_hdcBuf = 0;
_hbmpBuf = 0;
}
StatisticsView::~StatisticsView()
{
DeleteDC(_hdcBuf);
DeleteObject(_hbmpBuf);
}
void StatisticsView::SetProcess(int puid)
{
_process = puid;
DrawGraph();
}
void StatisticsView::TimerProc(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
_model->UpdateRate();
DrawGraph();
}
void StatisticsView::DrawGraph()
{
RECT stRect;
GetClientRect(_hWnd, &stRect);
int _width = stRect.right - stRect.left;
int _height = stRect.bottom - stRect.top;
// ------------------- ------------------- ------------------- -------------------
// Summary | Protocol | PacketSize | Rate |
// | | | | | | | |
// | | | | | | | |
// | | | | | | | |
// | | | | | | | |
// | | | | | | | |
// | | | | | | | |
// | | | | | | | |
// ------------------- ------------------- ------------------- -------------------
// Rectangle for summary box
int smr_x = 12;
int smr_y = 8;
int smr_width = 165;
int smr_height = _height - 8 - 10;
int smrct_x = 0;
int smrct_y = 0;
int smrct_width = 0;
int smrct_height = 0;
// Rectangle for protocol box
int ptl_x = smr_x + smr_width + 16;
int ptl_y = 8;
int ptl_width = 220 ;
int ptl_height = _height - 8 - 10;
// Rectangle for protocol box's content
int ptlct_x = 0;
int ptlct_y = 0;
int ptlct_width = 0;
int ptlct_height = 0;
// Rectangle for PacketSize Box
int psz_x = ptl_x + ptl_width + 16;
int psz_y = 8;
int psz_width = 160;
int psz_height = _height - 8 - 10 ;
// Rectangle for protocol box's content
int pszct_x = 0;
int pszct_y = 0;
int pszct_width = 0;
int pszct_height = 0;
// Rectangle for Rate Box
int rte_x = psz_x + psz_width + 16;
int rte_y = 8;
int rte_width = 160;
int rte_height = _height - 8 - 10 ;
// Rectangle for rate box's content
int rtect_x = 0;
int rtect_y = 0;
int rtect_width = 0;
int rtect_height = 0;
// Export Model Info
StatisticsModel::StModelItem item;
_model->Export(_process, item);
// Clear Background
Rectangle(_hdcBuf, -1, -1, _width + 1, _height + 1);
// Summary ------------------------------------------------------------------------------------
GwGroupbox boxSummay(_hdcBuf, smr_x, smr_y, smr_width, smr_height,
Language::GetString(IDS_STVIEW_SUMMARY), RGB(0x30, 0x51, 0x9B));
boxSummay.Paint();
boxSummay.GetContentArea(&smrct_x, &smrct_y, &smrct_width, &smrct_height);
__int64 avgTxPacketSize = 0;
__int64 avgRxPacketSize = 0;
__int64 txPacketCount = 0;
__int64 rxPacketCount = 0;
for (int i = 0; i < 1501; i++) // 1 to 1501+ bytes
{
avgTxPacketSize += (i + 1) * item.txPacketSize[i];
avgRxPacketSize += (i + 1) * item.rxPacketSize[i];
txPacketCount += item.txPacketSize[i];
rxPacketCount += item.rxPacketSize[i];
}
avgTxPacketSize = (txPacketCount == 0) ? 0 : avgTxPacketSize / txPacketCount;
avgRxPacketSize = (rxPacketCount == 0) ? 0 : avgRxPacketSize / rxPacketCount;
__int64 avgTxRate = 0;
__int64 avgRxRate = 0;
__int64 txSecondCount = 0;
__int64 rxSecondCount = 0;
for (int i = 1; i < 1025; i++) // 0 to 1024+ KB/s
{
avgTxRate += i * item.txRate[i];
avgRxRate += i * item.rxRate[i];
txSecondCount += item.txRate[i];
rxSecondCount += item.rxRate[i];
}
avgTxRate = (txSecondCount == 0) ? 0 : avgTxRate / txSecondCount;
avgRxRate = (rxSecondCount == 0) ? 0 : avgRxRate / rxSecondCount;
int txIdleRatio = (txSecondCount + item.txRate[0] == 0) ? 0 :
(int)(item.txRate[0] * 1000 / (txSecondCount + item.txRate[0])); // 0.0% ~ 100.0%
int rxIdleRatio = (rxSecondCount + item.rxRate[0] == 0) ? 0 :
(int)(item.rxRate[0] * 1000 / (rxSecondCount + item.rxRate[0]));
TCHAR buf[64];
_stprintf_s(buf, 64, TEXT("%s: %I64d"),
Language::GetString(IDS_STVIEW_AVG_TX_PKT_SIZE), avgTxPacketSize);
GwLabel lblAverageTxPacketSize(_hdcBuf, smrct_x, smrct_y + 4, smrct_width, smrct_height, buf);
_stprintf_s(buf, 64, TEXT("%s: %I64d"),
Language::GetString(IDS_STVIEW_AVG_RX_PKT_SIZE), avgRxPacketSize);
GwLabel lblAverageRxPacketSize(_hdcBuf, smrct_x, smrct_y + 24, smrct_width, smrct_height, buf);
_stprintf_s(buf, 64, TEXT("%s: %d.%d%%"),
Language::GetString(IDS_STVIEW_TX_IDLE_RATIO), txIdleRatio / 10, txIdleRatio % 10);
GwLabel lblTxIdleRatio(_hdcBuf, smrct_x, smrct_y + 44, smrct_width, smrct_height, buf);
_stprintf_s(buf, 64, TEXT("%s: %d.%d%%"),
Language::GetString(IDS_STVIEW_RX_IDLE_RATIO), rxIdleRatio / 10, rxIdleRatio % 10);
GwLabel lblRxIdleRatio(_hdcBuf, smrct_x, smrct_y + 64, smrct_width, smrct_height, buf);
_stprintf_s(buf, 64, TEXT("%s: %I64d KB/s"),
Language::GetString(IDS_STVIEW_AVG_TX_RATE), avgTxRate);
GwLabel lblAverageTxRate(_hdcBuf, smrct_x, smrct_y + 84, smrct_width, smrct_height, buf);
_stprintf_s(buf, 64, TEXT("%s: %I64d KB/s"),
Language::GetString(IDS_STVIEW_AVG_RX_RATE), avgRxRate);
GwLabel lblAverageRxRate(_hdcBuf, smrct_x, smrct_y + 104, smrct_width, smrct_height, buf);
lblAverageTxPacketSize.Paint();
lblAverageRxPacketSize.Paint();
lblTxIdleRatio.Paint();
lblRxIdleRatio.Paint();
lblAverageTxRate.Paint();
lblAverageRxRate.Paint();
// Protocol -----------------------------------------------------------------------------------
GwGroupbox boxProtocol(_hdcBuf, ptl_x, ptl_y, ptl_width, ptl_height,
Language::GetString(IDS_STVIEW_PROTOCOL), RGB(0x30, 0x51, 0x9B));
boxProtocol.Paint();
boxProtocol.GetContentArea(&ptlct_x, &ptlct_y, &ptlct_width, &ptlct_height);
COLORREF colors[4] =
{
RGB(0xB0, 0xC4, 0xDE),
RGB(0x9A, 0xCD, 0x32),
RGB(0xDE, 0xD8, 0x87),
RGB(0xC6, 0xE2, 0xFF)
};
const TCHAR *txDescs[4] =
{
Language::GetString(IDS_STVIEW_TX_TCP),
Language::GetString(IDS_STVIEW_TX_UDP),
Language::GetString(IDS_STVIEW_TX_ICMP),
Language::GetString(IDS_STVIEW_TX_OTHER),
};
__int64 txValues[4] =
{
item.tx.tcpBytes,
item.tx.udpBytes,
item.tx.icmpBytes,
item.tx.otherBytes
};
const TCHAR *rxDescs[4] =
{
Language::GetString(IDS_STVIEW_RX_TCP),
Language::GetString(IDS_STVIEW_RX_UDP),
Language::GetString(IDS_STVIEW_RX_ICMP),
Language::GetString(IDS_STVIEW_RX_OTHER),
};
__int64 rxValues[4] =
{
item.rx.tcpBytes,
item.rx.udpBytes,
item.rx.icmpBytes,
item.rx.otherBytes
};
GwPieChart txPieChart(_hdcBuf,
ptlct_x, ptlct_y, ptlct_width, (ptlct_height - 4) / 2,
txDescs, colors, txValues, 4);
txPieChart.Paint();
GwPieChart rxPieChart(_hdcBuf,
ptlct_x, ptlct_y + (ptlct_height - 4) / 2 + 4, ptlct_width, ptlct_height / 2,
rxDescs, colors, rxValues, 4);
rxPieChart.Paint();
// Packet Size --------------------------------------------------------------------------------
GwGroupbox boxPacketSize(_hdcBuf, psz_x, psz_y, psz_width, psz_height,
Language::GetString(IDS_STVIEW_PACKET_SIZE), RGB(0x30, 0x51, 0x9B));
boxPacketSize.Paint();
boxPacketSize.GetContentArea(&pszct_x, &pszct_y, &pszct_width, &pszct_height);
int pszScales[4] = {1, 100, 600, 1500};
GwLogHistogram txPszHistogram(_hdcBuf,
pszct_x, pszct_y, pszct_width, pszct_height / 2,
item.txPacketSize, 1501, pszScales, 4,
Language::GetString(IDS_STVIEW_TX), RGB(0xDF, 0x00, 0x24), 4, 4);
GwLogHistogram rxPszHistogram(_hdcBuf,
pszct_x, pszct_y + pszct_height / 2, pszct_width, pszct_height / 2,
item.rxPacketSize, 1501, pszScales, 4,
Language::GetString(IDS_STVIEW_RX), RGB(0x31, 0x77, 0xC1), 4, 4);
txPszHistogram.Paint();
rxPszHistogram.Paint();
// Rate ---------------------------------------------------------------------------------------
GwGroupbox boxRate(_hdcBuf, rte_x, rte_y, rte_width, rte_height,
Language::GetString(IDS_STVIEW_RATE), RGB(0x30, 0x51, 0x9B));
boxRate.Paint();
boxRate.GetContentArea(&rtect_x, &rtect_y, &rtect_width, &rtect_height);
int rteScales[3] = {10, 150, 1024};
GwLogHistogram txRteHistogram(_hdcBuf,
rtect_x, rtect_y, rtect_width, rtect_height / 2,
item.txRate + 1, 1025 - 1, rteScales, 3,
Language::GetString(IDS_STVIEW_TX), RGB(0xDF, 0x00, 0x24), 4, 4);
GwLogHistogram rxRteHistogram(_hdcBuf,
rtect_x, rtect_y + rtect_height / 2, rtect_width, rtect_height / 2,
item.rxRate + 1, 1025 - 1, rteScales, 3,
Language::GetString(IDS_STVIEW_RX), RGB(0x31, 0x77, 0xC1), 4, 4);
txRteHistogram.Paint();
rxRteHistogram.Paint();
// Write to Screen
BitBlt(_hdcTarget, 0, 0, _width, _height, _hdcBuf, 0, 0, SRCCOPY);
}
INT_PTR StatisticsView::DlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_INITDIALOG )
{
_hWnd = hWnd;
// Init GDI Objects
// - Device Context & Bitmap
_hdcTarget = GetDC(hWnd);
if (_hdcBuf == 0 )
{
_hdcBuf = CreateCompatibleDC(_hdcTarget);
_hbmpBuf = CreateCompatibleBitmap(_hdcTarget, 2000, 1200); // Suppose enough
SelectObject(_hdcBuf, _hbmpBuf);
}
// - Pen
SelectObject(_hdcBuf, GetStockObject(DC_PEN));
// - Brush
SelectObject(_hdcBuf, GetStockObject(DC_BRUSH));
// Start Timer
SetTimer(hWnd, 0, 1000, StatisticsView::TimerProc);
}
else if (uMsg == WM_CLOSE )
{
KillTimer(hWnd, 0);
ReleaseDC(hWnd, _hdcTarget);
_hdcTarget = 0;
DestroyWindow(hWnd);
}
else if (uMsg == WM_PAINT )
{
PAINTSTRUCT stPS;
BeginPaint(hWnd, &stPS);
DrawGraph();
EndPaint(hWnd, &stPS);
}
else if (uMsg == WM_SIZE )
{
DrawGraph();
}
else
{
return FALSE;
}
return TRUE;
}
| [
"feng32tc@gmail.com@87ccf362-1046-b798-cbb8-c0ac7894b67e"
] | feng32tc@gmail.com@87ccf362-1046-b798-cbb8-c0ac7894b67e |
4b60f413507d8457b555a5b4c0c4d50ee772ae78 | 14c41dd51d2ee95b1045831ebffa11b699b2bc03 | /lotofacil_grupo.hpp | 075737e397715dd1d75e4069d0a029fe261c33cc | [] | no_license | fabiuz/ltk_gerador_de_dados_lotofacil | c5965b369f4abc5e173fe8a5eb1f424710a9c81e | 9c2549927ee585f02cdf692524ca5f8054af34c8 | refs/heads/master | 2018-09-30T01:28:24.154247 | 2018-06-09T18:48:32 | 2018-06-09T18:48:32 | 112,659,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,779 | hpp | #ifndef LOTOFACIL_GRUPO_HPP
#define LOTOFACIL_GRUPO_HPP
#endif // LOTOFACIL_GRUPO_HPP
#include <cstdio>
/*
* No código abaixo, há vários parâmetros, ao invés disto, irei passar um arranjo com todas as bolas,
* neste caso, o código fica com mais desempenho.
*
*
long obter_id_grupo_2_bolas(long b1, long b2);
long obter_id_grupo_3_bolas(long b1, long b2, long b3);
long obter_id_grupo_4_bolas(long b1, long b2, long b3, long b4);
long obter_id_grupo_5_bolas(long b1, long b2, long b3, long b4, long b5);
long obter_id_grupo_6_bolas(long b1, long b2, long b3, long b4, long b5, long b6);
long obter_id_grupo_7_bolas(long b1, long b2, long b3, long b4, long b5, long b6, long b7);
long obter_id_grupo_8_bolas(long b1, long b2, long b2, long b2, long b2, long b2, long b2, long b2);
long obter_id_grupo_9_bolas(long b1, long b2, long b2, long b2, long b2, long b2, long b2, long b2, long b2);
long obter_id_grupo_10_bolas(long b1, long b2, long b2, long b2, long b2, long b2, long b2, long b2, long b2, long b2);
*/
long obter_id_grupo_2_bolas(const long * bolas);
long obter_id_grupo_3_bolas(const long * bolas);
long obter_id_grupo_4_bolas(const long * bolas);
long obter_id_grupo_5_bolas(const long * bolas);
long obter_id_grupo_6_bolas(const long * bolas);
long obter_id_grupo_7_bolas(const long * bolas);
long obter_id_grupo_8_bolas(const long * bolas);
long obter_id_grupo_9_bolas(const long * bolas);
long obter_id_grupo_10_bolas(const long * bolas);
bool gerar_grupo_id();
inline bool gerar_lotofacil_grupo(long ltf_id, long ltf_qt, const long * lotofacil_bolas, FILE ** f_lotofacil_grupo){
if(!((ltf_qt >= 15) && (ltf_qt <= 18))){
// Retorna 1, se há erro.
return 1;
}
FILE *f_arquivo = f_lotofacil_grupo[0];
long bolas[11]; // Será usado os índices de 1 a 10.
f_arquivo = f_lotofacil_grupo[2];
for(long b1 = 1; b1 <= ltf_qt; b1++){
for(long b2 = b1 + 1; b2 <= ltf_qt; b2++){
bolas[0] = 0;
bolas[1] = lotofacil_bolas[b1];
bolas[2] = lotofacil_bolas[b2];
long id_grupo = obter_id_grupo_2_bolas(bolas);
fprintf(f_arquivo, "\n%li;%li;%li", ltf_id, ltf_qt, id_grupo);
}
}
f_arquivo = f_lotofacil_grupo[3];
for(long b1 = 1; b1 <= ltf_qt; b1++){
for(long b2 = b1 + 1; b2 <= ltf_qt; b2++){
for(long b3 = b2 + 1; b3 <= ltf_qt; b3++){
bolas[0] = 0;
bolas[1] = lotofacil_bolas[b1];
bolas[2] = lotofacil_bolas[b2];
bolas[3] = lotofacil_bolas[b3];
long id_grupo = obter_id_grupo_3_bolas(bolas);
fprintf(f_arquivo, "\n%li;%li;%li", ltf_id, ltf_qt, id_grupo);
}
}
}
/*
f_arquivo = f_lotofacil_grupo[4];
for(long b1 = 1; b1 <= ltf_qt; b1++){
for(long b2 = b1 + 1; b2 <= ltf_qt; b2++){
for(long b3 = b2 + 1; b3 <= ltf_qt; b3++){
for(long b4 = b3 + 1; b4 <= ltf_qt; b4++){
bolas[0] = 0;
bolas[1] = lotofacil_bolas[b1];
bolas[2] = lotofacil_bolas[b2];
bolas[3] = lotofacil_bolas[b3];
bolas[4] = lotofacil_bolas[b4];
long id_grupo = obter_id_grupo_4_bolas(bolas);
fprintf(f_arquivo, "\n%li;%li;%li", ltf_id, ltf_qt, id_grupo);
}
}
}
}
f_arquivo = f_lotofacil_grupo[5];
for(long b1 = 1; b1 <= ltf_qt; b1++){
for(long b2 = b1 + 1; b2 <= ltf_qt; b2++){
for(long b3 = b2 + 1; b3 <= ltf_qt; b3++){
for(long b4 = b3 + 1; b4 <= ltf_qt; b4++){
for(long b5 = b4 + 1; b5 <= ltf_qt; b5++){
bolas[0] = 0;
bolas[1] = lotofacil_bolas[b1];
bolas[2] = lotofacil_bolas[b2];
bolas[3] = lotofacil_bolas[b3];
bolas[4] = lotofacil_bolas[b4];
bolas[5] = lotofacil_bolas[b5];
long id_grupo = obter_id_grupo_5_bolas(bolas);
fprintf(f_arquivo, "\n%li;%li;%li", ltf_id, ltf_qt, id_grupo);
}
}
}
}
}
*/
// Não iremos utilizar o código abaixo, pois, o arquivo *.csv é muito grande e
// também acho desnecessário.
/*
f_arquivo = f_lotofacil_grupo[6];
for(long b1 = 1; b1 <= ltf_qt; b1++){
for(long b2 = b1 + 1; b2 <= ltf_qt; b2++){
for(long b3 = b2 + 1; b3 <= ltf_qt; b3++){
for(long b4 = b3 + 1; b4 <= ltf_qt; b4++){
for(long b5 = b4 + 1; b5 <= ltf_qt; b5++)
for(long b6 = b5 + 1; b6 <= ltf_qt; b6++)
{
bolas[0] = 0;
bolas[1] = lotofacil_bolas[b1];
bolas[2] = lotofacil_bolas[b2];
bolas[3] = lotofacil_bolas[b3];
bolas[4] = lotofacil_bolas[b4];
bolas[5] = lotofacil_bolas[b5];
bolas[6] = lotofacil_bolas[b6];
long id_grupo = obter_id_grupo_6_bolas(bolas);
fprintf(f_arquivo, "\n%li;%li;%li", ltf_id, ltf_qt, id_grupo);
}
}
}
}
}
f_arquivo = f_lotofacil_grupo[7];
for(long b1 = 1; b1 <= ltf_qt; b1++){
for(long b2 = b1 + 1; b2 <= ltf_qt; b2++){
for(long b3 = b2 + 1; b3 <= ltf_qt; b3++){
for(long b4 = b3 + 1; b4 <= ltf_qt; b4++){
for(long b5 = b4 + 1; b5 <= ltf_qt; b5++){
for(long b6 = b5 + 1; b6 <= ltf_qt; b6++){
for(long b7 = b6 + 1; b7 <= ltf_qt; b7++)
{
bolas[0] = 0;
bolas[1] = lotofacil_bolas[b1];
bolas[2] = lotofacil_bolas[b2];
bolas[3] = lotofacil_bolas[b3];
bolas[4] = lotofacil_bolas[b4];
bolas[5] = lotofacil_bolas[b5];
bolas[6] = lotofacil_bolas[b6];
bolas[7] = lotofacil_bolas[b7];
long id_grupo = obter_id_grupo_7_bolas(bolas);
fprintf(f_arquivo, "\n%li;%li;%li", ltf_id, ltf_qt, id_grupo);
}
}
}
}
}
}
}
f_arquivo = f_lotofacil_grupo[8];
for(long b1 = 1; b1 <= ltf_qt; b1++){
for(long b2 = b1 + 1; b2 <= ltf_qt; b2++){
for(long b3 = b2 + 1; b3 <= ltf_qt; b3++){
for(long b4 = b3 + 1; b4 <= ltf_qt; b4++){
for(long b5 = b4 + 1; b5 <= ltf_qt; b5++){
for(long b6 = b5 + 1; b6 <= ltf_qt; b6++){
for(long b7 = b6 + 1; b7 <= ltf_qt; b7++)
for(long b8 = b7 + 1; b8 <= ltf_qt; b8++)
{
bolas[0] = 0;
bolas[1] = lotofacil_bolas[b1];
bolas[2] = lotofacil_bolas[b2];
bolas[3] = lotofacil_bolas[b3];
bolas[4] = lotofacil_bolas[b4];
bolas[5] = lotofacil_bolas[b5];
bolas[6] = lotofacil_bolas[b6];
bolas[7] = lotofacil_bolas[b7];
bolas[8] = lotofacil_bolas[b8];
long id_grupo = obter_id_grupo_8_bolas(bolas);
fprintf(f_arquivo, "\n%li;%li;%li", ltf_id, ltf_qt, id_grupo);
}
}
}
}
}
}
}
f_arquivo = f_lotofacil_grupo[9];
for(long b1 = 1; b1 <= ltf_qt; b1++){
for(long b2 = b1 + 1; b2 <= ltf_qt; b2++){
for(long b3 = b2 + 1; b3 <= ltf_qt; b3++){
for(long b4 = b3 + 1; b4 <= ltf_qt; b4++){
for(long b5 = b4 + 1; b5 <= ltf_qt; b5++){
for(long b6 = b5 + 1; b6 <= ltf_qt; b6++){
for(long b7 = b6 + 1; b7 <= ltf_qt; b7++){
for(long b8 = b7 + 1; b8 <= ltf_qt; b8++){
for(long b9 = b8 + 1; b9 <= ltf_qt; b9++)
{
bolas[0] = 0;
bolas[1] = lotofacil_bolas[b1];
bolas[2] = lotofacil_bolas[b2];
bolas[3] = lotofacil_bolas[b3];
bolas[4] = lotofacil_bolas[b4];
bolas[5] = lotofacil_bolas[b5];
bolas[6] = lotofacil_bolas[b6];
bolas[7] = lotofacil_bolas[b7];
bolas[8] = lotofacil_bolas[b8];
bolas[9] = lotofacil_bolas[b9];
long id_grupo = obter_id_grupo_9_bolas(bolas);
fprintf(f_arquivo, "\n%li;%li;%li", ltf_id, ltf_qt, id_grupo);
}
}
}
}
}
}
}
}
}
f_arquivo = f_lotofacil_grupo[10];
for(long b1 = 1; b1 <= ltf_qt; b1++){
for(long b2 = b1 + 1; b2 <= ltf_qt; b2++){
for(long b3 = b2 + 1; b3 <= ltf_qt; b3++){
for(long b4 = b3 + 1; b4 <= ltf_qt; b4++){
for(long b5 = b4 + 1; b5 <= ltf_qt; b5++){
for(long b6 = b5 + 1; b6 <= ltf_qt; b6++){
for(long b7 = b6 + 1; b7 <= ltf_qt; b7++){
for(long b8 = b7 + 1; b8 <= ltf_qt; b8++){
for(long b9 = b8 + 1; b9 <= ltf_qt; b9++)
for(long b10 = b9 + 1; b10 <= ltf_qt; b10++)
{
bolas[0] = 0;
bolas[1] = lotofacil_bolas[b1];
bolas[2] = lotofacil_bolas[b2];
bolas[3] = lotofacil_bolas[b3];
bolas[4] = lotofacil_bolas[b4];
bolas[5] = lotofacil_bolas[b5];
bolas[6] = lotofacil_bolas[b6];
bolas[7] = lotofacil_bolas[b7];
bolas[8] = lotofacil_bolas[b8];
bolas[9] = lotofacil_bolas[b9];
long id_grupo = obter_id_grupo_10_bolas(bolas);
fprintf(f_arquivo, "\n%li;%li;%li", ltf_id, ltf_qt, id_grupo);
}
}
}
}
}
}
}
}
}
*/
return true;
}
| [
"ccmaismais@yahoo.com"
] | ccmaismais@yahoo.com |
688e82c5e5d0bf975364ffcac6045b41d15a376a | f6fd5f8bcda62e2b9c3c2b0267c8245100316a10 | /codechef/JanuaryChallenge/DPARIS.cpp | c8130481568df276d7f7e53c83dd2e91afabb53b | [] | no_license | hymsly/CompetitiveProgramming | 9f292673dd6b1809deb354b9d9b0e85c820201f1 | daf91095fab74e5a4f6441e34263ea3db1290d4a | refs/heads/master | 2021-07-24T09:42:33.589976 | 2020-05-19T14:26:58 | 2020-05-19T14:26:58 | 172,566,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 811 | cpp | #include <bits/stdc++.h>
using namespace std;
#define fore(i, a, b) for (int i = a, to = b; i < to; i++)
#define all(v) v.begin(), v.end()
#define SZ(v) (int)v.size()
#define pb push_back
#define fi first
#define se second
typedef long long ll;
typedef pair<int, int> Pair;
const int INF = (2e9);
int main() {
ios::sync_with_stdio(0);
cin.tie(NULL);
int n, m;
cin >> n >> m;
int mini = INF, maxi = -INF;
int minIdx, maxIdx;
int num;
fore(i, 0, n) {
cin >> num;
if (maxi < num) {
maxi = num;
maxIdx = i;
}
}
fore(i, 0, m) {
cin >> num;
if (mini > num) {
mini = num;
minIdx = i;
}
}
fore(i, 0, m) cout << maxIdx << " " << i << '\n';
fore(i, 0, n) {
if (i == maxIdx) continue;
cout << i << " " << minIdx << '\n';
}
return 0;
}
| [
"hamaro2511@gmail.com"
] | hamaro2511@gmail.com |
279cfe9c25305c9d12e827ebe1fc6fe891acfb6a | 52b0eac90b9f30f279563b944777e7ac31dbd0a1 | /DotNetGotchas/CSharp/ClassInterfaceType/COMClient/COMClient.cpp | 0c93b302165448e1fce38aa6d81b5fcc45d81feb | [] | no_license | yanglr/dotNET-Gotchas | c638189ccac5ffd96ac75648d267080065a18c25 | 46373395d5b02891a8c191b32a01517484c2efbb | refs/heads/master | 2022-11-05T18:47:46.565267 | 2020-06-23T14:14:10 | 2020-06-23T14:14:10 | 274,420,477 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 160 | cpp | // COMClient.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
| [
"booktech@oreilly.com"
] | booktech@oreilly.com |
8b0ff0aede8cbda87552556eb34e49429901eaa3 | 9f0c51ab161e4adc1207e0bef70200c4ec4d20c5 | /src/kdc_arm_tf2/src/kdc_pose_tf.cpp | 60a1db28a13d50a47eca8f99584389052111a09b | [] | no_license | tartanBot/BOOST1 | b3f8229e20142a9d27c48f901d0b4a567e189105 | 637c2cfaac46eb3c41547bf56172c8f01ef456d4 | refs/heads/master | 2021-06-25T08:05:54.460186 | 2017-08-20T02:38:03 | 2017-08-20T02:38:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,082 | cpp | #include <ros/ros.h>
#include <tf2_ros/transform_listener.h>
#include <tf2_ros/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
void arucoPoseCallback(const geometry_msgs::TransformStamped::ConstPtr& msg)
{
static tf2_ros::TransformBroadcaster br;
geometry_msgs::TransformStamped transformStamped;
transformStamped.header.stamp = ros::Time::now();
transformStamped.header.frame_id = "duo3d_camera";
transformStamped.child_frame_id = "board1";
transformStamped.transform = msg->transform;
br.sendTransform(transformStamped);
}
int main(int argc, char** argv){
ros::init(argc, argv, "kdc_tf2_listener");
ros::NodeHandle node;
ros::Subscriber sub;
sub = node.subscribe("/ar_single_board/transform", 10, &arucoPoseCallback);
ros::spin();
return 0;
};
// void tfCallback(const geometry_msgs::TransformStamped& transformStamped){
// static tf2_ros::TransformBroadcaster br;
// tf2_ros::Buffer tfBuffer;
// tf2_ros::TransformListener tfListener(tfBuffer);
// transformStamped = tfBuffer.lookupTransform("board1", "base_link", ros::Time(0));
// br.sendTransform(transformStamped);
// }
// int main(int argc, char** argv){
// ros::init(argc, argv, "kdc_tf2_listener");
// ros::NodeHandle node;
// ros::Subscriber sub = node.subscribe("/ar_single_board/transform", 10 &tfCallback);
// ros::Publisher board_tf =
// node.advertise<geometry_msgs::TransformStamped>("kdc_arm", 10);
// // tf2_ros::Buffer tfBuffer;
// // tf2_ros::TransformListener tfListener(tfBuffer);
// // ros::Rate rate(10.0);
// // while (node.ok()){
// // geometry_msgs::TransformStamped transformStamped;
// // try{
// // transformStamped = tfBuffer.lookupTransform("board1", "base_link",
// // ros::Time(0));
// // }
// // catch (tf2::TransformException &ex) {
// // ROS_WARN("%s",ex.what());
// // ros::Duration(1.0).sleep();
// // continue;
// // }
// // board_tf.publish(transformStamped);
// rate.sleep();
// }
// return 0;
// }; | [
"merrittj@andrew.cmu.edu"
] | merrittj@andrew.cmu.edu |
582b0b8098367699d94e3d818a7c325ae44110e6 | 04579fb7426b9cf8d7b3877334bc927bb0c79e87 | /Source/TestingGrounds/AI/PatrolRoute.h | e644b210412a43b10ee3212c2f08c68a66fad081 | [] | no_license | SeanSiders/TestingGrounds | ad3fab8ce9b3b9c5df7e1ecea6effc54f8dde511 | 0335f849227ed3f123021094d9ed4e0ccff3893a | refs/heads/master | 2022-01-18T16:38:32.225650 | 2022-01-13T19:35:19 | 2022-01-13T19:35:19 | 170,135,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 430 | h | #pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "PatrolRoute.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class TESTINGGROUNDS_API UPatrolRoute : public UActorComponent
{
GENERATED_BODY()
public:
TArray<AActor*> GetPatrolPoints() const;
private:
UPROPERTY(EditInstanceOnly, Category = "Patrol Route")
TArray<AActor*> PatrolPoints;
};
| [
"sean.siders@icloud.com"
] | sean.siders@icloud.com |
40f49dba5510f6abb6c1424fd448b509eca06940 | 569c3e3312583b197433424d166ebb2b0105b843 | /C++/class/cbasse.cpp | 0afd1da4c4379169b223059e06a3ccb9a14a3a17 | [] | no_license | MagnetoWang/Mr-Wang-s-Code | 81c693562caca3a77ddf98ab8e6ecfa06de1d3c9 | 84de0734b2e6ffe6d40de6ac4e1f88dd62c27756 | refs/heads/master | 2021-01-21T15:04:41.861580 | 2018-05-01T13:33:24 | 2018-05-01T13:33:24 | 59,352,588 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 43 | cpp | #include "cbasse.h"
CBasse::CBasse()
{
}
| [
"1527672216@qq.com"
] | 1527672216@qq.com |
fb6efcb5d41fc0fa651afe2b68858b30a6ee0701 | aaa3eb8aa16289dd1a9235c7854bf55d5e557520 | /net/ssl/sslsocket.cpp | 3440a726340d3554c301794c6c6eca53632e8c16 | [] | no_license | yangjietadie/common | 5d46f3528ca16f728b92b2872838ac0b8eb302d5 | 2d87039d75d665b92d4f4cf368a422e656fa2b05 | refs/heads/master | 2023-03-19T23:30:52.659245 | 2019-07-29T03:04:52 | 2019-07-29T03:04:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,664 | cpp | // Copyright (c) 2015, Wang Yaofu
// All rights reserved.
//
// Author: Wang Yaofu, voipman@qq.com.
// Created: 06/03/2015
// Description: file of socket openssl.
#include <stdio.h>
#include "sslsocket.h"
using std::string;
namespace {
// extract error messages from error queue
void buildErrors(std::string& errors, int errno_copy) {
unsigned long errorCode;
char message[256];
errors.reserve(512);
while ((errorCode = ERR_get_error()) != 0) {
if (!errors.empty()) {
errors += "; ";
}
const char* reason = ERR_reason_error_string(errorCode);
if (reason != NULL) {
errors += reason;
}
}
if (errors.empty()) {
if (errno_copy != 0) {
errors += strerror(errno_copy);
}
}
}
}
// SSLContext implementation
SSLContext::SSLContext(const SSLProtocol& protocol) {
switch (protocol)
{
case SSLTLS:
ctx_ = SSL_CTX_new(SSLv23_method());
break;
case SSLv3:
ctx_ = SSL_CTX_new(SSLv3_method());
break;
case TLSv1_0:
ctx_ = SSL_CTX_new(TLSv1_method());
break;
case TLSv1_1:
ctx_ = SSL_CTX_new(TLSv1_1_method());
break;
case TLSv1_2:
ctx_ = SSL_CTX_new(TLSv1_2_method());
break;
default:
break;
}
if (ctx_ == NULL) {
std::string errors;
buildErrors(errors, errno);
throw SSLException("SSL_CTX_new: " + errors);
}
SSL_CTX_set_mode(ctx_, SSL_MODE_AUTO_RETRY);
// Disable horribly insecure SSLv2!
if (protocol == SSLTLS) {
SSL_CTX_set_options(ctx_, SSL_OP_NO_SSLv2);
}
}
SSLContext::~SSLContext() {
if (ctx_ != NULL) {
SSL_CTX_free(ctx_);
ctx_ = NULL;
}
}
SSL* SSLContext::createSSL() {
SSL* ssl = SSL_new(ctx_);
if (ssl == NULL) {
string errors;
buildErrors(errors, errno);
throw SSLException("SSL_new: " + errors);
}
return ssl;
}
SSLSocket::SSLSocket() {
}
SSLSocket::~SSLSocket() {
SSL_UnInit();
}
int SSLSocket::SSL_Init(const std::string& aCACertFile,
const std::string& aPrivKeyFile,
const std::string& aCipher,
bool aIsClient) {
// SSL library initialize.
SSL_library_init();
// load all SSL cipher.
OpenSSL_add_all_algorithms();
// load all SSL error message.
SSL_load_error_strings();
if (aIsClient) {
// SSL client.
mSsl_ctx = new SSLContext(SSLTLS);
if (mSsl_ctx == NULL) {
ERR_print_errors_fp(stderr);
return RET_ERROR;
}
}
else {
// SSL server.
// SSL_CTX(SSL Content Text) is created by SSL V2 and V3.
mSsl_ctx = new SSLContext(SSLTLS);
// V2 by SSLv2_server_method(), V3 by SSLv3_server_method().
if (mSsl_ctx == NULL) {
ERR_print_errors_fp(stderr);
return RET_ERROR;
}
// load user CA, it is sent to client. public key is in this CA.
if (SSL_CTX_use_certificate_file(mSsl_ctx->get(), aCACertFile.c_str(), SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
return RET_ERROR;
}
// load user private key.
if (SSL_CTX_use_PrivateKey_file(mSsl_ctx->get(), aPrivKeyFile.c_str(), SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
return RET_ERROR;
}
// check whether user private key is OK.
if (!SSL_CTX_check_private_key(mSsl_ctx->get())) {
ERR_print_errors_fp(stderr);
return RET_ERROR;
}
if (!aCipher.empty()) {
if (SSL_CTX_set_cipher_list(mSsl_ctx->get(), aCipher.c_str()) == 0) {
ERR_print_errors_fp(stderr);
return RET_ERROR;
}
}
}
return RET_OK;
}
void SSLSocket::SSL_UnInit() {
std::map<int, SSL*>::iterator it = mSsl.begin();
for (; it != mSsl.end(); ++it) {
SSL_shutdown(it->second);
SSL_free(it->second);
}
mSsl.clear();
if (mSsl_ctx != NULL) {
delete mSsl_ctx;
mSsl_ctx = NULL;
}
}
int SSLSocket::SSL_Read(int aSockId, char *aBuffer, int aLen) {
int32_t bytes = 0;
SSL* ssl = mSsl[aSockId];
for (int32_t retries = 0; retries < 5; retries++){
bytes = SSL_read(ssl, aBuffer, aLen);
if (bytes >= 0)
break;
if (SSL_get_error(ssl, bytes) == SSL_ERROR_SYSCALL) {
if (ERR_get_error() == 0 && errno == EINTR) {
continue;
}
}
std::string errors;
buildErrors(errors, errno);
throw SSLException(errors);
}
return bytes;
}
int SSLSocket::SSL_Write(int aSockId, char *aBuffer, int aLen) {
uint32_t written = 0;
SSL* ssl = mSsl[aSockId];
while (written < aLen) {
int32_t bytes = SSL_write(ssl, &aBuffer[written], aLen - written);
if (bytes <= 0) {
std::string errors;
buildErrors(errors, errno);
throw SSLException(errors);
}
written += bytes;
}
return written;
}
int SSLSocket::SSL_ConnHandShake(int aSockId, bool aIsClient) {
if (mSsl.find(aSockId) != mSsl.end()) {
SSL_SockClose(aSockId);
}
// create new SSL base on ctx.
mSsl[aSockId] = mSsl_ctx->createSSL();
// socket id is added into SSL.
SSL_set_fd(mSsl[aSockId], aSockId);
if (aIsClient) {
// create SSL client connection.
if (SSL_connect(mSsl[aSockId]) == RET_ERROR) {
ERR_print_errors_fp(stderr);
return RET_ERROR;
}
}
else {
// create SSL Server connection.
if (SSL_accept(mSsl[aSockId]) == RET_ERROR) {
ERR_print_errors_fp(stderr);
return RET_ERROR;
}
}
return RET_OK;
}
int SSLSocket::SSL_SockClose(int fd) {
if (mSsl.find(fd) == mSsl.end()) {
return RET_ERROR;
}
SSL_shutdown(mSsl[fd]);
SSL_free(mSsl[fd]);
mSsl.erase(fd);
return RET_OK;
}
void SSLSocket::ShowCerts(SSL * ssl) {
X509 *cert;
char *line;
cert = SSL_get_peer_certificate(ssl);
if (cert != NULL) {
fprintf(stderr, "CA Infos:\n");
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
fprintf(stderr, "CA: %s\n", line);
free(line);
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
fprintf(stderr, "Author: %s\n", line);
free(line);
X509_free(cert);
}
else {
fprintf(stderr, "no CA Infos.\n");
}
}
| [
"wangyaofu@didichuxing.com"
] | wangyaofu@didichuxing.com |
0f34189dc54139ad71d4d2acd19f4b4043a6aa17 | 367d2670c75d385d122bca60b9f550ca5b3888c1 | /gem5/src/gpu-compute/scheduler.cc | 3986658e0f4096611e74f37410a5df7d63894b2a | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.0-or-later",
"MIT"
] | permissive | Anish-Saxena/aqua_rowhammer_mitigation | 4f060037d50fb17707338a6edcaa0ac33c39d559 | 3fef5b6aa80c006a4bd6ed4bedd726016142a81c | refs/heads/main | 2023-04-13T05:35:20.872581 | 2023-01-05T21:10:39 | 2023-01-05T21:10:39 | 519,395,072 | 4 | 3 | Unlicense | 2023-01-05T21:10:40 | 2022-07-30T02:03:02 | C++ | UTF-8 | C++ | false | false | 2,308 | cc | /*
* Copyright (c) 2014-2017 Advanced Micro Devices, Inc.
* All rights reserved.
*
* For use for simulation and test purposes only
*
* 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 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 "gpu-compute/scheduler.hh"
#include "gpu-compute/of_scheduling_policy.hh"
#include "gpu-compute/rr_scheduling_policy.hh"
#include "params/ComputeUnit.hh"
Scheduler::Scheduler(const ComputeUnitParams *p)
{
if (p->execPolicy == "OLDEST-FIRST") {
schedPolicy = new OFSchedulingPolicy();
} else if (p->execPolicy == "ROUND-ROBIN") {
schedPolicy = new RRSchedulingPolicy();
} else {
fatal("Unimplemented scheduling policy.\n");
}
}
Wavefront*
Scheduler::chooseWave()
{
return schedPolicy->chooseWave(scheduleList);
}
void
Scheduler::bindList(std::vector<Wavefront*> *sched_list)
{
scheduleList = sched_list;
}
| [
"asaxena317@krishna-srv4.ece.gatech.edu"
] | asaxena317@krishna-srv4.ece.gatech.edu |
bd6bc5bfe548f1cac7e1c860dfad4f84263fbb44 | b50980d999e7a856545f41d67b309b943605317c | /generate_maze.cpp | eae94ac9be90c7b6db065059fe9c67f24c0849a7 | [] | no_license | Darren2017/Lab | ea81bf4f5bad0622d14b9ba93b3d23d3d4da0006 | b0d246a3ad254837d369568689e75e87679f51b6 | refs/heads/master | 2021-09-15T11:02:04.931872 | 2018-05-31T09:15:47 | 2018-05-31T09:15:47 | 125,730,538 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,155 | cpp | #include<iostream>
using namespace std;
short D[200][200] = {0}; //记录已走的路径
short Z[200][200] = {0}; //记录这里是否有墙
int nx[] = {1, 0, -1, 0};
int ny[] = {0, 1, 0, -1};
int M, N; //M-------高度 N --------------长度
void generate_maze(int x, int y); //产生一个迷宫,即打通相应的墙
void generate_wall(); //安放所有的墙
void print(); //显示迷宫
void read(); //读取长高
int main()
{
read();
generate_wall();
generate_maze(rand() % N, rand() % M);
print();
return 0;
}
void generate_maze(int x, int y){
D[x][y] = 1;
srand(time(0));
int n = 4, a[6];
for(int i = 1; i <= 4; i++){
a[i] = i;
}
random_shuffle(a+1,a+n+1);
for(int i = 0; i < 4; i++){
int xi = x + nx[a[i + 1] - 1];
int yi = y + ny[a[i + 1] - 1];
if(D[xi][yi] == 0 && xi < N && xi >= 0 && yi >= 0 && yi < M){
int mx = 2 * x + 1, my = 2 * y + 1;
if(i == 0){
Z[mx + 1][my] = 0;
}else if(i == 1){
Z[mx][my + 1] = 0;
}else if(i == 2){
Z[mx - 1][my] = 0;
}else{
Z[mx][my - 1] = 0;
}
generate_maze(xi, yi);
}
}
}
void generate_wall(){ //在偶数列和行安放墙
for(int i = 0; i < 2 * N + 1; i++){
if(i % 2 == 0){
for(int j = 0; j < 2 * M + 1; j++){
Z[i][j] = 1;
}
}
}
for(int i = 0; i < 2 * M + 1; i++){
if(i % 2 == 0){
for(int j = 0; j < 2 * N + 1; j++){
Z[j][i] = 1;
}
}
}
}
void print(){
for(int i = 0; i < 2 * N + 1; i++){
for(int j = 0; j < 2 * M + 1; j++){
if(Z[i][j]){
printf("# ");
}else{
printf(" ");
}
}
printf("\n");
}
}
void read(){
printf("please enter height of maze ");
scanf("%d", &M);
printf("please enter longth of maze ");
scanf("%d", &N);
} | [
"17362990052@163.com"
] | 17362990052@163.com |
3d12ed727512eca128e121e95adfb0ff9c9516fd | 726d8518a8c7a38b0db6ba9d4326cec172a6dde6 | /1209. Remove All Adjacent Duplicates in String II/Solution.cpp | 073f0caaceff6599ca61bc00e50c5083ea54cea0 | [] | no_license | faterazer/LeetCode | ed01ef62edbcfba60f5e88aad401bd00a48b4489 | d7ba416d22becfa8f2a2ae4eee04c86617cd9332 | refs/heads/master | 2023-08-25T19:14:03.494255 | 2023-08-25T03:34:44 | 2023-08-25T03:34:44 | 128,856,315 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 586 | cpp | #include <string>
#include <vector>
using namespace std;
class Solution {
public:
string removeDuplicates(string s, int k)
{
vector<pair<char, int>> buff;
for (const char &c : s) {
if (buff.empty() || buff.back().first != c)
buff.emplace_back(c, 1);
else
buff.back().second += 1;
if (buff.back().second == k)
buff.pop_back();
}
string res;
for (const pair<char, int> &p : buff)
res += string(p.second, p.first);
return res;
}
};
| [
"faterazer@outlook.com"
] | faterazer@outlook.com |
0d019bb84718a9a263abe33ff4716c57663235e5 | 99f04b10b1209f9f148eefe414a9592bd4f8fa88 | /test/maintest.cpp | 24e2202bf42a25107fdfca0cd5d5504712872e5b | [] | no_license | S-doud/sddlog | 160f90f61950995e297e0260836a18c4bf2f59dd | df9b3b9e988b64863f20ff591f3017edfc714758 | refs/heads/master | 2022-06-23T15:17:42.073303 | 2022-05-26T03:31:53 | 2022-05-26T03:31:53 | 256,119,838 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,339 | cpp | #include <thread>
#include <iostream>
#include <string.h>
#include "log.h"
using namespace std;
void threadFunc(int ind)
{
for (int i = 0; i < 100000; ++i)
{
LOG <<"thread"<<ind<<" : "<<i;
}
}
void type_test()
{
// 13 lines
cout << "----------type test-----------" << endl;
LOG << 0;
LOG << 1234567890123;
LOG << 1.0f;
LOG << 3.1415926;
LOG << (short)1;
LOG << (long long)1;
LOG << (unsigned int)1;
LOG << (unsigned long)1;
LOG << (long double) 1.6555556;
LOG << (unsigned long long) 1;
LOG << 'c';
LOG << "abcdefg";
LOG << string("This is a string");
}
void stressing_single_thread()
{
// 100000 lines
cout << "----------stressing test single thread-----------" << endl;
for (int i = 0; i < 100000; ++i)
{
LOG << i;
}
}
void stressing_multi_threads(int threadNum = 4)
{
// threadNum * 100000 lines
cout << "----------stressing test multi thread-----------" << endl;
thread tmp1(threadFunc,1);
thread tmp2(threadFunc, 2);
thread tmp3(threadFunc, 3);
thread tmp4(threadFunc, 4);
tmp1.join();
tmp2.join();
tmp3.join();
tmp4.join();
}
void other()
{
// 1 line
cout << "----------other test-----------" << endl;
LOG << "fddsa" << 'c' << 0 << 3.666 << string("This is a string");
}
int main(){
type_test();
stressing_single_thread();
stressing_multi_threads();
other();
return 0;
}
| [
"1272255407@qq.com"
] | 1272255407@qq.com |
34370d9f57f8a2254d657d7ed7dc8ff4e05c52f7 | 4c86881bd200e9a15b71b733174b3abc1924bf0d | /libSBML/src/validator/MathMLConsistencyValidator.h | f5f6b44be01108d8f75f55072aedb4c872d29a4b | [] | no_license | mgaldzic/copasi_api | 500f0d6da8349c611bafb8d8301af61fc07bb1b2 | 51b284295c2238da9c346999ff277c6883b8ca52 | refs/heads/master | 2021-01-01T06:04:39.888201 | 2011-09-16T05:29:21 | 2011-09-16T05:29:21 | 2,281,690 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,806 | h | /**
* @cond doxygen-libsbml-internal
*
* @file MathMLConsistencyValidator.h
* @brief Performs consistency checks on an SBML model
* @author Ben Bornstein
*
* $Id: MathMLConsistencyValidator.h 11634 2010-08-03 03:57:18Z mhucka $
* $HeadURL: https://sbml.svn.sourceforge.net/svnroot/sbml/trunk/libsbml/src/validator/MathMLConsistencyValidator.h $
*
*<!---------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright 2005-2010 California Institute of Technology.
* Copyright 2002-2005 California Institute of Technology and
* Japan Science and Technology Corporation.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution and
* also available online as http://sbml.org/software/libsbml/license.html
*----------------------------------------------------------------------- -->*/
#ifndef MathMLConsistencyValidator_h
#define MathMLConsistencyValidator_h
#ifdef __cplusplus
#include <sbml/validator/Validator.h>
LIBSBML_CPP_NAMESPACE_BEGIN
class MathMLConsistencyValidator: public Validator
{
public:
MathMLConsistencyValidator () :
Validator( LIBSBML_CAT_MATHML_CONSISTENCY ) { }
virtual ~MathMLConsistencyValidator () { }
/**
* Initializes this Validator with a set of Constraints.
*/
virtual void init ();
};
LIBSBML_CPP_NAMESPACE_END
#endif /* __cplusplus */
#endif /* MathMLConsistencyValidator_h */
/** @endcond */
| [
"mgaldzic@gmail.com"
] | mgaldzic@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.