blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7d7f0a577972ae3201b29c3c4be9909e9c26fd60 | abeb736f0dc1d40ea57e333659d4eaf8036418a5 | /include/singular/kernel/numeric/mpr_numeric.h | 36a49840afcf6281e652cb48852ff778b89c6b07 | [] | no_license | fingolfin/gap-osx-binary | 59825e1f7d2f7eb7417bc99dd65a756de3bf1d77 | b7ea78241904c5eb6d3726fb1ee627b48592e1c0 | refs/heads/master | 2021-01-10T11:30:51.316436 | 2015-10-02T09:54:53 | 2015-10-02T09:54:53 | 43,541,650 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,642 | h | #ifndef MPR_NUMERIC_H
#define MPR_NUMERIC_H
/****************************************
* Computer Algebra System SINGULAR *
****************************************/
/*
* ABSTRACT - multipolynomial resultants - numeric stuff
* ( root finder, vandermonde system solver, simplex )
*/
//-> include & define stuff
#include <coeffs/numbers.h>
#include <coeffs/mpr_global.h>
#include <coeffs/mpr_complex.h>
// define polish mode when finding roots
#define PM_NONE 0
#define PM_POLISH 1
#define PM_CORRUPT 2
//<-
//-> vandermonde system solver
/**
* vandermonde system solver for interpolating polynomials from their values
*/
class vandermonde
{
public:
vandermonde( const long _cn, const long _n,
const long _maxdeg, number *_p, const bool _homog = true );
~vandermonde();
/** Solves the Vandermode linear system
* \sum_{i=1}^{n} x_i^k-1 w_i = q_k, k=1,..,n.
* Any computations are done using type number to get high pecision results.
* @param q n-tuple of results (right hand of equations)
* @return w n-tuple of coefficients of resulting polynomial, lowest deg first
*/
number * interpolateDense( const number * q );
poly numvec2poly(const number * q );
private:
void init();
private:
long n; // number of variables
long cn; // real number of coefficients of poly to interpolate
long maxdeg; // degree of the polynomial to interpolate
long l; // max number of coefficients in poly of deg maxdeg = (maxdeg+1)^n
number *p; // evaluation point
number *x; // coefficients, determinend by init() from *p
bool homog;
};
//<-
//-> rootContainer
/**
* complex root finder for univariate polynomials based on laguers algorithm
*/
class rootContainer
{
public:
enum rootType { none, cspecial, cspecialmu, det, onepoly };
rootContainer();
~rootContainer();
void fillContainer( number *_coeffs, number *_ievpoint,
const int _var, const int _tdg,
const rootType _rt, const int _anz );
bool solver( const int polishmode= PM_NONE );
poly getPoly();
//gmp_complex & operator[] ( const int i );
inline gmp_complex & operator[] ( const int i )
{
return *theroots[i];
}
gmp_complex & evPointCoord( const int i );
inline gmp_complex * getRoot( const int i )
{
return theroots[i];
}
bool swapRoots( const int from, const int to );
int getAnzElems() { return anz; }
int getLDim() { return anz; }
int getAnzRoots() { return tdg; }
private:
rootContainer( const rootContainer & v );
/** Given the degree tdg and the tdg+1 complex coefficients ad[0..tdg]
* (generated from the number coefficients coeffs[0..tdg]) of the polynomial
* this routine successively calls "laguer" and finds all m complex roots in
* roots[0..tdg]. The bool var "polish" should be input as "true" if polishing
* (also by "laguer") is desired, "false" if the roots will be subsequently
* polished by other means.
*/
bool laguer_driver( gmp_complex ** a, gmp_complex ** roots, bool polish = true );
bool isfloat(gmp_complex **a);
void divlin(gmp_complex **a, gmp_complex x, int j);
void divquad(gmp_complex **a, gmp_complex x, int j);
void solvequad(gmp_complex **a, gmp_complex **r, int &k, int &j);
void sortroots(gmp_complex **roots, int r, int c, bool isf);
void sortre(gmp_complex **r, int l, int u, int inc);
/** Given the degree m and the m+1 complex coefficients a[0..m] of the
* polynomial, and given the complex value x, this routine improves x by
* Laguerre's method until it converges, within the achievable roundoff limit,
* to a root of the given polynomial. The number of iterations taken is
* returned at its.
*/
void laguer(gmp_complex ** a, int m, gmp_complex * x, int * its, bool type);
void computefx(gmp_complex **a, gmp_complex x, int m,
gmp_complex &f0, gmp_complex &f1, gmp_complex &f2,
gmp_float &ex, gmp_float &ef);
void computegx(gmp_complex **a, gmp_complex x, int m,
gmp_complex &f0, gmp_complex &f1, gmp_complex &f2,
gmp_float &ex, gmp_float &ef);
void checkimag(gmp_complex *x, gmp_float &e);
int var;
int tdg;
number * coeffs;
number * ievpoint;
rootType rt;
gmp_complex ** theroots;
int anz;
bool found_roots;
};
//<-
class slists; typedef slists * lists;
//-> class rootArranger
class rootArranger
{
public:
friend lists listOfRoots( rootArranger*, const unsigned int oprec );
rootArranger( rootContainer ** _roots,
rootContainer ** _mu,
const int _howclean = PM_CORRUPT );
~rootArranger() {}
void solve_all();
void arrange();
bool success() { return found_roots; }
private:
rootArranger( const rootArranger & );
rootContainer ** roots;
rootContainer ** mu;
int howclean;
int rc,mc;
bool found_roots;
};
//<-
//-> simplex computation
// (used by sparse matrix construction)
#define SIMPLEX_EPS 1.0e-12
/** Linear Programming / Linear Optimization using Simplex - Algorithm
*
* On output, the tableau LiPM is indexed by two arrays of integers.
* ipsov[j] contains, for j=1..m, the number i whose original variable
* is now represented by row j+1 of LiPM. (left-handed vars in solution)
* (first row is the one with the objective function)
* izrov[j] contains, for j=1..n, the number i whose original variable
* x_i is now a right-handed variable, rep. by column j+1 of LiPM.
* These vars are all zero in the solution. The meaning of n<i<n+m1+m2
* is the same as above.
*/
class simplex
{
public:
int m; // number of constraints, make sure m == m1 + m2 + m3 !!
int n; // # of independent variables
int m1,m2,m3; // constraints <=, >= and ==
int icase; // == 0: finite solution found;
// == +1 objective funtion unbound; == -1: no solution
int *izrov,*iposv;
mprfloat **LiPM; // the matrix (of size [m+2, n+1])
/** #rows should be >= m+2, #cols >= n+1
*/
simplex( int rows, int cols );
~simplex();
BOOLEAN mapFromMatrix( matrix m );
matrix mapToMatrix( matrix m );
intvec * posvToIV();
intvec * zrovToIV();
void compute();
private:
simplex( const simplex & );
void simp1( mprfloat **a, int mm, int ll[], int nll, int iabf, int *kp, mprfloat *bmax );
void simp2( mprfloat **a, int n, int l2[], int nl2, int *ip, int kp, mprfloat *q1 );
void simp3( mprfloat **a, int i1, int k1, int ip, int kp );
int LiPM_cols,LiPM_rows;
};
//<-
#endif /*MPR_NUMERIC_H*/
// local Variables: ***
// folded-file: t ***
// compile-command-1: "make installg" ***
// compile-command-2: "make install" ***
// End: ***
| [
"max@quendi.de"
] | max@quendi.de |
fc4705b07a8a1de6f6131d79d04ce0adc4407b25 | 952eaaff06d57b02cddbfa3ea244bbdca2f0e106 | /src/Utils/Utils/Math/AutomaticDifferentiation/AutomaticDifferentiationHelpers.h | 77c80cb9b08491090ebc4369f506802ceda790c0 | [
"BSD-3-Clause"
] | permissive | DockBio/utilities | 413cbde988d75a975b3e357c700caa87406c963b | 213ed5ac2a64886b16d0fee1fcecb34d36eea9e9 | refs/heads/master | 2023-02-25T20:50:19.211145 | 2020-04-27T20:41:03 | 2020-04-27T20:41:03 | 257,099,174 | 0 | 0 | BSD-3-Clause | 2020-04-27T20:41:05 | 2020-04-19T20:48:18 | null | UTF-8 | C++ | false | false | 8,450 | h | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#ifndef AUTOMATICDIFFERENTIATION_AUTOMATICDIFFERENTIATIONHELPERS_H
#define AUTOMATICDIFFERENTIATION_AUTOMATICDIFFERENTIATIONHELPERS_H
#include "../DerivOrderEnum.h"
#include "AutomaticDifferentiationTypesHelper.h"
#include "TypeDefinitions.h"
#include <Eigen/Core>
/**
*
* This header file contains functions that allow for common notation for common
* things that can be done at a different degree of derivatives.
*
*/
namespace Scine {
namespace Utils {
namespace AutomaticDifferentiation {
/**
* @brief Get the enum corresponding to the derivative order.
*/
inline derivOrder getDerivativeOrderEnum(unsigned order) {
return (order == 0) ? derivOrder::zero : order == 1 ? derivOrder::one : derivOrder::two;
}
/**
* @brief Get the integer corresponding to the derivative order.
*/
inline int getDerivativeOrder(derivOrder order) {
return (order == derivOrder::zero) ? 0 : order == derivOrder::one ? 1 : 2;
}
/**
* @brief Create a value with derivatives in 1 dimension and neglect the unnecessary derivatives.
*/
template<derivOrder o>
Value1DType<o> getFromFull(double v, double firstDer, double secondDer);
/**
* @brief Transform a double to a ValueWithDerivative in one dimension, with derivatives equal to zero.
*/
template<derivOrder o>
Value1DType<o> constant1D(double c);
/**
* @brief Transform v to a ValueWithDerivative in one dimension, with first derivative 1 and second derivative 0.
*/
template<derivOrder o>
Value1DType<o> variableWithUnitDerivative(double v);
/**
* @brief Transform a double to a ValueWithDerivative in three dimensions, with derivatives equal to zero.
*/
template<derivOrder o>
Value3DType<o> constant3D(double c);
/**
* @brief Get X as a value with derivatives in three dimensions. The only non-zero derivative is the first derivative in
* x-direction.
*/
template<derivOrder o>
Value3DType<o> toX(double x);
/**
* @brief Get Y as a value with derivatives in three dimensions. The only non-zero derivative is the first derivative in
* y-direction.
*/
template<derivOrder o>
Value3DType<o> toY(double y);
/** @brief Get Z as a value with derivatives in three dimensions. The only non-zero derivative is the first derivative
* in z-direction.
*/
template<derivOrder o>
Value3DType<o> toZ(double z);
/**
* @brief Get R-squared as a value with derivatives in three dimensions.
*/
template<derivOrder o>
Value3DType<o> toRSquared(double x, double y, double z);
/**
* @brief Get a value with derivatives in 3 dimensions from the value with derivatives in one dimension, given a vector
* R.
*/
template<derivOrder o>
Value3DType<o> get3Dfrom1D(Value1DType<o> v, const Eigen::Vector3d& R);
/**
* @brief Get the value with inverted derivatives (useful for pairs of derivatives for two atoms). The sign of the first
* derivatives changes.
*/
template<derivOrder o>
Value3DType<o> getValueWithOppositeDerivative(const Value3DType<o>& v);
/**
* @brief Extract the value with derivatives in 1 dimension as a double.
*/
template<derivOrder o>
double getValue1DAsDouble(const Value1DType<o>& v);
/**
* @brief Extract the value with derivatives in 3 dimension as a double.
*/
template<derivOrder o>
double getValue3DAsDouble(const Value3DType<o>& v);
/*
* Inline implementations of all functions declared above.
*/
template<>
inline double constant1D<derivOrder::zero>(double c) {
return c;
}
template<>
inline double variableWithUnitDerivative<derivOrder::zero>(double v) {
return v;
}
template<>
inline double getFromFull<derivOrder::zero>(double v, double /*firstDer*/, double /*secondDer*/) {
return v;
}
template<>
inline double constant3D<derivOrder::zero>(double c) {
return c;
}
template<>
inline double toX<derivOrder::zero>(double x) {
return x;
}
template<>
inline double toY<derivOrder::zero>(double y) {
return y;
}
template<>
inline double toZ<derivOrder::zero>(double z) {
return z;
}
template<>
inline double toRSquared<derivOrder::zero>(double x, double y, double z) {
return x * x + y * y + z * z;
}
template<>
inline double get3Dfrom1D<derivOrder::zero>(double v, const Eigen::Vector3d& /*R*/) {
return v;
}
template<>
inline double getValueWithOppositeDerivative<derivOrder::zero>(const double& v) {
return v;
}
template<>
inline double getValue1DAsDouble<derivOrder::zero>(const double& v) {
return v;
}
template<>
inline double getValue3DAsDouble<derivOrder::zero>(const double& v) {
return v;
}
template<>
inline First1D constant1D<derivOrder::one>(double c) {
return {c, 0};
}
template<>
inline First1D variableWithUnitDerivative<derivOrder::one>(double v) {
return {v, 1};
}
template<>
inline First1D getFromFull<derivOrder::one>(double v, double firstDer, double /*secondDer*/) {
return {v, firstDer};
}
template<>
inline First3D constant3D<derivOrder::one>(double c) {
return {c, 0, 0, 0};
}
template<>
inline First3D toX<derivOrder::one>(double x) {
return {x, 1, 0, 0};
}
template<>
inline First3D toY<derivOrder::one>(double y) {
return {y, 0, 1, 0};
}
template<>
inline First3D toZ<derivOrder::one>(double z) {
return {z, 0, 0, 1};
}
template<>
inline First3D toRSquared<derivOrder::one>(double x, double y, double z) {
return {x * x + y * y + z * z, 2 * x, 2 * y, 2 * z};
}
template<>
inline First3D get3Dfrom1D<derivOrder::one>(First1D v, const Eigen::Vector3d& R) {
Eigen::Vector3d normalizedR = R.normalized();
return {v.value(), v.derivative() * normalizedR.x(), v.derivative() * normalizedR.y(), v.derivative() * normalizedR.z()};
}
template<>
inline First3D getValueWithOppositeDerivative<derivOrder::one>(const First3D& v) {
return v.opposite();
}
template<>
inline double getValue1DAsDouble<derivOrder::one>(const First1D& v) {
return v.value();
}
template<>
inline double getValue3DAsDouble<derivOrder::one>(const First3D& v) {
return v.value();
}
template<>
inline Second1D constant1D<derivOrder::two>(double c) {
return {c, 0, 0};
}
template<>
inline Second1D variableWithUnitDerivative<derivOrder::two>(double v) {
return {v, 1, 0};
}
template<>
inline Second1D getFromFull<derivOrder::two>(double v, double firstDer, double secondDer) {
return {v, firstDer, secondDer};
}
template<>
inline Second3D constant3D<derivOrder::two>(double c) {
return {c, 0, 0, 0};
}
template<>
inline Second3D toX<derivOrder::two>(double x) {
return {x, 1, 0, 0};
}
template<>
inline Second3D toY<derivOrder::two>(double y) {
return {y, 0, 1, 0};
}
template<>
inline Second3D toZ<derivOrder::two>(double z) {
return {z, 0, 0, 1};
}
template<>
inline Second3D toRSquared<derivOrder::two>(double x, double y, double z) {
return {x * x + y * y + z * z, 2 * x, 2 * y, 2 * z, 2, 2, 2, 0, 0, 0};
}
template<>
inline Second3D get3Dfrom1D<derivOrder::two>(Second1D v, const Eigen::Vector3d& R) {
double norm = R.norm();
Eigen::Vector3d normalizedR = R / norm;
double firstDerivDividedByR = v.first() / norm;
return {v.value(),
v.first() * normalizedR.x(),
v.first() * normalizedR.y(),
v.first() * normalizedR.z(),
v.second() * normalizedR.x() * normalizedR.x() + firstDerivDividedByR * (1 - normalizedR.x() * normalizedR.x()),
v.second() * normalizedR.y() * normalizedR.y() + firstDerivDividedByR * (1 - normalizedR.y() * normalizedR.y()),
v.second() * normalizedR.z() * normalizedR.z() + firstDerivDividedByR * (1 - normalizedR.z() * normalizedR.z()),
v.second() * normalizedR.x() * normalizedR.y() - firstDerivDividedByR * normalizedR.x() * normalizedR.y(),
v.second() * normalizedR.x() * normalizedR.z() - firstDerivDividedByR * normalizedR.x() * normalizedR.z(),
v.second() * normalizedR.y() * normalizedR.z() - firstDerivDividedByR * normalizedR.y() * normalizedR.z()};
}
template<>
inline Second3D getValueWithOppositeDerivative<derivOrder::two>(const Second3D& v) {
return v.opposite();
}
template<>
inline double getValue1DAsDouble<derivOrder::two>(const Second1D& v) {
return v.value();
}
template<>
inline double getValue3DAsDouble<derivOrder::two>(const Second3D& v) {
return v.value();
}
} // namespace AutomaticDifferentiation
} // namespace Utils
} // namespace Scine
#endif // AUTOMATICDIFFERENTIATION_AUTOMATICDIFFERENTIATIONHELPERS_H
| [
"scine@phys.chem.ethz.ch"
] | scine@phys.chem.ethz.ch |
ac4b03591e5a48aa6d4d52397676d952d2ab627b | 521fd0388e69185d51cb20baa03c16c389d07099 | /385c.cpp | 1e2f72dd3d9c0fc015adc5246032ec92e10f4185 | [] | no_license | janani271/CP-solutions-4 | a46f25532781e02627c49c86980641308901f958 | 5ff5196a5e852abad64cc7d59491e5136799cf86 | refs/heads/master | 2022-11-08T22:28:11.769005 | 2020-06-29T08:39:05 | 2020-06-29T08:39:05 | 275,775,786 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,057 | cpp | #include<bits/stdc++.h>
using namespace std;
#define fastread ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define ll long long
ll MAX = 10000003;
ll prime[10000005] , a , n , i , fp[10000007] , q , l , r , temp;
void sieve()
{
for(i=2;i<MAX;i++)
{
if(i%2!=0)
prime[i] = i;
else
prime[i] = 2;
}
// for(i=2;i<MAX;i+=2)
// prime[i] = 2;
for(i=3;i*i<MAX;i++)
{
if(prime[i]==i)
{
// ll x = 2*i ,start = i*i;
for(ll j=i*i;j<MAX;j+=i)
// if(prime[j]==j)
prime[j] = i;
}
}
}
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
fastread;
sieve();
cin>>n;
for(i=0;i<n;i++)
{
cin>>a;
temp = a;
while(temp>1)
{
ll de = prime[temp];
fp[de]++;
while(temp%de==0)
temp = temp/de;
}
}
for(i=1;i<=MAX-3;i++)
{
fp[i] = fp[i-1] + fp[i];
}
cin>>q;
for(i=0;i<q;i++)
{
cin>>l>>r;
l = min(l,MAX-3);
r = min(r,MAX-3);
cout<<fp[r]-fp[l-1]<<"\n";
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
0ee31bf9cc02eb5a4913c85d7c82297e18883d9f | fa6b5a15bd5d7ed857c1705e26f58f7f6452c1cd | /SEARCHING AND SORTING/18.Mnimum_swap_to_sort_array.cpp | c61ac3518e05cfa0d34ed75afff54684386bf889 | [] | no_license | retro-2106/DSA_450_questions | d4cadc840f168a388db5258581712372be3e8629 | 7b23eba2661d6596870848ca3e3d1582236ca46f | refs/heads/main | 2023-06-14T13:08:35.856589 | 2021-07-04T11:28:21 | 2021-07-04T11:28:21 | 308,229,380 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 704 | cpp | int minSwaps(vector<int>&nums)
{
pair<int,int> arr[nums.size()];
for(int i=0;i<nums.size();i++)
{
arr[i].first = nums[i];
arr[i].second = i;
}
sort(arr,arr+nums.size());
vector<bool> visited(nums.size(),false);
int ans=0;
for(int i=0;i<nums.size();i++)
{
if(visited[i] || arr[i].second == i)
continue;
int cycles = 0;
int j = i;
while(!visited[j])
{
visited[j] = 1;
j = arr[j].second;
cycles++;
}
if(cycles > 0)
{
ans += (cycles - 1);
}
}
return ans;
}
| [
"ashishcool2106@gmail.com"
] | ashishcool2106@gmail.com |
c408a44e5e16864bc57150c0052fb89e3a236838 | 6289d2bc026a09c2c019cef03e2240fa400369d7 | /include/kimera-vio/frontend/OpticalFlowPredictor.h | a1f5266ac23c489898734a9710540f1c295df498 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | ManuelKugelmann/Kimera-VIO | 114e12363a54e2fbabb4dad6c0048ffaf57f59d6 | a4df3f0d503ba31065f9556d655dd993b75e5aa0 | refs/heads/master | 2022-11-22T03:52:53.343822 | 2020-06-19T20:42:29 | 2020-06-19T20:42:29 | 279,585,286 | 1 | 0 | BSD-2-Clause | 2020-07-14T12:56:51 | 2020-07-14T12:56:50 | null | UTF-8 | C++ | false | false | 5,248 | h | /* ----------------------------------------------------------------------------
* Copyright 2017, Massachusetts Institute of Technology,
* Cambridge, MA 02139
* All Rights Reserved
* Authors: Luca Carlone, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file OpticalFlowPredictor.h
* @brief Class that predicts optical flow between two images. This is
* helpful for the tracker to have a good initial guess for feature tracking.
* @author Antoni Rosinol
*/
#pragma once
#include <opencv2/opencv.hpp>
#include <gtsam/geometry/Rot3.h>
#include "kimera-vio/utils/Macros.h"
#include "kimera-vio/utils/UtilsOpenCV.h"
namespace VIO {
class OpticalFlowPredictor {
public:
KIMERA_POINTER_TYPEDEFS(OpticalFlowPredictor);
KIMERA_DELETE_COPY_CONSTRUCTORS(OpticalFlowPredictor);
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
OpticalFlowPredictor() = default;
virtual ~OpticalFlowPredictor() = default;
/**
* @brief predictFlow Predicts optical flow for a set of image keypoints.
* The optical flow determines the position of image features in consecutive
* frames.
* @param prev_kps: keypoints in previous (reference) image
* @param cam1_R_cam2: rotation from camera 1 to camera 2.
* @param next_kps: keypoints in next image.
* @return true if flow could be determined successfully
*/
virtual bool predictFlow(const KeypointsCV& prev_kps,
const gtsam::Rot3& cam1_R_cam2,
KeypointsCV* next_kps) = 0;
};
/**
* @brief The NoOpticalFlowPredictor class just assumes that the camera
* did not move and so the features on the previous frame remain at the same
* pixel positions in the current frame.
*/
class NoOpticalFlowPredictor : public OpticalFlowPredictor {
public:
KIMERA_POINTER_TYPEDEFS(NoOpticalFlowPredictor);
KIMERA_DELETE_COPY_CONSTRUCTORS(NoOpticalFlowPredictor);
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
NoOpticalFlowPredictor() = default;
virtual ~NoOpticalFlowPredictor() = default;
bool predictFlow(const KeypointsCV& prev_kps,
const gtsam::Rot3& /* inter_frame */,
KeypointsCV* next_kps) override {
*CHECK_NOTNULL(next_kps) = prev_kps;
return true;
}
};
/**
* @brief The RotationalOpticalFlowPredictor class predicts optical flow
* by using a guess of inter-frame rotation and assumes no translation btw
* frames.
*/
class RotationalOpticalFlowPredictor : public OpticalFlowPredictor {
public:
KIMERA_POINTER_TYPEDEFS(RotationalOpticalFlowPredictor);
KIMERA_DELETE_COPY_CONSTRUCTORS(RotationalOpticalFlowPredictor);
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
RotationalOpticalFlowPredictor(const cv::Matx33f& K, const cv::Size& img_size)
: K_(K),
K_inverse_(K.inv()),
img_size_(0.0f, 0.0f, img_size.width, img_size.height) {}
virtual ~RotationalOpticalFlowPredictor() = default;
bool predictFlow(const KeypointsCV& prev_kps,
const gtsam::Rot3& cam1_R_cam2,
KeypointsCV* next_kps) override {
CHECK_NOTNULL(next_kps);
// Handle case when rotation is small: just copy prev_kps
// Removed bcs even small rotations lead to huge optical flow at the borders
// of the image.
// Keep because then you save a lot of computation.
static constexpr double kSmallRotationTol = 1e-4;
if (std::abs(1.0 - std::abs(cam1_R_cam2.quaternion()[0])) <
kSmallRotationTol) {
*next_kps = prev_kps;
return true;
}
// We use a new object in case next_kps is pointing to prev_kps!
KeypointsCV predicted_kps;
// R is a relative rotation which takes a vector from the last frame to
// the current frame.
cv::Matx33f R = UtilsOpenCV::gtsamMatrix3ToCvMat(cam1_R_cam2.matrix());
// Get bearing vector for kpt, rotate knowing frame to frame rotation,
// get keypoints again
bool is_ok;
cv::Matx33f H = K_ * R.inv(cv::DECOMP_LU, &is_ok) * K_inverse_;
CHECK(is_ok);
const size_t& n_kps = prev_kps.size();
predicted_kps.reserve(n_kps);
for (size_t i = 0u; i < n_kps; ++i) {
// Create homogeneous keypoints.
const KeypointCV& prev_kpt = prev_kps[i];
cv::Vec3f p1(prev_kpt.x, prev_kpt.y, 1.0f);
cv::Vec3f p2 = H * p1;
// Project predicted bearing vectors to 2D again and re-homogenize.
KeypointCV new_kpt;
if (p2[2] > 0.0f) {
new_kpt = KeypointCV(p2[0] / p2[2], p2[1] / p2[2]);
} else {
LOG(WARNING) << "Landmark behind the camera:\n"
<< "- p1: " << p1 << '\n'
<< "- p2: " << p2;
new_kpt = prev_kpt;
}
// Check that keypoints remain inside the image boundaries!
if (img_size_.contains(new_kpt)) {
predicted_kps.push_back(new_kpt);
} else {
// Otw copy-paste previous keypoint.
predicted_kps.push_back(prev_kpt);
}
}
*next_kps = predicted_kps;
return true;
}
private:
const cv::Matx33f K_; // Intrinsic matrix of camera
const cv::Matx33f K_inverse_; // Cached inverse of K
const cv::Rect2f img_size_;
};
} // namespace VIO
| [
"tonirosinol@hotmail.com"
] | tonirosinol@hotmail.com |
f1a6b51879b536c7e5efee239e6b24eb10ceb414 | c4e9b125eda093d45c29cf6a812c1cf448651963 | /2dShooter/Bullet.h | 3ae21d5e1845fa68b81a82eeb19b0186adf806e6 | [
"MIT"
] | permissive | Bigfellahull/2dShooter | d7d741626d3fcbb6497e8194c05f6ad06bb6129a | 7d37bc414230eef3a7d140fc84d0d7ef56bc18e5 | refs/heads/master | 2021-09-08T07:40:37.421327 | 2021-09-07T14:46:40 | 2021-09-07T14:46:40 | 37,286,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | h | #pragma once
#include "Entity.h"
#include "EntityManager.h"
namespace SGS2D
{
class Bullet : public Entity
{
public:
Bullet(DirectX::SimpleMath::Vector2 position, DirectX::SimpleMath::Vector2 velocity);
void Update(InputManager& inputManager, float totalTime, float deltaTime);
};
} | [
"bigfellahull@hotmail.com"
] | bigfellahull@hotmail.com |
6864e0f2a9d741ca221cd9f325e87b86630d1280 | a37d3b38e5f31aa0129097e62c81ff12c666bf3b | /simulator/pytorch.cpp | 0b6a251c7381c93032f574b30ce312618108eb3a | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | frankie4fingers/bps-nav | 4f52dba1534e8d85cd8f02b1faf2a5a2a298c7df | 4c237ba3aaa9a99093065e184c2380b22bb6e574 | refs/heads/master | 2023-08-19T14:51:21.006332 | 2021-09-18T19:33:35 | 2021-10-19T20:59:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,286 | cpp | #include <ATen/ATen.h>
#include <ATen/cuda/CUDAContext.h>
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
using namespace std;
namespace py = pybind11;
// Create a tensor that references this memory
//
at::Tensor convertToTensorColor(const py::capsule &ptr_capsule,
int dev_id,
uint32_t batch_size,
const array<uint32_t, 2> &resolution)
{
uint8_t *dev_ptr(ptr_capsule);
array<int64_t, 4> sizes {{batch_size, resolution[0], resolution[1], 4}};
auto options = torch::TensorOptions()
.dtype(torch::kUInt8)
.device(torch::kCUDA, (short)dev_id);
return torch::from_blob(dev_ptr, sizes, options);
}
// Create a tensor that references this memory
//
at::Tensor convertToTensorDepth(const py::capsule &ptr_capsule,
int dev_id,
uint32_t batch_size,
const array<uint32_t, 2> &resolution)
{
float *dev_ptr(ptr_capsule);
array<int64_t, 3> sizes {{batch_size, resolution[0], resolution[1]}};
auto options = torch::TensorOptions()
.dtype(torch::kFloat32)
.device(torch::kCUDA, (short)dev_id);
return torch::from_blob(dev_ptr, sizes, options);
}
// TensorRT helpers
at::Tensor convertToTensorFCOut(const py::capsule &ptr_capsule,
int dev_id,
uint32_t batch_size,
uint32_t num_features)
{
__half *dev_ptr(ptr_capsule);
array<int64_t, 2> sizes {{batch_size, num_features}};
auto options = torch::TensorOptions()
.dtype(torch::kFloat16)
.device(torch::kCUDA, (short)dev_id);
return torch::from_blob(dev_ptr, sizes, options);
}
py::capsule tensorToCapsule(const at::Tensor &tensor)
{
return py::capsule(tensor.data_ptr());
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m)
{
m.def("make_color_tensor", &convertToTensorColor);
m.def("make_depth_tensor", &convertToTensorDepth);
m.def("make_fcout_tensor", &convertToTensorFCOut);
m.def("tensor_to_capsule", &tensorToCapsule);
}
| [
"bpshacklett@gmail.com"
] | bpshacklett@gmail.com |
5fd706f6e3590c9d11a4bc774b93071bad46b510 | a012dec356230389c3ea4d88ad7832953f81f4a5 | /Problems/KingdomRush/visualproblemsolver.cpp | 3bcb45fe5521f2523cd0bed942a064ffe664abd1 | [] | no_license | GaelReinaudi/CodeJamCrusher | 5f77483569922637ec51b813af16d47f108cafb5 | 9d04dcdea0f6e6c89b45b149da3cfa1829c9b8e9 | refs/heads/master | 2022-05-07T21:54:56.145189 | 2022-04-11T01:55:33 | 2022-04-11T01:55:33 | 18,425,774 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,536 | cpp | #include "stdafx.h"
#include "visualproblemsolver.h"
#include "KingdomRushCase.h"
QFile m_FileIn;
QFile m_FileOut;
KingdomRush::KingdomRush(QWidget *parent, Qt::WFlags flags)
: QWidget(parent, flags)
, m_NumberCase(0)
, m_ShowFileContents(true)
{
ui.setupUi(this);
// reload settings
QSettings settings("CodeJam", "KingdomRush");
m_FileInPath = settings.value("fileInPath", "").toString();
m_SampleTableFromWebSite = settings.value("sampleTableFromWebSite", "").toString();
if(m_FileInPath != "") {
// re-load a previously loaded file
LoadFile();
}
else if(m_SampleTableFromWebSite != "") {
LoadSample();
}
connect(ui.pUseSampleButton, SIGNAL(clicked(bool)), this, SLOT(LoadSample()));
connect(&m_watcher, SIGNAL(progressValueChanged(int)), ui.pProgressBar, SLOT(setValue(int)));
connect(&m_watcher, SIGNAL(finished()), this, SLOT(EventFinishedComputation()));
ui.pFailedButton->hide();
move(0, 50);
restoreGeometry(settings.value("geometry").toByteArray());
}
KingdomRush::~KingdomRush()
{
m_FileIn.close();
m_FileOut.close();
QSettings settings("CodeJam", "KingdomRush");
settings.clear();
settings.setValue("fileInPath", m_FileInPath);
settings.setValue("sampleTableFromWebSite", m_SampleTableFromWebSite);
settings.setValue("geometry", saveGeometry());
}
void KingdomRush::MultiThreadedCompute(VectorCases & allCases)
{
// solving and making the output
QFuture<void> future = QtConcurrent::mappedReduced(allCases, SolveCase, AppendResult, QtConcurrent::OrderedReduce | QtConcurrent::SequentialReduce);
m_watcher.setFuture(future);
}
void KingdomRush::SequencialCompute( VectorCases & allCases )
{
foreach(KingdomRushCase theCase, allCases) {
QString result = SolveCase(theCase);
AppendResult(theCase, result);
}
EventFinishedComputation();
}
void KingdomRush::dropEvent( QDropEvent* event )
{
const QMimeData* pMime = event->mimeData();
if(pMime->hasUrls()) {
m_FileInPath = pMime->urls().first().toLocalFile();
LoadFile();
}
else if(pMime->hasText()) {
m_SampleTableFromWebSite = pMime->text();
LoadSample();
}
}
QString KingdomRush::MakeSampleInput( QString strFromSampleDrop )
{
strFromSampleDrop = strFromSampleDrop.trimmed();
if(strFromSampleDrop.startsWith("Input"))
strFromSampleDrop = strFromSampleDrop.remove("Input").trimmed();
if(strFromSampleDrop.startsWith("Output"))
strFromSampleDrop = strFromSampleDrop.remove("Output").trimmed();
int indOut = strFromSampleDrop.lastIndexOf("Case #1");
QString sampleIn = strFromSampleDrop.left(indOut).trimmed();
QString sampleOut;
if(indOut != -1)
sampleOut = strFromSampleDrop.remove(0, indOut).trimmed();
ui.pEditSampleInput->setPlainText(sampleIn);
ui.pEditSampleOutput->setPlainText(sampleOut);
return sampleIn;
}
VectorCases KingdomRush::ParseInput(QTextStream & inputStream)
{
inputStream >> m_NumberCase;
ui.pProgressBar->setRange(1, m_NumberCase);
VectorCases allCases(m_NumberCase);
inputStream.readLine();
// reading each case
for(int iCase = 1; iCase <= m_NumberCase; iCase++) {
// sets the number of the case for latter filling the output file
allCases[iCase-1].m_CaseNumber = iCase;
// parse the data specific to that case
allCases[iCase-1].ParseCase(inputStream);
}
return allCases;
}
QString KingdomRush::MakeFileInOut( QString pathInput /*= ""*/)
{
QString content;
m_FileIn.close();
QString fileOutName;
if(pathInput.isEmpty()) {
fileOutName = "SampleOut.txt";
m_FileOut.setFileName(fileOutName);
}
else {
m_FileIn.setFileName(pathInput);
fileOutName = QDir("../Outputs/").exists() ? "../Outputs/" : "";
fileOutName += "KingdomRush";
if(m_FileIn.fileName().contains("small")) {
fileOutName += "-Small.txt";
m_FileOut.setFileName(fileOutName);
}
else if(m_FileIn.fileName().contains("large")) {
fileOutName += "-Large.txt";
m_FileOut.setFileName(fileOutName);
}
else {
fileOutName += ".txt";
m_FileOut.setFileName(fileOutName);
}
if(m_ShowFileContents) {
if(m_FileIn.open(QIODevice::ReadOnly | QIODevice::Text)) {
content = QTextStream(&m_FileIn).readAll();
}
else {
content = QString("Cannot display Input: %1").arg(m_FileOut.fileName());
}
}
m_FileIn.close();
if(!m_FileIn.open(QIODevice::ReadOnly | QIODevice::Text))
return QString("Cannot open Input: %1\r\n%2").arg(m_FileIn.error()).arg(m_FileIn.fileName());
}
m_FileOut.close();
if(!m_FileOut.open(QFile::WriteOnly | QFile::Truncate | QIODevice::Text))
return QString("Cannot open Output: %1\r\n%2").arg(m_FileOut.error()).arg(m_FileOut.fileName());
return content;
}
void KingdomRush::LoadSample()
{
// if we load the sample, we ignore every memory of a file
m_FileInPath.clear();
// we also call the make file but with no argument it will write to SampleOut.txt
MakeFileInOut();
QString theInput = MakeSampleInput(m_SampleTableFromWebSite);
QTextStream inputStream(&theInput);
VectorCases allCases = ParseInput(inputStream);
ui.pEditDrop->setPlainText(m_SampleTableFromWebSite);
ui.pGroupSamplOut->setVisible(true);
// MultiThreadedCompute(allCases);
SequencialCompute(allCases);
}
void KingdomRush::LoadFile()
{
QString content = MakeFileInOut(m_FileInPath);
QTextStream inputStream(&m_FileIn);
// makes the case's data
VectorCases allCases = ParseInput(inputStream);
ui.pEditDrop->setPlainText(m_FileInPath);
ui.pEditSampleInput->setPlainText(content);
ui.pEditSampleOutput->clear();
ui.pGroupSamplOut->setVisible(false);
MultiThreadedCompute(allCases);
}
void KingdomRush::CompareBoxesOutput()
{
bool passes = false;
QString strIn = ui.pEditSampleOutput->toPlainText().trimmed();
QString strOut = ui.pEditComputedOutput->toPlainText().trimmed();
if(!ui.pEditSampleOutput->toPlainText().isEmpty())
passes = strIn == strOut;
ui.pPassedCheckBox->setChecked(passes);
}
void KingdomRush::EventFinishedComputation()
{
m_FileIn.close();
m_FileOut.close();
QString content;
if(m_ShowFileContents) {
if(m_FileOut.open(QIODevice::ReadOnly | QIODevice::Text))
content = QTextStream(&m_FileOut).readAll();
else
content = QString("Cannot display Output: %1").arg(m_FileOut.fileName());
}
m_FileIn.close();
m_FileOut.close();
ui.pEditComputedOutput->setPlainText(content);
bool compFailed = ui.pEditComputedOutput->find("failed");
if(compFailed)
ui.pFailedButton->show();
else
ui.pFailedButton->hide();
CompareBoxesOutput();
}
void AppendResult( KingdomRushCase & theCase, const QString & resultCase )
{
QTextStream out(&m_FileOut);
out << resultCase << endl;
} | [
"gael.reinaudi@gmail.com"
] | gael.reinaudi@gmail.com |
3a08c5aaaf409a5be9512d8acde3ada81bbf7114 | c0a0eeaf4d679e33bc082a860ff1f48a8667bd1f | /src/ThumbnailDelegate.h | 1b9cebcec8706e66baa4b1de507fae9cccdace9d | [] | no_license | ErikssonM/freefall-photo | eb04143ae06c75520418fe38807c1865f3217c50 | 80cb91c90801e352eafb14fff799b890f1557b07 | refs/heads/master | 2022-07-05T22:13:14.314618 | 2020-05-18T16:11:12 | 2020-05-18T16:11:12 | 264,116,668 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | h | #ifndef THUMBNAILDELEGATE_H
#define THUMBNAILDELEGATE_H
#include <QObject>
#include <QPainter>
#include <QStyledItemDelegate>
#include "ImageItem.h"
class ThumbnailDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
using QStyledItemDelegate::QStyledItemDelegate;
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const override;
QSize sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const override;
bool editorEvent(QEvent *event, QAbstractItemModel *model,
const QStyleOptionViewItem &option,
const QModelIndex &index) override;
};
#endif | [
"60point3@gmail.com"
] | 60point3@gmail.com |
0d9a9ec42ce2dfa76903f440202fdcec1cf48944 | b20e4be69d9cd327b782a031d440328bea3d5e57 | /interview_bit/DP/longestIncreasingSubsequence.cpp | 63a0cb31a28558182db3512f510265692efe1f9e | [] | no_license | manishaparuthi/manisha_cpp | c825e6f83f4cab592094094617f82a30bff52066 | de739d4716fef32214934e87ceaed453c188d3a6 | refs/heads/master | 2021-06-04T03:25:47.297005 | 2019-04-19T15:04:07 | 2019-04-19T15:04:07 | 105,850,895 | 8 | 8 | null | 2018-08-18T17:09:16 | 2017-10-05T04:56:04 | C++ | UTF-8 | C++ | false | false | 471 | cpp | int Solution::lis(const vector<int> &A) {
int size = A.size();
vector <int> LIS(size,1);
for(int i = 0 ; i < size ; i++)
{
for(int j = 0 ; j < i ; j++)
{
if((A[i] > A[j]) && (LIS[i] < LIS[j] + 1))
{
LIS[i] = LIS[j] + 1;
}
}
}
int max = LIS[0];
for(int i = 0 ;i < size ; i++)
{
if(max < LIS[i]){
max = LIS[i];
}
}
return max;
}
| [
"noreply@github.com"
] | noreply@github.com |
edaa3d3b56de032fa68ce7cb1dd3fb3577bbe824 | 61ffb3b79ef70dfc23a8420e410340f6b9be7d42 | /Sections1_12/pointer_parsing2.cpp | ae0e546239ad3fa18a47e92852836d5aeec7d6df | [] | no_license | VargheseVibin/cpp-training-codelite | 42d046bd9e30838ad2362c5bb2398da9e4c3551c | 34b54ba5ba4a355aa588ff7e3dd9061b48603c88 | refs/heads/main | 2023-03-06T18:35:08.550564 | 2021-02-22T20:51:19 | 2021-02-22T20:51:19 | 325,937,151 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 305 | cpp | #include <iostream>
using namespace std ;
void swapNumbers(int *a, int *b) {
int c {*a};
*a=*b;
*b=c;
}
int main () {
int a {100} ;
int b {200} ;
cout << "a=" << a << "; b=" << b << endl ;
swapNumbers(&a,&b);
cout << "a=" << a << "; b=" << b << endl ;
return 0;
} | [
"vibinvvarghese@gmail.com"
] | vibinvvarghese@gmail.com |
e1d751da056efc6b5b0d96c3d9e62e38d1913f75 | 955129b4b7bcb4264be57cedc0c8898aeccae1ca | /python/mof/cpp/MySticMerchantMgr.h | 90f3264002dcc72042e9f3c395258cc98d06ccc5 | [] | no_license | PenpenLi/Demos | cf270b92c7cbd1e5db204f5915a4365a08d65c44 | ec90ebea62861850c087f32944786657bd4bf3c2 | refs/heads/master | 2022-03-27T07:33:10.945741 | 2019-12-12T08:19:15 | 2019-12-12T08:19:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,295 | h | #ifndef MOF_MYSTICMERCHANTMGR_H
#define MOF_MYSTICMERCHANTMGR_H
class MySticMerchantMgr{
public:
void getMySticMerchantDataByIndex(int,int);
void getMySticMerchantPropsDataIndex(int,int);
void ackUpMysteriousList(int,int,int);
void reqBuyMysteriousGoods(int,int,int);
void comparePropsByLvl(MysteriousInfo, MysteriousInfo);
void getMySticMerchantDataIndex(int, int);
void ackBuyMysteriousExchangelist(int, std::vector<obj_mysterious, std::allocator<obj_mysterious>>);
void ackBuyMysteriousSpeciallist(int, std::vector<obj_mysterious, std::allocator<obj_mysterious>>);
void ackBuyMysteriousExchangelist(int,std::vector<obj_mysterious,std::allocator<obj_mysterious>>);
void getMySticMerchantDataByIndex(int, int);
void reqMysteriousList(int);
void getDataSize(int);
void setNextUpdateTime(int);
void ackBuyMysteriousGoods(int, int, int);
void compareProps(MysteriousInfo,MysteriousInfo);
void comparer(MysteriousInfo,MysteriousInfo);
void ackUpMysteriousList(int, int, int);
void getUpdateGoldNum(void);
void getShopPorpsVec(void);
void ~MySticMerchantMgr();
void getNextUpdateTime(void);
void ackBuyMysteriousGoods(int,int,int);
void comparer(MysteriousInfo, MysteriousInfo);
void reqExchangeProps(int,int,int);
void clearData(int);
void getUpdateNum(void);
void deleteItemByIndex(int,int,int);
void ackMysteriousList(int, int, int, int, int, int, std::vector<obj_mysteriousInfo, std::allocator<obj_mysteriousInfo>>);
void compareProps(MysteriousInfo, MysteriousInfo);
void ackMysteriousList(int,int,int,int,int,int,std::vector<obj_mysteriousInfo,std::allocator<obj_mysteriousInfo>>);
void ackBuyMysteriousSpeciallist(int,std::vector<obj_mysterious,std::allocator<obj_mysterious>>);
void ackExchangeProps(int, int, int);
void reqBuyMysteriousGoods(int, int, int);
void getMysticMerchantPropsDataByIndex(int,int);
void getMySticMerchantPropsDataIndex(int, int);
void getShopPropsSize(void);
void reqUpMysteriousList(int);
void deleteItemByIndex(int, int, int);
void getShopPropsByIndex(int);
void getMysticMerchantPropsDataByIndex(int, int);
void getMySticMerchantDataIndex(int,int);
void MySticMerchantMgr(void);
void ackExchangeProps(int,int,int);
void comparePropsByLvl(MysteriousInfo,MysteriousInfo);
void reqExchangeProps(int, int, int);
}
#endif | [
"xiaobin0860@gmail.com"
] | xiaobin0860@gmail.com |
e7770465bc8c730cabae5e891ba3275ecb84f61a | 41bd4e46fae9bc53a3bd0494f80d0b1f195e03ee | /Sandbox/World3D/include/shader.h | 7ced18cc729803f98aa7261e561ba21330f0123d | [] | no_license | VictorNetto/Bunch | ab965735e717089a9de3ab9e91bac20332f4bcd6 | d04eef6a84f8e825b614e7eabd49a6a2f8a653e4 | refs/heads/master | 2020-04-15T14:41:11.983522 | 2019-02-04T18:49:47 | 2019-02-04T18:49:47 | 164,762,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,806 | h | #pragma once
#include "GL/glew.h"
#include "glm/glm.hpp"
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
class Shader
{
public:
Shader(const char* vertexPath, const char* fragmentPath);
void build();
void use() const;
// 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:
const char* m_vertexPath;
const char* m_fragmentPath;
bool m_initialized;
unsigned int ID;
}; | [
"vigonetto@gmail.com"
] | vigonetto@gmail.com |
00fad48fb000508668b8d152d6ba01386f677464 | fc8b47153a85e5d42db981b348658d0be9fe0385 | /csqlbot/csqlbot/mysqlbot.h | fc6631f5e031c91009a48dd7fc272ff7e4fd8065 | [] | no_license | BackupTheBerlios/sqlbot | e2d004478e0c358779a4ee4abd56f5125bfa3d1d | 3acb474f4cb2915eccb676ecdaed03a8642b6c36 | refs/heads/master | 2016-09-06T15:51:45.300668 | 2004-10-07T18:59:45 | 2004-10-07T18:59:45 | 40,073,145 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,915 | h | /***************************************************************************
botmysql.h - description
-------------------
begin : Tue Oct 14 2003
copyright : (C) 2003 by Steve Gray
email :
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#ifndef BOTMYSQL_H
#define BOTMYSQL_H
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <dclib/core/cstring.h>
#include "mysqlcon.h"
class MySqlBot {
public:
MySqlBot(MySqlCon * mySql);
~MySqlBot();
void GetBotConfig();
void GetHubConfig(int hubId);
CString GetBotName(){ return bcName;}
CString GetBotMaster(){ return bcMaster;}
CString GetBotIP(){ return bcIP;}
int GetBotTCPport(){ return bcTCPport;}
int GetBotUDPport(){ return bcUDPport;}
CString GetBotConnection(){ return bcConnection;}
CString GetBotDescription(){ return bcDescription;}
CString GetBotSharePath(){ return bcSharePath;}
private:
CString bcName;
CString bcMaster;
CString bcIP;
int bcTCPport;
int bcUDPport;
CString bcConnection;
CString bcDescription;
CString bcSharePath;
CString bcLogDir;
MySqlCon * bcMySql;
};
#endif
| [
"nutter"
] | nutter |
1e6dc737499563fd8437c0bca0b8cac4a57d737a | 036c026ca90f4a4a663f914b5333ecd1da9ff4d3 | /bin/windows/obj/src/lime/_backend/native/_NativeApplication/ApplicationEventInfo.cpp | 3992d8836325034900087ebe62a3547fab146278 | [] | no_license | alexey-kolonitsky/hxlines | d049f9ea9cc038eaca814d99f26588abb7e67f44 | 96e1e7ff58b787985d87512e78929a367e27640b | refs/heads/master | 2021-01-22T04:27:53.064692 | 2018-05-18T02:06:09 | 2018-05-18T02:06:09 | 102,267,235 | 0 | 1 | null | 2018-03-25T19:11:08 | 2017-09-03T13:40:29 | C++ | UTF-8 | C++ | false | true | 5,564 | cpp | // Generated by Haxe 3.4.0 (git build development @ d2a02e8)
#include <hxcpp.h>
#ifndef INCLUDED_lime__backend_native__NativeApplication_ApplicationEventInfo
#include <lime/_backend/native/_NativeApplication/ApplicationEventInfo.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_e0c2b4da9d832f26_734_new,"lime._backend.native._NativeApplication.ApplicationEventInfo","new",0x285f59a7,"lime._backend.native._NativeApplication.ApplicationEventInfo.new","lime/_backend/native/NativeApplication.hx",734,0xb13849fd)
HX_LOCAL_STACK_FRAME(_hx_pos_e0c2b4da9d832f26_744_clone,"lime._backend.native._NativeApplication.ApplicationEventInfo","clone",0x3158bc64,"lime._backend.native._NativeApplication.ApplicationEventInfo.clone","lime/_backend/native/NativeApplication.hx",744,0xb13849fd)
namespace lime{
namespace _backend{
namespace native{
namespace _NativeApplication{
void ApplicationEventInfo_obj::__construct( ::Dynamic type,hx::Null< int > __o_deltaTime){
int deltaTime = __o_deltaTime.Default(0);
HX_STACKFRAME(&_hx_pos_e0c2b4da9d832f26_734_new)
HXLINE( 736) this->type = type;
HXLINE( 737) this->deltaTime = deltaTime;
}
Dynamic ApplicationEventInfo_obj::__CreateEmpty() { return new ApplicationEventInfo_obj; }
void *ApplicationEventInfo_obj::_hx_vtable = 0;
Dynamic ApplicationEventInfo_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< ApplicationEventInfo_obj > _hx_result = new ApplicationEventInfo_obj();
_hx_result->__construct(inArgs[0],inArgs[1]);
return _hx_result;
}
bool ApplicationEventInfo_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x7cde2bc3;
}
::lime::_backend::native::_NativeApplication::ApplicationEventInfo ApplicationEventInfo_obj::clone(){
HX_GC_STACKFRAME(&_hx_pos_e0c2b4da9d832f26_744_clone)
HXLINE( 744) return ::lime::_backend::native::_NativeApplication::ApplicationEventInfo_obj::__alloc( HX_CTX ,this->type,this->deltaTime);
}
HX_DEFINE_DYNAMIC_FUNC0(ApplicationEventInfo_obj,clone,return )
ApplicationEventInfo_obj::ApplicationEventInfo_obj()
{
}
hx::Val ApplicationEventInfo_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"type") ) { return hx::Val( type); }
break;
case 5:
if (HX_FIELD_EQ(inName,"clone") ) { return hx::Val( clone_dyn()); }
break;
case 9:
if (HX_FIELD_EQ(inName,"deltaTime") ) { return hx::Val( deltaTime); }
}
return super::__Field(inName,inCallProp);
}
hx::Val ApplicationEventInfo_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"type") ) { type=inValue.Cast< int >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"deltaTime") ) { deltaTime=inValue.Cast< int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void ApplicationEventInfo_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("deltaTime","\x25","\x3c","\x5c","\xf5"));
outFields->push(HX_HCSTRING("type","\xba","\xf2","\x08","\x4d"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo ApplicationEventInfo_obj_sMemberStorageInfo[] = {
{hx::fsInt,(int)offsetof(ApplicationEventInfo_obj,deltaTime),HX_HCSTRING("deltaTime","\x25","\x3c","\x5c","\xf5")},
{hx::fsInt,(int)offsetof(ApplicationEventInfo_obj,type),HX_HCSTRING("type","\xba","\xf2","\x08","\x4d")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *ApplicationEventInfo_obj_sStaticStorageInfo = 0;
#endif
static ::String ApplicationEventInfo_obj_sMemberFields[] = {
HX_HCSTRING("deltaTime","\x25","\x3c","\x5c","\xf5"),
HX_HCSTRING("type","\xba","\xf2","\x08","\x4d"),
HX_HCSTRING("clone","\x5d","\x13","\x63","\x48"),
::String(null()) };
static void ApplicationEventInfo_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(ApplicationEventInfo_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void ApplicationEventInfo_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(ApplicationEventInfo_obj::__mClass,"__mClass");
};
#endif
hx::Class ApplicationEventInfo_obj::__mClass;
void ApplicationEventInfo_obj::__register()
{
hx::Object *dummy = new ApplicationEventInfo_obj;
ApplicationEventInfo_obj::_hx_vtable = *(void **)dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("lime._backend.native._NativeApplication.ApplicationEventInfo","\x35","\xfa","\xe1","\x53");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = ApplicationEventInfo_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(ApplicationEventInfo_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< ApplicationEventInfo_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = ApplicationEventInfo_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = ApplicationEventInfo_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = ApplicationEventInfo_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace lime
} // end namespace _backend
} // end namespace native
} // end namespace _NativeApplication
| [
"akalanitski@playtika.com"
] | akalanitski@playtika.com |
05caffda9a44a01c9a4b9b85e516a6f33473654e | 1d14766f1b8081d2d4e6ed8c54965948e3bd23a4 | /QwtRasterPolt/ColorBar.h | 0d0a6119ab4902d760d00e0099344c1bc8c171d8 | [] | no_license | VeinySoft/BeiJingQiXiang2018 | 5e4f3ddff5619ca07c41d481de4bcdd65ebb7551 | 9fcfc81d9be091fb4bc44b653ebe9657a5efbd9b | refs/heads/master | 2023-01-19T03:51:16.528367 | 2020-11-24T05:55:46 | 2020-11-24T05:55:46 | 268,947,863 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 752 | h | #pragma once
class ColorBar
{
public:
enum BarStyle { LINEAR, NONLINEARITY};
struct COLOR_UNIT
{
int fr, fg, fb, fa;
};
typedef std::map<float, ColorBar::COLOR_UNIT> COLOR_MAP, *P_COLOR_MAP;
typedef std::pair<float, ColorBar::COLOR_UNIT> COLOR_PAIR;
typedef COLOR_MAP::iterator COLOR_MAP_INTERATOR, *P_COLOR_MAP_INTERATOR;
ColorBar();
virtual ~ColorBar();
virtual void LoadData(const std::string& strFile) = 0;
virtual ColorBar::BarStyle GetBarStyle() = 0;
inline int GetColorCount() { return m_ColorCount; }
int GetValueSet(std::vector<float>* pSet);
int GetColor(float fV, ColorBar::COLOR_UNIT* pColor);
int GetColor(float fV, QColor* pColor);
protected:
ColorBar::COLOR_MAP m_ColorMap;
int m_ColorCount;
BarStyle m_Style;
};
| [
"veiny_yxy@163.com"
] | veiny_yxy@163.com |
9fa0427ed699bd6e0fa5979e99b911d8dba2aec6 | 23e393f8c385a4e0f8f3d4b9e2d80f98657f4e1f | /Win32 Programming/CtlColorExplorer/CtlColor.cpp | 6d0cad40c2eb286bffbc0d8f608808e812f6f467 | [] | no_license | IgorYunusov/Mega-collection-cpp-1 | c7c09e3c76395bcbf95a304db6462a315db921ba | 42d07f16a379a8093b6ddc15675bf777eb10d480 | refs/heads/master | 2020-03-24T10:20:15.783034 | 2018-06-12T13:19:05 | 2018-06-12T13:19:05 | 142,653,486 | 3 | 1 | null | 2018-07-28T06:36:35 | 2018-07-28T06:36:35 | null | UTF-8 | C++ | false | false | 13,674 | cpp | // CtlColor.cpp : implementation file
//
#include "stdafx.h"
#include "CtlColorExplorer.h"
#include "Color.h"
#include "rgb.h"
#include "CtlColor.h"
#include "colors.h"
#include "sibling.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CCtlColorParms property page
IMPLEMENT_DYNCREATE(CCtlColorParms, CPropertyPage)
CCtlColorParms::CCtlColorParms(UINT caption, UINT msg) : CPropertyPage(CCtlColorParms::IDD, caption)
{
//{{AFX_DATA_INIT(CCtlColorParms)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
msgid = msg;
}
CCtlColorParms::~CCtlColorParms()
{
}
void CCtlColorParms::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CCtlColorParms)
DDX_Control(pDX, IDC_TEXTCOLOR_CAPTION, c_TextColorCaption);
DDX_Control(pDX, IDC_BKCOLOR_CAPTION, c_BkColorCaption);
DDX_Control(pDX, IDC_BKBRUSH_CAPTION, c_BkBrushCaption);
DDX_Control(pDX, IDC_FONTGROUP, c_FontGroup);
DDX_Control(pDX, IDC_CHANGEFONT, c_ChangeFont);
DDX_Control(pDX, IDC_SAMPLE, c_Sample);
DDX_Control(pDX, IDC_CLEARFONT, c_ClearFont);
DDX_Control(pDX, IDC_NOSETFONT, c_NoSetFont);
DDX_Control(pDX, IDC_FACENAME, c_FaceName);
DDX_Control(pDX, IDC_RGBTEXT, c_RGBText);
DDX_Control(pDX, IDC_RGBBR, c_RGBBrush);
DDX_Control(pDX, IDC_RGBBKG, c_RGBBkg);
DDX_Control(pDX, IDC_BKBRUSH, c_BkBrush);
DDX_Control(pDX, IDC_TEXTCOLOR, c_TextColor);
DDX_Control(pDX, IDC_BKCOLOR, c_BkColor);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CCtlColorParms, CPropertyPage)
//{{AFX_MSG_MAP(CCtlColorParms)
ON_CBN_SELENDOK(IDC_BKBRUSH, OnSelendokBkbrush)
ON_CBN_SELENDOK(IDC_BKCOLOR, OnSelendokBkcolor)
ON_CBN_SELENDOK(IDC_TEXTCOLOR, OnSelendokTextcolor)
ON_BN_CLICKED(IDC_CHANGEFONT, OnChangefont)
ON_BN_CLICKED(IDC_NOSETFONT, OnNosetfont)
ON_BN_CLICKED(IDC_CLEARFONT, OnClearfont)
ON_WM_DESTROY()
ON_BN_CLICKED(IDC_TRANSPARENT, OnTransparent)
ON_BN_CLICKED(IDC_OPAQUE, OnOpaque)
//}}AFX_MSG_MAP
ON_MESSAGE(PSM_QUERYSIBLINGS, OnQuerySiblings)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CCtlColorParms message handlers
/****************************************************************************
* CCtlColorParms::enableFontOptions
* Result: void
*
* Effect:
* Enables or disables the font options
****************************************************************************/
void CCtlColorParms::enableFontOptions()
{
// note that we can't change the font for a MessageBox, or its
// background brush
if(msgid == CTLCOLOR_MSGBOX)
{ /* disable unused controls */
c_ChangeFont.EnableWindow(FALSE);
c_BkColor.EnableWindow(FALSE);
c_BkColorCaption.EnableWindow(FALSE);
} /* disable unused controls */
BOOL enable = c_ChangeFont.IsWindowEnabled();
c_NoSetFont.EnableWindow(enable && font.m_hObject != NULL);
c_ClearFont.EnableWindow(enable && font.m_hObject != NULL);
c_FontGroup.EnableWindow(enable);
if(enable)
c_Sample.SetFont(&font);
else
c_Sample.ShowWindow(SW_HIDE);
}
void CCtlColorParms::enableColorOptions()
{
BOOL opaque = IsDlgButtonChecked(IDC_OPAQUE);
c_BkColor.EnableWindow(opaque);
c_BkColorCaption.EnableWindow(opaque);
c_RGBBkg.ShowWindow(opaque ? SW_SHOW : SW_HIDE);
if(msgid == CTLCOLOR_SCROLLBAR)
{ /* no text in scrollbar */
c_TextColor.EnableWindow(FALSE);
c_TextColorCaption.EnableWindow(FALSE);
c_RGBText.ShowWindow(SW_HIDE);
} /* no text in scrollbar */
}
BOOL CCtlColorParms::OnInitDialog()
{
CPropertyPage::OnInitDialog();
c_BkColor.LoadColors();
if(msgid == CTLCOLOR_MSGBOX)
c_BkColor.SetColor(GetSysColor(COLOR_3DFACE));
else
c_BkColor.SetColor(GetSysColor(COLOR_WINDOW));
c_RGBBkg.SetWindowText(c_BkColor.GetColor());
c_TextColor.LoadColors();
c_TextColor.SetColor(GetSysColor(COLOR_WINDOWTEXT));
c_RGBText.SetWindowText(c_TextColor.GetColor());
c_BkBrush.LoadColors();
if(msgid == CTLCOLOR_DLG || msgid == CTLCOLOR_BTN
|| msgid == CTLCOLOR_MSGBOX)
c_BkBrush.SetColor(GetSysColor(COLOR_3DFACE));
else
c_BkBrush.SetColor(GetSysColor(COLOR_WINDOW));
c_RGBBrush.SetWindowText(c_BkBrush.GetColor());
CheckRadioButton(IDC_TRANSPARENT, IDC_OPAQUE, IDC_OPAQUE);
CString s;
s.LoadString(IDS_DEFAULTFONT);
c_FaceName.SetWindowText(s);
CFont * cfont = GetFont();
if(cfont != NULL)
{ /* has dialog font */
LOGFONT lf;
cfont->GetObject(sizeof(lf), &lf);
font.CreateFontIndirect(&lf);
} /* has dialog font */
enableFontOptions();
enableColorOptions();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
/****************************************************************************
* CCtlColorParms::SetDC(UINT type, CDC * dc)
* Inputs:
* UINT type: CTLCOLOR_ type
* CDC * dc: Display context to modify
* Result: LRESULT (HBRUSH)
* Brush to use for painting the background of the control
* Effect:
* Modifies the display context:
* SetBkColor of the selected background color
* SetBkMode of the selected background mode
* SetTextColor of the selected text color
****************************************************************************/
LRESULT CCtlColorParms::SetDC(UINT type, CDC * dc)
{
if(type != msgid)
return 0; // doesn't match us
// The type is correct
// Select the text color
COLORREF color = c_TextColor.GetColor();
if(color != COLOR_NONE)
{ /* has text color */
dc->SetTextColor(color);
} /* has text color */
// Set the text background color
color = c_BkColor.GetColor();
if(color != COLOR_NONE)
{ /* has text background */
dc->SetBkColor(color);
} /* has text background */
// Select the background mode
if(IsDlgButtonChecked(IDC_TRANSPARENT))
dc->SetBkMode(TRANSPARENT);
else
dc->SetBkMode(OPAQUE);
#if 0
// If the font is defined, select it into the DC
if(font.m_hObject != NULL && !c_NoSelectObject.GetCheck())
{ /* select the font */
// This should really be written as
// dc->SelectObject(font);
// But due to a bug in MFC 4.1 (and perhaps other versions)
// that code will generate an ASSERT failure due to failure to
// initialize the m_hAttribDC member when the DC is "faked up"
// for the WM_CTLCOLOR message. This calls the low-level API
// function. Ugly, but it works
::SelectObject(dc->m_hDC, font.m_hObject);
} /* select the font */
#endif
// Select the background brush and return it
color = (COLORREF)c_BkBrush.GetColor();
if(color != COLOR_NONE)
{ /* has background brush */
if(brush.m_hObject != NULL)
brush.DeleteObject();
brush.CreateSolidBrush(color);
return (LRESULT)brush.m_hObject;
} /* has background brush */
return 0; // NULL brush handle
}
/****************************************************************************
* CCtlColorParms::SetFont
* Inputs:
* UINT type: Type code, CTLCOLOR_
* CWND * wnd: Window handle to set it in
* Result: LRESULT (HFONT)
* Previous font handle
* Effect:
* Calls the SetFont method on the CWnd
****************************************************************************/
LRESULT CCtlColorParms::SetFont(UINT type, CWnd * wnd)
{
if(type != msgid)
return 0; // doesn't match
CFont * cf = wnd->GetFont();
HFONT hfont;
if(cf == NULL)
hfont = NULL;
else
hfont = (HFONT)(cf->m_hObject);
if(hfont != font.m_hObject && !c_NoSetFont.GetCheck())
wnd->SetFont(&font, FALSE);
return (LRESULT)hfont;
}
/****************************************************************************
* CCtlColorParms::OnQuerySiblings
* Inputs:
* WPARAM wParam: LOWORD: Control type ID
* HIWORD: operation to perform
* LPARAM lParam: HIWORD(wParam) == SIBLING_SETDC: DC to modify
* HIWORD(wParam) == SIBLING_SETFONT: window handle
* Result: LRESULT
* SIBLING_SETDC: The brush to use to paint the background
* SIBLING_SETFONT: The old font handle
* Effect:
* Modifies the DC if the control type ID matches
****************************************************************************/
LRESULT CCtlColorParms::OnQuerySiblings(WPARAM wParam, LPARAM lParam)
{
switch(HIWORD(wParam))
{ /* op */
case SIBLING_SETDC:
return SetDC(LOWORD(wParam), (CDC *)lParam);
case SIBLING_SETFONT:
return SetFont(LOWORD(wParam), (CWnd *)lParam);
} /* op */
return 0; // should never get here
}
void CCtlColorParms::OnSelendokBkbrush()
{
c_RGBBrush.SetWindowText(c_BkBrush.GetColor());
}
void CCtlColorParms::OnSelendokBkcolor()
{
c_RGBBkg.SetWindowText(c_BkColor.GetColor());
}
void CCtlColorParms::OnSelendokTextcolor()
{
c_RGBText.SetWindowText(c_TextColor.GetColor());
}
/****************************************************************************
* CCtlColorParms::getWeightString
* Inputs:
* int weight: Weight of font
* Result: CString
* String which is the weight
* Effect:
* Loads the string and uses a temporary CString object to return the
* value
****************************************************************************/
CString CCtlColorParms::getWeightString(int weight)
{
CString s;
s = _T("");
switch(weight)
{ /* decode */
case FW_THIN:
s.LoadString(IDS_THIN);
break;
case FW_EXTRALIGHT:
s.LoadString(IDS_EXTRALIGHT);
break;
case FW_LIGHT:
s.LoadString(IDS_LIGHT);
break;
case FW_NORMAL:
s.LoadString(IDS_NORMAL);
break;
case FW_MEDIUM:
s.LoadString(IDS_MEDIUM);
break;
case FW_SEMIBOLD:
s.LoadString(IDS_SEMIBOLD);
break;
case FW_BOLD:
s.LoadString(IDS_BOLD);
break;
case FW_EXTRABOLD:
s.LoadString(IDS_EXTRABOLD);
break;
case FW_HEAVY:
s.LoadString(IDS_HEAVY);
break;
default:
s.Format("(%d)", weight);
break;
} /* decode */
return s;
}
void CCtlColorParms::OnChangefont()
{
LOGFONT lf;
CFontDialog fd(&lf);
if(font.m_hObject != NULL)
{ /* has font */
font.GetObject(sizeof(lf), &lf);
fd.m_cf.Flags |= CF_INITTOLOGFONTSTRUCT;
} /* has font */
else
{ /* no font */
memset(&lf, 0, sizeof(lf));
} /* no font */
fd.m_cf.rgbColors = c_TextColor.GetColor();
if(fd.DoModal())
{ /* OK */
c_TextColor.SetColor(fd.m_cf.rgbColors);
// temporary until we get full set of colors defined
c_RGBText.SetWindowText(fd.m_cf.rgbColors);
} /* OK */
font.DeleteObject();
if(!font.CreateFontIndirect(&fd.m_lf))
{ /* failed */
// NYI: MessageBox
CString s;
s.LoadString(IDS_DEFAULTFONT);
c_FaceName.SetWindowText(s);
} /* failed */
else
{ /* success */
CString s;
s.Format("%s %d %s", fd.m_lf.lfFaceName,
abs(fd.m_lf.lfHeight),
getWeightString(fd.m_lf.lfWeight));
c_FaceName.SetWindowText(s);
} /* success */
enableFontOptions();
}
void CCtlColorParms::OnNosetfont()
{
// TODO: Add your control notification handler code here
}
void CCtlColorParms::OnClearfont()
{
if(font.m_hObject != NULL)
{ /* clear font */
font.DeleteObject();
CString s;
s.LoadString(IDS_DEFAULTFONT);
c_FaceName.SetWindowText(s);
} /* clear font */
enableFontOptions();
}
void CCtlColorParms::OnDestroy()
{
CPropertyPage::OnDestroy();
font.DeleteObject();
}
void CCtlColorParms::OnTransparent()
{
enableColorOptions();
}
void CCtlColorParms::OnOpaque()
{
enableColorOptions();
}
| [
"wyrover@gmail.com"
] | wyrover@gmail.com |
f9571c26480d91a3008d0de03f749daa1e330041 | 3245c4b49e77d599b517e13a0ac209db823eb9c5 | /tests/own/rfc4234core.txt.inc | f184121602f2e047871f64af43ff846d04370891 | [] | no_license | glyn/bap | ceb7c3d161d39d09467943467d755f3468a26c74 | 849cae23a6b2df8d1d875ed0f9bab51b907842a6 | refs/heads/master | 2022-11-23T11:53:17.902259 | 2020-05-19T13:42:37 | 2020-05-19T13:42:37 | 265,182,788 | 0 | 0 | null | 2020-05-19T07:57:43 | 2020-05-19T07:57:43 | null | UTF-8 | C++ | false | false | 81 | inc | ABNF = ALPHA / BIT / CHAR / CTL /
DQUOTE / HEXDIG / LWSP / OCTET / VCHAR
| [
"stefan.eissing@dd8174f5-eb3e-0410-b25e-edeba5481af1"
] | stefan.eissing@dd8174f5-eb3e-0410-b25e-edeba5481af1 |
9326ee39d59c413bc5496dbd621d453660c3fab0 | bcb7ff52da955e602bdd8b226f25ce7dfc87395c | /code/external-vxworks-system-headers/include/cppold/stl/string_fwd.h | d2af9e19f01c35d2bfea2ae8765bae9aa58b2fef | [] | no_license | gheckman/UniLang-rewrite | 66920857e5e55e066ddf9e841a56df90d35521ec | a8c18622d0fee4fd91232fa969224a69d58add2f | refs/heads/master | 2021-01-19T07:23:23.296757 | 2016-05-06T20:21:21 | 2016-05-06T20:21:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,457 | h | /*
* Copyright (c) 1997
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*/
#ifndef __SGI_STL_STRING_FWD_H
#define __SGI_STL_STRING_FWD_H
#include <stddef.h>
__STL_BEGIN_NAMESPACE
#ifdef __STL_USE_STD_ALLOCATORS
template <class _Tp> class allocator;
#else /* __STL_USE_STD_ALLOCATORS */
template <bool __threads, int __inst> class _Default_alloc_template;
typedef _Default_alloc_template<true, 0> _Alloc;
#endif /* __STL_USE_STD_ALLOCATORS */
template <class _CharT> struct char_traits;
template <class _CharT,
class _Traits = char_traits<_CharT>,
class _Alloc = __STL_DEFAULT_ALLOCATOR(_CharT) >
class basic_string;
typedef basic_string<char> string;
typedef basic_string<wchar_t> wstring;
template <class _CharT, class _Traits, class _Alloc>
void _S_string_copy(const basic_string<_CharT,_Traits,_Alloc>&, _CharT*,
size_t);
__STL_END_NAMESPACE
#endif /* __SGI_STL_STRING_FWD_H */
// Local Variables:
// mode:C++
// End:
| [
"thickey@f2si.net"
] | thickey@f2si.net |
d0f0018c55ad5db77ccc12209e57410c37cbdeef | c09d02c051122a45e0d497a155d139ef5e3d0cf7 | /src/input/FPSController.cpp | 44b8486b34b95311b82490578824620c5d7efb9b | [] | no_license | Maduiini/derelictfactory | 2b0b01d3cfd60a04518417471a1fffe4860479a9 | d29bae62cb9838a50714c6951fedb38595447103 | refs/heads/master | 2020-04-06T07:08:39.143552 | 2014-05-29T13:03:11 | 2014-05-29T13:03:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,568 | cpp |
#include "FPSController.h"
#include "../scene/GameObject.h"
#include <cmath>
namespace der
{
FPSController::FPSController()
: m_rot_x(0.0f)
, m_rot_y(0.0f)
, m_jump_y(0.0f)
, m_jump_velocity(0.0f)
, m_crouch_y(0.0f)
, m_head_bobble_state(0.0f)
, m_speed(0.0f)
{ }
void FPSController::update(float delta_time)
{
const float rotate_speed = 0.002f; // rad/pixel
const float gravity = -9.81f;
const float jump_power = key_down(Key::Left_Shift) ? 6.0f : 3.0f;
const float crouch_speed = 4.0f;
const float crouch_depth = 0.8f;
const float crouch_speed_modifier = 0.2f + 0.8f * (-crouch_depth - m_crouch_y) / -crouch_depth;
const float acceleration = 0.5f;
const float walk_speed = 3.0f;
const float run_speed = 10.0f;
const float friction = 0.93f;
const float max_speed = crouch_speed_modifier * (key_down(Key::Left_Shift) ? run_speed : walk_speed);
const Matrix3 rot = get_object()->get_rotation_matrix();
Vector3 right3, up3, forward3;
rot.get_basis(right3, up3, forward3);
forward3.y = 0.0f;
right3.y = 0.0f;
forward3.normalize();
right3.normalize();
Vector2 forward = Vector2(forward3.x, forward3.z);
Vector2 right = Vector2(right3.x, right3.z);
Vector2 delta = Vector2::zero;
if (key_down(Key::W))
delta += forward;
if (key_down(Key::S))
delta -= forward;
if (key_down(Key::D))
delta += right;
if (key_down(Key::A))
delta -= right;
bool overspeed = m_speed.length2() > max_speed * max_speed;
if (!overspeed)
m_speed += delta * acceleration;
if (overspeed || delta == Vector2::zero)
m_speed *= friction;
m_head_bobble_state += m_speed.length() * delta_time;
Vector3 speed3 = Vector3(m_speed.x, 0.0f, m_speed.y);
get_object()->move(speed3 * delta_time);
// Gravity and jumping
if (m_jump_y > 0.0f)
{
m_jump_velocity += gravity * delta_time;
m_jump_y += m_jump_velocity * delta_time;
}
else
{
m_jump_y = 0.0f; // Prevent falling too low
if (key_down(Key::Space))
{
m_jump_velocity = jump_power;
m_jump_y += m_jump_velocity * delta_time;
}
}
// Crouching
if (key_down(Key::Left_Control) && m_crouch_y > -crouch_depth)
m_crouch_y += (-crouch_depth - m_crouch_y) * crouch_speed * delta_time;
if (!key_down(Key::Left_Control) && m_crouch_y < 0.0f)
m_crouch_y += -m_crouch_y * crouch_speed * delta_time;
// Set y-position
const float head_bobble = m_jump_y > 0.0f? 0.0f : sin(m_head_bobble_state * 1.5f) * 0.05f;
Vector3 position = get_object()->get_position();
position.y = eye_level + m_crouch_y + m_jump_y + head_bobble;
get_object()->set_position(position);
if (key_pressed(Key::Left_Alt))
toggle_mouse_captured();
if (is_mouse_captured())
{
const Vector2 mouse_delta = get_mouse_delta() * rotate_speed;
m_rot_x += mouse_delta.y;
m_rot_y += mouse_delta.x;
}
Quaternion rot_x, rot_y;
rot_x.rotation_x(m_rot_x);
rot_y.rotation_y(m_rot_y);
get_object()->set_rotation(rot_y * rot_x);
}
} // der
| [
"maqqr@users.noreply.github.com"
] | maqqr@users.noreply.github.com |
fe6b537ea2541bedf3fa18ce8e4a5fecd9e6675c | c9eee7113b2fc96eb51fb7e9fc150cfc53ee233c | /src/fileutils-win32.cpp | a9f597b8463cf62786b1075c6e51e5bcc0549092 | [
"BSD-2-Clause"
] | permissive | Pawn-Debugger/Plugin | 5f03a818ed65642b56839d84752ce81ed8611dfa | c5b478787dfaf5d43676ff98c63f9306c8b8dacc | refs/heads/master | 2021-05-12T19:22:31.342638 | 2018-02-27T21:57:02 | 2018-02-27T21:57:02 | 117,091,900 | 15 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,515 | cpp | // Copyright (c) 2011-2015 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <string>
#include <vector>
#include <Windows.h>
#include "fileutils.h"
namespace fileutils {
const char kNativePathSepChar = '\\';
const char *kNativePathSepString = "\\";
const char kNativePathListSepChar = ';';
const char *kNativePathListSepString = ";";
void GetDirectoryFiles(const std::string &directory, const std::string &pattern,
std::vector<std::string> &files)
{
std::string fileName;
fileName.append(directory);
fileName.append(kNativePathSepString);
fileName.append(pattern);
WIN32_FIND_DATA findFileData;
HANDLE hFindFile = FindFirstFile(fileName.c_str(), &findFileData);
if (hFindFile == INVALID_HANDLE_VALUE) {
return;
}
do {
if (!(findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
files.push_back(findFileData.cFileName);
}
} while (FindNextFile(hFindFile, &findFileData) != 0);
FindClose(hFindFile);
}
std::string GetCurrentWorkingtDirectory() {
DWORD size = GetCurrentDirectoryA(0, NULL);
std::vector<char> buffer(size);
GetCurrentDirectoryA(buffer.size(), &buffer[0]);
return std::string(&buffer[0]);
}
} // namespace fileutils
| [
"misiur66+github@gmail.com"
] | misiur66+github@gmail.com |
92e2dee12ea60663ada1808885171a60c3c1151b | dff8a221638932704df714b30df53de003342571 | /ch16/ch16/ex16_56.h | 079d6350404b9303555a1bb5744c086637b03975 | [] | no_license | DevinChang/cpp | 1327da268cbbde4981c055c2e98301d63e9ca46b | f35ee6f7b2d9217bd2d40db55a697330aeffc7e8 | refs/heads/master | 2021-01-20T13:55:55.399888 | 2017-05-18T08:01:15 | 2017-05-18T08:01:15 | 90,538,499 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 189 | h | #pragma once
#include "ex16_48.h"
#include "ex16_53.h"
template <typename...Args>
std::ostream &errorMsg(std::ostream &os, const Args&... rest) {
return print(os, debug_rep(rest)...);
} | [
"DevinChang@126.com"
] | DevinChang@126.com |
00bd7be5bdcbc87718e67980b010e34574013dd7 | ebacc5b1b457b08eac119e43c030281c98343aeb | /Boost_Study/stringandtext/06.cpp | 8d93d1b6c3be413640cf936183b52f909973dae3 | [] | no_license | deardeng/learning | e9993eece3ed22891f2e54df7c8cf19bf1ce89f4 | 338d6431cb2d64b25b3d28bbdd3e47984f422ba2 | refs/heads/master | 2020-05-17T13:12:43.808391 | 2016-02-11T16:24:09 | 2016-02-11T16:24:09 | 19,692,141 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 612 | cpp | #include <string>
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <assert.h>
#include <iomanip>
#include <boost/algorithm//string.hpp>
using namespace boost;
using namespace std;
int main()
{
string str("readme.txt");
if(ends_with(str, "txt"))
{
cout << to_upper_copy(str) + " UPPER" << endl;
assert(ends_with(str, "txt"));
}
replace_first(str, "readme", "followme");
cout << str << endl;
vector<char> v(str.begin(), str.end());
vector<char> v2 = to_upper_copy(erase_first_copy(v, "txt"));
for(int i=0; i<v2.size(); ++i)
{
cout << v2[i];
}
} | [
"565620795@qq.com"
] | 565620795@qq.com |
7f8e75ec45f6048d3fa96f4059c9671ce235bce2 | bb2fde26d6bc67ce6854da2233feee177f60a450 | /src/vsp_aero/solver/WOPWOP.H | 812367d31a02a3ff2a2cb797a0cc1799a8813c41 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | planes/OpenVSP | cf9fe402c37c5bec5c66e132a185490526b54bde | d08fd4438d18e8c3784b4db5a1ca6566bf93e7cf | refs/heads/main | 2023-01-24T05:27:17.245713 | 2020-12-11T04:06:15 | 2020-12-11T04:06:15 | 320,462,750 | 0 | 0 | NOASSERTION | 2020-12-11T04:02:53 | 2020-12-11T04:02:51 | null | UTF-8 | C++ | false | false | 4,499 | h | //
// This file is released under the terms of the NASA Open Source Agreement (NOSA)
// version 1.3 as detailed in the LICENSE file which accompanies this software.
//
//////////////////////////////////////////////////////////////////////
#ifndef WOPWOP_H
#define WOPWOP_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include "utils.H"
#define WOPWOP_CONSTANT 1
#define WOPWOP_PERIODIC 2
#define WOPWOP_APERIODIC 3
// Definition of the WOPWOP class
class WOPWOP {
private:
// Rotor information
int RotorID_;
int NumberOfBlades_;
int *SurfaceForBlade_;
int NumberOfBladesSections_;
FILE **RotorLoadingGeometryFile_;
FILE **RotorLoadingFile_;
FILE **RotorThicknessGeometryFile_;
FILE *BPMFile_;
// Wing information
int WingID_;
int NumberOfWingSurfaces_;
int *SurfaceForWing_;
int NumberOfWingSections_;
FILE **WingLoadingGeometryFile_;
FILE **WingLoadingFile_;
FILE **WingThicknessGeometryFile_;
// Body information
int BodyID_;
int NumberOfBodySurfaces_;
int *SurfaceForBody_;
int NumberOfBodySections_;
FILE **BodyThicknessGeometryFile_;
// File IO
FILE *OpenLoadingGeometryFile(int i, char *FileName, FILE **File);
FILE *OpenLoadingFile(int i, char *FileName, FILE **File);
FILE *OpenThicknessGeometryFile(int i, char *FileName, FILE **File);
public:
// Constructor, Destructor, Copy
WOPWOP(void);
~WOPWOP(void);
WOPWOP(const WOPWOP &WopWopRotor);
WOPWOP& operator=(const WOPWOP &WopWopRotor);
// Size the lists
void SizeBladeList(int NumberOfBlades);
void SizeWingSurfaceList(int NumberOfSurfaces);
void SizeBodySurfaceList(int NumberOfSurfaces);
// Rotor Info
int &RotorID(void) { return RotorID_; };
int NumberOfBlades(void) { return NumberOfBlades_; };
int &SurfaceForBlade(int i) { return SurfaceForBlade_[i]; };
int &NumberOfBladesSections(void) { return NumberOfBladesSections_; };
// Wing Info
int &WingID(void) { return WingID_; };
int &NumberOfWingSurfaces(void) { return NumberOfWingSurfaces_; };
int &SurfaceForWing(int i) { return SurfaceForWing_[i]; };
int &NumberOfWingSections(void) { return NumberOfWingSections_; };
// Body Info
int &BodyID(void) { return BodyID_; };
int &NumberOfBodySurfaces(void) { return NumberOfBodySurfaces_; };
int &SurfaceForBody(int i) { return SurfaceForBody_[i]; };
int &NumberOfBodySections(void) { return NumberOfBodySections_; };
// Rotor files
FILE *OpenLoadingGeometryFileForBlade(int i, char *FileName) { return OpenLoadingGeometryFile(i, FileName, RotorLoadingGeometryFile_); };
FILE *OpenLoadingFileForBlade(int i, char *FileName) { return OpenLoadingFile(i, FileName, RotorLoadingFile_); };
FILE *OpenThicknessGeometryFileForBlade(int i, char *FileName) { return OpenThicknessGeometryFile(i, FileName, RotorThicknessGeometryFile_); };
FILE *OpenBPMFile(char *FileName);
FILE *LoadingGeometryFileForBlade(int i) { return RotorLoadingGeometryFile_[i]; };
FILE *LoadingFileForBlade(int i) { return RotorLoadingFile_[i]; };
FILE *ThicknessGeometryFileForBlade(int i) { return RotorThicknessGeometryFile_[i]; };
FILE *BPMFile(void) { return BPMFile_; };
// Wing files
FILE *OpenLoadingGeometryFileForWingSurface(int i, char *FileName) { return OpenLoadingGeometryFile(i, FileName, WingLoadingGeometryFile_); };
FILE *OpenLoadingFileForWingSurface(int i, char *FileName) { return OpenLoadingFile(i, FileName, WingLoadingFile_); };
FILE *OpenThicknessGeometryFileForWingSurface(int i, char *FileName) { return OpenThicknessGeometryFile(i, FileName, WingThicknessGeometryFile_); };
FILE *LoadingGeometryFileForWingSurface(int i) { return WingLoadingGeometryFile_[i]; };
FILE *LoadingFileForWingSurface(int i) { return WingLoadingFile_[i]; };
FILE *ThicknessGeometryFileForWingSurface(int i) { return WingThicknessGeometryFile_[i]; };
// Body files
FILE *OpenThicknessGeometryFileForBodySurface(int i, char *FileName) { return OpenThicknessGeometryFile(i, FileName, BodyThicknessGeometryFile_); };
FILE *ThicknessGeometryFileForBodySurface(int i) { return BodyThicknessGeometryFile_[i]; };
void CloseFiles(void);
};
#endif
| [
"justin.gravett@esaero.com"
] | justin.gravett@esaero.com |
362d3d33f0fdea9d11849f0bbedcddff9d6bb411 | d5a86064cbb9437e06c29c1d423ec7e6915135d2 | /libdevelop/fndnet/src/WnUtility.h | aeecf5ccbc0a4f7bc7de164086eb65b874e2ca0c | [] | no_license | feixuedudu/ericbase | e4c0d844a0c12210c1a9b0116316b8fc6ebe887a | 3cad970bfadf560d8b8da01e31044ec7eb61db7f | refs/heads/master | 2021-06-09T12:12:58.005602 | 2016-12-26T14:37:59 | 2016-12-26T14:37:59 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,491 | h | /// \file WnUtility.h
/// \brief BASE功能类的声明文件
/// \author
/// \version 1.0
/// \date 2011-07-20
/// \history 2011-07-20 新建
#ifdef _WIN32
#pragma once
#endif
/// \brief BASE功能类
class WnUtility
{
public:
/// \brief 获取基础IO服务对象指针
static WnUtility* GetInstance();
/// \brief 删除基础IO服务对象
static void Delete();
/// \brief 获取时间值
/// \return 时间值
unsigned __int64 GetTimeValue();
/// \brief 整数转换为网络字节流
/// \param Int 整数值
/// \param pbStream 流指针
template<typename Integer>
void IntegerToStream(Integer Int, unsigned char* pbStream)
{
unsigned int unStreamSize = sizeof(Int);
unsigned int unCount = 0;
for(unCount = 0; unCount < unStreamSize; unCount++)
{
pbStream[unStreamSize - 1 - unCount] = Int & 0xFF;
Int >>= 8;
}
}
/// \brief 网络字节流转换为整数
/// \param pbStream 流指针
/// \param Int 整数值
template<typename Integer>
void StreamToInteger(unsigned char* pbStream, Integer& Int)
{
unsigned int unStreamSize = sizeof(Int);
unsigned int unCount = 0;
Int = 0;
for(unCount = 0; unCount < unStreamSize; unCount++)
{
Int = (Int << 8) | pbStream[unCount];
}
}
private:
/// \brief 构造函数
WnUtility(void);
/// \brief 析构函数
~WnUtility(void);
private:
/// \brief 功能对象的静态指针
static WnUtility* s_poUtility;
};
| [
"kaishansheng@163.com"
] | kaishansheng@163.com |
a49319abd555164fda40572a4390e1fed1e64f96 | 7b284f1fbcc311af4cb8dbba232edc15fa83f92c | /GamePad.cpp | 60d98ae063c1a6f21cb5bdf715bd1507815a9591 | [] | no_license | fml927/WPILib | 1123754dbe3d80e2d211eb6425c0d01b4fa184b7 | 282bbb57302d39958e59f12c4af16edbf934a5c7 | refs/heads/master | 2020-06-14T00:06:26.983892 | 2013-07-07T04:59:11 | 2013-07-07T04:59:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,940 | cpp | #include "GamePad.h"
#include "DriverStation.h"
#include "Utility.h"
//#include "WPIStatus.h"
/**
* Construct an instance of a gamepad.
* The gamepad index is the usb port on the drivers station.
*
* @param port The port on the driver station that the joystick is plugged into.
*/
GamePad::GamePad(unsigned port)
: m_ds (NULL)
, m_port (port)
, m_axes (NULL)
, m_buttons (NULL)
{
InitGamePad(kNumAxisTypes, kNumButtonTypes);
m_axes[kLeftXAxis] = kDefaultLeftXAxis;
m_axes[kLeftYAxis] = kDefaultLeftYAxis;
m_axes[kRightXAxis] = kDefaultRightXAxis;
m_axes[kRightYAxis] = kDefaultRightYAxis;
m_axes[kRockerXAxis] = kDefaultRockerXAxis;
m_axes[kRockerYAxis] = kDefaultRockerYAxis;
m_buttons[kButton01] = kDefaultButton01;
m_buttons[kButton02] = kDefaultButton02;
m_buttons[kButton03] = kDefaultButton03;
m_buttons[kButton04] = kDefaultButton04;
m_buttons[kButton05] = kDefaultButton05;
m_buttons[kButton06] = kDefaultButton06;
m_buttons[kButton07] = kDefaultButton07;
m_buttons[kButton08] = kDefaultButton08;
m_buttons[kButton09] = kDefaultButton09;
m_buttons[kButton10] = kDefaultButton10;
m_buttons[kButton11] = kDefaultButton11;
m_buttons[kButton12] = kDefaultButton12;
}
void GamePad::InitGamePad(unsigned numAxisTypes, unsigned numButtonTypes)
{
m_ds = DriverStation::GetInstance();
m_axes = new unsigned[numAxisTypes];
m_buttons = new unsigned[numButtonTypes];
}
GamePad::~GamePad()
{
delete [] m_buttons;
delete [] m_axes;
}
/**
* Get the X value of the gamepad's left joystick.
*/
float GamePad::GetLeftX(void)
{
return GetRawAxis(m_axes[kLeftXAxis]);
}
/**
* Get the Y value of the gamepad's left joystick.
*/
float GamePad::GetLeftY(void)
{
return -GetRawAxis(m_axes[kLeftYAxis]);
}
/**
* Get the X value of the gamepad's right joystick.
*/
float GamePad::GetRightX(void)
{
return GetRawAxis(m_axes[kRightXAxis]);
}
/**
* Get the Y value of the gamepad's right joystick.
*/
float GamePad::GetRightY(void)
{
return -GetRawAxis(m_axes[kRightYAxis]);
}
/**
* Get the X value of the gamepad's rocker.
*/
float GamePad::GetRockerX(void)
{
return GetRawAxis(m_axes[kRockerXAxis]);
}
/**
* Get the Y value of the gamepad's rocker.
*/
float GamePad::GetRockerY(void)
{
return GetRawAxis(m_axes[kRockerYAxis]);
}
/**
* Get the value of the axis.
*
* @param axis The axis to read [1-6].
* @return The value of the axis.
*/
float GamePad::GetRawAxis(unsigned axis)
{
return m_ds->GetStickAxis(m_port, axis);
}
/**
* For the current gamepad, return the axis determined by the argument.
*
* This is for cases where the gamepad axis is returned programatically, otherwise one of the
* previous functions would be preferable (for example GetLeftX()).
*
* @param axis The axis to read.
* @return The value of the axis.
*/
float GamePad::GetAxis(AxisType axis)
{
switch(axis)
{
case kLeftXAxis: return this->GetLeftX();
case kLeftYAxis: return -this->GetLeftY();
case kRightXAxis: return this->GetRightX();
case kRightYAxis: return -this->GetRightY();
case kRockerXAxis: return this->GetRockerX();
case kRockerYAxis: return this->GetRockerY();
default:
// wpi_fatal(BadJoystickAxis);
return 0.0;
}
}
/**
* Read the state of button 1 on the gamepad.
*
* @return The state of the button.
*/
bool GamePad::GetButton01(void)
{
return GetRawButton(m_buttons[kButton01]);
}
/**
* Read the state of button 2 on the gamepad.
*
* @return The state of the button.
*/
bool GamePad::GetButton02(void)
{
return GetRawButton(m_buttons[kButton02]);
}
/**
* Read the state of button 3 on the gamepad.
*
* @return The state of the button.
*/
bool GamePad::GetButton03(void)
{
return GetRawButton(m_buttons[kButton03]);
}
/**
* Read the state of button 4 on the gamepad.
*
* @return The state of the button.
*/
bool GamePad::GetButton04(void)
{
return GetRawButton(m_buttons[kButton04]);
}
/**
* Read the state of button 5 on the gamepad.
*
* @return The state of the button.
*/
bool GamePad::GetButton05(void)
{
return GetRawButton(m_buttons[kButton05]);
}
/**
* Read the state of button 6 on the gamepad.
*
* @return The state of the button.
*/
bool GamePad::GetButton06(void)
{
return GetRawButton(m_buttons[kButton06]);
}
/**
* Read the state of button 7 on the gamepad.
*
* @return The state of the button.
*/
bool GamePad::GetButton07(void)
{
return GetRawButton(m_buttons[kButton07]);
}
/**
* Read the state of button 8 on the gamepad.
*
* @return The state of the button.
*/
bool GamePad::GetButton08(void)
{
return GetRawButton(m_buttons[kButton08]);
}
/**
* Read the state of button 9 on the gamepad.
*
* @return The state of the button.
*/
bool GamePad::GetButton09(void)
{
return GetRawButton(m_buttons[kButton09]);
}
/**
* Read the state of button 10 on the gamepad.
*
* @return The state of the button.
*/
bool GamePad::GetButton10(void)
{
return GetRawButton(m_buttons[kButton10]);
}
/**
* Read the state of button 11 on the gamepad.
*
* @return The state of the button.
*/
bool GamePad::GetButton11(void)
{
return GetRawButton(m_buttons[kButton11]);
}
/**
* Read the state of button 12 on the gamepad.
*
* @return The state of the button.
*/
bool GamePad::GetButton12(void)
{
return GetRawButton(m_buttons[kButton12]);
}
/**
* Get the button value for buttons 1 through 12.
*
* The buttons are returned in a single 16 bit value with one bit representing the state
* of each button. The appropriate button is returned as a boolean value.
*
* @param button The button number to be read.
* @return The state of the button.
**/
bool GamePad::GetRawButton(unsigned button)
{
return ((0x1 << (button-1)) & m_ds->GetStickButtons(m_port)) != 0;
}
/**
* Get buttons based on an enumerated type.
*
* The button type will be looked up in the list of buttons and then read.
*
* @param button The type of button to read.
* @return The state of the button.
*/
bool GamePad::GetButton(ButtonType button)
{
switch (button)
{
case kButton01: return GetButton01();
case kButton02: return GetButton02();
case kButton03: return GetButton03();
case kButton04: return GetButton04();
case kButton05: return GetButton05();
case kButton06: return GetButton06();
case kButton07: return GetButton07();
case kButton08: return GetButton08();
case kButton09: return GetButton09();
case kButton10: return GetButton10();
case kButton11: return GetButton11();
case kButton12: return GetButton12();
default:
wpi_assert(false);
return false;
}
}
float GamePad::GetX(JoystickHand hand)
{
return 0;
}
float GamePad::GetY(JoystickHand hand){
return 0;
}
float GamePad::GetZ(){
return 0;
}
float GamePad::GetTwist(){
return 0;
}
float GamePad::GetThrottle(){
return 0;
}
bool GamePad::GetTrigger(JoystickHand hand){
return false;
}
bool GamePad::GetTop(JoystickHand hand){
return false;
}
bool GamePad::GetBumper(JoystickHand hand){
return false;
}
| [
"jefferson.clements@gmail.com"
] | jefferson.clements@gmail.com |
c83bd8f74e6b091d8160194dac6c91317399e572 | e8ca7bd9a0ce9e5ed75d5d53aec33fce60ee73ba | /src/init.cpp | 214dcfd9a04fddc306a71924c71465a6db0db0ab | [
"MIT"
] | permissive | masterofnix/securealumnicoin3 | b8ac9c794deacebffed33acc38ad4a877768e30b | df2f699d2391dcb4e17733d83ac21d15da3c00e4 | refs/heads/master | 2020-12-25T18:17:04.686341 | 2014-12-01T23:10:17 | 2014-12-01T23:10:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,630 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "net.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/crypto.h>
#ifndef WIN32
#include <signal.h>
#endif
using namespace std;
using namespace boost;
CWallet* pwalletMain;
CClientUIInterface uiInterface;
#ifdef WIN32
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
// accessing block files, don't count towards to fd_set size limit
// anyway.
#define MIN_CORE_FILEDESCRIPTORS 0
#else
#define MIN_CORE_FILEDESCRIPTORS 150
#endif
// Used to pass flags to the Bind() function
enum BindFlags {
BF_NONE = 0,
BF_EXPLICIT = (1U << 0),
BF_REPORT_ERROR = (1U << 1)
};
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
//
// Thread management and startup/shutdown:
//
// The network-processing threads are all part of a thread group
// created by AppInit() or the Qt main() function.
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets fRequestShutdown, which triggers
// the DetectShutdownThread(), which interrupts the main thread group.
// DetectShutdownThread() then exits, which causes AppInit() to
// continue (it .joins the shutdown thread).
// Shutdown() is then
// called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// Note that if running -daemon the parent process returns from AppInit2
// before adding any threads to the threadGroup, so .join_all() returns
// immediately and the parent exits from main().
//
// Shutdown for Qt is very similar, only it uses a QTimer to detect
// fRequestShutdown getting set, and then does the normal Qt
// shutdown thing.
//
volatile bool fRequestShutdown = false;
void StartShutdown()
{
fRequestShutdown = true;
}
bool ShutdownRequested()
{
return fRequestShutdown;
}
static CCoinsViewDB *pcoinsdbview;
void Shutdown()
{
printf("Shutdown : In progress...\n");
static CCriticalSection cs_Shutdown;
TRY_LOCK(cs_Shutdown, lockShutdown);
if (!lockShutdown) return;
RenameThread("bitcoin-shutoff");
nTransactionsUpdated++;
StopRPCThreads();
ShutdownRPCMining();
if (pwalletMain)
bitdb.Flush(false);
GenerateBitcoins(false, NULL);
StopNode();
{
LOCK(cs_main);
if (pwalletMain)
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
if (pblocktree)
pblocktree->Flush();
if (pcoinsTip)
pcoinsTip->Flush();
delete pcoinsTip; pcoinsTip = NULL;
delete pcoinsdbview; pcoinsdbview = NULL;
delete pblocktree; pblocktree = NULL;
}
if (pwalletMain)
bitdb.Flush(true);
boost::filesystem::remove(GetPidFile());
UnregisterWallet(pwalletMain);
if (pwalletMain)
delete pwalletMain;
printf("Shutdown : done\n");
}
//
// Signal handlers are very limited in what they are allowed to do, so:
//
void DetectShutdownThread(boost::thread_group* threadGroup)
{
// Tell the main threads to shutdown.
while (!fRequestShutdown)
{
MilliSleep(200);
if (fRequestShutdown)
threadGroup->interrupt_all();
}
}
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#if !defined(QT_GUI)
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
Shutdown();
}
ReadConfigFile(mapArgs, mapMultiArgs);
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to bitcoind / RPC client
std::string strUsage = _("Securealumnicoin version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" securealumnicoind [options] " + "\n" +
" securealumnicoind [options] <command> [params] " + _("Send command to -server or securealumnicoind") + "\n" +
" securealumnicoind [options] help " + _("List commands") + "\n" +
" securealumnicoind [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "securealumnicoin:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
#if !defined(WIN32)
fDaemon = GetBoolArg("-daemon");
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
CreatePidFile(GetPidFile(), pid);
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet) {
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
}
if (detectShutdownThread)
{
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect bitcoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return (fRet ? 0 : 1);
}
#endif
bool static InitError(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
return false;
}
bool static InitWarning(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
return true;
}
bool static Bind(const CService &addr, unsigned int flags) {
if (!(flags & BF_EXPLICIT) && IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError)) {
if (flags & BF_REPORT_ERROR)
return InitError(strError);
return false;
}
return true;
}
// Core-specific options shared between UI and daemon
std::string HelpMessage()
{
string strUsage = _("Options:") + "\n" +
" -? " + _("This help message") + "\n" +
" -conf=<file> " + _("Specify configuration file (default: securealumnicoin.conf)") + "\n" +
" -pid=<file> " + _("Specify pid file (default: securealumnicoind.pid)") + "\n" +
" -gen " + _("Generate coins (default: 0)") + "\n" +
" -datadir=<dir> " + _("Specify data directory") + "\n" +
" -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
" -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
" -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
" -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
" -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
" -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
" -port=<port> " + _("Listen for connections on <port> (default: 40333 or testnet: 50333)") + "\n" +
" -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
" -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
" -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
" -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
" -externalip=<ip> " + _("Specify your own public address") + "\n" +
" -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
" -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
" -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n" +
" -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
" -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n" +
" -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n" +
" -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
" -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
" -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
" -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
" -bloomfilters " + _("Allow peers to set bloom filters (default: 1)") + "\n" +
#ifdef USE_UPNP
#if USE_UPNP
" -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
#else
" -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
#endif
#endif
" -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
" -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.0001)") + "\n" +
#ifdef QT_GUI
" -server " + _("Accept command line and JSON-RPC commands") + "\n" +
#endif
#if !defined(WIN32) && !defined(QT_GUI)
" -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
#endif
" -testnet " + _("Use the test network") + "\n" +
" -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
" -debugnet " + _("Output extra network debugging information") + "\n" +
" -logtimestamps " + _("Prepend debug output with timestamp (default: 1)") + "\n" +
" -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
" -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
#ifdef WIN32
" -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
#endif
" -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
" -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
" -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 40332 or testnet: 50332)") + "\n" +
" -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
#ifndef QT_GUI
" -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
#endif
" -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n" +
" -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
" -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
" -spendzeroconfchange " + _("Spend unconfirmed change when sending transactions (default: 1)") + "\n" +
" -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" +
" -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
" -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
" -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
" -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
" -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n" +
" -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n" +
" -txindex " + _("Maintain a full transaction index (default: 0)") + "\n" +
" -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n" +
" -maxorphantx=<n> " + _("Keep at most <n> unconnectable transactions in memory (default: 25)") + "\n" +
" -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n" +
" -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n" +
"\n" + _("Block creation options:") + "\n" +
" -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
" -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
" -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
"\n" + _("SSL options: (see the Securealumnicoin Wiki for SSL setup instructions)") + "\n" +
" -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
" -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
" -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
" -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
return strUsage;
}
struct CImportingNow
{
CImportingNow() {
assert(fImporting == false);
fImporting = true;
}
~CImportingNow() {
assert(fImporting == true);
fImporting = false;
}
};
void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
{
RenameThread("bitcoin-loadblk");
// -reindex
if (fReindex) {
CImportingNow imp;
int nFile = 0;
while (true) {
CDiskBlockPos pos(nFile, 0);
FILE *file = OpenBlockFile(pos, true);
if (!file)
break;
printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
LoadExternalBlockFile(file, &pos);
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
printf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
InitBlockIndex();
}
// hardcoded $DATADIR/bootstrap.dat
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
CImportingNow imp;
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
printf("Importing bootstrap.dat...\n");
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
// -loadblock=
BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
FILE *file = fopen(path.string().c_str(), "rb");
if (file) {
CImportingNow imp;
printf("Importing %s...\n", path.string().c_str());
LoadExternalBlockFile(file);
}
}
}
/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2(boost::thread_group& threadGroup)
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
{
return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
}
#endif
#ifndef WIN32
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#endif
// ********************************************************* Step 2: parameter interactions
fTestNet = GetBoolArg("-testnet");
fBloomFilters = GetBoolArg("-bloomfilters", true);
if (fBloomFilters)
nLocalServices |= NODE_BLOOM;
if (mapArgs.count("-bind")) {
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
SoftSetBoolArg("-listen", true);
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
SoftSetBoolArg("-dnsseed", false);
SoftSetBoolArg("-listen", false);
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a proxy server is specified
SoftSetBoolArg("-listen", false);
}
if (!GetBoolArg("-listen", true)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
SoftSetBoolArg("-upnp", false);
SoftSetBoolArg("-discover", false);
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
SoftSetBoolArg("-discover", false);
}
if (GetBoolArg("-salvagewallet")) {
// Rewrite just private keys: rescan to find transactions
SoftSetBoolArg("-rescan", true);
}
// Make sure enough file descriptors are available
int nBind = std::max((int)mapArgs.count("-bind"), 1);
nMaxConnections = GetArg("-maxconnections", 125);
nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
if (nFD < MIN_CORE_FILEDESCRIPTORS)
return InitError(_("Not enough file descriptors available."));
if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = GetBoolArg("-debug");
fBenchmark = GetBoolArg("-benchmark");
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = GetArg("-par", 0);
if (nScriptCheckThreads <= 0)
nScriptCheckThreads += boost::thread::hardware_concurrency();
if (nScriptCheckThreads <= 1)
nScriptCheckThreads = 0;
else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
// -debug implies fDebug*
if (fDebug)
fDebugNet = true;
else
fDebugNet = GetBoolArg("-debugnet");
if (fDaemon)
fServer = true;
else
fServer = GetBoolArg("-server");
/* force fServer when running without GUI */
#if !defined(QT_GUI)
fServer = true;
#endif
fPrintToConsole = GetBoolArg("-printtoconsole");
fPrintToDebugger = GetBoolArg("-printtodebugger");
fLogTimestamps = GetBoolArg("-logtimestamps", true);
bool fDisableWallet = GetBoolArg("-disablewallet", false);
if (mapArgs.count("-timeout"))
{
int nNewTimeout = GetArg("-timeout", 5000);
if (nNewTimeout > 0 && nNewTimeout < 600000)
nConnectTimeout = nNewTimeout;
}
// Continue to put "/P2SH/" in the coinbase to monitor
// BIP16 support.
// This can be removed eventually...
const char* pszP2SH = "/P2SH/";
COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
// Fee-per-kilobyte amount considered the same as "free"
// If you are mining, be careful setting this:
// if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
if (mapArgs.count("-mintxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
CTransaction::nMinTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str()));
}
if (mapArgs.count("-minrelaytxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
CTransaction::nMinRelayTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str()));
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
if (nTransactionFee > 0.25 * COIN)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
}
bSpendZeroConfChange = GetArg("-spendzeroconfchange", true);
if (mapArgs.count("-mininput"))
{
if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
}
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
std::string strDataDir = GetDataDir().string();
// Make sure only a single Bitcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Securealumnicoin is probably already running."), strDataDir.c_str()));
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("Securealumnicoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
printf("Using data directory %s\n", strDataDir.c_str());
printf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
std::ostringstream strErrors;
if (fDaemon)
fprintf(stdout, "Securealumnicoin server starting\n");
if (nScriptCheckThreads) {
printf("Using %u threads for script verification\n", nScriptCheckThreads);
for (int i=0; i<nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
}
int64 nStart;
#if defined(USE_SSE2)
scrypt_detect_sse2();
#endif
// ********************************************************* Step 5: verify wallet database integrity
if (!fDisableWallet) {
uiInterface.InitMessage(_("Verifying wallet..."));
if (!bitdb.Open(GetDataDir()))
{
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str());
} catch(boost::filesystem::filesystem_error &error) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
return InitError(msg);
}
}
if (GetBoolArg("-salvagewallet"))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
return false;
}
if (filesystem::exists(GetDataDir() / "wallet.dat"))
{
CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."), strDataDir.c_str());
InitWarning(msg);
}
if (r == CDBEnv::RECOVER_FAIL)
return InitError(_("wallet.dat corrupt, salvage failed"));
}
} // (!fDisableWallet)
// ********************************************************* Step 6: network initialization
int nSocksVersion = GetArg("-socks", 5);
if (nSocksVersion != 4 && nSocksVersion != 5)
return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
#if defined(USE_IPV6)
#if ! USE_IPV6
else
SetLimited(NET_IPV6);
#endif
#endif
CService addrProxy;
bool fProxy = false;
if (mapArgs.count("-proxy")) {
addrProxy = CService(mapArgs["-proxy"], 9050);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
#ifdef USE_IPV6
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
#endif
SetNameProxy(addrProxy, nSocksVersion);
}
fProxy = true;
}
// -tor can override normal proxy, -notor disables tor entirely
if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
CService addrOnion;
if (!mapArgs.count("-tor"))
addrOnion = addrProxy;
else
addrOnion = CService(mapArgs["-tor"], 9050);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
SetProxy(NET_TOR, addrOnion, 5);
SetReachable(NET_TOR);
}
// see Step 2: parameter interactions for more information about these
fNoListen = !GetBoolArg("-listen", true);
fDiscover = GetBoolArg("-discover", true);
fNameLookup = GetBoolArg("-dns", true);
bool fBound = false;
if (!fNoListen) {
if (mapArgs.count("-bind")) {
BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
}
}
else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
#ifdef USE_IPV6
fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
#endif
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip")) {
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
// ********************************************************* Step 7: load block chain
fReindex = GetBoolArg("-reindex");
// Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
filesystem::path blocksDir = GetDataDir() / "blocks";
if (!filesystem::exists(blocksDir))
{
filesystem::create_directories(blocksDir);
bool linked = false;
for (unsigned int i = 1; i < 10000; i++) {
filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
if (!filesystem::exists(source)) break;
filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
try {
filesystem::create_hard_link(source, dest);
printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
linked = true;
} catch (filesystem::filesystem_error & e) {
// Note: hardlink creation failing is not a disaster, it just means
// blocks will get re-downloaded from peers.
printf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
break;
}
}
if (linked)
{
fReindex = true;
}
}
// cache size calculations
size_t nTotalCache = GetArg("-dbcache", 25) << 20;
if (nTotalCache < (1 << 22))
nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB
size_t nBlockTreeDBCache = nTotalCache / 8;
if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
nTotalCache -= nBlockTreeDBCache;
size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
nTotalCache -= nCoinDBCache;
nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
bool fLoaded = false;
while (!fLoaded) {
bool fReset = fReindex;
std::string strLoadError;
uiInterface.InitMessage(_("Loading block index..."));
nStart = GetTimeMillis();
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
if (fReindex)
pblocktree->WriteReindexing(true);
if (!LoadBlockIndex()) {
strLoadError = _("Error loading block database");
break;
}
// If the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
if (!mapBlockIndex.empty() && pindexGenesisBlock == NULL)
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
// Initialize the block index (no-op if non-empty database was already loaded)
if (!InitBlockIndex()) {
strLoadError = _("Error initializing block database");
break;
}
// Check for changed -txindex state
if (fTxIndex != GetBoolArg("-txindex", false)) {
strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
break;
}
uiInterface.InitMessage(_("Verifying blocks..."));
if (!VerifyDB(GetArg("-checklevel", 3),
GetArg( "-checkblocks", 288))) {
strLoadError = _("Corrupted block database detected");
break;
}
} catch(std::exception &e) {
strLoadError = _("Error opening block database");
break;
}
fLoaded = true;
} while(false);
if (!fLoaded) {
// first suggest a reindex
if (!fReset) {
bool fRet = uiInterface.ThreadSafeMessageBox(
strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
if (fRet) {
fReindex = true;
fRequestShutdown = false;
} else {
return false;
}
} else {
return InitError(strLoadError);
}
}
}
// as LoadBlockIndex can take several minutes, it's possible the user
// requested to kill bitcoin-qt during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
// ********************************************************* Step 8: load wallet
if (fDisableWallet) {
printf("Wallet disabled!\n");
pwalletMain = NULL;
} else {
uiInterface.InitMessage(_("Loading wallet..."));
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet("wallet.dat");
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
InitWarning(msg);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of Securealumnicoin") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart Securealumnicoin to complete") << "\n";
printf("%s", strErrors.str().c_str());
return InitError(strErrors.str());
}
else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
strErrors << _("Cannot write default address") << "\n";
}
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan"))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb("wallet.dat");
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
else
pindexRescan = pindexGenesisBlock;
}
if (pindexBest && pindexBest != pindexRescan)
{
uiInterface.InitMessage(_("Rescanning..."));
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
nWalletDBUpdated++;
}
} // (!fDisableWallet)
// ********************************************************* Step 9: import blocks
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ConnectBestBlock(state))
strErrors << "Failed to connect best block";
std::vector<boost::filesystem::path> vImportFiles;
if (mapArgs.count("-loadblock"))
{
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
vImportFiles.push_back(strFile);
}
threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
// ********************************************************* Step 10: load peers
uiInterface.InitMessage(_("Loading addresses..."));
nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
if (!strErrors.str().empty())
return InitError(strErrors.str());
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
StartNode(threadGroup);
// InitRPCMining is needed here so getwork/getblocktemplate in the GUI debug console works properly.
InitRPCMining();
if (fServer)
StartRPCThreads();
// Generate coins in the background
if (pwalletMain)
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
// ********************************************************* Step 12: finished
uiInterface.InitMessage(_("Done loading"));
if (pwalletMain) {
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
}
return !fRequestShutdown;
}
| [
"masterofnix@gmx.de"
] | masterofnix@gmx.de |
862d31ec8fccaa8e66978c6e8029a8bf5fbafc71 | bdf27704a92e3bae6d53f792702e436c13aca68f | /FPSProject/Source/FPSProject/FPSController.h | 86c3490f6878e71f524376f9294a358007709cb6 | [
"MIT"
] | permissive | TragicDragoon20/UnrealEngine-FPSController | 4653828a2c65ddfe2ce0cdf97800ef79927fc51a | 0d87735c349c4aece1bce0dac84107e1b24b160c | refs/heads/master | 2022-07-22T14:21:36.228087 | 2020-05-20T16:41:33 | 2020-05-20T16:42:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 913 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "FPSController.generated.h"
UCLASS()
class FPSPROJECT_API AFPSController : public ACharacter
{
GENERATED_BODY()
public:
// Sets default values for this character's properties
AFPSController();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
UFUNCTION()
void MoveForward(float Value);
UFUNCTION()
void MoveRight(float Value);
UFUNCTION()
void StartJump();
UFUNCTION()
void StopJump();
UPROPERTY(VisibleAnywhere)
class UCameraComponent* FPSCameraComponent;
};
| [
"cm227781@falmouth.ac.uk"
] | cm227781@falmouth.ac.uk |
0a34fa6b28567d28336209be7572abb5e8178160 | 6ed4f889fd6c274c742c9030af983654bdb88e87 | /udp/udp_socket.hpp | f7e5c9e44e586e0c32c37bc991ddd39ee38d8260 | [
"MIT"
] | permissive | Life4gal/asio_proxy | efd10c9eb45621a435444ff5ed388de0f0e8ab48 | 4ef205c771cce4173c7fd109dde7add764e917dc | refs/heads/master | 2023-07-05T07:11:54.229205 | 2021-08-03T13:25:08 | 2021-08-03T13:25:08 | 386,954,962 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,916 | hpp | #pragma once
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/udp.hpp>
#include "../common/address.hpp"
namespace proxy::udp
{
struct udp_socket
{
using socket_type = boost::asio::ip::udp::socket;
using io_context_type = boost::asio::io_context;
using endpoint_type = boost::asio::ip::udp::endpoint;
using size_type = size_t;
using value_type = unsigned char;
template <size_type N>
using stream_type = std::array<value_type, N>;
constexpr static size_type buffer_size = 4 * 1024;
constexpr static size_type basic_sample_size = 16;
using buffer_type = stream_type<buffer_size>;
using address_type = common::address;
udp_socket(
io_context_type& io_context,
const address_type& listen_address
);
bool close(boost::system::error_code& shutdown_ec, boost::system::error_code& close_ec);
void close();
template <typename Handler>
requires requires(Handler&& h)
{
{
h(std::declval<const boost::system::error_code&>(), std::declval<size_type>())
} -> std::same_as<void>;
}
void async_receive(Handler&& handler)
{
socket_.async_receive_from(boost::asio::buffer(buffer_), remote_, std::forward<Handler>(handler));
}
size_type send_to(const buffer_type& buffer, size_type max_size_in_bytes, const address_type& address);
[[nodiscard]] std::string sample_buffer(size_type size = basic_sample_size) const;
[[nodiscard]] address_type get_remote_address() const;
[[nodiscard]] std::string get_remote_address_string() const;
[[nodiscard]] address_type get_local_address() const;
[[nodiscard]] std::string get_local_address_string() const;
[[nodiscard]] std::string get_session_id() const;
socket_type socket_;
endpoint_type remote_;
buffer_type buffer_;
static endpoint_type make_endpoint(const address_type& address);
static address_type make_address(const endpoint_type& endpoint);
};
}
| [
"life4gal@gmail.com"
] | life4gal@gmail.com |
e025f7a021c50e8d05b55f00aff027abb31fbd66 | 2de45d37d5a5c34e341da1e88f0c0465036d8981 | /qcoin-master/src/test/ratecheck_tests.cpp | 25e6abb064bcbd058c85389306289d9e67e5377b | [
"MIT"
] | permissive | Qcoinn/qcoin-master | 0f121596f8a9d3f1ff13837bb0c7611c8985671c | baad627b72d177de4dc4bad5eb34ec8986ea5c3b | refs/heads/master | 2021-01-25T13:06:23.506133 | 2018-03-02T04:15:18 | 2018-03-02T04:15:18 | 123,529,322 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,851 | cpp | // Copyright (c) 2014-2017 The Qcoin Core developers
#include "governance.h"
#include "test/test_qcoin.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(ratecheck_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(ratecheck_test)
{
CRateCheckBuffer buffer;
BOOST_CHECK(buffer.GetCount() == 0);
BOOST_CHECK(buffer.GetMinTimestamp() == numeric_limits<int64_t>::max());
BOOST_CHECK(buffer.GetMaxTimestamp() == 0);
BOOST_CHECK(buffer.GetRate() == 0.0);
buffer.AddTimestamp(1);
std::cout << "buffer.GetMinTimestamp() = " << buffer.GetMinTimestamp() << std::endl;
BOOST_CHECK(buffer.GetCount() == 1);
BOOST_CHECK(buffer.GetMinTimestamp() == 1);
BOOST_CHECK(buffer.GetMaxTimestamp() == 1);
BOOST_CHECK(buffer.GetRate() == 0.0);
buffer.AddTimestamp(2);
BOOST_CHECK(buffer.GetCount() == 2);
BOOST_CHECK(buffer.GetMinTimestamp() == 1);
BOOST_CHECK(buffer.GetMaxTimestamp() == 2);
//BOOST_CHECK(fabs(buffer.GetRate() - 2.0) < 1.0e-9);
BOOST_CHECK(buffer.GetRate() == 0.0);
buffer.AddTimestamp(3);
BOOST_CHECK(buffer.GetCount() == 3);
BOOST_CHECK(buffer.GetMinTimestamp() == 1);
BOOST_CHECK(buffer.GetMaxTimestamp() == 3);
int64_t nMin = buffer.GetMinTimestamp();
int64_t nMax = buffer.GetMaxTimestamp();
double dRate = buffer.GetRate();
std::cout << "buffer.GetCount() = " << buffer.GetCount() << std::endl;
std::cout << "nMin = " << nMin << std::endl;
std::cout << "nMax = " << nMax << std::endl;
std::cout << "buffer.GetRate() = " << dRate << std::endl;
//BOOST_CHECK(fabs(buffer.GetRate() - (3.0/2.0)) < 1.0e-9);
BOOST_CHECK(buffer.GetRate() == 0.0);
buffer.AddTimestamp(4);
BOOST_CHECK(buffer.GetCount() == 4);
BOOST_CHECK(buffer.GetMinTimestamp() == 1);
BOOST_CHECK(buffer.GetMaxTimestamp() == 4);
//BOOST_CHECK(fabs(buffer.GetRate() - (4.0/3.0)) < 1.0e-9);
BOOST_CHECK(buffer.GetRate() == 0.0);
buffer.AddTimestamp(5);
BOOST_CHECK(buffer.GetCount() == 5);
BOOST_CHECK(buffer.GetMinTimestamp() == 1);
BOOST_CHECK(buffer.GetMaxTimestamp() == 5);
BOOST_CHECK(fabs(buffer.GetRate() - (5.0/4.0)) < 1.0e-9);
buffer.AddTimestamp(6);
BOOST_CHECK(buffer.GetCount() == 5);
BOOST_CHECK(buffer.GetMinTimestamp() == 2);
BOOST_CHECK(buffer.GetMaxTimestamp() == 6);
BOOST_CHECK(fabs(buffer.GetRate() - (5.0/4.0)) < 1.0e-9);
CRateCheckBuffer buffer2;
std::cout << "Before loop tests" << std::endl;
for(int64_t i = 1; i < 11; ++i) {
std::cout << "In loop: i = " << i << std::endl;
buffer2.AddTimestamp(i);
BOOST_CHECK(buffer2.GetCount() == (i <= 5 ? i : 5));
BOOST_CHECK(buffer2.GetMinTimestamp() == max(int64_t(1), i - 4));
BOOST_CHECK(buffer2.GetMaxTimestamp() == i);
}
}
BOOST_AUTO_TEST_SUITE_END()
| [
"36142786+Qcoinmn@users.noreply.github.com"
] | 36142786+Qcoinmn@users.noreply.github.com |
20214251de5fe6805b67cb5a2e6d0e17e90b96f5 | 415980fd8919e316194677d7192eb73b6c74f172 | /ecs/include/alibabacloud/ecs/model/DeleteNetworkInterfacePermissionRequest.h | c086da39641b9a3a7324562960ee496e87871009 | [
"Apache-2.0"
] | permissive | cctvbtx/aliyun-openapi-cpp-sdk | c3174d008a81afa1c3874825a6c5524e9ffc0f81 | 6d801b67b6d9b3034a29678e6b820eb88908c45b | refs/heads/master | 2020-06-20T01:19:45.307426 | 2019-07-14T15:46:19 | 2019-07-14T15:46:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,705 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_ECS_MODEL_DELETENETWORKINTERFACEPERMISSIONREQUEST_H_
#define ALIBABACLOUD_ECS_MODEL_DELETENETWORKINTERFACEPERMISSIONREQUEST_H_
#include <string>
#include <vector>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <alibabacloud/ecs/EcsExport.h>
namespace AlibabaCloud
{
namespace Ecs
{
namespace Model
{
class ALIBABACLOUD_ECS_EXPORT DeleteNetworkInterfacePermissionRequest : public RpcServiceRequest
{
public:
DeleteNetworkInterfacePermissionRequest();
~DeleteNetworkInterfacePermissionRequest();
long getResourceOwnerId()const;
void setResourceOwnerId(long resourceOwnerId);
long getCallerParentId()const;
void setCallerParentId(long callerParentId);
bool getProxy_original_security_transport()const;
void setProxy_original_security_transport(bool proxy_original_security_transport);
std::string getProxy_original_source_ip()const;
void setProxy_original_source_ip(const std::string& proxy_original_source_ip);
std::string getOwnerIdLoginEmail()const;
void setOwnerIdLoginEmail(const std::string& ownerIdLoginEmail);
std::string getCallerType()const;
void setCallerType(const std::string& callerType);
std::string getAccessKeyId()const;
void setAccessKeyId(const std::string& accessKeyId);
std::string getSourceRegionId()const;
void setSourceRegionId(const std::string& sourceRegionId);
std::string getSecurityToken()const;
void setSecurityToken(const std::string& securityToken);
std::string getRegionId()const;
void setRegionId(const std::string& regionId);
bool getEnable()const;
void setEnable(bool enable);
std::string getRequestContent()const;
void setRequestContent(const std::string& requestContent);
std::string getCallerBidEmail()const;
void setCallerBidEmail(const std::string& callerBidEmail);
std::string getCallerUidEmail()const;
void setCallerUidEmail(const std::string& callerUidEmail);
long getCallerUid()const;
void setCallerUid(long callerUid);
std::string getApp_ip()const;
void setApp_ip(const std::string& app_ip);
std::string getNetworkInterfacePermissionId()const;
void setNetworkInterfacePermissionId(const std::string& networkInterfacePermissionId);
std::string getResourceOwnerAccount()const;
void setResourceOwnerAccount(const std::string& resourceOwnerAccount);
std::string getOwnerAccount()const;
void setOwnerAccount(const std::string& ownerAccount);
std::string getCallerBid()const;
void setCallerBid(const std::string& callerBid);
long getOwnerId()const;
void setOwnerId(long ownerId);
bool getProxy_trust_transport_info()const;
void setProxy_trust_transport_info(bool proxy_trust_transport_info);
bool getAk_mfa_present()const;
void setAk_mfa_present(bool ak_mfa_present);
bool getSecurity_transport()const;
void setSecurity_transport(bool security_transport);
std::string getRequestId()const;
void setRequestId(const std::string& requestId);
bool getForce()const;
void setForce(bool force);
private:
long resourceOwnerId_;
long callerParentId_;
bool proxy_original_security_transport_;
std::string proxy_original_source_ip_;
std::string ownerIdLoginEmail_;
std::string callerType_;
std::string accessKeyId_;
std::string sourceRegionId_;
std::string securityToken_;
std::string regionId_;
bool enable_;
std::string requestContent_;
std::string callerBidEmail_;
std::string callerUidEmail_;
long callerUid_;
std::string app_ip_;
std::string networkInterfacePermissionId_;
std::string resourceOwnerAccount_;
std::string ownerAccount_;
std::string callerBid_;
long ownerId_;
bool proxy_trust_transport_info_;
bool ak_mfa_present_;
bool security_transport_;
std::string requestId_;
bool force_;
};
}
}
}
#endif // !ALIBABACLOUD_ECS_MODEL_DELETENETWORKINTERFACEPERMISSIONREQUEST_H_ | [
"haowei.yao@alibaba-inc.com"
] | haowei.yao@alibaba-inc.com |
629fda3723d47b41ebe4c5706980a2672dd508d8 | de65543fa6dbf9d99f7748b85ef6e9b35ffc128a | /UpdateAgent/hookapi.cpp | 200c389869b00f7211bac750f8ca140f6f3ed882 | [] | no_license | jadesnake/UpdateAgent | 3d95b0a6e10255ac132de711f0d916c57534380e | 033014d1217c4c17b3a684c7d0cb9bf1387cc918 | refs/heads/master | 2021-01-17T12:45:06.040029 | 2017-07-19T03:17:34 | 2017-07-19T03:17:34 | 56,961,613 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,647 | cpp | // ApiHook.cpp: implementation of the CApiHook class.
#include "stdafx.h"
#include "Hookapi.h"
#include <stdio.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#define OPEN_FLAGS ( PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE )
CApiHook::CApiHook()
{
InitializeCriticalSection(&m_cs);
}
CApiHook ::~CApiHook()
{
CloseHandle(hProc);
DeleteCriticalSection(&m_cs);
}
void CApiHook::SetHookOn(void)
{
DWORD dwOldFlag;
if (WriteProcessMemory(hProc, m_lpHookFunc, m_NewFunc, 5, 0))
{
return;
}
dwOldFlag = ::GetLastError();
return;
}
void CApiHook::SetHookOff(void)
{
DWORD dwOldFlag;
if (WriteProcessMemory(hProc, m_lpHookFunc, m_OldFunc, 5, 0))
{
return;
}
return;
}
BOOL CApiHook::Initialize(LPCTSTR lpLibFileName, LPCSTR lpProcName, FARPROC lpNewFunc)
{
HMODULE hModule;
hModule = LoadLibrary(lpLibFileName);
if (NULL == hModule)
return FALSE;
m_lpHookFunc = GetProcAddress(hModule, lpProcName);
if (NULL == m_lpHookFunc)
return FALSE;
DWORD dwProcessID = GetCurrentProcessId();
DWORD dwOldFlag;
hProc = GetCurrentProcess( /*OPEN_FLAGS,0,dwProcessID*/);
if (hProc == NULL)
{
return FALSE;
}
if (ReadProcessMemory(hProc, m_lpHookFunc, m_OldFunc, 5, 0))
{
m_NewFunc[0] = 0xe9;
DWORD * pNewFuncAddress;
pNewFuncAddress = (DWORD *)& m_NewFunc[1];
*pNewFuncAddress = (DWORD)lpNewFunc - (DWORD)m_lpHookFunc - 5;
return TRUE;
}
return FALSE;
}
void CApiHook::Lock()
{
EnterCriticalSection(&m_cs);
}
void CApiHook::Unlock()
{
LeaveCriticalSection(&m_cs);
} | [
"jiayh@servyou.com.cn"
] | jiayh@servyou.com.cn |
102419bae950d247b64a8fddac93216e3f0dd9c4 | a3696f7f62511521c974ebb654cdf0162d28c4e6 | /emscripten/bullet/src/Logic/Physic/Trimesh.cpp | a9fdeed67c3b677e224c23293b21c6dce2013463 | [] | no_license | templeblock/geneticAlgorithm_experiment | de4aef6fec14e82483886769b440b26ab020cb2c | 856042364afad278663937b5a86d210fa1202fb0 | refs/heads/master | 2021-06-18T06:27:43.911471 | 2017-05-19T19:16:36 | 2017-05-19T19:16:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,351 | cpp |
#include "Trimesh.hpp"
#include <Bullet/btBulletDynamicsCommon.h>
namespace Physic
{
Trimesh::Trimesh(const std::vector<float>& buffer, const std::vector<int>& indices, int id)
: m_id(id)
{
unsigned int vertNumber = buffer.size();
m_pArr_Vertices = new float[buffer.size()];
memcpy(m_pArr_Vertices, &buffer[0], buffer.size() * sizeof(float));
int vertStride = 3 * sizeof(float);
unsigned int triangleNumber = indices.size() / 3;
m_pArr_Indices = new int[indices.size()];
memcpy(m_pArr_Indices, &indices[0], indices.size() * sizeof(int));
int indexStride = 3 * sizeof(int);
m_pIndexVertexArrays = new btTriangleIndexVertexArray(
triangleNumber, m_pArr_Indices, indexStride,
vertNumber, m_pArr_Vertices, vertStride
);
bool useQuantizedAabbCompression = true;
m_pShape = new btBvhTriangleMeshShape(m_pIndexVertexArrays, useQuantizedAabbCompression);
m_pMotionState = new btDefaultMotionState(btTransform(btQuaternion(0.0, 0.0, 0.0, 1.0), btVector3(0, 0, 0)));
btScalar mass = 0;
btVector3 localInertia(0,0,0);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, m_pMotionState, m_pShape, localInertia);
m_pBbody = new btRigidBody(rbInfo);
}
Trimesh::~Trimesh()
{
delete m_pBbody;
delete m_pMotionState;
delete m_pShape;
delete m_pIndexVertexArrays;
delete[] m_pArr_Indices;
delete[] m_pArr_Vertices;
}
};
| [
"guillaume.bouchet@epitech.eu"
] | guillaume.bouchet@epitech.eu |
f141f4ffc622f3cb7ea1dd013ee37732991c7524 | c0f1cb8c6deb774a3b14e01844e6074cd6ae56e0 | /jc_pir_led_radio_2/jc_pir_led_radio_2.ino | 6f17a07254e02d290a764d15bd1bf733d06927e7 | [] | no_license | jgc/Arduino | 672edf29598b2fa22ac86325cffdd8ab6c6d70ec | eecdf6bdc557d128ded5e6a4ae1846f1fa02e580 | refs/heads/master | 2021-01-10T19:41:09.369287 | 2014-04-05T21:47:37 | 2014-04-05T21:47:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,195 | ino | // 2014-03-20
// Changes not uploaded
// changed led delay from 2000 to 500 ms
// report count corrected
#include <JeeLib.h>
ISR(WDT_vect) { Sleepy::watchdogEvent(); } // interrupt handler for JeeLabs Sleepy power saving
#define myNodeID 2 // RF12 node ID in the range 1-30
#define network 100 // RF12 Network group
#define freq RF12_868MHZ // Frequency of RFM12B module
#define pirdelay 60000 // Duration of sleep between measurements, in ms
//########################################################################################################################
//Data Structure to be sent, it is variable in size and we only send 2+n*2 bytes where n is the number of DS18B20 sensors attached
//########################################################################################################################
typedef struct {
int supplyV;
int motion;
int code;
int count;
} Payload;
Payload temptx;
int numSensors;
Port pir (3); // PIR sensor is connected to DIO3 (pin 2) of port 3
uint8_t state;
int reportcount = 0;
int reportdelaymin = 5; // minutes
int reportdelay = 60 * reportdelaymin;
int pircount = 0;
int ledV = 0;
int LEDR = 7;
int LEDG = 17;
int POW = 16;
void blinkLed(){
if (ledV == 0){
digitalWrite(LEDR, LOW);
digitalWrite(LEDG, LOW);
}
if (ledV == 1){
digitalWrite(LEDR, HIGH);
digitalWrite(LEDG, HIGH);
}
if (ledV == 2){
digitalWrite(LEDR, HIGH);
digitalWrite(LEDG, LOW);
}
if (ledV == 3){
digitalWrite(LEDR, LOW);
digitalWrite(LEDG, HIGH);
}
delay(500);
digitalWrite(LEDR, LOW);
digitalWrite(LEDG, LOW);
ledV = 0;
}
void setup () {
pinMode(POW, OUTPUT);
digitalWrite(POW, HIGH);
pinMode(LEDR, OUTPUT);
digitalWrite(LEDR, HIGH);
pinMode(LEDG, OUTPUT);
digitalWrite(LEDG, HIGH);
delay(1000);
ledV = 1;
blinkLed();
ledV = 2;
blinkLed();
ledV = 2;
blinkLed();
delay(15000);
ledV = 1;
blinkLed();
rf12_initialize(myNodeID,freq,network); // Initialize RFM12 with settings defined above
rf12_control(0xC000); // Adjust low battery voltage to 2.2V
rf12_sleep(0); // Put the RFM12 to sleep
PRR = bit(PRTIM1); // only keep timer 0 going
ADCSRA &= ~ bit(ADEN); // Disable the ADC
bitSet (PRR, PRADC); // Power down ADC
bitClear (ACSR, ACIE); // Disable comparitor interrupts
bitClear (ACSR, ACD); // Power down analogue comparitor
Serial.begin(57600);
Serial.print("\n[pir_demo]");
pir.mode(INPUT);
pir.mode2(INPUT);
pir.digiWrite2(1); // pull-up
}
void loop () {
if (pir.digiRead() != state) {
state = pir.digiRead();
Serial.print("\nPIR ");
Serial.print(state ? "on " : "off");
if (state == 1){
ledV = 2;
blinkLed();
temptx.motion = 1;
temptx.code = 9;
temptx.count = pircount;
rfwrite();
ledV = 3;
blinkLed();
pircount++;
if (pircount > 3){
ledV = 1;
blinkLed();
//delay(30000);
Sleepy::loseSomeTime(30000);
pircount = 0;
}
}
}
reportcount++;
Sleepy::loseSomeTime(1000);
//delay(1000);
if (reportcount >= reportdelay){
temptx.motion = 0;
temptx.code = 0;
temptx.count = 0;
rfwrite();
reportcount = 0;
}
}
//--------------------------------------------------------------------------------------------------
// Send payload data via RF
//--------------------------------------------------------------------------------------------------
static void rfwrite(){
rf12_sleep(-1); //wake up RF module
vccRead();
while (!rf12_canSend())
rf12_recvDone();
//rf12_sendStart(0, &temptx, numSensors*2 + 2); // two bytes for the battery reading, then 2*numSensors for the number of DS18B20s attached to Funky
rf12_sendStart(0, &temptx, 8, 1); // two bytes for the battery reading, then 2*numSensors for the number of DS18B20s attached to Funky
//1 as 4th argument
rf12_sendWait(2); //wait for RF to finish sending while in standby mode
rf12_sleep(0); //put RF module to sleep
}
//--------------------------------------------------------------------------------------------------
// Reads current voltage
//--------------------------------------------------------------------------------------------------
void vccRead(){
bitClear(PRR, PRADC); // power up the ADC
ADCSRA |= bit(ADEN); // enable the ADC
Sleepy::loseSomeTime(10);
//delay(10);
temptx.supplyV = map(analogRead(6), 0, 1023, 0, 660);
ADCSRA &= ~ bit(ADEN); // disable the ADC
bitSet(PRR, PRADC); // power down the ADC
}
long vccRead2() {
long result;
// Read 1.1V reference against AVcc
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate AVcc in mV
temptx.supplyV = result;
//return result;
}
int freeRam () {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
| [
"jgcy@yahoo.com"
] | jgcy@yahoo.com |
95d75b0ab3f193a61e6968d62ead2f79c6a955a6 | 634120df190b6262fccf699ac02538360fd9012d | /Develop/CSCommon/source/CSPartyMember.cpp | dbea230a9a183445a20444ad18b49ae0ea91ae44 | [] | no_license | ktj007/Raiderz_Public | c906830cca5c644be384e68da205ee8abeb31369 | a71421614ef5711740d154c961cbb3ba2a03f266 | refs/heads/master | 2021-06-08T03:37:10.065320 | 2016-11-28T07:50:57 | 2016-11-28T07:50:57 | 74,959,309 | 6 | 4 | null | 2016-11-28T09:53:49 | 2016-11-28T09:53:49 | null | UTF-8 | C++ | false | false | 2,607 | cpp | #include "stdafx.h"
#include "CSPartyMember.h"
#include "CTransData.h"
CSPartyMember::CSPartyMember()
: m_nStatusFlag(0)
, m_nHP(0)
, m_nEN(0)
, m_nSTA(0)
, m_nLevel(0)
, m_nFieldID(0)
, m_nChannelID(INVALID_CHANNELID)
, m_nTalentStyle(TS_NONE)
, m_isSetted(false)
{
// do nothing
}
CSPartyMember::CSPartyMember(MUID uidMember, tstring strMemberName)
: m_UID(uidMember)
, m_nStatusFlag(0)
, m_nHP(0)
, m_nEN(0)
, m_nSTA(0)
, m_strName(strMemberName)
, m_nLevel(0)
, m_nFieldID(0)
, m_nChannelID(INVALID_CHANNELID)
, m_nTalentStyle(TS_NONE)
, m_isSetted(false)
{
// do noting
}
CSPartyMember::~CSPartyMember()
{
// do nothing
}
void CSPartyMember::Assign(const TD_PARTY_MEMBER& tdPartyMember, const vector<int>& vecBuff)
{
m_UID = tdPartyMember.m_uidPlayer;
m_nStatusFlag = tdPartyMember.nStatusFlag;
m_nHP = tdPartyMember.nHP;
m_nEN = tdPartyMember.nEN;
m_nSTA = tdPartyMember.nSTA;
m_strName = tdPartyMember.szName;
m_nLevel = tdPartyMember.nLevel;
m_nFieldID = tdPartyMember.nFieldID;
m_nChannelID = tdPartyMember.nChannelID;
m_nTalentStyle = static_cast<TALENT_STYLE>(tdPartyMember.nTalentStyle);
m_vecBuff = vecBuff;
m_isSetted = true;
}
void CSPartyMember::Export(TD_PARTY_MEMBER* pPartyMember, vector<int>* pVecBuff) const
{
pPartyMember->m_uidPlayer = m_UID;
pPartyMember->nStatusFlag = m_nStatusFlag;
pPartyMember->nHP = m_nHP;
pPartyMember->nEN = m_nEN;
pPartyMember->nSTA = m_nSTA;
pPartyMember->nLevel = m_nLevel;
pPartyMember->nFieldID = m_nFieldID;
pPartyMember->nChannelID = m_nChannelID;
pPartyMember->nTalentStyle = static_cast<uint8>(m_nTalentStyle);
_tcsncpy_s(pPartyMember->szName, m_strName.c_str(), _TRUNCATE);
if (pVecBuff)
*pVecBuff = m_vecBuff;
}
void CSPartyMember::Update(const CSPartyMember* pPartyMember)
{
m_nStatusFlag = pPartyMember->m_nStatusFlag;
m_nHP = pPartyMember->m_nHP;
m_nEN = pPartyMember->m_nEN;
m_nSTA = pPartyMember->m_nSTA;
m_strName = pPartyMember->m_strName;
m_nLevel = pPartyMember->m_nLevel;
m_nFieldID = pPartyMember->m_nFieldID;
m_nChannelID = pPartyMember->m_nChannelID;
m_nTalentStyle = static_cast<TALENT_STYLE>(pPartyMember->m_nTalentStyle);
m_vecBuff = pPartyMember->m_vecBuff;
m_isSetted = true;
}
void CSPartyMember::DoOffline(void)
{
m_nHP = 0;
m_nEN = 0;
m_nSTA = 0;
m_nStatusFlag = 0;
SetBitSet(m_nStatusFlag, UPS_OFFLINE);
}
void CSPartyMember::SetUID(MUID uidMember)
{
m_UID = uidMember;
}
MUID CSPartyMember::GetUID(void) const
{
return m_UID;
}
tstring CSPartyMember::GetName(void) const
{
return m_strName;
}
bool CSPartyMember::IsSetted(void) const
{
return m_isSetted;
}
| [
"espause0703@gmail.com"
] | espause0703@gmail.com |
c9a82368ed17976f5de9f2b7d5044b024ccf471a | ecab21462fc75df52132b11349d8e7a0dcd3218c | /gen/blink/bindings/modules/v8/V8DeprecatedStorageInfo.h | b1db9590bfa9a775fe2c8407d55a24e767f848db | [
"Apache-2.0"
] | permissive | mensong/MiniBlink | 4688506a0e9e8f0ed5e6d6daaf470255be2a68b8 | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | refs/heads/master | 2023-03-29T04:40:53.198842 | 2021-04-07T01:56:02 | 2021-04-07T01:56:02 | 161,746,209 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,081 | h | // Copyright 2014 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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#ifndef V8DeprecatedStorageInfo_h
#define V8DeprecatedStorageInfo_h
#include "bindings/core/v8/ScriptWrappable.h"
#include "bindings/core/v8/ToV8.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8DOMWrapper.h"
#include "bindings/core/v8/WrapperTypeInfo.h"
#include "modules/ModulesExport.h"
#include "modules/quota/DeprecatedStorageInfo.h"
#include "platform/heap/Handle.h"
namespace blink {
class V8DeprecatedStorageInfo {
public:
MODULES_EXPORT static bool hasInstance(v8::Local<v8::Value>, v8::Isolate*);
static v8::Local<v8::Object> findInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*);
MODULES_EXPORT static v8::Local<v8::FunctionTemplate> domTemplate(v8::Isolate*);
static DeprecatedStorageInfo* toImpl(v8::Local<v8::Object> object)
{
return toScriptWrappable(object)->toImpl<DeprecatedStorageInfo>();
}
MODULES_EXPORT static DeprecatedStorageInfo* toImplWithTypeCheck(v8::Isolate*, v8::Local<v8::Value>);
MODULES_EXPORT static const WrapperTypeInfo wrapperTypeInfo;
static void refObject(ScriptWrappable*);
static void derefObject(ScriptWrappable*);
template<typename VisitorDispatcher>
static void trace(VisitorDispatcher visitor, ScriptWrappable* scriptWrappable)
{
visitor->trace(scriptWrappable->toImpl<DeprecatedStorageInfo>());
}
static const int internalFieldCount = v8DefaultWrapperInternalFieldCount + 0;
static void installConditionallyEnabledProperties(v8::Local<v8::Object>, v8::Isolate*) { }
static void preparePrototypeObject(v8::Isolate*, v8::Local<v8::Object> prototypeObject, v8::Local<v8::FunctionTemplate> interfaceTemplate) { }
};
template <>
struct V8TypeOf<DeprecatedStorageInfo> {
typedef V8DeprecatedStorageInfo Type;
};
} // namespace blink
#endif // V8DeprecatedStorageInfo_h
| [
"mail0668@gmail.com"
] | mail0668@gmail.com |
cb77c74105f3a9ae62bdd6941f29484b71ff1047 | 2f27e474319f0c53a4034d19e0a647de54ebd872 | /28_07_2014/main.cpp | 38d67a9c9db9711b63ed344c842138e1597afb3b | [] | no_license | kur5cpp/Justyna | 3d5f7ed2700bb8f99f51d44b20d564b28a26a3ae | f187ad83ad83a9c0970d596f9f48d3351f48cb36 | refs/heads/master | 2020-06-05T17:14:48.578583 | 2014-08-05T11:02:41 | 2014-08-05T11:02:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,650 | cpp | #include <iostream>
#include <string>
using namespace std;
struct Osoba
{
string imie;
int wiek;
};
Osoba** wypelnij_tabl(Osoba** tabl, int rozmiar)
{
cout << "Podaj imie i wiek: " << endl;
for(int i = 0; i < rozmiar; ++i)
{
*(tabl + i) = new Osoba;
cin >> (*(tabl + i))->imie;
cin >> (*(tabl + i))->wiek;
}
return tabl;
}
Osoba** usun_osobe(Osoba** tabl, int& rozmiar, string imie)
{
int flag = 0;
for(int i = 0; i < rozmiar; ++i)
{
if((*(tabl + i))->imie == imie)
flag = 1;
}
if(flag == 1)
{
--rozmiar;
Osoba** nowa_tabl = new Osoba*[rozmiar];
for(int i = 0, j = 0; i < (rozmiar + 1); ++i)
{
if( (*(tabl + i))->imie != imie )
{
*(nowa_tabl + j) = new Osoba;
(*(nowa_tabl + j))->imie = (*(tabl + i))->imie;
(*(nowa_tabl + j))->wiek = (*(tabl + i))->wiek;
++j;
}
}
for(int i = 0; i < (rozmiar + 1); ++i)
delete *(tabl + i);
delete []tabl;
return nowa_tabl;
}
else
return tabl; // gdy nie znaleziono takiego imienia
}
Osoba** dodaj_osobe(Osoba** tabl, int& rozmiar, string n_imie, int n_wiek)
{
++rozmiar;
Osoba** nowa_tabl = new Osoba*[rozmiar];
for(int i = 0; i < (rozmiar - 1); ++i)
{
*(nowa_tabl + i) = new Osoba;
(*(nowa_tabl + i))->imie = (*(tabl + i))->imie;
(*(nowa_tabl + i))->wiek = (*(tabl + i))->wiek;
}
*(nowa_tabl + rozmiar - 1) = new Osoba;
(*(nowa_tabl + rozmiar - 1))->imie = n_imie;
(*(nowa_tabl + rozmiar - 1))->wiek = n_wiek;
for(int i = 0; i < (rozmiar - 1); ++i)
delete *(tabl + i);
delete []tabl;
return nowa_tabl;
}
void wysw_tabl(Osoba** tabl, int rozmiar)
{
for(int i = 0; i < rozmiar ; ++i)
cout << (*(tabl + i))-> imie << "\t" << (*(tabl + i))->wiek << endl;
}
int main()
{
int rozmiar = 3;
Osoba** baza = new Osoba*[rozmiar];
baza = wypelnij_tabl(baza, rozmiar);
cout << endl << "Lista osob: " << endl;
wysw_tabl(baza, rozmiar);
cout << endl << "Kogo usuwamy?" << endl;
string kogo;
cin >> kogo;
baza = usun_osobe(baza, rozmiar, kogo);
cout << endl << "Aktualna lista osob: " << endl;
wysw_tabl(baza, rozmiar);
cout << endl << "Kogo dodajemy? Imie i wiek: " << endl;
string imie;
cin >> imie;
int wiek;
cin >> wiek;
baza = dodaj_osobe(baza, rozmiar, imie, wiek);
cout << endl << "Aktualna lista osob: " << endl;
wysw_tabl(baza, rozmiar);
return 0;
}
| [
"kur5cpp@users.noreply.github.com"
] | kur5cpp@users.noreply.github.com |
ef1c41c7aaa9c8e6791d9a9c922c9187ac2f78a9 | da1ba0378e1ed8ff8380afb9072efcd3bbead74e | /google/cloud/iam/iam_connection.h | cb9a1e62d5d051c767551fd7ccc0134115aabbf7 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Jseph/google-cloud-cpp | 76894af7ce744cd44304b48bea32d5116ded7497 | fd8e70650ebac0c10bac4b293972e79eef46b128 | refs/heads/master | 2022-10-18T13:07:01.710328 | 2022-10-01T18:16:16 | 2022-10-01T18:16:16 | 192,397,663 | 0 | 0 | null | 2019-06-17T18:22:36 | 2019-06-17T18:22:35 | null | UTF-8 | C++ | false | false | 7,062 | h | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/iam/admin/v1/iam.proto
#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_IAM_IAM_CONNECTION_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_IAM_IAM_CONNECTION_H
#include "google/cloud/iam/iam_connection_idempotency_policy.h"
#include "google/cloud/iam/internal/iam_retry_traits.h"
#include "google/cloud/iam/internal/iam_stub.h"
#include "google/cloud/backoff_policy.h"
#include "google/cloud/options.h"
#include "google/cloud/status_or.h"
#include "google/cloud/stream_range.h"
#include "google/cloud/version.h"
#include <memory>
namespace google {
namespace cloud {
namespace iam {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
using IAMRetryPolicy = ::google::cloud::internal::TraitBasedRetryPolicy<
iam_internal::IAMRetryTraits>;
using IAMLimitedTimeRetryPolicy =
::google::cloud::internal::LimitedTimeRetryPolicy<
iam_internal::IAMRetryTraits>;
using IAMLimitedErrorCountRetryPolicy =
::google::cloud::internal::LimitedErrorCountRetryPolicy<
iam_internal::IAMRetryTraits>;
/**
* The `IAMConnection` object for `IAMClient`.
*
* This interface defines virtual methods for each of the user-facing overload
* sets in `IAMClient`. This allows users to inject custom behavior
* (e.g., with a Google Mock object) when writing tests that use objects of type
* `IAMClient`.
*
* To create a concrete instance, see `MakeIAMConnection()`.
*
* For mocking, see `iam_mocks::MockIAMConnection`.
*/
class IAMConnection {
public:
virtual ~IAMConnection() = 0;
virtual Options options() { return Options{}; }
virtual StreamRange<google::iam::admin::v1::ServiceAccount>
ListServiceAccounts(
google::iam::admin::v1::ListServiceAccountsRequest request);
virtual StatusOr<google::iam::admin::v1::ServiceAccount> GetServiceAccount(
google::iam::admin::v1::GetServiceAccountRequest const& request);
virtual StatusOr<google::iam::admin::v1::ServiceAccount> CreateServiceAccount(
google::iam::admin::v1::CreateServiceAccountRequest const& request);
virtual StatusOr<google::iam::admin::v1::ServiceAccount> PatchServiceAccount(
google::iam::admin::v1::PatchServiceAccountRequest const& request);
virtual Status DeleteServiceAccount(
google::iam::admin::v1::DeleteServiceAccountRequest const& request);
virtual StatusOr<google::iam::admin::v1::UndeleteServiceAccountResponse>
UndeleteServiceAccount(
google::iam::admin::v1::UndeleteServiceAccountRequest const& request);
virtual Status EnableServiceAccount(
google::iam::admin::v1::EnableServiceAccountRequest const& request);
virtual Status DisableServiceAccount(
google::iam::admin::v1::DisableServiceAccountRequest const& request);
virtual StatusOr<google::iam::admin::v1::ListServiceAccountKeysResponse>
ListServiceAccountKeys(
google::iam::admin::v1::ListServiceAccountKeysRequest const& request);
virtual StatusOr<google::iam::admin::v1::ServiceAccountKey>
GetServiceAccountKey(
google::iam::admin::v1::GetServiceAccountKeyRequest const& request);
virtual StatusOr<google::iam::admin::v1::ServiceAccountKey>
CreateServiceAccountKey(
google::iam::admin::v1::CreateServiceAccountKeyRequest const& request);
virtual StatusOr<google::iam::admin::v1::ServiceAccountKey>
UploadServiceAccountKey(
google::iam::admin::v1::UploadServiceAccountKeyRequest const& request);
virtual Status DeleteServiceAccountKey(
google::iam::admin::v1::DeleteServiceAccountKeyRequest const& request);
virtual StatusOr<google::iam::v1::Policy> GetIamPolicy(
google::iam::v1::GetIamPolicyRequest const& request);
virtual StatusOr<google::iam::v1::Policy> SetIamPolicy(
google::iam::v1::SetIamPolicyRequest const& request);
virtual StatusOr<google::iam::v1::TestIamPermissionsResponse>
TestIamPermissions(google::iam::v1::TestIamPermissionsRequest const& request);
virtual StreamRange<google::iam::admin::v1::Role> QueryGrantableRoles(
google::iam::admin::v1::QueryGrantableRolesRequest request);
virtual StreamRange<google::iam::admin::v1::Role> ListRoles(
google::iam::admin::v1::ListRolesRequest request);
virtual StatusOr<google::iam::admin::v1::Role> GetRole(
google::iam::admin::v1::GetRoleRequest const& request);
virtual StatusOr<google::iam::admin::v1::Role> CreateRole(
google::iam::admin::v1::CreateRoleRequest const& request);
virtual StatusOr<google::iam::admin::v1::Role> UpdateRole(
google::iam::admin::v1::UpdateRoleRequest const& request);
virtual StatusOr<google::iam::admin::v1::Role> DeleteRole(
google::iam::admin::v1::DeleteRoleRequest const& request);
virtual StatusOr<google::iam::admin::v1::Role> UndeleteRole(
google::iam::admin::v1::UndeleteRoleRequest const& request);
virtual StreamRange<google::iam::admin::v1::Permission>
QueryTestablePermissions(
google::iam::admin::v1::QueryTestablePermissionsRequest request);
virtual StatusOr<google::iam::admin::v1::QueryAuditableServicesResponse>
QueryAuditableServices(
google::iam::admin::v1::QueryAuditableServicesRequest const& request);
virtual StatusOr<google::iam::admin::v1::LintPolicyResponse> LintPolicy(
google::iam::admin::v1::LintPolicyRequest const& request);
};
/**
* A factory function to construct an object of type `IAMConnection`.
*
* The returned connection object should not be used directly; instead it
* should be passed as an argument to the constructor of IAMClient.
*
* The optional @p options argument may be used to configure aspects of the
* returned `IAMConnection`. Expected options are any of the types in
* the following option lists:
*
* - `google::cloud::CommonOptionList`
* - `google::cloud::GrpcOptionList`
* - `google::cloud::UnifiedCredentialsOptionList`
* - `google::cloud::iam::IAMPolicyOptionList`
*
* @note Unexpected options will be ignored. To log unexpected options instead,
* set `GOOGLE_CLOUD_CPP_ENABLE_CLOG=yes` in the environment.
*
* @param options (optional) Configure the `IAMConnection` created by
* this function.
*/
std::shared_ptr<IAMConnection> MakeIAMConnection(Options options = {});
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
namespace gcpcxxV1 = GOOGLE_CLOUD_CPP_NS; // NOLINT(misc-unused-alias-decls)
} // namespace iam
} // namespace cloud
} // namespace google
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_IAM_IAM_CONNECTION_H
| [
"noreply@github.com"
] | noreply@github.com |
7bac112e8ca50ea0473e9fc38ab7d421389a8bae | f29b09b1b428ff25731cbdfaa499c18102f36d5e | /lib/src/move/mli_mov_runtime.cc | 2408ea1367167196137bb4c7cdda29142e43e95d | [
"BSD-3-Clause"
] | permissive | foss-for-synopsys-dwc-arc-processors/embarc_mli | ee4c052ec97e242706dd14cee4f6cb27421c23a1 | b364bc137463a076a4fd9bed38b2143644c23c3a | refs/heads/mli_dev | 2023-04-13T13:39:48.458305 | 2022-11-07T13:30:32 | 2022-11-08T19:59:49 | 170,473,341 | 31 | 8 | NOASSERTION | 2023-03-25T01:18:02 | 2019-02-13T08:50:37 | C++ | UTF-8 | C++ | false | false | 2,234 | cc | /*
* Copyright 2022, Synopsys, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-3-Clause license found in
* the LICENSE file in the root directory of this source tree.
*
*/
#include <cstring>
#include "mli_debug.h"
#include "mli_ref_compiler_api.hpp"
#include "mli_ref_private_types.hpp"
#include "mli_ref_runtime_api.hpp"
namespace snps_arc::metaware::mli::ref {
Move::Move(void* kernel_private_data_buffer, size_t size, uint64_t membases[],
int num_mems) {
MLI_ASSERT(size == sizeof(MovePrivateData));
MovePrivateData private_data;
memcpy(&private_data, kernel_private_data_buffer, sizeof(MovePrivateData));
MLI_ASSERT(private_data.kernel_id == kMoveId);
MLI_ASSERT(private_data.size == sizeof(MovePrivateData));
m_src_it = TensorIterator<InternalBuffer, kMoveRank, kMoveIterRank>(private_data.src_it, membases, num_mems);
m_dst_it = TensorIterator<InternalBuffer, kMoveRank, kMoveIterRank>(private_data.dst_it, membases, num_mems);
m_src_it.Reset();
m_dst_it.Reset();
}
mli_status Move::Issue() {
TensorIterator<InternalBuffer, kMoveRank, kMoveIterRank> src_it =
m_src_it.GetSubTensorIterator();
TensorIterator<InternalBuffer, kMoveRank, kMoveIterRank> dst_it =
m_dst_it.GetSubTensorIterator();
int32_t count[kMoveRank] = {0};
for (uint32_t i = 0; i < kMoveRank; i++) {
count[i] = src_it.GetTensorShape(i);
if (count[i] <= 0) count[i] = 1;
}
src_it.SetCount(count);
dst_it.SetCount(count);
bool src_done = false;
bool dst_done = false;
while (!src_done) {
switch (src_it.get_elem_size()) {
case 1:
dst_it.write(src_it.template read<uint8_t>());
break;
case 2:
dst_it.write(src_it.template read<uint16_t>());
break;
case 4:
dst_it.write(src_it.template read<uint32_t>());
break;
default:
MLI_ASSERT(false);
}
src_done = src_it.Next();
dst_done = dst_it.Next();
MLI_ASSERT(src_done == dst_done);
}
return MLI_STATUS_OK;
}
mli_status Move::Prefetch() {
return MLI_STATUS_OK;
}
mli_status Move::Update() {
m_src_it.Next();
m_dst_it.Next();
return MLI_STATUS_OK;
}
} // namespace snps_arc::metaware::mli::ref | [
"jacco@synopsys.com"
] | jacco@synopsys.com |
af50c3f7c9ac89b1844340f7b280177590d227c7 | 54003b117d21b43bd0a8139be4ba8c1b94461566 | /SiaCore/_ISiaEvents_CP.h | 62255cbbac47cb2efc027ffbf3d60302f76e3235 | [] | no_license | uri247/SIA | 4682375a1b580930dd36ad4045c70633a34e7975 | fdf873228138d5c80c93f1b0f385763644d9be7c | refs/heads/master | 2021-01-10T19:21:12.745370 | 2013-07-15T21:34:15 | 2013-07-15T21:34:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | h | #pragma once
template<class T>
class CProxy_ISiaEvents :
public ATL::IConnectionPointImpl<T, &__uuidof(_ISiaEvents)>
{
public:
HRESULT Fire_complete(LONG code)
{
HRESULT hr = S_OK;
T * pThis = static_cast<T *>(this);
int cConnections = m_vec.GetSize();
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
pThis->Lock();
CComPtr<IUnknown> punkConnection = m_vec.GetAt(iConnection);
pThis->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection.p);
if (pConnection)
{
CComVariant avarParams[1];
avarParams[0] = code;
avarParams[0].vt = VT_I4;
CComVariant varResult;
DISPPARAMS params = { avarParams, NULL, 1, 0 };
hr = pConnection->Invoke(800, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
return hr;
}
};
// Wizard-generated connection point proxy class
// WARNING: This file may be regenerated by the wizard
#pragma once
| [
"u@london.org.il"
] | u@london.org.il |
fd06f7e29dc84d7a6c3f4ba31e8d93d9e56f9777 | 1fb90121cf23575e9e5f18d6891da2edf111be63 | /GenesisEngine/GenesisEngine/DataStructures_Test.cpp | 9c88f6e76128e59a4ad5db239e8a03c60ff44727 | [] | no_license | njk464/Genesis_Engine | a918c9a72f909fc8f89fce118a52a37f8be47b9c | 56e96f65a18d32aaeb8ff27df67e9d9a2e94ed67 | refs/heads/master | 2020-04-09T14:03:37.215141 | 2015-09-28T22:44:31 | 2015-09-28T22:44:31 | 41,561,293 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 608 | cpp | #include "DataStructuresTest.h"
DataStructuresTest(){
// to be implemented
}
~DataStructuresTest(){
// to be implemented
}
int runTest(){
if(runArrayTest()) return 1;
if(runStackTest()) return 2;
if(runQueueTest()) return 3;
if(runVectorTest()) return 4;
if(runMatrixTest()) return 5;
return 0;
}
int runArrayTest(){
// to be implemented
return 0;
}
int runStackTest(){
// to be implemented
return 0;
}
int runQueueTest(){
// to be implemented
return 0;
}
int runVectorTest(){
// to be implemented
return 0;
}
int runMatrixTest(){
// to be implemented
return 0;
}
| [
"zack441@mac.com"
] | zack441@mac.com |
0dd15275a33ae2c792d57cd77be89a34f58f817c | c31f01f84f7c03215cc666750e968ba49fd1b847 | /src/net/nb_secure_socket.h | bdbcb6679dc26cd696dc16598b005fe939afe06d | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | alex-ozdemir/pbrt-v3 | 2e133cabf4769690fb7e0e6ddde873b503a06a2e | 09646a606572ea0bc7adfbcc5a3c55c2da447321 | refs/heads/master | 2020-04-16T15:25:11.903586 | 2019-03-10T06:55:56 | 2019-03-10T06:55:56 | 165,702,016 | 0 | 0 | BSD-2-Clause | 2019-01-14T17:12:49 | 2019-01-14T17:12:49 | null | UTF-8 | C++ | false | false | 2,305 | h | /* -*-mode:c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
#ifndef PBRT_NET_NB_SECURE_SOCKET_H
#define PBRT_NET_NB_SECURE_SOCKET_H
#include <string>
#include <deque>
#include "secure_socket.h"
class NBSecureSocket : public SecureSocket
{
public:
enum class State { not_connected = 0,
/* connect() */
needs_connect,
needs_ssl_read_to_connect,
needs_ssl_write_to_connect,
/* accept() */
needs_accept,
needs_ssl_read_to_accept,
needs_ssl_write_to_accept,
needs_ssl_write_to_write,
needs_ssl_write_to_read,
needs_ssl_read_to_write,
needs_ssl_read_to_read,
ready,
closed };
enum class Mode { not_set, connect, accept };
private:
Mode mode_ { Mode::not_set };
State state_ { State::not_connected };
std::deque<std::string> write_buffer_ {};
std::string read_buffer_ {};
public:
NBSecureSocket( SecureSocket && sock )
: SecureSocket( std::move( sock ) )
{}
void connect();
void accept();
void continue_SSL_connect();
void continue_SSL_accept();
void continue_SSL_write();
void continue_SSL_read();
std::string ezread();
void ezwrite( const std::string & msg ) { write_buffer_.emplace_back( msg ); }
void ezwrite( std::string && msg ) { write_buffer_.emplace_back( move( msg ) ); }
unsigned int buffer_bytes() const;
bool something_to_write() { return ( write_buffer_.size() > 0 ); }
bool something_to_read() { return ( read_buffer_.size() > 0 ); }
State state() const { return state_; }
Mode mode() const { return mode_; }
bool ready() const { return state_ == State::ready; }
bool connected() const
{
return ( state_ != State::needs_connect ) and
( state_ != State::needs_ssl_read_to_connect ) and
( state_ != State::needs_ssl_write_to_connect );
}
bool accepted() const
{
return ( state_ != State::needs_accept ) and
( state_ != State::needs_ssl_read_to_accept ) and
( state_ != State::needs_ssl_write_to_accept );
}
};
#endif /* PBRT_NET_NB_SECURE_SOCKET_H */
| [
"sfouladi@gmail.com"
] | sfouladi@gmail.com |
2e436eeb42e225bc3aeab21bee58e5152de5be28 | 8799d3e93f6edb753d09616651067af2346e0016 | /题目/数论/LightOJ-1336.cpp | b1b6546b96c3aca7699bb2bf81dd1a69f8e8f9d6 | [] | no_license | StarPolygen/Code_Library | 560b6c07af9f975e81efdeda60ce031b5dff3a22 | a259f4e003817b317d4847222235edc09e4e5380 | refs/heads/master | 2021-07-13T06:18:09.796797 | 2020-07-24T13:03:11 | 2020-07-24T13:03:11 | 184,305,507 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,072 | cpp | //找规律
//询问不超过n的 约束和为even的数有多少
//根据题面中的公式: 约束和函数 = p1^(e1+1)-1/p1-1 * p2^(e2+1)-1/p2-1 *......pk^(ek+1)-1/pk-1
//直接分析出:当且仅当n存在质因数pk不为2,且ek为奇数,约束和函数为偶数
//反面得出:n的所有不为2的质因数指数必须为偶数,才会让约束和函数为奇数,之后陷入僵局,不知如何统计这种数字的个数
//化简后:其实就是2*x^2 和 x^2的数的个数,因此用n减去2倍的完全平方数和完全平方数的个数即可
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main() {
int T;scanf("%d",&T); int Cas=0;
while(T--){
Cas++;
ll n; scanf("%lld",&n);
ll num1 = (ll)sqrt(n);
ll num2 = (ll)sqrt(n/2.0);
if((num1+1) * (num1+1) <= n) num1++;
if(num1 * num1 > n) num1--;
if(2ll * num2 *num2 > n) num2--;
if(2ll * (num2+1) * (num2+1) <= n) num2++;
printf("Case %d: %lld\n",Cas,n-num1-num2);
}
return 0;
} | [
"34528868+StarPolygen@users.noreply.github.com"
] | 34528868+StarPolygen@users.noreply.github.com |
23eea93215a160de90fec97a63f882601b613c97 | 8c0ef2f2714369fb3d6dbe8be03186e2d9d29d37 | /ImageProcess/core.cpp | 559c7c99b381f0acc8f850a6af81de15e8d52902 | [] | no_license | LiuRyu/RyuImprocSet | 14ba04c29bde3360b5440be82edd5b103e832e13 | b53ec8fcfca073e572585f076f81458a32549694 | refs/heads/master | 2021-05-15T17:09:35.890579 | 2017-12-08T09:38:27 | 2017-12-08T09:38:27 | 107,485,603 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 9,959 | cpp | #include "stdafx.h"
#include <stdio.h>
#include <malloc.h>
#include <math.h>
#include "types.h"
#include "core.h"
RyuPoint ryuPoint(int x, int y)
{
RyuPoint p;
p.x = x;
p.y = y;
return p;
}
RyuRect ryuRect(int x, int y, int width, int height)
{
RyuRect r;
r.x = x;
r.y = y;
r.width = width;
r.height = height;
return r;
}
RyuSize ryuSize(int width, int height)
{
RyuSize s;
s.width = width;
s.height = height;
return s;
}
RyuPoint ryuDivideIntPoint(int point)
{
int dx = 0, dy = 0;
int s = 0;
RyuPoint pt;
dx = point >> 16;
s = dx & 0x8000;
pt.x = (0 == s) ? (dx & 0x0000ffff) : (dx | 0xffff0000);
dy = point & 0x0000ffff;
s = dy & 0x8000;
pt.y = (0 == s) ? (dy) : (dy | 0xffff0000);
return pt;
}
int ryuDistanceBtPoints(RyuPoint pt1, RyuPoint pt2)
{
int d = 0;
d = (pt1.x - pt2.x) * (pt1.x - pt2.x) + (pt1.y - pt2.y) * (pt1.y - pt2.y);
d = (int)(sqrt(d * 1.0) + 0.5);
return d;
}
RyuROI * ryuCreateROI( int xOffset, int yOffset, int width, int height )
{
RyuROI * roi = 0;
roi = (RyuROI *) malloc( sizeof(RyuROI) );
if( !roi ) {
printf("ERROR! Bad alloc_ptr of ryuCreateROI, roi = 0x%x\n", roi);
return 0;
}
roi->xOffset = xOffset;
roi->yOffset = yOffset;
roi->width = width;
roi->height = height;
return roi;
}
void ryuSetImageROI( RyuImage* image, RyuRect rect )
{
if( !image ) {
printf( "ERROR! Invalid input of ryuSetImageROI, image = 0x%x\n", image );
return;
}
rect.width += rect.x;
rect.height += rect.y;
rect.x = RYUMAX( rect.x, 0 );
rect.y = RYUMAX( rect.y, 0 );
rect.width = RYUMIN( rect.width, image->width );
rect.height = RYUMIN( rect.height, image->height );
rect.width -= rect.x;
rect.height -= rect.y;
if( image->roi ) {
image->roi->xOffset = rect.x;
image->roi->yOffset = rect.y;
image->roi->width = rect.width;
image->roi->height = rect.height;
}
else
image->roi = ryuCreateROI( rect.x, rect.y, rect.width, rect.height );
return;
}
RyuRect ryuGetImageROI( const RyuImage * image )
{
RyuRect rect = ryuRect( 0, 0, 0, 0 );
if( !image ) {
printf( "ERROR! Invalid input of ryuGetImageROI, image = 0x%x\n", image );
return rect;
}
if( image->roi )
rect = ryuRect( image->roi->xOffset, image->roi->yOffset,
image->roi->width, image->roi->height );
else
rect = ryuRect( 0, 0, image->width, image->height );
return rect;
}
void cvResetImageROI( RyuImage * image )
{
if( !image ) {
printf( "ERROR! Invalid input of cvResetImageROI, image = 0x%x\n", image );
return;
}
if( image->roi ) {
free( image->roi );
image->roi = 0;
}
return;
}
RyuImage * ryuCreateImageHeader( RyuSize size, int depth, int channels )
{
RyuImage * img = 0;
img = ( RyuImage * ) malloc( sizeof(RyuImage) );
if( !img ) {
printf("ERROR! Bad alloc_ptr of ryuCreateImageHeader, img = 0x%x\n", img);
return 0;
}
ryuInitImageHeader( img, size, depth, channels );
return img;
}
void * ryuInitImageHeader( RyuImage * image, RyuSize size, int depth, int channels )
{
if( !image ) {
printf( "ERROR! Invalid input of ryuInitImageHeader, image = 0x%x\n", image );
return 0;
}
memset( image, 0, sizeof(*image) );
image->nSize = sizeof( *image );
if( size.width < 0 || size.height < 0 ) {
printf( "ERROR! Bad input of ryuInitImageHeader, size.width = %d, size.height = %d\n",
size.width, size.height );
return 0;
}
if( (depth != (int)RYU_DEPTH_8C && depth != (int)RYU_DEPTH_16S &&
depth != (int)RYU_DEPTH_32N) || channels < 0 ) {
printf( "ERROR! Bad input of ryuInitImageHeader, depth = %d, channels = %d\n",
depth, channels );
return 0;
}
image->width = size.width;
image->height = size.height;
if( image->roi ) {
image->roi->xOffset = image->roi->yOffset = 0;
image->roi->width = size.width;
image->roi->height = size.height;
}
image->nChannels = RYUMAX( channels, 1 );
image->depth = depth;
image->widthStep = image->width * image->nChannels * (depth >> 3);
image->imageSize = image->widthStep * image->height;
return image;
}
RyuImage * ryuCreateImage(RyuSize size, int depth, int channels)
{
RyuImage * img = ryuCreateImageHeader( size, depth, channels );
if( !img ) {
printf( "ERROR! Bad alloc_ptr of ryuCreateImage, img = 0x%x\n", img );
return 0;
}
img->imageData = (unsigned char *) malloc( img->imageSize );
if( !img->imageData ) {
printf( "ERROR! Bad alloc_ptr of ryuCreateImage, imagedata = 0x%x\n", img->imageData );
return 0;
}
return img;
}
void ryuReleaseImageHeader( RyuImage ** image )
{
if( !image ) {
printf( "ERROR! Invalid input of ryuReleaseImageHeader, image = 0x%x\n", image );
return;
}
if( *image ) {
RyuImage * img = *image;
*image = 0;
if( img->roi ) {
free( img->roi );
img->roi = 0;
}
free( img );
img = 0;
}
return;
}
void ryuReleaseImage( RyuImage ** image )
{
if( !image ) {
printf( "ERROR! Invalid input of ryuReleaseImage, image = 0x%x\n", image );
return;
}
if( *image ) {
RyuImage * img = *image;
*image = 0;
free( img->imageData );
ryuReleaseImageHeader( &img );
}
}
void * ryuSetImage( RyuImage * image, RyuSize size, int depth, int channels )
{
int step = 0;
if( !image ) {
printf( "ERROR! Invalid input of ryuSetImage, image = 0x%x\n", image );
return 0;
}
if( size.width < 0 || size.height < 0 ) {
printf( "ERROR! Bad input of ryuSetImage, size.width = %d, size.height = %d\n",
size.width, size.height );
return 0;
}
if( (depth != (int)RYU_DEPTH_8C && depth != (int)RYU_DEPTH_16S &&
depth != (int)RYU_DEPTH_32N) || channels <= 0 ) {
printf( "ERROR! Bad input of ryuSetImage, depth = %d, channels = %d\n",
depth, channels );
return 0;
}
step = size.width * channels * (depth >> 3);
if( step * size.height > image->imageSize ) {
printf( "ERROR! Bad value, too large size for imagedata, set size = %d\n",
step * size.height );
return 0;
}
image->width = size.width;
image->height = size.height;
image->nChannels = channels;
image->depth = depth;
image->widthStep = step;
return image;
}
void ryuZero( RyuImage * image )
{
RyuRect rect = ryuRect( 0, 0, 0, 0 );
int i = 0, base = 0, setcount = 0;
if( !image ) {
printf( "ERROR! Invalid input of ryuSetImage, image = 0x%x\n", image );
return;
}
if( !image->imageData ) {
printf( "ERROR! Bad address of ryuSetImage, imagedata = 0x%x\n", image->imageData );
return;
}
if( !image->roi ) {
memset( image->imageData, 0, image->widthStep * image->height );
} else {
base = image->roi->yOffset * image->widthStep + image->roi->xOffset * image->nChannels * (image->depth>>3);
setcount = image->roi->width* image->nChannels * (image->depth>>3);
for( i = 0; i < rect.height; i++ ) {
memset( image->imageData+base, 0, setcount );
base += image->widthStep;
}
}
return;
}
RyuSize ryuGetSize(RyuImage * image)
{
RyuSize sz;
sz.width = image->width;
sz.height = image->height;
return sz;
}
int ryuGetPixel(RyuImage * image, RyuPoint pt)
{
if( !image ) {
printf( "ERROR! Invalid input of ryuSetImage, image = 0x%x\n", image );
return -1;
}
if( !image->imageData ) {
printf( "ERROR! Bad address of ryuSetImage, imagedata = 0x%x\n", image->imageData );
return -2;
}
return ((int)(image->imageData + pt.y * image->widthStep + pt.x));
}
int ryuSetPixel(RyuImage * image, RyuPoint pt, unsigned char val)
{
if( !image ) {
printf( "ERROR! Invalid input of ryuSetImage, image = 0x%x\n", image );
return -1;
}
if( !image->imageData ) {
printf( "ERROR! Bad address of ryuSetImage, imagedata = 0x%x\n", image->imageData );
return -2;
}
*(image->imageData + pt.y * image->widthStep + pt.x) = val;
return 1;
}
// 调整图像大小,目前只具备缩小功能
int ryuResizeImage(RyuImage * img_in, RyuImage * img_out)
{
double ZoomRatioW = 0.0;
double ZoomRatioH = 0.0;
double ZoomAccW = 0.0, ZoomAccH = 0.0;
int i = 0, j = 0;
unsigned char * pIn = 0, * pOut = 0;
//unsigned char * pInL = 0, * pOutL = 0;
if( !img_in || !img_out ) {
printf( "ERROR! Invalid input of ryuSetImage, img_in = 0x%x, img_out = 0x%x\n",
img_in, img_out );
return -1;
}
if( !img_in->imageData || !img_out->imageData ) {
printf( "ERROR! Bad address of ryuSetImage, img_in data = 0x%x, img_out data = 0x%x\n",
img_in->imageData, img_out->imageData );
return -2;
}
ZoomRatioW = img_in->width * 1.0 / img_out->width;
ZoomRatioH = img_in->height * 1.0 / img_out->height;
for(j = 0; j < img_out->height; j++) {
ZoomAccW = 0.0;
pIn = img_in->imageData + (int)(ZoomAccH+0.5) * img_in->widthStep;
pOut = img_out->imageData + j * img_out->widthStep;
for(i = 0; i < img_out->width; i++) {
pOut[i] = pIn[(int)(ZoomAccW+0.5)];
ZoomAccW = ZoomAccW + ZoomRatioW;
}
ZoomAccH = ZoomAccH + ZoomRatioH;
}
return 1;
}
int ryuSub(RyuImage * src1, RyuImage * src2, RyuImage * dst)
{
int i = 0, j = 0;
unsigned char * pIn1 = 0, * pIn2 = 0, * pOut = 0;
unsigned char * pInL1 = 0, * pInL2 = 0, * pOutL = 0;
if( !src1 || !src2 || !dst) {
printf("ERROR! Invalid input of ryuSetImage, src1 = 0x%x, src2 = 0x%x,\
dst = 0x%x\n",
src1, src2, dst);
return -1;
}
if(src1->width != src2->width || src1->width != dst->width
|| src1->height != src2->height || src1->height != dst->height) {
printf("ERROR! Invalid image sizes, image must be same scale.\n");
return -1;
}
if( !src1->imageData || !src2->imageData || !dst->imageData) {
printf("ERROR! Bad address of ryuSetImage, src1 data = 0x%x, \
src2 data = 0x%x, dst data = 0x%x\n",
src1->imageData, src2->imageData, dst->imageData);
return -1;
}
pInL1 = src1->imageData;
pInL2 = src2->imageData;
pOutL = dst->imageData;
for(j = 0; j < src1->height; j++) {
pIn1 = pInL1;
pIn2 = pInL2;
pOut = pOutL;
for(i = 0; i < src1->width; i++) {
*pOut = (*pIn1 > *pIn2) ? (*pIn1 - *pIn2) : 0;
pIn1++;
pIn2++;
pOut++;
}
pInL1 += src1->widthStep;
pInL2 += src2->widthStep;
pOutL += dst->widthStep;
}
return 1;
} | [
"312724752@qq.com"
] | 312724752@qq.com |
be2c3abd81c8053ae774aa8a00352f227a1ec6fd | 8d9eed7eb8163ba64c49835c04db140f73821b56 | /eowu-data/src/Field.hpp | e79018f8ff27b7c2359cf07c23ffbd31bf2c0aed | [] | no_license | nfagan/eowu | 96dba654495e26ab3e39cd20ca489acf55de6a5d | 5116f3306a3f7e813502ba00427fdc418850d28f | refs/heads/master | 2020-03-27T14:18:11.835137 | 2019-01-02T18:08:19 | 2019-01-02T18:08:19 | 146,655,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,233 | hpp | //
// Field.hpp
// eowu
//
// Created by Nick Fagan on 9/7/18.
//
#pragma once
#include "Types.hpp"
#include "Serialize.hpp"
#include <string>
#include <vector>
#include <initializer_list>
#include "../../eowu-gl/deps/variant/include/mpark/variant.hpp"
namespace eowu {
namespace data {
template<typename ...T>
struct Field {
using value_type = mpark::variant<T..., std::vector<Field<T...>>>;
std::string name;
value_type value;
Field() = default;
template<typename K>
Field(const std::string &name_, const K &value_) : name(name_), value(value_) {}
};
using Struct = Field<double, bool, std::string, std::vector<double>, std::vector<std::string>>;
std::vector<eowu::data::Struct> make_nested(const eowu::data::Struct &other);
std::vector<eowu::data::Struct> make_nested();
}
namespace serialize {
template<typename ...T>
void serialize(const eowu::data::Field<T...> &field, eowu::serialize::ByteArrayType &into, eowu::u32 flag = 0u);
template<typename ...T>
void serialize(const std::vector<eowu::data::Field<T...>> &fields, eowu::serialize::ByteArrayType &into, eowu::u32 flag = 0u);
}
}
#include "Field.hh"
| [
"nick@fagan.org"
] | nick@fagan.org |
4d72cfc0aa16ea7ed0cd1f7b1fafdef84edf56af | 8c452a6719f25b5d3a7266a1074064f79d93aa66 | /src/gfx/Gfx.h | 3db4330e0ceda2687db3f42e748477d2b8ecda29 | [
"Zlib"
] | permissive | Jeetendranani/mud | 941e1215f9a9adbf51513fb4c6e5bfefa04c91eb | dd595948f1f246e541d6e243a5add2a4b1d1435e | refs/heads/master | 2020-04-29T04:05:13.384455 | 2019-03-12T16:56:25 | 2019-03-12T16:56:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,133 | h | // Copyright (c) 2019 Hugo Amiard hugo.amiard@laposte.net
// This software is provided 'as-is' under the zlib License, see the LICENSE.txt file.
// This notice and the license may not be removed or altered from any source distribution.
#pragma once
#ifndef MUD_MODULES
#include <stl/string.h>
#include <stl/span.h>
#endif
#include <gfx/Forward.h>
#include <gfx/Node3.h>
#include <gfx/Light.h>
namespace mud
{
namespace gfx
{
export_ MUD_GFX_EXPORT func_ void setup_pipeline_minimal(GfxSystem& gfx);
export_ MUD_GFX_EXPORT meth_ TPool<Node3>& nodes(Scene& scene);
export_ MUD_GFX_EXPORT meth_ TPool<Item>& items(Scene& scene);
export_ MUD_GFX_EXPORT meth_ TPool<Mime>& mimes(Scene& scene);
export_ MUD_GFX_EXPORT meth_ TPool<Light>& lights(Scene& scene);
export_ MUD_GFX_EXPORT meth_ TPool<Flare>& flares(Scene& scene);
export_ MUD_GFX_EXPORT func_ void update_item_aabb(Item& item);
export_ MUD_GFX_EXPORT func_ void update_item_lights(Scene& scene, Item& item);
export_ MUD_GFX_EXPORT func_ Gnode& node(Gnode& parent, Ref object = {}, const vec3& position = vec3(0.f), const quat& rotation = ZeroQuat, const vec3& scale = vec3(1.f));
export_ MUD_GFX_EXPORT Gnode& node(Gnode& parent, Ref object, const mat4& transform);
export_ MUD_GFX_EXPORT Gnode& node(Gnode& parent, Ref object, const Transform& transform);
export_ MUD_GFX_EXPORT Gnode& transform(Gnode& parent, Ref object, const vec3& position, const quat& rotation, const vec3& scale);
export_ MUD_GFX_EXPORT Gnode& transform(Gnode& parent, Ref object, const vec3& position, const quat& rotation);
export_ MUD_GFX_EXPORT func_ Item& shape(Gnode& parent, const Shape& shape, const Symbol& symbol, uint32_t flags = 0, Material* material = nullptr, size_t instances = 0);
export_ MUD_GFX_EXPORT void draw(Scene& scene, const mat4& transform, const Shape& shape, const Symbol& symbol, uint32_t flags = 0);
export_ MUD_GFX_EXPORT func_ void draw(Gnode& parent, const Shape& shape, const Symbol& symbol, uint32_t flags = 0);
export_ MUD_GFX_EXPORT func_ Item& sprite(Gnode& parent, const Image256& image, const vec2& size, uint32_t flags = 0, Material* material = nullptr, size_t instances = 0);
export_ MUD_GFX_EXPORT func_ Item& item(Gnode& parent, const Model& model, uint32_t flags = 0, Material* material = nullptr, size_t instances = 0, span<mat4> transforms = {});
export_ MUD_GFX_EXPORT func_ void prefab(Gnode& parent, const Prefab& prefab, bool transform = true, uint32_t flags = 0, Material* material = nullptr, size_t instances = 0, span<mat4> transforms = {});
export_ MUD_GFX_EXPORT func_ Item* model(Gnode& parent, const string& name, uint32_t flags = 0, Material* material = nullptr, size_t instances = 0);
export_ MUD_GFX_EXPORT func_ Mime& animated(Gnode& parent, Item& item);
export_ MUD_GFX_EXPORT func_ Flare& flows(Gnode& parent, const Flow& emitter, uint32_t flags = 0, size_t instances = 0);
export_ MUD_GFX_EXPORT func_ Light& light(Gnode& parent, LightType type, bool shadows, Colour colour, float range = 0.f, float attenuation = 0.5f);
export_ MUD_GFX_EXPORT func_ Light& sun_light(Gnode& parent, float azimuth, float elevation);
export_ MUD_GFX_EXPORT func_ void radiance(Gnode& parent, const string& texture, BackgroundMode background);
using ManualJob = void(*)(Render&, const Pass&);
using CustomSky = void(*)(Render&);
export_ MUD_GFX_EXPORT void manual_job(Gnode& parent, PassType pass, ManualJob job);
export_ MUD_GFX_EXPORT void custom_sky(Gnode& parent, CustomSky func);
export_ MUD_GFX_EXPORT Light& direct_light_node(Gnode& parent);
export_ MUD_GFX_EXPORT Light& direct_light_node(Gnode& parent, const quat& rotation);
export_ MUD_GFX_EXPORT func_ Light& direct_light_node(Gnode& parent, const vec3& direction);
export_ MUD_GFX_EXPORT func_ Material& unshaded_material(GfxSystem& gfx, cstring name, const Colour& colour);
export_ MUD_GFX_EXPORT Material& pbr_material(GfxSystem& gfx, cstring name, const PbrMaterialBlock& pbr_block);
export_ MUD_GFX_EXPORT func_ Material& pbr_material(GfxSystem& gfx, cstring name, const Colour& albedo, float metallic = 0.f, float roughness = 1.f);
}
}
| [
"hugo.amiard@laposte.net"
] | hugo.amiard@laposte.net |
de1fbdfff4639962307a39af2254967ee79f0d1f | 9a45c7750372697364481b441a12c7751d0dcb0d | /scanArray/longestOnes_Kchanges.cpp | e28fbe628e6cdff6d994a5ee4401dc6471613d33 | [] | no_license | ginobilinie/codeBook | 5879c4b714ab0f618d43e86d79599bf0cbf42ef5 | 6c16e0aeab16cca9a4c75cf91880b27bf37f5e1d | refs/heads/master | 2021-01-12T07:14:26.705431 | 2019-04-05T03:18:01 | 2019-04-05T03:18:01 | 76,921,542 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 542 | cpp | class Solution {
public:
int longestOnes(vector<int>& A, int K) {
int res = 0, zero = 0, left = 0;
for (int right = 0; right < A.size(); right++) {
if (A[right] == 0)
zero++;
while (zero > K) {
if (A[left] == 0)
{
zero--;
}
left++;
}
// cout<<left<<":"<<right<<":"<<zero<<endl;
res = max(res, right - left + 1);
}
return res;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
65e59b9dfddef650163ac1c514a85b7b99c90bea | 682951909d1deace6ee672da6dec718501754d61 | /Tree/Binary Tree/Heap/절댓값_힙_백준.cpp | 0575f268f30051b68f9845afa65b052c3a227bfc | [] | no_license | ctwc55/Algorithm_studying | 378f3633e9d727ca55b5979c7d2e642488f11b59 | 61f6b76548f18ba34711a84fb84a6b768d510ae2 | refs/heads/master | 2021-06-26T06:55:17.225224 | 2020-11-02T14:44:06 | 2020-11-02T14:44:06 | 168,961,868 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,983 | cpp | #include <bits/stdc++.h>
#define MAXN 100000000
using namespace std;
pair<int,int> heap[100001]; //first:org second:abs
int heap_size=0;
void absMinHeap(int n){
if(n==1) return;
if(heap[n/2].second>heap[n].second&&heap[n/2].second!=0) swap(heap[n/2], heap[n]);
else if(heap[n/2].second==heap[n].second){
if(heap[n/2].first>heap[n].first) swap(heap[n/2], heap[n]);
}
absMinHeap(n/2);
return;
}
void rmvRoot(int n){
int small, small_i;
if(n>heap_size/2) return;
if(heap[(n*2)+1].second==0){
small=heap[n*2].second;
small_i=n*2;
}
else{
if(heap[n*2].second==heap[(n*2)+1].second){
small=(heap[n*2].first<heap[(n*2)+1].first)?heap[n*2].second:heap[(n*2)+1].second;
small_i=(heap[n*2].first<heap[(n*2)+1].first)?n*2:(n*2)+1;
}
else{
small=(heap[n*2].second<heap[(n*2)+1].second)?heap[n*2].second:heap[(n*2)+1].second;
small_i=(heap[n*2].second<heap[(n*2)+1].second)?n*2:(n*2)+1;
}
}
if(heap[n].second<small) return;
else if(heap[n].second>small){
swap(heap[n], heap[small_i]);
rmvRoot(small_i);
}
else if(heap[n].second==small){
if(heap[n].first>heap[small_i].first){
swap(heap[n], heap[small_i]);
rmvRoot(small_i);
}
}
return;
}
int main()
{
int n, ord;
scanf("%d", &n);
for(int i=0;i<n;i++){
scanf("%d", &ord);
if(ord!=0){
heap[++heap_size].first=ord;
heap[heap_size].second=abs(ord);
absMinHeap(heap_size);
}
else{
printf("%d\n", heap[1].first);
if(heap_size>0){
heap[1].first=heap[heap_size].first;
heap[1].second=heap[heap_size].second;
heap[heap_size].first=0;
heap[heap_size].second=0;
heap_size--;
rmvRoot(1);
}
}
}
}
| [
"thstmdduftm@naver.com"
] | thstmdduftm@naver.com |
1983f3ab6e60e6928c035c40fd3a57a9e381ac36 | ab62f6fe96f590b70fe510d0f802b6f9bd323ab5 | /include/CountingSort.h | 5f24ef55103b2b4b07affe22012ff9d68c1b820d | [] | no_license | happysnail/mSortare2 | f9d0815faad55383c378c480312adcc7bb0f9bc0 | 9cc9799405394944a2450dab6f4e31218fc76b9f | refs/heads/master | 2020-07-03T22:14:45.573439 | 2017-02-27T09:37:04 | 2017-02-27T09:37:04 | 74,225,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,167 | h | #ifndef COUNTINGSORT_H
#define COUNTINGSORT_H
#include "Sort.h"
#include <iostream>
#include <fstream>
class CountingSort : public Sort
{
public:
CountingSort();
virtual ~CountingSort();
void sort(int vect[], int size){
int *a,*b,*c,n=size,i,j;
a = new int [n];
b = new int [n];
c = new int [n];
for(i=0;i<n;i++){
b[i]=0;
c[i]=a[i]=vect[i];
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
if (a[i]<a[j])
b[j]++;
else
b[i]++;
}
for(i=0;i<n;i++)
a[b[i]]=c[i];
cout<<endl<<"Sortarea prin numarare a avut loc cu succes";
if(n<30){
cout<<endl<<"Vectorul sortat este:"<<endl;
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
}
}
//Grafic
void sortg(int vect[], int size){
int a[25],b[25],c[25],n=size,i,j;
cout<<endl<<endl<<"Counting Sort."<<endl;
for(i=0;i<n;i++){
b[i]=0;
c[i]=a[i]=vect[i];
}
cout<<"Vectorul initial: "<<endl;
for(int i=n; i>0;i--)
{
for(int j=0;j<n;j++)
if(a[j]>=i)
cout<<"_ ";
else
cout<<" ";
cout<<endl;
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
if (a[i]<a[j])
b[j]++;
else
b[i]++;
}
for(i=0;i<n;i++)
a[b[i]]=c[i];
cout<<"Mutarea 1:"<<endl;
for(int i=n; i>0;i--)
{
for(int j=0;j<n;j++)
if(a[j]>=i)
cout<<"_ ";
else
cout<<" ";
cout<<endl;
}
}
protected:
private:
};
#endif // COUNTINGSORT_H
| [
"carp.adi96@gmail.com"
] | carp.adi96@gmail.com |
3db6ca608202083faae456d61067ed19910cf01d | 92418ed0ed1be6558e2f9098858885f238703b60 | /BNAPlatform-weighted-network-win64-cuda-20140905/src/CorMat/CUCorMat/CUCorMat/CorMat.cpp | 6632eb6fc684a223da0f53908880c14e9de72420 | [] | no_license | BNAplatform-organization/codeVSassembly-function | 04875f1e845ec7faabaa173b4e06758062a684e7 | 6b0391a79d6d0806fba8d56904d2ecdbf325cc1b | refs/heads/master | 2020-04-14T05:09:36.023795 | 2015-12-25T12:56:36 | 2015-12-25T12:56:36 | 38,564,118 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,247 | cpp |
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include <ctime>
#include <cmath>
#include <iomanip>
#include "dirent.h"
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;
typedef float real__t;
typedef unsigned int uint__t;
const int HdrLen = 352;
double ProbCut = 0.5;
const int blocksize = 1024*1024*48;
bool rs_flag = true;
bool cormat_flag = false;
char mask_dt;
void CorMat_cpu(real__t * Cormat, real__t * BOLD, int N, int L);
int CorMat_gpu(real__t * Cormat, real__t * BOLD, int N, int L, int Batch_size);
long long FormFullGraph(bool * adjacent, real__t * Cormat, int N, real__t threshold);
real__t FormFullGraph_s(bool * adjacent, real__t * Cormat, int N, long long threshold);
void post_block (real__t * Cormat, real__t * Cormat_blocked, int dim, int block_size,bool fishtran_flag);
void FormCSRGraph(int * R, int * C, real__t *V, bool * adjacent, int N , real__t *Cormat);
long long find_max(real__t *Cormat, long long M1);
real__t select_GPU(real__t *Cormat, long long M1, long long k);
real__t fishertrans(real__t r)
{
real__t z;
if (r==1) r -= 1e-6;
z = 0.5*log((1+r)/(1-r));
return z;
}
real__t inv_fishertrans(real__t z)
{
real__t r;
r = exp(2*z);
r = (r-1)/(r+1);
return r;
}
int main(int argc, char * argv[])
{
clock_t total_time = clock();
if (argc < 5)
{
cerr<<"Input format: .\\CorMat.exe Dir_for_BOLD threshold_for_mask(0~1) to_average(y/n) threshold_type(r/s) threshold_for_correletaion_coefficient(s)(0~1)\n"
<<"For example: .\\CorMat.exe d:\\BOLD 0.5 y r 0.2 0.25 0.3\n"<<endl;
exit(1);
}
int L, N = 0, i = 0, j = 0, k = 0, l = 0, total_size;
clock_t time;
DIR *dp;
struct dirent *dirp;
if (NULL == (dp = opendir(argv[1])))
{
printf("can't open %s", argv[1]);
exit (1);
}
int FileNumber = 0;
string filenametmp;
while((dirp = readdir(dp)) != NULL)
{
filenametmp = string(dirp->d_name);
//cout<<filenametmp.c_str()<<"!"<<endl;
if (filenametmp.find_last_of('.') == -1)
continue;
if(filenametmp.length()>4 && filenametmp.substr(filenametmp.find_last_of('.'),4).compare(".nii") == 0 && filenametmp.size() - filenametmp.find_last_of('.') - 1 == 3)
{
if (filenametmp.compare("mask.nii")!=0)
FileNumber++;
}
}
cout<<FileNumber<<" file(s) to be processed."<<endl;
closedir(dp);
string *filename = new string[FileNumber];
dp = opendir(argv[1]);
i = 0;
while((dirp = readdir(dp)) != NULL)
{
filenametmp = string(dirp->d_name);
// cout<<"here";
if (filenametmp.find_last_of('.') == -1)
continue;
if(filenametmp.length()>4 && filenametmp.substr(filenametmp.find_last_of('.'),4).compare(".nii") == 0 && filenametmp.size() - filenametmp.find_last_of('.') - 1 == 3)
{
if (filenametmp.compare("mask.nii")!=0)
filename[i++] = filenametmp;
}
}
real__t ProbCut = (real__t)atof(argv[2]);
int NumS = argc - 6;
real__t * r_thresh = new real__t [NumS];
real__t * s_thresh = new real__t [NumS];
if (argv[5][0] == 'r' || argv[5][0] == 'R' )
for (i = 0; i < NumS; i++)
r_thresh[i] = (real__t)atof(argv[6+i]);
else if (argv[5][0] == 's' || argv[5][0] == 'S' )
{
rs_flag = false;
memset(r_thresh, 0, sizeof(real__t)*NumS);
for (i = 0; i < NumS; i++)
s_thresh[i] = (real__t)atof(argv[6+i]);
}
else {
cout << "threshold type error! \nr for correlation threshold\ns for spasity threshold\n";
exit(1);
}
if(argv[4][0]=='y' || argv[4][0]=='Y')
{
cormat_flag = true;
}
else if (argv[4][0]=='N' || argv[4][0]=='n')
{
cormat_flag = false;
}
else
{
cout << "to_save_cor_matrix type error! \ny to save the whole correlation matrix \nn to save only csr format of adjacency matrix\n";
exit(1);
}
// read input files and parameters
if (argv[1][strlen(argv[1]) - 1] == '\\')
argv[1][strlen(argv[1]) - 1] = 0;
ifstream fin(string(argv[1]).append("\\mask.nii").c_str(), ios::binary);
if (!fin.good())
{ cout<<"Can't open\t"<<string(argv[1]).append("\\mask.nii").c_str()<<endl; return 0;}
short hdr[HdrLen / 2];
fin.read((char*)hdr, HdrLen);
cout<<"mask datatype : "<< hdr[35]<<" "<<hdr[36]<<endl;
mask_dt = hdr[35];
total_size = hdr[21] * hdr[22] * hdr[23]; // Total number of voxels
real__t * mask = new float [total_size];
if (mask_dt==2)
{
unsigned char *mask_uc = new unsigned char[total_size];
fin.read((char *) mask_uc, sizeof(unsigned char) * total_size);
for (int vm = 0; vm<total_size; vm++)
mask[vm] = (float) mask_uc[vm];
delete [] mask_uc;
}
else if(mask_dt==16)
{
fin.read((char *)mask, sizeof(float) * total_size);
}
else
{
cout<<"mask data-type error, Only the type of unsigned char and float can be handled.\n";
//system("pause");
return -1;
}
fin.close();
// Count the number of the valid voxels
for (k = 0; k < total_size; k++)
N += (mask[k] >= ProbCut);
cout<<"Data size: "<<hdr[21] <<"x"<<hdr[22]<<"x"<<hdr[23] <<", Grey voxel count: "<<N<<"."<<endl;
// swap the largest threshold to the beginning
int min_idx = 0;
for (i = 0; i < NumS; i++)
if (r_thresh[i] < r_thresh[min_idx])
min_idx = i;
real__t temp = r_thresh[0];
r_thresh[0] = r_thresh[min_idx];
r_thresh[min_idx] = temp;
// CSR format
int Rlength = N + 1;
long long Clength;
int * R = new int[Rlength];
int * C;
real__t *V;
//process, do not average
if (argv[3][0] == 'n' || argv[3][0] == 'N' || argv[3][0] == 'b' || argv[3][0] == 'B' )
for (int i = 0; i < FileNumber; i++)
{
string a = string(argv[1]).append("\\").append(filename[i]);
cout<<"\ncalculating correlation for "<<a.c_str()<<" ..."<<endl;
ifstream fin(a.c_str(), ios_base::binary);
// Get the length of the time sequence
if (!fin.good())
{ cout<<"Can't open\t"<<a.c_str()<<endl; return 0;}
fin.read((char*)hdr, HdrLen);
L = hdr[24];
real__t * BOLD = new real__t [L * N];
if (hdr[36] == 64) // double
{
double * InData = new double [L * total_size];
fin.read((char*)InData, sizeof(double) * L * total_size);
fin.close();
// Get the BOLD signal for all the valid voxels
for (int i = -1, k = 0; k < total_size; k++)
if (mask[k] >= ProbCut)
for (i++, l = 0; l < L; l++)
{
BOLD[l*N+i] = InData[l*total_size+k];
}
cout<<"BOLD length: "<<L<<", Data type: double."<<endl;
delete []InData;
}
else if (hdr[36] == 32) //float
{
real__t *InData = new float [L * total_size];
fin.read((char*)InData, sizeof(float) * L * total_size);
fin.close();
// Get the BOLD signal for all the valid voxels
for (int i = -1, k = 0; k < total_size; k++)
if (mask[k] >= ProbCut)
for (i++, l = 0; l < L; l++)
{
BOLD[l*N+i] = InData[l*total_size+k];
}
cout<<"BOLD length: "<<L<<", Data type: float."<<N<<endl;
delete []InData;
}
else
{
cerr<<"Error: Data type is neither float nor double."<<endl;
}
// set some parameters
int Batch_size = 1024 * 3; // should not be smaller than 1024 !
int Num_Blocks = (N + Batch_size - 1) / Batch_size;
long long M2 = Num_Blocks * (Num_Blocks + 1) / 2;
M2 *= Batch_size * Batch_size;
real__t * Cormat_blocked = new real__t [M2];
long long M1 = (N-1);
M1 *= N;
M1 /= 2;
real__t * Cormat_gpu = new real__t [M1];
// Begin computing correlation
time = clock();
CorMat_gpu(Cormat_blocked, BOLD, N, L, Batch_size);
time = clock() - time;
memset((void*)Cormat_gpu, 0, sizeof(real__t) * M1);
cout<<"GPU correlation time: "<<time<<"ms"<<endl;
post_block(Cormat_gpu, Cormat_blocked, N, Batch_size, 0);
// CorMat_cpu(Cormat_cpu, BOLD, N, L);
//CorMat_gpu(Cormat_blocked, BOLD, N, L, Batch_size);
//time = clock() - time;
//cout<<"GPU correlation time: "<<time<<"ms"<<endl;
//time = clock();
//memset((void*)Cormat_gpu, 0, sizeof(real__t) * M1);
//cout<<"Postprocessing ..."<<endl;
//post_block(Cormat_gpu, Cormat_blocked, N, Batch_size);
/*int kkk = 0;
for (int i = 0; i < N; i++)
for (int j = i+1; j < N; j++)
{
if (fabs(Cormat_gpu[kkk] - Cormat_cpu[kkk]) > 1e-6)
{
cout<<"cuole"<<'\t'<<Cormat_gpu[kkk]<<'\t'<<Cormat_cpu[kkk]<<'\t'<<i<<'\t'<<j<<endl;
getchar();
}
kkk++;
}*/
delete []Cormat_blocked;
char sparsity[30];
char Graph_size[30];
string OutCor = a.substr(0, a.find_last_of('.')).append("_").append(string(itoa(N, Graph_size, 10)));
if(cormat_flag == true)
{
string cormat_filename = OutCor;
cormat_filename.append(".cormat");
ofstream cormat_file;
cormat_file.open(cormat_filename.c_str(), ios::binary | ios::out);
cormat_file.write((char*)&M1, sizeof(int));
cormat_file.write((char*)Cormat_gpu,sizeof(real__t)*M1);
cormat_file.close();
}
string Outfilename;
ofstream fout;
bool * adjacent = new bool [(long long)N*N];
for (k = 0; k < NumS; k++)
{
// Form full graph
time = clock();
//cout<<"threshold for r = "<<r_thresh[k]<<endl;
if (rs_flag){
Clength = FormFullGraph(adjacent, Cormat_gpu, N, r_thresh[k]);
s_thresh[k] = 100.0 * Clength / M1 / 2;
}
else {
cout<<"\nthreshold for sparsity = "<<s_thresh[k]<<endl;
Clength = (long long) 2*M1*s_thresh[k]/100.0;
Clength += Clength%2;
r_thresh[k] = FormFullGraph_s(adjacent, Cormat_gpu, N, Clength/2);
}
//cout<<"Clength = "<<Clength<<endl;
time = clock() - time;
cout<<"time for forming full graph (ms):\t" <<time<<endl;
//if (k == 0)
C = new int [Clength];
V = new real__t [Clength];
// form csr graph
//time = clock();
FormCSRGraph(R, C, V, adjacent, N, Cormat_gpu);
//time = clock() - time;
// cout<<"time for forming csr graph (ms):\t" <<time<<endl;
// write files
//for (int i=0;i<Rlength;i++)
// cout<<R[i]<<' ';
sprintf_s(sparsity, "_spa%.3f%%_cor%.3f", s_thresh[k],r_thresh[k]);
Outfilename = OutCor;
Outfilename.append(sparsity).append(".csr");
cout<<"generating "<<Outfilename.c_str()<< "..."<<endl;
fout.open(Outfilename.c_str(), ios::binary | ios::out);
fout.write((char*)&Rlength, sizeof(int));
fout.write((char*)R, sizeof(int) * Rlength);
fout.write((char*)&Clength, sizeof(int));
fout.write((char*)C, sizeof(int) * Clength);
fout.write((char*)&Clength, sizeof(int));
fout.write((char*)V, sizeof(real__t) * Clength);
fout.close();
delete []C;
delete []V;
}
/*
long long hisogram[21] = {0};
real__t avg=0;
int illegal=0;
for (long long z=0; z<M1; z++){
if (Cormat_gpu[z]<1000 || Cormat_gpu[z]>-1000)
{
hisogram[(int) ((Cormat_gpu[z]+1.05)*10)]++;
avg += Cormat_gpu[z];
}
else illegal++;
}
avg = avg/M1;
ofstream fo;
fo.open("E:\\xumo\\onenii\\hisogram.txt");
fo <<"\n=====================================\n";
for (int num=0; num<21;num++){
fo<<(100.0*(double) hisogram[num])/M1<<endl;
}
fo<<"\n=====================================\n";
fo<<endl<<avg;
fo<<endl<<100.0*((double) illegal)/M1;
fo<<"\n=====================================\n";
fo.close();
*/
delete []adjacent;
delete []Cormat_gpu;
delete []BOLD;
}
if (argv[3][0] == 'y' || argv[3][0] == 'Y' || argv[3][0] == 'b' || argv[3][0] == 'B' )
{
// set some parameters
int Batch_size = 1024 * 3; // should not be smaller than 1024 !
int Num_Blocks = (N + Batch_size - 1) / Batch_size;
long long M2 = Num_Blocks * (Num_Blocks + 1) / 2;
M2 *= Batch_size * Batch_size;
real__t * Cormat_blocked = new real__t [M2];
long long M1 = (N-1);
M1 *= N;
M1 /= 2;
real__t * Cormat_gpu = new real__t [M1];
memset((void*)Cormat_gpu, 0, sizeof(real__t) * M1);
//real__t * Cormat_blocked_ = new real__t [M2];
//real__t * Cormat_gpu_ = new real__t [M2];
for (int i = 0; i < FileNumber; i++)
{
//check whether the first int are identical!
string a = string(argv[1]).append("\\").append(filename[i]);
cout<<"\ncalculating correlation for "<<a.c_str()<<" ..."<<endl;
ifstream fin(a.c_str(), ios_base::binary);
// Get the length of the time sequence
if (!fin.good())
{ cout<<"Can't open\t"<<a.c_str()<<endl; return 0;}
fin.read((char*)hdr, HdrLen);
L = hdr[24];
real__t * BOLD = new real__t [L * N];
if (hdr[36] == 64) // double
{
double * InData = new double [L * total_size];
fin.read((char*)InData, sizeof(double) * L * total_size);
fin.close();
// Get the BOLD signal for all the valid voxels
for (int i = -1, k = 0; k < total_size; k++)
if (mask[k] >= ProbCut)
for (i++, l = 0; l < L; l++)
{
BOLD[l*N+i] = InData[l*total_size+k];
}
cout<<"BOLD length: "<<L<<", Data type: double."<<endl;
delete []InData;
}
else if (hdr[36] == 32) //float
{
real__t *InData = new float [L * total_size];
fin.read((char*)InData, sizeof(float) * L * total_size);
fin.close();
// Get the BOLD signal for all the valid voxels
for (int i = -1, k = 0; k < total_size; k++)
if (mask[k] >= ProbCut)
for (i++, l = 0; l < L; l++)
{
BOLD[l*N+i] = InData[l*total_size+k];
}
cout<<"BOLD length: "<<L<<", Data type: float."<<N<<endl;
delete []InData;
}
else
{
cerr<<"Error: Data type is neither float nor double."<<endl;
}
// Begin computing correlation
time = clock();
// if (i == 0)
{ CorMat_gpu(Cormat_blocked, BOLD, N, L, Batch_size);
//CorMat_cpu(Cormat_gpu, BOLD, N, L);
}
// else
{
// CorMat_gpu(Cormat_blocked_, BOLD, N, L, Batch_size);
//CorMat_cpu(Cormat_gpu_, BOLD, N, L);
}
time = clock() - time;
cout<<"GPU correlation time: "<<time<<"ms"<<endl;
if (argv[3][1] == 'f' || argv[3][1] == 'F')
post_block(Cormat_gpu, Cormat_blocked, N, Batch_size,1);
else if (argv[3][1] == 'n' || argv[3][1] == 'N')
post_block(Cormat_gpu, Cormat_blocked, N, Batch_size,0);
/*
for (int i = 0; i < M1; i++)
{
Cormat_gpu[i] = i;
}
int id = 0;
for (int i = 0; i < (N + Batch_size-1)/Batch_size; i++)
{
for (int j = i+1; j < (N + Batch_size-1)/Batch_size; j++)
{
for (int ii = 0; ii < Batch_size ; ii++)
{
for (int jj = 0; jj < Batch_size; jj++)
{
Cormat_blocked[id]=(float)((long long)i * );
id ++;
}
}
}
} */
delete []BOLD;
}
/*int count = 0;
for (int i = 0; i < M2; i++)
{
if(fabs(Cormat_blocked[i] - Cormat_blocked_[i])>0.2)
{
//cout<<i<<"\t"<<Cormat_blocked[i]<<"\t"<<Cormat_blocked_[i]<<endl;
count ++;//system("pause");
}
Cormat_blocked[i] += Cormat_blocked_[i];
}
cout<<"count = "<<count<<endl;
for (int i = 0; i < M1; i++)
{
Cormat_gpu[i] += Cormat_gpu_[i];
} */
delete []Cormat_blocked;
if (argv[3][1] == 'f' || argv[3][1] == 'F')
for (int i = 0; i < M1; i++)
{
Cormat_gpu[i] /= FileNumber;
Cormat_gpu[i] = inv_fishertrans(Cormat_gpu[i]);
}
else
for (int i = 0; i < M1; i++)
{
Cormat_gpu[i] /= FileNumber;
}
char sparsity[30];
char Graph_size[30];
string b = string(argv[1]);
string OutCor;
if (b.find_last_of('\\') == -1)
OutCor = b.append("\\");
else
OutCor = b.append(b.substr(b.find_last_of('\\'), b.length() - b.find_last_of('\\')));
OutCor.append("_").append(string(itoa(FileNumber, Graph_size, 10))).append("_").append(string(itoa(N, Graph_size, 10)));
if(cormat_flag == true)
{
string cormat_filename = OutCor;
cormat_filename.append(".cormat");
ofstream cormat_file;
cormat_file.open(cormat_filename.c_str(), ios::binary | ios::out);
cormat_file.write((char*)&M1, sizeof(int));
cormat_file.write((char*)Cormat_gpu,sizeof(real__t)*M1);
cormat_file.close();
}
string Outfilename;
ofstream fout;
//output the dense float corr matrix to compute p values
//Outfilename = OutCor;
//Outfilename.append("_nft.corr_mat");
//fout.open(Outfilename, ios::binary | ios::out);
//fout.write((char*)&N, sizeof(int));
//fout.write((char*)Cormat_gpu, sizeof(float) * M1);
//fout.close();
bool * adjacent = new bool [(long long)N*N];
for (k = 0; k < NumS; k++)
{
// Form full graph
time = clock();
if (rs_flag){
Clength = FormFullGraph(adjacent, Cormat_gpu, N, r_thresh[k]);
s_thresh[k] = 100.0 * Clength / M1 / 2;
}
else {
Clength = (long long) 2*M1*s_thresh[k]/100.0;
Clength += Clength%2;
r_thresh[k] = FormFullGraph_s(adjacent, Cormat_gpu, N, Clength/2);
}
time = clock() - time;
cout<<"time for forming full graph (ms):\t" <<time<<endl;
//if (k == 0)
C = new int [Clength];
V = new real__t [Clength];
//form csr graph
time = clock();
FormCSRGraph(R, C, V, adjacent, N, Cormat_gpu);
time = clock() - time;
cout<<"time for forming csr graph (ms):\t" <<time<<endl;
// write files
sprintf_s(sparsity, "_spa%.3f%%_cor%.3f", s_thresh[k],r_thresh[k]);
Outfilename = OutCor;
Outfilename.append(sparsity).append(".csr");
cout<<"generating "<<Outfilename.c_str()<< "..."<<endl;
fout.open(Outfilename.c_str(), ios::binary | ios::out);
fout.write((char*)&Rlength, sizeof(int));
fout.write((char*)R, sizeof(int) * Rlength);
fout.write((char*)&Clength, sizeof(int));
fout.write((char*)C, sizeof(int) * Clength);
fout.write((char*)&Clength, sizeof(int));
fout.write((char*)V, sizeof(real__t) * Clength);
fout.close();
delete []C;
delete []V;
}
/*
long long hisogram[21] = {0};
real__t avg=0;
int illegal=0;
for (long long z=0; z<M1; z++){
if (Cormat_gpu[z]<1000 || Cormat_gpu[z]>-1000)
{
hisogram[(int) ((Cormat_gpu[z]+1.05)*10)]++;
avg += Cormat_gpu[z];
}
else illegal++;
}
avg = avg/M1;
ofstream fo;
fo.open("E:\\xumo\\4Dnii\\hisogramavg.txt");
fo <<"\n=====================================\n";
for (int num=0; num<21;num++){
fo<<(100.0*(double) hisogram[num])/M1<<endl;
}
fo<<"\n=====================================\n";
fo<<endl<<avg;
fo<<endl<<100.0*((double) illegal)/M1;
fo<<"\n=====================================\n";
fo.close();
*/
delete []adjacent;
delete []Cormat_gpu;
}
delete []R;
delete []mask;
delete []r_thresh;
delete []filename;
total_time = clock() - total_time;
cout<<"total elapsed time: "<<1.0*total_time/1000<<" s."<<endl;
cout<<"==========================================================="<<endl;
return 0;
}
long long FormFullGraph(bool * adjacent, real__t * Cormat, int N, real__t threshold)
{
long long index = 0;
long long nonZeroCount = 0;
memset(adjacent, 0, sizeof(bool) * (long long)N * N);
for(int i = 0; i < N; i++)
for(int j = i+1; j < N; j++)
{ if (Cormat[index] > 1)
{
cout<< Cormat[index]<<endl;
cout<<"FormFullGraph:illegal correlation coefficient\n";
exit(1);
}
if (Cormat[index] > threshold)
{
nonZeroCount += (adjacent[(long long)i * N + j] = adjacent[(long long)j * N + i] = true);
}
index ++;
}
return nonZeroCount * 2;
}
long long partition(real__t *A, long long m,long long p){
long long i;
real__t tem;
real__t v;
v=A[m];i=m+1;
//cout<<v<<endl;
while(1){
while(A[i]>v && i<p)
i++;
while(A[p]<=v && i<=p)
p--;
if(i<p){
tem=A[i];A[i]=A[p];A[p]=tem;
}else break;
}
A[m]=A[p];A[p]=v;return (p);
}
void select(real__t *A,long long n,long long k){
long long j,m,r;
m=0;r=n-1;
cout<<"k = "<<k<<endl;
while(1){
j=r;
//cout<<"m = "<<m<<" ; r = "<< r<< endl;
//cout<<"A[m] = "<<A[m]<<" ; A[r] = "<< A[r]<< endl;
//clock_t time = clock();
j=partition(A, m,j);
//time = clock() - time;
//cout<<"partition time : "<<time<<"; j ="<<j<<endl;
//cout<<"j = "<<j<<endl;
if(k-1==j)break;
else if(k-1<j) r=j-1;
else m=j+1;
}
}
real__t FormFullGraph_s(bool * adjacent, real__t * Cormat, int N, long long threshold)
{
long long M1 = (N-1);
M1 *= N;
M1 /= 2;
//long long M = ((M1-2+blocksize)/blocksize)*blocksize+1;
// clock_t time = clock();
// cout<<"max_correlation : "<<Cormat[find_max(Cormat,M1)]<<endl;
// time = clock()-time;
// cout<<"find max time : "<<time<<endl;
real__t * Cormat_copy = new real__t[M1];
//real__t * Cormat_copy = new real__t[M];
memcpy (Cormat_copy, Cormat, (long long) M1*sizeof(real__t));
//memcpy (Cormat_copy, Cormat, (long long) M1*sizeof(real__t));
//memset (Cormat_copy+M1, 0, (long long) (M-M1)*sizeof(real__t));
/*for (long long i=0 ; i < M1; i++)
{
if (Cormat[i] >0.94) cout<< Cormat_copy[i]<<endl;
if (Cormat_copy[i] != Cormat[i]) cout<<"i = "<<i<<endl;
}*/
//select_GPU(Cormat_copy, M1, threshold);
select(Cormat_copy, M1, threshold);
real__t r_threshold = Cormat_copy[threshold-1];
cout <<"corresponding r_threshold = "<<r_threshold<<endl;
delete []Cormat_copy;
//long long n_edge = FormFullGraph(adjacent, Cormat, N, r_threshold);
long long index = 0;
long long nonZeroCount = 0;
stack<int> s_i;
stack<int> s_j;
int i_for_del;
int j_for_del;
memset(adjacent, 0, sizeof(bool) *(long long) N * N);
for(int i = 0; i < N; i++)
{
//if (nonZeroCount >= threshold)
// break;
for(int j = i+1; j < N; j++)
{ if (Cormat[index] > 1 || Cormat[index] < 0)
{
cout<<"FormFullGraph:illegal correlation coefficient\n";
cin >> j;
exit(1);
}
if (Cormat[index] >= r_threshold )
nonZeroCount += (adjacent[(long long)i * N + j] = adjacent[(long long)j * N + i] = true);
if (Cormat[index] == r_threshold)
{ s_i.push(i);s_j.push(j); }
if (nonZeroCount > threshold)
{
if (s_i.empty()) cout<<"nonZeroCount number error!";
adjacent[(long long)(s_i.top()) * N + s_j.top()] = false;
adjacent[(long long)(s_j.top()) * N + s_i.top()] = false;
s_i.pop(); s_j.pop(); nonZeroCount--;
}
index ++;
}
}
if (nonZeroCount != threshold)
{
cout<<"expected edge number = "<<threshold<<"\nreal edge number = "<<nonZeroCount<<endl;
cin >> threshold;
exit(1);
}
return r_threshold;
}
void post_block (real__t * Cormat, real__t * Cormat_blocked, int N, int block_size,bool fishtran_flag)
{
/* int i = 0;
int block_cnt = (N + block_size - 1) / block_size;
real__t * src, * dst;
src = Cormat_blocked;
dst = Cormat;
for (i = 0; i < (block_cnt - 1) * block_size ; i++)
{
int offset = i % block_size + 1;
memcpy(dst, src + offset, sizeof(real__t) * (block_size - offset));
dst += block_size - offset;
src += block_size * block_size;
for (int j = i / block_size + 1; j < block_cnt - 1; j++)
{
memcpy(dst, src, sizeof(real__t) * block_size);
dst += block_size;
src += block_size * block_size;
}
memcpy(dst, src, sizeof(real__t) * (N % block_size));
dst += N % block_size;
src += block_size - ((i+1) % block_size != 0) * block_size * block_size * (block_cnt - 1 - i / block_size);
}
for (; i < N; i++)
{
int offset = i % block_size + 1;
memcpy(dst, src + offset, sizeof(real__t) * (N % block_size - offset));
dst += (N % block_size - offset);
src += block_size;
}
*/
int block_cnt = (N + block_size - 1)/ block_size;
long long index = 0;
int nonzeros = 0;
if (fishtran_flag)
for (int i = 0; i < N; i++)
for (int j = i + 1; j < N; j++)
{
int block_row = i / block_size;
int block_col = j / block_size;
int block_i = i % block_size;
int block_j = j % block_size;
long long offset =block_row * (2*block_cnt - block_row + 1) / 2 + block_col - block_row;
offset *= block_size * block_size;
if (Cormat_blocked[(long long)block_i*block_size + block_j + offset]>=-1 && Cormat_blocked[(long long)block_i*block_size + block_j + offset]<=1)
Cormat[index] += fishertrans(Cormat_blocked[(long long)block_i*block_size + block_j + offset]);
index ++;
}
else
for (int i = 0; i < N; i++)
for (int j = i + 1; j < N; j++)
{
int block_row = i / block_size;
int block_col = j / block_size;
int block_i = i % block_size;
int block_j = j % block_size;
long long offset =block_row * (2*block_cnt - block_row + 1) / 2 + block_col - block_row;
offset *= block_size * block_size;
if (Cormat_blocked[(long long)block_i*block_size + block_j + offset]>=-1 && Cormat_blocked[(long long)block_i*block_size + block_j + offset]<=1)
Cormat[index] += Cormat_blocked[(long long)block_i*block_size + block_j + offset];
index ++;
}
}
void FormCSRGraph(int * R, int * C, real__t *V, bool * adjacent, int N, real__t *Cormat)
{
int count = 0;
long long Cindex = 0;
long long index = 0;
R[0] = 0;
for(long long i = 0; i < N; i++)
{
for(long long j = 0; j < N; j++)
{
if(adjacent[(long long)i*N+j])
{
count ++;
C[Cindex] = j;
if (i < j)
index = i*N - (1+i)*i/2 + j - (i+1);
else if (i > j)
index = j*N - (1+j)*j/2 + i - (j+1);
else{
cout<<" diag not 0"<<endl;
system("pause");
}
V[Cindex] = Cormat[index];
Cindex++;
}
}
R[i+1] = count;
}
}
void CorMat_cpu(real__t * Cormat, real__t * BOLD, int N, int L)
{
// transposing the BOLD signal
real__t * BOLD_t = new real__t [L * N];
memset(BOLD_t, 0, sizeof(real__t) * L * N);
for (int i = 0; i < L; i ++)
for (int j = 0; j < N; j++)
{
BOLD_t[j * L + i] = BOLD[i * N + j];
}
// Normalize
for (int i = 0; i < N; i++)
{
real__t * row = BOLD_t + i * L;
double sum1 = 0, sum2 = 0;
for (int l = 0; l < L; l++)
{
sum1 += row[l];
}
sum1 /= L;
for (int l = 0; l < L; l++)
{
sum2 += (row[l] - sum1) * (row[l] - sum1);
}
sum2 = sqrt(sum2);
for (int l = 0; l < L; l++)
{
row[l] = (row[l] - sum1) / sum2;;
}
}
// GEMM
double sum3;
for (int k = 0, i = 0; i < N; i++)
for (int j = i+1; j < N; j++)
{
sum3 = 0;
for (int l = 0; l < L; l++)
{
sum3 += BOLD_t[i*L+l] * BOLD_t[j*L+l];
}
Cormat[k++] = sum3;
}
delete []BOLD_t;
} | [
"newstart15lerond@163.com"
] | newstart15lerond@163.com |
4d898eae27e1bce365f628c05a8c22847550f036 | 462f49a433db351e229232dc6ac3501a15c7a399 | /hangman/GameLauncher.h | e3ac7a35431c5b1a7e34be7a0b89bcd936699f47 | [] | no_license | sintaxiz/cpp-labs | 4d7bb5db80e458eeab76656c922f3dcf5d64bfc8 | 20c7f03cd128463bb607b5e6d6c45f4d59bca01a | refs/heads/master | 2023-02-04T09:19:07.874317 | 2020-12-27T12:01:18 | 2020-12-27T12:01:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 170 | h | #pragma once
#include <string>
namespace hangman {
class GameLauncher {
public:
~GameLauncher() = default;
static void startGame();
};
}
| [
"natashaleind@gmail.com"
] | natashaleind@gmail.com |
db21e3222864bcb1505b63de9614df8bb849869b | bc0ff8053a3551768e30463a002b366b847196e1 | /src/graph.h | ee28927b081eba6c497f04aeec224c89f01022a8 | [] | no_license | wutzi15/makefiles | c343f5e36da2c08540a957e2fdcd0c1b11babca8 | 82ca2b9b85e68ac51bf576ae19d0a3e6b2fcdf8a | refs/heads/master | 2021-01-01T16:12:49.345893 | 2011-07-30T15:50:22 | 2011-07-30T15:50:22 | 2,129,172 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 172 | h | #ifndef _GRAPH
#define _GRAPH
#include "pref.h"
//#include "boost/filesystem.hpp"
void graph(std::string name,bool big);
inline void init();
void AtlasStyle();
#endif | [
"wutzi@Cqubebook2.local"
] | wutzi@Cqubebook2.local |
e55d3cb882aea3c5c69d05f609c5e62bd7220090 | d0d734998632a1db39459ee07c244adb47e8797d | /GeoServer/src/main.cpp | c4500d4ae2343446351bd163e8f67d9a730b2dd8 | [] | no_license | GPUWorks/webAsmPlay | 68ade4b47ee5fc33ebabdda07d799ed6d7f23548 | 13d29ed6f4754abc7c8796689badd6e73da606d3 | refs/heads/master | 2020-04-06T22:46:58.927041 | 2018-11-15T07:40:42 | 2018-11-15T07:40:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,706 | cpp |
/**
╭━━━━╮╱╱╱╱╱╱╱╱╱╭╮╱╭━━━╮╱╱╱╱╱╱╭╮
┃╭╮╭╮┃╱╱╱╱╱╱╱╱╱┃┃╱┃╭━╮┃╱╱╱╱╱╱┃┃
╰╯┃┃╰╯╭━╮╭━━╮╭╮┃┃╱┃┃╱╰╯╭━━╮╭━╯┃╭━━╮
╱╱┃┃╱╱┃╭╯┃╭╮┃┣┫┃┃╱┃┃╱╭╮┃╭╮┃┃╭╮┃┃┃━┫
╱╱┃┃╱╱┃┃╱┃╭╮┃┃┃┃╰╮┃╰━╯┃┃╰╯┃┃╰╯┃┃┃━┫
╱╱╰╯╱╱╰╯╱╰╯╰╯╰╯╰━╯╰━━━╯╰━━╯╰━━╯╰━━╯
// 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.
\\author Matthew Tang
\\email trailcode@gmail.com
\\copyright 2018
*/
#include <webAsmPlay/Debug.h>
#include <geoServer/GeoServer.h>
using namespace std;
void (*debugLoggerFunc)(const std::string & file, const size_t line, const std::string & message) = NULL;
void dmessCallback(const string & file, const size_t line, const string & message)
{
cout << file << " " << line << " " << message;
}
void showHelp()
{
const char* helpMessage = R"help(
__ __
__ __ \_\ __ __ \_\ __ __ __
\_\ /_/ \/_/ /_/ \/_/ \_\ /_/
.-. \.-./ .-. .-./ .-. .-./ .-. .-\ .-. \.-./ .-.
//-\\_//-\\_//-\\_//-\\_//-\\_//-\\_// \\_//-\\_//-\\_//-\\_//-\\
__( '-' '-'\ '-' '-' /'-' '-'\__'-' '-'__/'-' '-'\__
/_/)) \__ __/\ \_\ /_/ \_\
___\_// \_\ /_/ \__
/_/ (( \_\
)) __
__ // /_/
\_\_((_/___ ╭━━━╮╱╱╱╱╱╱╱╱╭━━━╮
)) \_\ ┃╭━╮┃╱╱╱╱╱╱╱╱┃╭━╮┃
\\ ┃┃╱╰╯╭━━╮╭━━╮┃╰━━╮╭━━╮╭━╮╭╮╭╮╭━━╮╭━╮
)) _ ┃┃╭━╮┃┃━┫┃╭╮┃╰━━╮┃┃┃━┫┃╭╯┃╰╯┃┃┃━┫┃╭╯
__ // /_/ ┃╰┻━┃┃┃━┫┃╰╯┃┃╰━╯┃┃┃━┫┃┃╱╰╮╭╯┃┃━┫┃┃
\_\_(( ╰━━━╯╰━━╯╰━━╯╰━━━╯╰━━╯╰╯╱╱╰╯╱╰━━╯╰╯
\\
)) __ Usage:
__ // /_/
\_\_((_/___ geoServer <path to vector file>
)) \_\
\\ Supported file types:
)) _
__ // /_/ .shp
\_\_((_/ .osm (OpenStreetMap xml file format)
\\ .geo (GeoServer file format)
)) __
__ // /_/ Create .geo:
\_\_((_/___
)) \_\ geoServer --convert <vector file> <.geo file>
\\
)) _ Help (This message):
__ // /_/
\_\_((_/___ geoServer --help
)) \_\ __ __
\\ __ __ \_\ __ __ \_\ __ __ __
__ )) \_\ /_/ \/_/ /_/ \/_/ \_\ /_/
\_\_(( .-. \.-./ .-. .-./ .-. .-./ .-. .-\ .-. \.-./ .-.
\\_//-\\_//-\\_//-\\_//-\\_//-\\_//-\\_// \\_//-\\_//-\\_//-\\_//-\\
'dc\__'-' '-'\ '-' '-' /'-' '-'\__'-' '-'__/'-' '-'\__
\_\ \__ __/\ \_\ /_/ \_\
\_\ /_/ \__
\_\
)help";
cout << helpMessage << endl;
exit(0);
}
int main(const int argc, char ** argv)
{
if(argc == 1) { showHelp() ;}
if(argc > 1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h"))) { showHelp() ;}
debugLoggerFunc = &dmessCallback;
GeoServer s;
s.addGeoFile(argv[1]);
s.start();
return 0;
} | [
"trailcode@gmail.com"
] | trailcode@gmail.com |
37903ea31eed91fe446e26ac495a038b811ef8e2 | 9d2d18eead188651365b2c79017e11296609f36d | /Power_of_Four/submission1.cpp | d5c8c6997337ab13d0624cfed9133a77f98b09e9 | [] | no_license | Zhanghq8/Leetcode_notes | 5605fb361645d8ffa1153012c4b6d63718037cd9 | a51eafa78524a1ee873da325f79e7e56eaaa0b7d | refs/heads/master | 2021-07-10T01:27:14.878587 | 2020-08-02T01:09:40 | 2020-08-02T01:09:40 | 174,649,314 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 533 | cpp | #include <iostream>
#include <string>
using namespace std;
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n == 0) {
return false;
}
if (n == 1) {
return true;
}
double temp = n;
while (temp >= 4) {
if ((int)temp % 4 != 0) {
return false;
}
temp = temp / 4.0;
if ((int)temp == temp && temp == 1) {
return true;
}
}
return false;
}
};
| [
"hzhang8@wpi.edu"
] | hzhang8@wpi.edu |
2ae08ff4008f647b89c90ba9b0df521c5aca5476 | eefb836e9ec761c2b1f102b4007ed7ab6380c7a2 | /code/delta/core/modules/shle/libSceNpTrophy/libSceNpTrophy_api.cpp | 23d2abf9739314e7ab5a972f2d3cd57c14ddd2fa | [] | no_license | RyuDanuer/ps4delta | be6ee054ca3ae59159ecbcc59addb77c6f60c85f | e3ee468357fa0fbbd428d52034fc84e76b851c4c | refs/heads/master | 2020-09-25T05:18:15.631545 | 2019-12-02T20:13:54 | 2019-12-02T20:13:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,113 | cpp |
// Copyright (C) 2019 Force67
// This file was generated on Sat Sep 7 22:01:27 2019
#include "../../ModuleLinker.h"
#include "libSceNpTrophy.h"
static const mlink::FunctionInfo functions[] = {
{0x6939C7B3B5BFF549, &sceNpTrophyAbortHandle},
{0x72A1A460037F811C, &sceNpTrophyCaptureScreenshot},
{0x5DB9236E86D99426, &sceNpTrophyCreateContext},
{0xABB53AB440107FB7, &sceNpTrophyCreateHandle},
{0x1355ABC1DD3B2EBF, &sceNpTrophyDestroyContext},
{0x18D705E2889D6346, &sceNpTrophyDestroyHandle},
{0x1CBC33D5F448C9C0, &sceNpTrophyGetGameIcon},
{0x6183F77F65B4F688, &sceNpTrophyGetGameInfo},
{0xC38B8C3E612B0F82, &sceNpTrophyGetGroupIcon},
{0xC1353019FB292A27, &sceNpTrophyGetGroupInfo},
{0x7812FE97A1C6F719, &sceNpTrophyGetTrophyIcon},
{0xAAA515183810066D, &sceNpTrophyGetTrophyInfo},
{0x2C7B9298EDD22DDF, &sceNpTrophyGetTrophyUnlockState},
{0xBBDA6592A6B67B49, &sceNpTrophyIntAbortHandle},
{0xA44E7286BA32F66D, &sceNpTrophyIntCheckNetSyncTitles},
{0x79D3C8385A4402F5, &sceNpTrophyIntCreateHandle},
{0x0D2877117A6A010E, &sceNpTrophyIntDestroyHandle},
{0xB2783DF2A50BCCF0, &sceNpTrophyIntGetLocalTrophySummary},
{0xB77090CDA83BFF3B, &sceNpTrophyIntGetProgress},
{0x8C5FE60A01AEBDB4, &sceNpTrophyIntGetRunningTitle},
{0x3DE0320630B9929F, &sceNpTrophyIntGetRunningTitles},
{0x3C4A34F4392ABF4A, &sceNpTrophyIntGetTrpIconByUri},
{0x905F738E7940CC80, &sceNpTrophyIntNetSyncTitle},
{0x5178B27DA6F114D4, &sceNpTrophyIntNetSyncTitles},
{0x4C9080C6DA3D4845, &sceNpTrophyRegisterContext},
{0x77D8E974FCF97FFF, &sceNpTrophyShowTrophyList},
{0xFEA8E6D9F144EB83, &sceNpTrophySystemIsServerAvailable},
{0xDBCC6645415AA3AF, &sceNpTrophyUnlockTrophy},
{0x052A128223151E76, &unk_BSoSgiMVHnY},
{0x149656DA81D41C59, &unk_FJZW2oHUHFk},
{0x1EDE8C35397F8DEE, &unk_Ht6MNTl_je4},
{0x213526BE904F686D, &unk_ITUmvpBPaG0},
{0x24C49AA44B431FD4, &unk_JMSapEtDH9Q},
{0x26C4670CA473BD1C, &unk_JsRnDKRzvRw},
{0x27325D87F24BB6ED, &unk_JzJdh_JLtu0},
{0x316E7282866A101B, &unk_MW5ygoZqEBs},
{0x3686D5C03F2A7106, &unk_NobVwD8qcQY},
{0x39C9651C515C4242, &unk_OcllHFFcQkI},
{0x435F36C74AD3EF92, &unk_Q182x0rT75I},
{0x45DD8504E404D3DE, &unk_Rd2FBOQE094},
{0x464B746D5C9A6B86, &unk_Rkt0bVyaa4Y},
{0x468E2C23DC60625E, &unk_Ro4sI9xgYl4},
{0x4AC18B2937D67E6D, &unk_SsGLKTfWfm0},
{0x5344CE4A29DFBAFC, &unk_U0TOSinfuvw},
{0x59D0945092D0A1D3, &unk_WdCUUJLQodM},
{0x5EA2CBB2F978F240, &unk_XqLLsvl48kA},
{0x5F8EECE006A63C68, &unk_X47s4AamPGg},
{0x69786F7F63A66E21, &unk_aXhvf2OmbiE},
{0x701CD711DCD5CEFB, &unk_cBzXEdzVzvs},
{0x764DBBA254B80841, &unk_dk27olS4CEE},
{0x795D6BB4BAFE7B2B, &unk_eV1rtLr_eys},
{0x83477104D4ECA42D, &unk_g0dxBNTspC0},
{0x86F75386756FC1D6, &unk_hvdThnVvwdY},
{0x8AA61FC42D76B1A9, &unk_iqYfxC12sak},
{0x915E033F439330DA, &unk_kV4DP0OTMNo},
{0x9469E6E4A83FCE90, &unk_lGnm5Kg_zpA},
{0x959499A0DF01B2D2, &unk_lZSZoN8BstI},
{0x9611385D2F4E257B, &unk_lhE4XS9OJXs},
{0x996B6C9C763C2598, &unk_mWtsnHY8JZg},
{0x9D7AF9461A3C06A9, &unk_nXr5Rho8Bqk},
{0x9DD2DE3561317991, &unk_ndLeNWExeZE},
{0x9F2B4DFF7FE976F2, &unk_nytN_3_pdvI},
{0x9F80071876FFA5F6, &unk_n4AHGHb_pfY},
{0xA732FE680934B500, &unk_pzL_aAk0tQA},
{0xA89DC8BEB3A85E0D, &unk_qJ3IvrOoXg0},
{0xABA78032E7172043, &unk_q6eAMucXIEM},
{0xB094839C94491E12, &unk_sJSDnJRJHhI},
{0xB0A185158E7D92C6, &unk_sKGFFY59ksY},
{0xB40C675E9CC3805C, &unk_tAxnXpzDgFw},
{0xB50DED5DF559ADE5, &unk_tQ3tXfVZreU},
{0xB55D7C9FC39C85E2, &unk_tV18n8OcheI},
{0xC8327FAFFF1FE12E, &unk_yDJ_r_8f4S4},
{0xC9726581796322D9, &unk_yXJlgXljItk},
{0xCC38C5D86FBAB48D, &unk_zDjF2G_6tI0},
{0xCFC4423F9DFA18E3, &unk_z8RCP536GOM},
{0xDB4C0031B5CFFEED, &unk_20wAMbXP_u0},
{0xDED58AA4D2A7E7E2, &unk_3tWKpNKn5_I},
{0xE10605C02EED9F85, &unk_4QYFwC7tn4U},
{0xE7406F618CCF4EC6, &unk_50BvYYzPTsY},
{0xE8439F4B9483828A, &unk_6EOfS5SDgoo},
{0xECA87CEAF26AB71C, &unk_7Kh86vJqtxw},
{0xED63E3E0A085DC3F, &unk_7WPj4KCF3D8},
{0xEFE391D5353940E0, &unk_7_OR1TU5QOA},
{0xF1A2E52C728FF8DA, &unk_8aLlLHKP_No},
{0xF8EF6F5350A91990, &unk__O9vU1CpGZA},
{0xFA7A2DD770447552, &unk__not13BEdVI},
{0xFCB0BD86E7660FE6, &unk__LC9hudmD_Y},
};
MODULE_INIT(libSceNpTrophy);
| [
"prelink835@gmail.com"
] | prelink835@gmail.com |
a4369e811112dd21859ba7ea7e4e5b5014994c77 | 801f7ed77fb05b1a19df738ad7903c3e3b302692 | /refactoringOptimisation/differentiatedCAD/occt-min-topo-src/src/MeshVS/MeshVS_DataMapIteratorOfDataMapOfTwoColorsMapOfInteger.hxx | e968315ce3c2505289daddc2f95f481af096db18 | [] | no_license | salvAuri/optimisationRefactoring | 9507bdb837cabe10099d9481bb10a7e65331aa9d | e39e19da548cb5b9c0885753fe2e3a306632d2ba | refs/heads/master | 2021-01-20T03:47:54.825311 | 2017-04-27T11:31:24 | 2017-04-27T11:31:24 | 89,588,404 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 212 | hxx |
#ifndef MeshVS_DataMapIteratorOfDataMapOfTwoColorsMapOfInteger_HeaderFile
#define MeshVS_DataMapIteratorOfDataMapOfTwoColorsMapOfInteger_HeaderFile
#include <MeshVS_DataMapOfTwoColorsMapOfInteger.hxx>
#endif
| [
"salvatore.auriemma@opencascade.com"
] | salvatore.auriemma@opencascade.com |
77be49ac279d4af25da5cec014955f2bb7586fbd | 46019d4194f4f1a30dcc89e9a9e659d76fc02427 | /examples/stream_dump.cpp | f413626b262a056b5cb659dfb739a6d9b695bf20 | [
"BSD-2-Clause"
] | permissive | LightBitsLabs/libtins | 54517ab67cd2365fe4edb2a7786bf035f4402a60 | d68235b5d9f9876d9b967575ecd01e367ae86d10 | refs/heads/master | 2023-06-21T14:52:30.952254 | 2017-10-29T15:09:10 | 2017-10-29T15:09:10 | 95,368,486 | 0 | 0 | null | 2017-10-29T15:09:11 | 2017-06-25T15:29:49 | C++ | UTF-8 | C++ | false | false | 6,022 | cpp | /*
* Copyright (c) 2017, Matias Fontanini
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <iostream>
#include <sstream>
#include "tins/tcp_ip/stream_follower.h"
#include "tins/sniffer.h"
#include "tins/packet.h"
#include "tins/ip_address.h"
#include "tins/ipv6_address.h"
using std::cout;
using std::cerr;
using std::endl;
using std::bind;
using std::string;
using std::to_string;
using std::ostringstream;
using std::exception;
using Tins::Sniffer;
using Tins::SnifferConfiguration;
using Tins::PDU;
using Tins::TCPIP::StreamFollower;
using Tins::TCPIP::Stream;
// This example takes an interface and a port as an argument and
// it listens for TCP streams on the given interface and port.
// It will reassemble TCP streams and show the traffic sent by
// both the client and the server.
// Convert the client endpoint to a readable string
string client_endpoint(const Stream& stream) {
ostringstream output;
// Use the IPv4 or IPv6 address depending on which protocol the
// connection uses
if (stream.is_v6()) {
output << stream.client_addr_v6();
}
else {
output << stream.client_addr_v4();
}
output << ":" << stream.client_port();
return output.str();
}
// Convert the server endpoint to a readable string
string server_endpoint(const Stream& stream) {
ostringstream output;
if (stream.is_v6()) {
output << stream.server_addr_v6();
}
else {
output << stream.server_addr_v4();
}
output << ":" << stream.server_port();
return output.str();
}
// Concat both endpoints to get a readable stream identifier
string stream_identifier(const Stream& stream) {
ostringstream output;
output << client_endpoint(stream) << " - " << server_endpoint(stream);
return output.str();
}
// Whenever there's new client data on the stream, this callback is executed.
void on_client_data(Stream& stream) {
// Construct a string out of the contents of the client's payload
string data(stream.client_payload().begin(), stream.client_payload().end());
// Now print it, prepending some information about the stream
cout << client_endpoint(stream) << " >> "
<< server_endpoint(stream) << ": " << endl << data << endl;
}
// Whenever there's new server data on the stream, this callback is executed.
// This does the same thing as on_client_data
void on_server_data(Stream& stream) {
string data(stream.server_payload().begin(), stream.server_payload().end());
cout << server_endpoint(stream) << " >> "
<< client_endpoint(stream) << ": " << endl << data << endl;
}
// When a connection is closed, this callback is executed.
void on_connection_closed(Stream& stream) {
cout << "[+] Connection closed: " << stream_identifier(stream) << endl;
}
// When a new connection is captured, this callback will be executed.
void on_new_connection(Stream& stream) {
// Print some information about the new connection
cout << "[+] New connection " << stream_identifier(stream) << endl;
// Now configure the callbacks on it.
// First, we want on_client_data to be called every time there's new client data
stream.client_data_callback(&on_client_data);
// Same thing for server data, but calling on_server_data
stream.server_data_callback(&on_server_data);
// When the connection is closed, call on_connection_closed
stream.stream_closed_callback(&on_connection_closed);
}
int main(int argc, char* argv[]) {
if (argc != 3) {
cout << "Usage: " << argv[0] << " <interface> <port>" << endl;
return 1;
}
try {
// Construct the sniffer configuration object
SnifferConfiguration config;
// Only capture TCP traffic sent from/to the given port
config.set_filter("tcp port " + to_string(stoi(string(argv[2]))));
// Construct the sniffer we'll use
Sniffer sniffer(argv[1], config);
cout << "Starting capture on interface " << argv[1] << endl;
// Now construct the stream follower
StreamFollower follower;
// We just need to specify the callback to be executed when a new
// stream is captured. In this stream, you should define which callbacks
// will be executed whenever new data is sent on that stream
// (see on_new_connection)
follower.new_stream_callback(&on_new_connection);
// Now start capturing. Every time there's a new packet, call
// follower.process_packet
sniffer.sniff_loop([&](PDU& packet) {
follower.process_packet(packet);
return true;
});
}
catch (exception& ex) {
cerr << "Error: " << ex.what() << endl;
return 1;
}
}
| [
"matias.fontanini@gmail.com"
] | matias.fontanini@gmail.com |
3a4d36367ee506a57a76e4dd83abaeb24ea3519e | bd6882b7bfe41cd0216e885586ff6b3618a2c4b8 | /include/fast_io_legacy_impl/c/universal_crt.h | 45c6aa46c0b217ab19a8ae4fa27fc773b156a77f | [
"MIT"
] | permissive | strott/fast_io | f80f2f6b597a6c33fb171319073900e489b6366d | ea92b4816710d6b9bd863b112341e956dc65ec5e | refs/heads/master | 2022-11-23T17:04:59.535552 | 2020-07-28T20:36:42 | 2020-07-28T20:36:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,220 | h | #pragma once
namespace fast_io
{
/*
referenced from win10sdk ucrt
C:\Program Files (x86)\Windows Kits\10\Source\10.0.19041.0\ucrt
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// Internal Stream Types (__crt_stdio_stream and friends)
//
//-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// Ensure that __crt_stdio_stream_data* and FILE* pointers are freely convertible:
struct ucrt_stdio_stream_data
{
union
{
FILE public_file;
char* ptr;
};
char* base;
int cnt;
long flags;
long file;
int charbuf;
int bufsiz;
char* tmpfname;
};
*/
namespace details::ucrt_hack
{
static_assert(sizeof(FILE)==sizeof(char*));
template<std::integral T=char>
inline [[gnu::may_alias]] T* get_fp_ptr(FILE* fp) noexcept
{
T* b;
memcpy(std::addressof(b),reinterpret_cast<std::byte*>(fp),sizeof(T*));
return b;
}
template<std::integral T>
inline void set_fp_ptr(FILE* fp,[[gnu::may_alias]] T* b) noexcept
{
memcpy(reinterpret_cast<std::byte*>(fp),std::addressof(b),sizeof(T*));
}
template<std::integral T=char>
inline [[gnu::may_alias]] T* get_fp_base(FILE* fp) noexcept
{
T* b;
memcpy(std::addressof(b),reinterpret_cast<std::byte*>(fp)+sizeof(uintptr_t),sizeof(T*));
return b;
}
inline int get_fp_cnt(FILE* fp) noexcept
{
constexpr std::size_t offset{sizeof(uintptr_t)*2};
int b;
memcpy(std::addressof(b),reinterpret_cast<std::byte*>(fp)+offset,sizeof(int));
return b;
}
inline void set_fp_cnt(FILE* fp,int b) noexcept
{
constexpr std::size_t offset{sizeof(uintptr_t)*2};
memcpy(reinterpret_cast<std::byte*>(fp)+offset,
std::addressof(b),sizeof(int));
}
inline long get_fp_flags(FILE* fp)
{
constexpr std::size_t offset{sizeof(uintptr_t)*2+sizeof(int)};
long b;
memcpy(std::addressof(b),reinterpret_cast<std::byte*>(fp)+offset,sizeof(long));
return b;
}
inline void set_fp_flags(FILE* fp,long flags)
{
constexpr std::size_t offset{sizeof(uintptr_t)*2+sizeof(int)};
memcpy(reinterpret_cast<std::byte*>(fp)+offset,std::addressof(flags),sizeof(long));
}
inline int get_fp_bufsiz(FILE* fp) noexcept
{
constexpr std::size_t offset{sizeof(uintptr_t)*2+sizeof(int)+sizeof(long)*2+sizeof(int)};
int b;
memcpy(std::addressof(b),reinterpret_cast<std::byte*>(fp)+offset,sizeof(int));
return b;
}
}
inline char* ibuffer_begin(c_io_observer_unlocked cio)
{
using namespace details::ucrt_hack;
return get_fp_base(cio.fp);
}
inline char* ibuffer_curr(c_io_observer_unlocked cio)
{
using namespace details::ucrt_hack;
return get_fp_ptr(cio.fp);
}
inline char* ibuffer_end(c_io_observer_unlocked cio)
{
using namespace details::ucrt_hack;
return get_fp_ptr(cio.fp)+get_fp_cnt(cio.fp);
}
inline void ibuffer_set_curr(c_io_observer_unlocked cio,char* ptr)
{
using namespace details::ucrt_hack;
set_fp_cnt(cio.fp,get_fp_ptr(cio.fp)-ptr+get_fp_cnt(cio.fp));
set_fp_ptr(cio.fp,ptr);
}
//extern "C" int __stdcall __acrt_stdio_refill_and_read_narrow_nolock(FILE*) noexcept;
inline bool underflow(c_io_observer_unlocked cio)
{
using namespace details::ucrt_hack;
ibuffer_set_curr(cio,ibuffer_end(cio));
if(_fgetc_nolock(cio.fp)==EOF)[[unlikely]]
return false;
set_fp_cnt(cio.fp,get_fp_cnt(cio.fp)+1);
set_fp_ptr(cio.fp,get_fp_ptr(cio.fp)-1);
return true;
}
inline char* obuffer_begin(c_io_observer_unlocked cio)
{
using namespace details::ucrt_hack;
return get_fp_base(cio.fp);
}
inline char* obuffer_curr(c_io_observer_unlocked cio)
{
using namespace details::ucrt_hack;
return get_fp_ptr(cio.fp);
}
inline char* obuffer_end(c_io_observer_unlocked cio)
{
using namespace details::ucrt_hack;
return get_fp_base(cio.fp)+get_fp_bufsiz(cio.fp);
}
inline void obuffer_set_curr(c_io_observer_unlocked cio,char* ptr)
{
using namespace details::ucrt_hack;
set_fp_cnt(cio.fp,get_fp_ptr(cio.fp)-ptr+get_fp_cnt(cio.fp));
set_fp_ptr(cio.fp,ptr);
set_fp_flags(cio.fp,get_fp_flags(cio.fp)|0x010000);
}
//extern "C" int __stdcall __acrt_stdio_flush_and_write_narrow_nolock(int,FILE*) noexcept;
inline void overflow(c_io_observer_unlocked cio,char ch)
{
obuffer_set_curr(cio,obuffer_end(cio));
if(_fputc_nolock(static_cast<int>(static_cast<unsigned char>(ch)),cio.fp)==EOF)[[unlikely]]
#ifdef __cpp_exceptions
throw posix_error();
#else
fast_terminate();
#endif
}
[[gnu::may_alias]] inline wchar_t* ibuffer_begin(wc_io_observer_unlocked cio)
{
return details::ucrt_hack::get_fp_base<wchar_t>(cio.fp);
}
[[gnu::may_alias]] inline wchar_t* ibuffer_curr(wc_io_observer_unlocked cio)
{
using namespace details::ucrt_hack;
return get_fp_ptr<wchar_t>(cio.fp);
}
[[gnu::may_alias]] inline wchar_t* ibuffer_end(wc_io_observer_unlocked cio)
{
using namespace details::ucrt_hack;
return get_fp_ptr<wchar_t>(cio.fp)+(get_fp_cnt(cio.fp)/sizeof(wchar_t));
}
inline void ibuffer_set_curr(wc_io_observer_unlocked cio, [[gnu::may_alias]] wchar_t* ptr)
{
using namespace details::ucrt_hack;
set_fp_cnt(cio.fp,(get_fp_ptr<wchar_t>(cio.fp)-ptr)*sizeof(wchar_t)+get_fp_cnt(cio.fp));
set_fp_ptr(cio.fp,ptr);
}
inline bool underflow(wc_io_observer_unlocked cio)
{
using namespace details::ucrt_hack;
ibuffer_set_curr(cio,ibuffer_end(cio));
if(_fgetwc_nolock(cio.fp)==EOF)[[unlikely]]
return false;
set_fp_cnt(cio.fp,get_fp_cnt(cio.fp)+1);
set_fp_ptr(cio.fp,get_fp_ptr(cio.fp)-1);
return true;
}
[[gnu::may_alias]] inline wchar_t* obuffer_begin(wc_io_observer_unlocked cio)
{
using namespace details::ucrt_hack;
return get_fp_base<wchar_t>(cio.fp);
}
[[gnu::may_alias]] inline wchar_t* obuffer_curr(wc_io_observer_unlocked cio)
{
using namespace details::ucrt_hack;
return get_fp_ptr<wchar_t>(cio.fp);
}
[[gnu::may_alias]] inline wchar_t* obuffer_end(wc_io_observer_unlocked cio)
{
using namespace details::ucrt_hack;
return get_fp_base<wchar_t>(cio.fp)+get_fp_bufsiz(cio.fp)/sizeof(wchar_t);
}
inline void obuffer_set_curr(wc_io_observer_unlocked cio,[[gnu::may_alias]] wchar_t* ptr)
{
using namespace details::ucrt_hack;
set_fp_cnt(cio.fp,(get_fp_ptr<wchar_t>(cio.fp)-ptr)*sizeof(wchar_t)+get_fp_cnt(cio.fp));
set_fp_ptr(cio.fp,ptr);
set_fp_flags(cio.fp,get_fp_flags(cio.fp)|0x010000);
}
//extern "C" wint_t __stdcall __acrt_stdio_flush_and_write_wide_nolock(wint_t,FILE*) noexcept;
inline void overflow(wc_io_observer_unlocked cio,wchar_t ch)
{
using namespace details::ucrt_hack;
obuffer_set_curr(cio,obuffer_end(cio));
if(_fputwc_nolock(static_cast<wint_t>(static_cast<std::make_unsigned_t<wchar_t>>(ch)),cio.fp)==WEOF)[[unlikely]]
#ifdef __cpp_exceptions
throw posix_error();
#else
fast_terminate();
#endif
}
inline bool obuffer_is_active(c_io_observer_unlocked cio)
{
return details::ucrt_hack::get_fp_base(cio.fp);
}
inline bool obuffer_is_active(wc_io_observer_unlocked cio)
{
return details::ucrt_hack::get_fp_base(cio.fp);
}
static_assert(buffer_io_stream<c_io_observer_unlocked>);
static_assert(buffer_io_stream<wc_io_observer_unlocked>);
static_assert(maybe_buffer_output_stream<c_io_observer_unlocked>);
static_assert(maybe_buffer_output_stream<wc_io_observer_unlocked>);
static_assert(!buffer_io_stream<basic_c_io_observer_unlocked<char8_t>>);
} | [
"euloanty@live.com"
] | euloanty@live.com |
56b7f4817f68b6faba292fa8dae73487f23a6c78 | 1913e2595ab0bfec71f28a953a46e624514b55e8 | /exercises/05-collections/bracketing-balance/src/bracketing-balance.cpp | f0dbf2c53c81f43081d630750d7af1201535597b | [] | no_license | eugene-shcherbo/programming-abstractions | 4c43149a980a51a836e97c5ee85953eb457d0a40 | f1b7c8db3e5a33f349e638e5a9c06a21bd8420cc | refs/heads/master | 2021-02-18T07:45:08.296484 | 2020-11-25T07:46:16 | 2020-11-25T07:47:00 | 245,175,467 | 0 | 0 | null | 2020-03-10T14:36:06 | 2020-03-05T13:50:27 | C++ | UTF-8 | C++ | false | false | 1,387 | cpp | #include <iostream>
#include <string>
#include "stack.h"
#include "console.h"
using namespace std;
bool checkBalance(const string& text);
bool bracketsMatch(char br1, char br2);
void testCheckBalance(const string& text, bool expected);
int main() {
testCheckBalance("(([])", false);
testCheckBalance(")(", false);
testCheckBalance("{(})", false);
testCheckBalance("{ s = 2 * (a[2] + 3); x = (1 + (2)); }", true);
return 0;
}
void testCheckBalance(const string& text, bool expected) {
bool actual = checkBalance(text);
cout << "Bracketing operators is " << (actual ? "" : "not ") << "balanced in the string \""
<< text << "\"." << endl;
cout << "Result: " << (actual == expected ? "Success." : "Failed.") << endl;
}
bool checkBalance(const string& text) {
Stack<char> brackets;
for (char ch: text) {
if (ch == '(' || ch == '[' || ch == '{') {
brackets.push(ch);
} else if (ch == ')' || ch == ']' || ch == '}') {
if (brackets.isEmpty() || !bracketsMatch(brackets.peek(), ch)) {
return false;
} else {
brackets.pop();
}
}
}
return brackets.isEmpty();
}
bool bracketsMatch(char br1, char br2) {
return (br1 == '{' && br2 == '}')
|| (br1 == '[' && br2 == ']')
|| (br1 == '(' && br2 == ')');
}
| [
"eugene.shcherbo@gmail.com"
] | eugene.shcherbo@gmail.com |
c947be54cd864c3642492f65184abfd63f316054 | 2a60eb5064dcc45824fe7a1ea073c35647c5407f | /src/client/ui/AuthFailedWindow.h | d77765cc504dbffe8bd64d2cd00489901892adf6 | [] | no_license | Victorique-GOSICK/engine | a20627a34191c4cdcd6f71acb7970e9176c55214 | a7828cfc610530080dafb70c5664794bde2aaac7 | refs/heads/master | 2021-07-20T00:04:28.543152 | 2017-10-27T18:42:29 | 2017-10-27T18:42:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 504 | h | /**
* @file
*/
#pragma once
#include "ui/Window.h"
#include "core/Common.h"
namespace frontend {
class AuthFailedWindow: public ui::Window {
public:
AuthFailedWindow(Window* parent) :
ui::Window(parent) {
core_assert_always(loadResourceFile("ui/window/client-authfailed.tb.txt"));
}
bool OnEvent(const tb::TBWidgetEvent &ev) override {
if (ev.type == tb::EVENT_TYPE_CLICK && ev.target->GetID() == TBIDC("ok")) {
Close();
return true;
}
return ui::Window::OnEvent(ev);
}
};
}
| [
"martin.gerhardy@gmail.com"
] | martin.gerhardy@gmail.com |
12253adde75760c3d90d937722f4e5d25585a8ba | e83650d4c2fe5fe04f1d12ce0817da6532104264 | /Road to compe c++/worngsubtrack.cpp | 6a3e3ff45ece58a7cc462fccc39de2143f403819 | [] | no_license | ackermanjayjay/Road-to-Epic | bc983aef8b80aa54f7941fbcb5760ca284665751 | 3fe2839518ca62e1700613882452810e8089ab49 | refs/heads/main | 2023-07-11T23:06:18.609798 | 2021-08-18T03:41:35 | 2021-08-18T03:41:35 | 371,303,091 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 182 | cpp | #include <iostream>
using namespace std;
int main() {
int a ;
int b ;
cin>>a>>b;
for(int i=0; i<b; i++)
{
if(a%10==0)
{
a/=10;
}else{
a--;
}
}
cout<<a;
} | [
"reza23198@gmail.com"
] | reza23198@gmail.com |
e6766bb12b3c348d5e6376cb31e53263258a5b28 | e5e5e8b07e8cd21f23fd4befbc7e7aceb1bf61f5 | /src/common/timings.cc | 657a519fa8d2578488785c84a9a8352fe05067e1 | [
"BSD-3-Clause",
"MIT"
] | permissive | sumoprojects/sumokoin | c4074f7b4f40c909b9d9dc9ce01521adb3cccb3e | 2857d0bffd36bf2aa579ef80518f4cb099c98b05 | refs/heads/master | 2022-03-04T02:21:41.550045 | 2021-08-22T04:32:04 | 2021-08-22T04:32:04 | 89,453,021 | 175 | 245 | NOASSERTION | 2021-08-22T04:32:05 | 2017-04-26T07:45:08 | C++ | UTF-8 | C++ | false | false | 3,017 | cc | #include <string.h>
#include <errno.h>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include "misc_log_ex.h"
#include "timings.h"
#define N_EXPECTED_FIELDS (8+11)
TimingsDatabase::TimingsDatabase()
{
}
TimingsDatabase::TimingsDatabase(const std::string &filename):
filename(filename)
{
load();
}
TimingsDatabase::~TimingsDatabase()
{
save();
}
bool TimingsDatabase::load()
{
instances.clear();
if (filename.empty())
return true;
FILE *f = fopen(filename.c_str(), "r");
if (!f)
{
MDEBUG("Failed to load timings file " << filename << ": " << strerror(errno));
return false;
}
while (1)
{
char s[4096];
if (!fgets(s, sizeof(s), f))
break;
char *tab = strchr(s, '\t');
if (!tab)
{
MWARNING("Bad format: no tab found");
continue;
}
const std::string name = std::string(s, tab - s);
std::vector<std::string> fields;
char *ptr = tab + 1;
boost::split(fields, ptr, boost::is_any_of(" "));
if (fields.size() != N_EXPECTED_FIELDS)
{
MERROR("Bad format: wrong number of fields: got " << fields.size() << " expected " << N_EXPECTED_FIELDS);
continue;
}
instance i;
unsigned int idx = 0;
i.t = atoi(fields[idx++].c_str());
i.npoints = atoi(fields[idx++].c_str());
i.min = atof(fields[idx++].c_str());
i.max = atof(fields[idx++].c_str());
i.mean = atof(fields[idx++].c_str());
i.median = atof(fields[idx++].c_str());
i.stddev = atof(fields[idx++].c_str());
i.npskew = atof(fields[idx++].c_str());
i.deciles.reserve(11);
for (int n = 0; n < 11; ++n)
{
i.deciles.push_back(atoi(fields[idx++].c_str()));
}
instances.insert(std::make_pair(name, i));
}
fclose(f);
return true;
}
bool TimingsDatabase::save()
{
if (filename.empty())
return true;
FILE *f = fopen(filename.c_str(), "w");
if (!f)
{
MERROR("Failed to write to file " << filename << ": " << strerror(errno));
return false;
}
for (const auto &i: instances)
{
fprintf(f, "%s", i.first.c_str());
fprintf(f, "\t%lu", (unsigned long)i.second.t);
fprintf(f, " %zu", i.second.npoints);
fprintf(f, " %f", i.second.min);
fprintf(f, " %f", i.second.max);
fprintf(f, " %f", i.second.mean);
fprintf(f, " %f", i.second.median);
fprintf(f, " %f", i.second.stddev);
fprintf(f, " %f", i.second.npskew);
for (uint64_t v: i.second.deciles)
fprintf(f, " %lu", (unsigned long)v);
fputc('\n', f);
}
fclose(f);
return true;
}
std::vector<TimingsDatabase::instance> TimingsDatabase::get(const char *name) const
{
std::vector<instance> ret;
auto range = instances.equal_range(name);
for (auto i = range.first; i != range.second; ++i)
ret.push_back(i->second);
std::sort(ret.begin(), ret.end(), [](const instance &e0, const instance &e1){ return e0.t < e1.t; });
return ret;
}
void TimingsDatabase::add(const char *name, const instance &i)
{
instances.insert(std::make_pair(name, i));
}
| [
"quang.vu@sumokoin.org"
] | quang.vu@sumokoin.org |
8aabe79f0859ffd2c29a0e519ddc5e0a901dc92d | 82597438550782d228ccba2a182fa48c8f90ce18 | /Value Oriented ADT/1310/CSC1310/CD.h | 523236d3dbaec395b396076d54af5703a8fa2658 | [] | no_license | HoldenHA/CSC1310 | 5d423eeb5ef58a007f409034d90c851c80418cf9 | 27fcfd8d6321486578730ad6596a22abfcd32db4 | refs/heads/master | 2021-08-30T18:28:32.348626 | 2017-12-19T00:59:31 | 2017-12-19T00:59:31 | 114,416,877 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | h | #if !defined CD_H
#define CD_H
#include "Song.h"
#include "Text.h"
using CSC1310::String;
#include "ListArray.h"
using CSC1310::ListArray;
namespace CSC1310
{
class CD
{
private:
String* artist;
String* title;
int year;
int rating;
int num_tracks;
ListArray<Song>* songs;
public:
CD(String* artist, String* title, int year, int rating, int num_tracks);
virtual ~CD();
String* getKey();
String* getArtist();
void addSong(String* title, String* length);
void displayCD();
static ListArray<CD>* readCDs(const char* file_name);
static int compare_items(CD* one, CD* two);
static int compare_keys(String* sk, CD* cd);
static char getRadixChar(CD* cd, int index); //1-based
};
}
#endif
| [
"itsholden@gmail.com"
] | itsholden@gmail.com |
594b6833bce2ac6cb87174b4007a7d9f1e8706c8 | cefd6c17774b5c94240d57adccef57d9bba4a2e9 | /Data/include/Poco/Data/SimpleRowFormatter.h | e8c67fc34c6066a2262b07982847be27ee08eb08 | [
"BSL-1.0"
] | permissive | adzhou/oragle | 9c054c25b24ff0a65cb9639bafd02aac2bcdce8b | 5442d418b87d0da161429ffa5cb83777e9b38e4d | refs/heads/master | 2022-11-01T05:04:59.368831 | 2014-03-12T15:50:08 | 2014-03-12T15:50:08 | 17,238,063 | 0 | 1 | BSL-1.0 | 2022-10-18T04:23:53 | 2014-02-27T05:39:44 | C++ | UTF-8 | C++ | false | false | 3,752 | h | //
// RowFormatter.h
//
// $Id: //poco/Main/Data/include/Poco/Data/SimpleRowFormatter.h#1 $
//
// Library: Data
// Package: DataCore
// Module: SimpleRowFormatter
//
// Definition of the RowFormatter class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Data_SimpleRowFormatter_INCLUDED
#define Data_SimpleRowFormatter_INCLUDED
#include "Poco/Data/Data.h"
#include "Poco/Data/RowFormatter.h"
namespace Poco {
namespace Data {
class Data_API SimpleRowFormatter: public RowFormatter
/// A simple row formatting class.
{
public:
//typedef RowFormatter::NameVec NameVec;
//typedef RowFormatter::NameVecPtr NameVecPtr;
//typedef RowFormatter::ValueVec ValueVec;
static const int DEFAULT_COLUMN_WIDTH = 16;
SimpleRowFormatter(std::streamsize columnWidth = DEFAULT_COLUMN_WIDTH);
/// Creates the SimpleRowFormatter and sets the column width to specified value.
SimpleRowFormatter(const SimpleRowFormatter& other);
/// Creates the copy of the supplied SimpleRowFormatter.
SimpleRowFormatter& operator = (const SimpleRowFormatter& row);
/// Assignment operator.
~SimpleRowFormatter();
/// Destroys the SimpleRowFormatter.
void swap(SimpleRowFormatter& other);
/// Swaps the row formatter with another one.
std::string& formatNames(const NameVecPtr pNames, std::string& formattedNames);
/// Formats the row field names.
std::string& formatValues(const ValueVec& vals, std::string& formattedValues);
/// Formats the row values.
int rowCount() const;
/// Returns row count.
void setColumnWidth(std::streamsize width);
/// Sets the column width.
std::streamsize getColumnWidth() const;
/// Returns the column width.
private:
std::streamsize _colWidth;
int _rowCount;
};
///
/// inlines
///
inline int SimpleRowFormatter::rowCount() const
{
return _rowCount;
}
inline void SimpleRowFormatter::setColumnWidth(std::streamsize columnWidth)
{
_colWidth = columnWidth;
}
inline std::streamsize SimpleRowFormatter::getColumnWidth() const
{
return _colWidth;
}
} } // namespace Poco::Data
namespace std
{
template<>
inline void swap<Poco::Data::SimpleRowFormatter>(Poco::Data::SimpleRowFormatter& s1,
Poco::Data::SimpleRowFormatter& s2)
/// Full template specalization of std:::swap for SimpleRowFormatter
{
s1.swap(s2);
}
}
#endif // Data_SimpleRowFormatter_INCLUDED
| [
"adzhou@hp.com"
] | adzhou@hp.com |
512561db2c3cf7feb4cbc93c567534955f66de17 | 6d610c9256fc17e833383e4d2c873482870b2094 | /ofApp.cpp | 9a30c8ea8167cc56dc645a0c710555db306c6858 | [] | no_license | junkiyoshi/Insta20180307 | 369571382738522a80a952e1b401fa8d52419b93 | 29c1dc226e90b4e424ffd7a12bd182a2b10e6ae9 | refs/heads/master | 2020-04-07T11:21:59.444760 | 2018-03-07T08:51:52 | 2018-03-07T08:51:52 | 124,207,053 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,080 | cpp | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup() {
ofSetFrameRate(60);
ofBackground(239);
ofSetWindowTitle("Insta");
ofSetRectMode(ofRectMode::OF_RECTMODE_CENTER);
}
//--------------------------------------------------------------
void ofApp::update() {
}
//--------------------------------------------------------------
void ofApp::draw() {
ofTranslate(ofGetWidth() / 2, ofGetHeight() / 2);
float size = 100;
for (int i = 60; i > 0; i--) {
float deg = ofNoise(i * 0.005 + ofGetFrameNum() * 0.005) * 720;
float x = (i * 5) * cos(deg * DEG_TO_RAD);
float y = (i * 5) * sin(deg * DEG_TO_RAD);
ofPoint point = ofPoint(x, y);
ofPushMatrix();
ofTranslate(point);
ofRotate(deg);
ofFill();
ofSetColor(239);
ofDrawRectangle(ofPoint(0, 0), size, size);
ofNoFill();
ofSetColor(39);
ofDrawRectangle(ofPoint(0, 0), size, size);
ofPopMatrix();
}
}
//--------------------------------------------------------------
int main() {
ofSetupOpenGL(720, 720, OF_WINDOW);
ofRunApp(new ofApp());
} | [
"nakauchi.k@g-hits.co.jp"
] | nakauchi.k@g-hits.co.jp |
52f685f95787d97d8432d8fff68366dc56a8c5e2 | 1cb28e7f237ff6ca9c3ce7e4cc530185aa98e3de | /ShadowPointLight.cpp | 68f83c1535a44bd2b0b1b2c3f7722d1883cae12e | [] | no_license | jonathanvdc/computer-graphics | 1aa40c7b90ff7dbe5aa2185953eb67f28daa189c | 62b9f518026b4e75b7fcaac6f7048617369c816f | refs/heads/master | 2021-05-06T04:22:43.616582 | 2017-12-21T10:37:27 | 2017-12-21T10:37:27 | 114,994,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,949 | cpp | #include "ShadowPointLight.h"
#include <algorithm>
#include <memory>
#include "IDepthBuffer.h"
#include "ILight.h"
#include "ILightComponent.h"
#include "IProjection.h"
#include "ISurface.h"
#include "ITransformation.h"
#include "PixelPosition.h"
#include "ReflectionProperties.h"
#include "Vector2.h"
#include "Vector3.h"
#include "Vector4.h"
using namespace Engine;
/// \brief Creates a shadow point light from the given arguments.
ShadowPointLight::ShadowPointLight(Vector3 Position, std::shared_ptr<ILightComponent> Component, std::shared_ptr<IDepthBuffer> Mask, std::shared_ptr<ITransformation<Vector3>> GlobalTransformation, std::shared_ptr<IProjection> Projection, std::shared_ptr<ITransformation<Vector2>> ShapeTransformation)
: Position(Position), Component(Component), Mask(Mask), GlobalTransformation(GlobalTransformation), Projection(Projection), ShapeTransformation(ShapeTransformation)
{ }
/// \brief Clamps the given integer between the given values.
int ShadowPointLight::Clamp(int Value, int Min, int Max) const
{
return std::max<int>(std::min<int>(Value, Max), Min);
}
/// \brief Gets the light's color for the given point, normal and
/// reflection properties.
Vector4 ShadowPointLight::GetColor(Vector3 Point, Vector3 Normal, ReflectionProperties Properties) const
{
if (this->IsShadowed(Point))
return Vector4();
else
{
auto offset = this->Position - Point;
return this->Component->GetColor(Point, Normal,
offset.Normalize(), Properties);
}
}
/// \brief Determines whether the given point is shadowed by another
/// point.
bool ShadowPointLight::IsShadowed(Vector3 Point) const
{
auto transPt = this->GlobalTransformation->Transform(Point);
auto projPt = this->ShapeTransformation->Transform(this->Projection->Project(transPt));
int width = (int)this->Mask->getWidth() - 1;
int height = (int)this->Mask->getHeight() - 1;
int x1 = this->Clamp((int)projPt.X, 0, width);
int x2 = this->Clamp(x1 + 1, 0, width);
int y1 = this->Clamp((int)projPt.Y, 0, height);
int y2 = this->Clamp(y1 + 1, 0, height);
double alphax = projPt.X - (double)x1;
double alphay = projPt.Y - (double)y1;
double topLeft = this->Mask->getItem(PixelPosition(x1, y1));
double bottomLeft = this->Mask->getItem(PixelPosition(x1, y2));
double topRight = this->Mask->getItem(PixelPosition(x2, y1));
double bottomRight = this->Mask->getItem(PixelPosition(x2, y2));
double top = (1.0 - alphax) * topLeft + alphax * topRight;
double bottom = (1.0 - alphax) * bottomLeft + alphax * bottomRight;
double totalDepth = (1.0 - alphay) * top + alphay * bottom;
double epsilon = 0.0001;
double depth = 1.0 / totalDepth;
double depthDiff = transPt.Z - depth;
return depth * depth > epsilon && depthDiff * depthDiff > epsilon;
} | [
"jonathan.vdc@outlook.com"
] | jonathan.vdc@outlook.com |
aa2995ecdeb47a2e7f5c0717c7c39b6d8ed49c4d | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_new_log_7206.cpp | eeb0c36f15756acb2a5b50c733b6933c7d515324 | [] | 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 | 50 | cpp | fprintf(stderr, "Error: %s\n", htdbm->ctx.errstr); | [
"993273596@qq.com"
] | 993273596@qq.com |
ede492843d83f876fedb3f3937ee7476221b5745 | 5e3db2bd0227ec1a761ee0f3c7100fb2aca8e5fb | /LeetCodeSolutions/peakIndexInMountainArray(2).cpp | c95e53a16c3705dcc720ad296ae85ecb39614161 | [] | no_license | Raunak173/hacktoberfest | e09eaff87c6e2eb12935c03f404c17e20146f9a8 | 1d21f9a314bfb05674fa793a2a80eedceeca6eda | refs/heads/main | 2023-08-16T04:05:09.908878 | 2021-10-14T09:58:14 | 2021-10-14T09:58:14 | 417,076,974 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 331 | cpp | class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int low=0;
int high=arr.size()-1;
while(low<=high)
{
int mid=low+(high-low)/2;
if(arr[mid]<arr[mid+1])
low=mid+1;
else
high=mid-1;
}
return low;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
7b955d2135e65ffacf24c247dc8f7a46c3d05f65 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/make/hunk_1030.cpp | 73c79508b3617ca7a78e670cd913708041e2f2d2 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 492 | cpp | if (jobserver_fds->idx > 1)
fatal (NILF, _("internal error: multiple --jobserver-fds options"));
- /* The combination of a pipe + !job_slots means we're using the
- jobserver. If !job_slots and we don't have a pipe, we can start
- infinite jobs. */
-
- if (job_slots != 0)
- fatal (NILF, _("internal error: --jobserver-fds unexpected"));
-
/* Now parse the fds string and make sure it has the proper format. */
cp = jobserver_fds->list[0];
| [
"993273596@qq.com"
] | 993273596@qq.com |
406552a24d9b1186831a553bd76522048801e324 | 9f3d0bad72a5a0bfa23ace7af8dbf63093be9c86 | /vendor/shaderc/third_party/spirv-tools/test/binary_to_text_test.cpp | d7adae34b681ca729a7897fa9eb1b2043eb17275 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"GPL-3.0-or-later",
"GPL-3.0-only",
"LicenseRef-scancode-khronos",
"LicenseRef-scancode-nvidia-2002",
"MIT",
"BSD-3-Clause",
"Zlib"
] | permissive | 0xc0dec/solo | ec700066951f7ef5c90aee4ae505bb5e85154da2 | 6c7f78da49beb09b51992741df3e47067d1b7e10 | refs/heads/master | 2023-04-27T09:23:15.554730 | 2023-02-26T11:46:16 | 2023-02-26T11:46:16 | 28,027,226 | 37 | 2 | Zlib | 2023-04-19T19:39:31 | 2014-12-15T08:19:32 | C++ | UTF-8 | C++ | false | false | 22,933 | cpp | // Copyright (c) 2015-2016 The Khronos Group Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "unit_spirv.h"
#include <sstream>
#include "gmock/gmock.h"
#include "source/spirv_constant.h"
#include "test_fixture.h"
namespace {
using spvtest::AutoText;
using spvtest::ScopedContext;
using spvtest::TextToBinaryTest;
using std::get;
using std::tuple;
using ::testing::Combine;
using ::testing::Eq;
using ::testing::HasSubstr;
class BinaryToText : public ::testing::Test {
public:
BinaryToText() : context(spvContextCreate(SPV_ENV_UNIVERSAL_1_0)) {}
~BinaryToText() { spvContextDestroy(context); }
virtual void SetUp() {
const char* textStr = R"(
OpSource OpenCL_C 12
OpMemoryModel Physical64 OpenCL
OpSourceExtension "PlaceholderExtensionName"
OpEntryPoint Kernel %1 "foo"
OpExecutionMode %1 LocalSizeHint 1 1 1
%2 = OpTypeVoid
%3 = OpTypeBool
%4 = OpTypeInt 8 0
%5 = OpTypeInt 8 1
%6 = OpTypeInt 16 0
%7 = OpTypeInt 16 1
%8 = OpTypeInt 32 0
%9 = OpTypeInt 32 1
%10 = OpTypeInt 64 0
%11 = OpTypeInt 64 1
%12 = OpTypeFloat 16
%13 = OpTypeFloat 32
%14 = OpTypeFloat 64
%15 = OpTypeVector %4 2
)";
spv_text_t text = {textStr, strlen(textStr)};
spv_diagnostic diagnostic = nullptr;
spv_result_t error =
spvTextToBinary(context, text.str, text.length, &binary, &diagnostic);
if (error) {
spvDiagnosticPrint(diagnostic);
spvDiagnosticDestroy(diagnostic);
ASSERT_EQ(SPV_SUCCESS, error);
}
}
virtual void TearDown() { spvBinaryDestroy(binary); }
// Compiles the given assembly text, and saves it into 'binary'.
void CompileSuccessfully(std::string text) {
spv_diagnostic diagnostic = nullptr;
EXPECT_EQ(SPV_SUCCESS, spvTextToBinary(context, text.c_str(), text.size(),
&binary, &diagnostic));
}
spv_context context;
spv_binary binary;
};
TEST_F(BinaryToText, Default) {
spv_text text = nullptr;
spv_diagnostic diagnostic = nullptr;
ASSERT_EQ(
SPV_SUCCESS,
spvBinaryToText(context, binary->code, binary->wordCount,
SPV_BINARY_TO_TEXT_OPTION_NONE, &text, &diagnostic));
printf("%s", text->str);
spvTextDestroy(text);
}
TEST_F(BinaryToText, MissingModule) {
spv_text text;
spv_diagnostic diagnostic = nullptr;
EXPECT_EQ(
SPV_ERROR_INVALID_BINARY,
spvBinaryToText(context, nullptr, 42, SPV_BINARY_TO_TEXT_OPTION_NONE,
&text, &diagnostic));
EXPECT_THAT(diagnostic->error, Eq(std::string("Missing module.")));
if (diagnostic) {
spvDiagnosticPrint(diagnostic);
spvDiagnosticDestroy(diagnostic);
}
}
TEST_F(BinaryToText, TruncatedModule) {
// Make a valid module with zero instructions.
CompileSuccessfully("");
EXPECT_EQ(SPV_INDEX_INSTRUCTION, binary->wordCount);
for (size_t length = 0; length < SPV_INDEX_INSTRUCTION; length++) {
spv_text text = nullptr;
spv_diagnostic diagnostic = nullptr;
EXPECT_EQ(
SPV_ERROR_INVALID_BINARY,
spvBinaryToText(context, binary->code, length,
SPV_BINARY_TO_TEXT_OPTION_NONE, &text, &diagnostic));
ASSERT_NE(nullptr, diagnostic);
std::stringstream expected;
expected << "Module has incomplete header: only " << length
<< " words instead of " << SPV_INDEX_INSTRUCTION;
EXPECT_THAT(diagnostic->error, Eq(expected.str()));
spvDiagnosticDestroy(diagnostic);
}
}
TEST_F(BinaryToText, InvalidMagicNumber) {
CompileSuccessfully("");
std::vector<uint32_t> damaged_binary(binary->code,
binary->code + binary->wordCount);
damaged_binary[SPV_INDEX_MAGIC_NUMBER] ^= 123;
spv_diagnostic diagnostic = nullptr;
spv_text text;
EXPECT_EQ(
SPV_ERROR_INVALID_BINARY,
spvBinaryToText(context, damaged_binary.data(), damaged_binary.size(),
SPV_BINARY_TO_TEXT_OPTION_NONE, &text, &diagnostic));
ASSERT_NE(nullptr, diagnostic);
std::stringstream expected;
expected << "Invalid SPIR-V magic number '" << std::hex
<< damaged_binary[SPV_INDEX_MAGIC_NUMBER] << "'.";
EXPECT_THAT(diagnostic->error, Eq(expected.str()));
spvDiagnosticDestroy(diagnostic);
}
struct FailedDecodeCase {
std::string source_text;
std::vector<uint32_t> appended_instruction;
std::string expected_error_message;
};
using BinaryToTextFail =
spvtest::TextToBinaryTestBase<::testing::TestWithParam<FailedDecodeCase>>;
TEST_P(BinaryToTextFail, EncodeSuccessfullyDecodeFailed) {
EXPECT_THAT(EncodeSuccessfullyDecodeFailed(GetParam().source_text,
GetParam().appended_instruction),
Eq(GetParam().expected_error_message));
}
INSTANTIATE_TEST_CASE_P(
InvalidIds, BinaryToTextFail,
::testing::ValuesIn(std::vector<FailedDecodeCase>{
{"", spvtest::MakeInstruction(SpvOpTypeVoid, {0}),
"Error: Result Id is 0"},
{"", spvtest::MakeInstruction(SpvOpConstant, {0, 1, 42}),
"Error: Type Id is 0"},
{"%1 = OpTypeVoid", spvtest::MakeInstruction(SpvOpTypeVoid, {1}),
"Id 1 is defined more than once"},
{"%1 = OpTypeVoid\n"
"%2 = OpNot %1 %foo",
spvtest::MakeInstruction(SpvOpNot, {1, 2, 3}),
"Id 2 is defined more than once"},
{"%1 = OpTypeVoid\n"
"%2 = OpNot %1 %foo",
spvtest::MakeInstruction(SpvOpNot, {1, 1, 3}),
"Id 1 is defined more than once"},
// The following are the two failure cases for
// Parser::setNumericTypeInfoForType.
{"", spvtest::MakeInstruction(SpvOpConstant, {500, 1, 42}),
"Type Id 500 is not a type"},
{"%1 = OpTypeInt 32 0\n"
"%2 = OpTypeVector %1 4",
spvtest::MakeInstruction(SpvOpConstant, {2, 3, 999}),
"Type Id 2 is not a scalar numeric type"},
}), );
INSTANTIATE_TEST_CASE_P(
InvalidIdsCheckedDuringLiteralCaseParsing, BinaryToTextFail,
::testing::ValuesIn(std::vector<FailedDecodeCase>{
{"", spvtest::MakeInstruction(SpvOpSwitch, {1, 2, 3, 4}),
"Invalid OpSwitch: selector id 1 has no type"},
{"%1 = OpTypeVoid\n",
spvtest::MakeInstruction(SpvOpSwitch, {1, 2, 3, 4}),
"Invalid OpSwitch: selector id 1 is a type, not a value"},
{"%1 = OpConstantTrue !500",
spvtest::MakeInstruction(SpvOpSwitch, {1, 2, 3, 4}),
"Type Id 500 is not a type"},
{"%1 = OpTypeFloat 32\n%2 = OpConstant %1 1.5",
spvtest::MakeInstruction(SpvOpSwitch, {2, 3, 4, 5}),
"Invalid OpSwitch: selector id 2 is not a scalar integer"},
}), );
TEST_F(TextToBinaryTest, OneInstruction) {
const std::string input = "OpSource OpenCL_C 12\n";
EXPECT_EQ(input, EncodeAndDecodeSuccessfully(input));
}
// Exercise the case where an operand itself has operands.
// This could detect problems in updating the expected-set-of-operands
// list.
TEST_F(TextToBinaryTest, OperandWithOperands) {
const std::string input = R"(OpEntryPoint Kernel %1 "foo"
OpExecutionMode %1 LocalSizeHint 100 200 300
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%1 = OpFunction %1 None %3
)";
EXPECT_EQ(input, EncodeAndDecodeSuccessfully(input));
}
using RoundTripInstructionsTest = spvtest::TextToBinaryTestBase<
::testing::TestWithParam<tuple<spv_target_env, std::string>>>;
TEST_P(RoundTripInstructionsTest, Sample) {
EXPECT_THAT(EncodeAndDecodeSuccessfully(get<1>(GetParam()),
SPV_BINARY_TO_TEXT_OPTION_NONE,
get<0>(GetParam())),
Eq(get<1>(GetParam())));
}
// clang-format off
INSTANTIATE_TEST_CASE_P(
NumericLiterals, RoundTripInstructionsTest,
// This test is independent of environment, so just test the one.
Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1,
SPV_ENV_UNIVERSAL_1_2),
::testing::ValuesIn(std::vector<std::string>{
"%1 = OpTypeInt 12 0\n%2 = OpConstant %1 1867\n",
"%1 = OpTypeInt 12 1\n%2 = OpConstant %1 1867\n",
"%1 = OpTypeInt 12 1\n%2 = OpConstant %1 -1867\n",
"%1 = OpTypeInt 32 0\n%2 = OpConstant %1 1867\n",
"%1 = OpTypeInt 32 1\n%2 = OpConstant %1 1867\n",
"%1 = OpTypeInt 32 1\n%2 = OpConstant %1 -1867\n",
"%1 = OpTypeInt 64 0\n%2 = OpConstant %1 18446744073709551615\n",
"%1 = OpTypeInt 64 1\n%2 = OpConstant %1 9223372036854775807\n",
"%1 = OpTypeInt 64 1\n%2 = OpConstant %1 -9223372036854775808\n",
// 16-bit floats print as hex floats.
"%1 = OpTypeFloat 16\n%2 = OpConstant %1 0x1.ff4p+16\n",
"%1 = OpTypeFloat 16\n%2 = OpConstant %1 -0x1.d2cp-10\n",
// 32-bit floats
"%1 = OpTypeFloat 32\n%2 = OpConstant %1 -3.275\n",
"%1 = OpTypeFloat 32\n%2 = OpConstant %1 0x1.8p+128\n", // NaN
"%1 = OpTypeFloat 32\n%2 = OpConstant %1 -0x1.0002p+128\n", // NaN
"%1 = OpTypeFloat 32\n%2 = OpConstant %1 0x1p+128\n", // Inf
"%1 = OpTypeFloat 32\n%2 = OpConstant %1 -0x1p+128\n", // -Inf
// 64-bit floats
"%1 = OpTypeFloat 64\n%2 = OpConstant %1 -3.275\n",
"%1 = OpTypeFloat 64\n%2 = OpConstant %1 0x1.ffffffffffffap-1023\n", // small normal
"%1 = OpTypeFloat 64\n%2 = OpConstant %1 -0x1.ffffffffffffap-1023\n",
"%1 = OpTypeFloat 64\n%2 = OpConstant %1 0x1.8p+1024\n", // NaN
"%1 = OpTypeFloat 64\n%2 = OpConstant %1 -0x1.0002p+1024\n", // NaN
"%1 = OpTypeFloat 64\n%2 = OpConstant %1 0x1p+1024\n", // Inf
"%1 = OpTypeFloat 64\n%2 = OpConstant %1 -0x1p+1024\n", // -Inf
})), );
// clang-format on
INSTANTIATE_TEST_CASE_P(
MemoryAccessMasks, RoundTripInstructionsTest,
Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1,
SPV_ENV_UNIVERSAL_1_2),
::testing::ValuesIn(std::vector<std::string>{
"OpStore %1 %2\n", // 3 words long.
"OpStore %1 %2 None\n", // 4 words long, explicit final 0.
"OpStore %1 %2 Volatile\n",
"OpStore %1 %2 Aligned 8\n",
"OpStore %1 %2 Nontemporal\n",
// Combinations show the names from LSB to MSB
"OpStore %1 %2 Volatile|Aligned 16\n",
"OpStore %1 %2 Volatile|Nontemporal\n",
"OpStore %1 %2 Volatile|Aligned|Nontemporal 32\n",
})), );
INSTANTIATE_TEST_CASE_P(
FPFastMathModeMasks, RoundTripInstructionsTest,
Combine(
::testing::Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1,
SPV_ENV_UNIVERSAL_1_2),
::testing::ValuesIn(std::vector<std::string>{
"OpDecorate %1 FPFastMathMode None\n",
"OpDecorate %1 FPFastMathMode NotNaN\n",
"OpDecorate %1 FPFastMathMode NotInf\n",
"OpDecorate %1 FPFastMathMode NSZ\n",
"OpDecorate %1 FPFastMathMode AllowRecip\n",
"OpDecorate %1 FPFastMathMode Fast\n",
// Combinations show the names from LSB to MSB
"OpDecorate %1 FPFastMathMode NotNaN|NotInf\n",
"OpDecorate %1 FPFastMathMode NSZ|AllowRecip\n",
"OpDecorate %1 FPFastMathMode NotNaN|NotInf|NSZ|AllowRecip|Fast\n",
})), );
INSTANTIATE_TEST_CASE_P(LoopControlMasks, RoundTripInstructionsTest,
Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_0,
SPV_ENV_UNIVERSAL_1_1,
SPV_ENV_UNIVERSAL_1_2),
::testing::ValuesIn(std::vector<std::string>{
"OpLoopMerge %1 %2 None\n",
"OpLoopMerge %1 %2 Unroll\n",
"OpLoopMerge %1 %2 DontUnroll\n",
"OpLoopMerge %1 %2 Unroll|DontUnroll\n",
})), );
INSTANTIATE_TEST_CASE_P(LoopControlMasksV11, RoundTripInstructionsTest,
Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_1,
SPV_ENV_UNIVERSAL_1_2),
::testing::ValuesIn(std::vector<std::string>{
"OpLoopMerge %1 %2 DependencyInfinite\n",
"OpLoopMerge %1 %2 DependencyLength 8\n",
})), );
INSTANTIATE_TEST_CASE_P(SelectionControlMasks, RoundTripInstructionsTest,
Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_0,
SPV_ENV_UNIVERSAL_1_1,
SPV_ENV_UNIVERSAL_1_2),
::testing::ValuesIn(std::vector<std::string>{
"OpSelectionMerge %1 None\n",
"OpSelectionMerge %1 Flatten\n",
"OpSelectionMerge %1 DontFlatten\n",
"OpSelectionMerge %1 Flatten|DontFlatten\n",
})), );
INSTANTIATE_TEST_CASE_P(FunctionControlMasks, RoundTripInstructionsTest,
Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_0,
SPV_ENV_UNIVERSAL_1_1,
SPV_ENV_UNIVERSAL_1_2),
::testing::ValuesIn(std::vector<std::string>{
"%2 = OpFunction %1 None %3\n",
"%2 = OpFunction %1 Inline %3\n",
"%2 = OpFunction %1 DontInline %3\n",
"%2 = OpFunction %1 Pure %3\n",
"%2 = OpFunction %1 Const %3\n",
"%2 = OpFunction %1 Inline|Pure|Const %3\n",
"%2 = OpFunction %1 DontInline|Const %3\n",
})), );
INSTANTIATE_TEST_CASE_P(
ImageMasks, RoundTripInstructionsTest,
Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_0, SPV_ENV_UNIVERSAL_1_1,
SPV_ENV_UNIVERSAL_1_2),
::testing::ValuesIn(std::vector<std::string>{
"%2 = OpImageFetch %1 %3 %4\n",
"%2 = OpImageFetch %1 %3 %4 None\n",
"%2 = OpImageFetch %1 %3 %4 Bias %5\n",
"%2 = OpImageFetch %1 %3 %4 Lod %5\n",
"%2 = OpImageFetch %1 %3 %4 Grad %5 %6\n",
"%2 = OpImageFetch %1 %3 %4 ConstOffset %5\n",
"%2 = OpImageFetch %1 %3 %4 Offset %5\n",
"%2 = OpImageFetch %1 %3 %4 ConstOffsets %5\n",
"%2 = OpImageFetch %1 %3 %4 Sample %5\n",
"%2 = OpImageFetch %1 %3 %4 MinLod %5\n",
"%2 = OpImageFetch %1 %3 %4 Bias|Lod|Grad %5 %6 %7 %8\n",
"%2 = OpImageFetch %1 %3 %4 ConstOffset|Offset|ConstOffsets"
" %5 %6 %7\n",
"%2 = OpImageFetch %1 %3 %4 Sample|MinLod %5 %6\n",
"%2 = OpImageFetch %1 %3 %4"
" Bias|Lod|Grad|ConstOffset|Offset|ConstOffsets|Sample|MinLod"
" %5 %6 %7 %8 %9 %10 %11 %12 %13\n"})), );
INSTANTIATE_TEST_CASE_P(
NewInstructionsInSPIRV1_2, RoundTripInstructionsTest,
Combine(::testing::Values(SPV_ENV_UNIVERSAL_1_2),
::testing::ValuesIn(std::vector<std::string>{
"OpExecutionModeId %1 SubgroupsPerWorkgroupId %2\n",
"OpExecutionModeId %1 LocalSizeId %2 %3 %4\n",
"OpExecutionModeId %1 LocalSizeHintId %2\n",
"OpDecorateId %1 AlignmentId %2\n",
"OpDecorateId %1 MaxByteOffsetId %2\n",
})), );
using MaskSorting = TextToBinaryTest;
TEST_F(MaskSorting, MasksAreSortedFromLSBToMSB) {
EXPECT_THAT(EncodeAndDecodeSuccessfully(
"OpStore %1 %2 Nontemporal|Aligned|Volatile 32"),
Eq("OpStore %1 %2 Volatile|Aligned|Nontemporal 32\n"));
EXPECT_THAT(
EncodeAndDecodeSuccessfully(
"OpDecorate %1 FPFastMathMode NotInf|Fast|AllowRecip|NotNaN|NSZ"),
Eq("OpDecorate %1 FPFastMathMode NotNaN|NotInf|NSZ|AllowRecip|Fast\n"));
EXPECT_THAT(
EncodeAndDecodeSuccessfully("OpLoopMerge %1 %2 DontUnroll|Unroll"),
Eq("OpLoopMerge %1 %2 Unroll|DontUnroll\n"));
EXPECT_THAT(
EncodeAndDecodeSuccessfully("OpSelectionMerge %1 DontFlatten|Flatten"),
Eq("OpSelectionMerge %1 Flatten|DontFlatten\n"));
EXPECT_THAT(EncodeAndDecodeSuccessfully(
"%2 = OpFunction %1 DontInline|Const|Pure|Inline %3"),
Eq("%2 = OpFunction %1 Inline|DontInline|Pure|Const %3\n"));
EXPECT_THAT(EncodeAndDecodeSuccessfully(
"%2 = OpImageFetch %1 %3 %4"
" MinLod|Sample|Offset|Lod|Grad|ConstOffsets|ConstOffset|Bias"
" %5 %6 %7 %8 %9 %10 %11 %12 %13\n"),
Eq("%2 = OpImageFetch %1 %3 %4"
" Bias|Lod|Grad|ConstOffset|Offset|ConstOffsets|Sample|MinLod"
" %5 %6 %7 %8 %9 %10 %11 %12 %13\n"));
}
using OperandTypeTest = TextToBinaryTest;
TEST_F(OperandTypeTest, OptionalTypedLiteralNumber) {
const std::string input =
"%1 = OpTypeInt 32 0\n"
"%2 = OpConstant %1 42\n"
"OpSwitch %2 %3 100 %4\n";
EXPECT_EQ(input, EncodeAndDecodeSuccessfully(input));
}
using IndentTest = spvtest::TextToBinaryTest;
TEST_F(IndentTest, Sample) {
const std::string input = R"(
OpCapability Shader
OpMemoryModel Logical GLSL450
%1 = OpTypeInt 32 0
%2 = OpTypeStruct %1 %3 %4 %5 %6 %7 %8 %9 %10 ; force IDs into double digits
%11 = OpConstant %1 42
OpStore %2 %3 Aligned|Volatile 4 ; bogus, but not indented
)";
const std::string expected =
R"( OpCapability Shader
OpMemoryModel Logical GLSL450
%1 = OpTypeInt 32 0
%2 = OpTypeStruct %1 %3 %4 %5 %6 %7 %8 %9 %10
%11 = OpConstant %1 42
OpStore %2 %3 Volatile|Aligned 4
)";
EXPECT_THAT(
EncodeAndDecodeSuccessfully(input, SPV_BINARY_TO_TEXT_OPTION_INDENT),
expected);
}
using FriendlyNameDisassemblyTest = spvtest::TextToBinaryTest;
TEST_F(FriendlyNameDisassemblyTest, Sample) {
const std::string input = R"(
OpCapability Shader
OpMemoryModel Logical GLSL450
%1 = OpTypeInt 32 0
%2 = OpTypeStruct %1 %3 %4 %5 %6 %7 %8 %9 %10 ; force IDs into double digits
%11 = OpConstant %1 42
)";
const std::string expected =
R"(OpCapability Shader
OpMemoryModel Logical GLSL450
%uint = OpTypeInt 32 0
%_struct_2 = OpTypeStruct %uint %3 %4 %5 %6 %7 %8 %9 %10
%uint_42 = OpConstant %uint 42
)";
EXPECT_THAT(EncodeAndDecodeSuccessfully(
input, SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES),
expected);
}
TEST_F(TextToBinaryTest, ShowByteOffsetsWhenRequested) {
const std::string input = R"(
OpCapability Shader
OpMemoryModel Logical GLSL450
%1 = OpTypeInt 32 0
%2 = OpTypeVoid
)";
const std::string expected =
R"(OpCapability Shader ; 0x00000014
OpMemoryModel Logical GLSL450 ; 0x0000001c
%1 = OpTypeInt 32 0 ; 0x00000028
%2 = OpTypeVoid ; 0x00000038
)";
EXPECT_THAT(EncodeAndDecodeSuccessfully(
input, SPV_BINARY_TO_TEXT_OPTION_SHOW_BYTE_OFFSET),
expected);
}
// Test version string.
TEST_F(TextToBinaryTest, VersionString) {
auto words = CompileSuccessfully("");
spv_text decoded_text = nullptr;
EXPECT_THAT(spvBinaryToText(ScopedContext().context, words.data(),
words.size(), SPV_BINARY_TO_TEXT_OPTION_NONE,
&decoded_text, &diagnostic),
Eq(SPV_SUCCESS));
EXPECT_EQ(nullptr, diagnostic);
EXPECT_THAT(decoded_text->str, HasSubstr("Version: 1.0\n"))
<< EncodeAndDecodeSuccessfully("");
spvTextDestroy(decoded_text);
}
// Test generator string.
// A test case for the generator string. This allows us to
// test both of the 16-bit components of the generator word.
struct GeneratorStringCase {
uint16_t generator;
uint16_t misc;
std::string expected;
};
using GeneratorStringTest = spvtest::TextToBinaryTestBase<
::testing::TestWithParam<GeneratorStringCase>>;
TEST_P(GeneratorStringTest, Sample) {
auto words = CompileSuccessfully("");
EXPECT_EQ(2u, SPV_INDEX_GENERATOR_NUMBER);
words[SPV_INDEX_GENERATOR_NUMBER] =
SPV_GENERATOR_WORD(GetParam().generator, GetParam().misc);
spv_text decoded_text = nullptr;
EXPECT_THAT(spvBinaryToText(ScopedContext().context, words.data(),
words.size(), SPV_BINARY_TO_TEXT_OPTION_NONE,
&decoded_text, &diagnostic),
Eq(SPV_SUCCESS));
EXPECT_THAT(diagnostic, Eq(nullptr));
EXPECT_THAT(std::string(decoded_text->str), HasSubstr(GetParam().expected));
spvTextDestroy(decoded_text);
}
INSTANTIATE_TEST_CASE_P(GeneratorStrings, GeneratorStringTest,
::testing::ValuesIn(std::vector<GeneratorStringCase>{
{SPV_GENERATOR_KHRONOS, 12, "Khronos; 12"},
{SPV_GENERATOR_LUNARG, 99, "LunarG; 99"},
{SPV_GENERATOR_VALVE, 1, "Valve; 1"},
{SPV_GENERATOR_CODEPLAY, 65535, "Codeplay; 65535"},
{SPV_GENERATOR_NVIDIA, 19, "NVIDIA; 19"},
{SPV_GENERATOR_ARM, 1000, "ARM; 1000"},
{SPV_GENERATOR_KHRONOS_LLVM_TRANSLATOR, 38,
"Khronos LLVM/SPIR-V Translator; 38"},
{SPV_GENERATOR_KHRONOS_ASSEMBLER, 2,
"Khronos SPIR-V Tools Assembler; 2"},
{SPV_GENERATOR_KHRONOS_GLSLANG, 1,
"Khronos Glslang Reference Front End; 1"},
{1000, 18, "Unknown(1000); 18"},
{65535, 32767, "Unknown(65535); 32767"},
}), );
} // anonymous namespace
| [
"0xc0dec@gmail.com"
] | 0xc0dec@gmail.com |
c1a096ba1c1b4fe6f3fcd3f90d667172003be994 | 0b6617ba233ad141411cbf55531b036f765ede31 | /ImageIdentification/build/include/QCAR/MultiTarget.h | 4873299cc2794075b208a31a5c1ab6b76f0b3cea | [] | no_license | nofailyoung/ImageIdentification | a33d77a9163d2cdde1bdff54397e285e08c8c7f4 | 68ad65fc9d21dd678ee81cea29610edff967b3c4 | refs/heads/master | 2021-01-18T16:40:26.995496 | 2015-03-23T03:34:54 | 2015-03-23T03:34:54 | 62,685,794 | 1 | 0 | null | 2016-07-06T02:46:45 | 2016-07-06T02:46:45 | null | UTF-8 | C++ | false | false | 3,464 | h | /*===============================================================================
Copyright (c) 2010-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
Vuforia is a trademark of QUALCOMM Incorporated, registered in the United States
and other countries. Trademarks of QUALCOMM Incorporated are used with permission.
@file
MultiTarget.h
@brief
Header file for MultiTarget class.
===============================================================================*/
#ifndef _QCAR_MULTITARGET_H_
#define _QCAR_MULTITARGET_H_
// Include files
#include <Trackable.h>
#include <ObjectTarget.h>
#include <Matrices.h>
#include <Trackable.h>
namespace QCAR
{
// Forward declarations
struct Matrix34F;
/// A set of multiple targets with a fixed spatial relation
/**
* Methods to modify a MultiTarget must not be called while the
* corresponding DataSet is active. The dataset must be deactivated first
* before reconfiguring a MultiTarget.
*/
class QCAR_API MultiTarget : public ObjectTarget
{
public:
/// Returns the Trackable class' type
static Type getClassType();
/// Returns the number of Trackables that form the MultiTarget.
virtual int getNumParts() const = 0;
/// Provides write access to a specific Trackable.
/**
* Returns NULL if the index is invalid.
*/
virtual Trackable* getPart(int idx) = 0;
/// Provides read-only access to a specific Trackable.
/**
* Returns NULL if the index is invalid.
*/
virtual const Trackable* getPart(int idx) const = 0;
/// Provides write access to a specific Trackable.
/**
* Returns NULL if no Trackable with the given name exists
* in the MultiTarget.
*/
virtual Trackable* getPart(const char* name) = 0;
/// Provides read-only access to a specific Trackable.
/**
* Returns NULL if no Trackable with the given name exists
* in the MultiTarget.
*/
virtual const Trackable* getPart(const char* name) const = 0;
/// Adds a Trackable to the MultiTarget.
/**
* Returns the index of the new part on success.
* Returns -1 in case of error, e.g. when adding a Part that is already
* added or if the corresponding DataSet is currently active. Use the
* returned index to set the Part's pose via setPartPose().
*/
virtual int addPart(Trackable* trackable) = 0;
/// Removes a Trackable from the MultiTarget.
/**
* Returns true on success.
* Returns false if the index is invalid or if the corresponding DataSet
* is currently active.
*/
virtual bool removePart(int idx) = 0;
/// Defines a Part's spatial offset to the MultiTarget center
/**
* Per default a new Part has zero offset (no translation, no rotation).
* In this case the pose of the Part is identical with the pose of the
* MultiTarget. If there is more than one Part in a MultiTarget
* then at least one must have an offset, or the Parts are co-located.
* Returns false if the index is invalid or if the corresponding DataSet
* is currently active.
*/
virtual bool setPartOffset(int idx, const Matrix34F& offset) = 0;
/// Retrieves the spatial offset of a Part to the MultiTarget center
/**
* Returns false if the Part's index is invalid.
*/
virtual bool getPartOffset(int idx, Matrix34F& offset) const = 0;
};
} // namespace QCAR
#endif //_QCAR_MULTITARGET_H_
| [
"zjjmusic@163.com"
] | zjjmusic@163.com |
8c54229cdc0d02bfa666d67088ada7b932b758bb | 81b23315fdba81c40ac8934f2e1d990d968eb1ef | /statement_table.cpp | 53498799f8524eb77a281d94ec3dd9d348b4d5c6 | [] | no_license | yuu511/Compilers_CS104a | 52889e8b342bff0f5c17944c03f7bb08da426b31 | 3106e3392a145e0575747c4df5bfd77e71548bad | refs/heads/master | 2020-05-18T16:10:01.986384 | 2019-08-26T11:05:09 | 2019-08-26T11:05:09 | 184,513,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 314 | cpp | #include "statement_table.h"
statement::statement (astree *expr_,reg *t0_ ){
expr = expr_;
t0 = t0_;
condition = nullptr;
label = nullptr;
op = nullptr;
t1 = nullptr;
t2 = nullptr;
}
statement::~statement(){
delete label;
delete condition;
delete t0;
delete op;
delete t1;
delete t2;
}
| [
"pipimi@tfwno.gf"
] | pipimi@tfwno.gf |
1db4b8cae5e7bc0a0479dc08f7e684909f8418ce | 8d9f708fb5683300ab4fdf33be0e456d73855c82 | /Coursework/Coursework/SwordBladeMesh.cpp | 0d4c523530c60f5f9a1462a1e1c80bdecfbbec0a | [] | no_license | teseabrook/Honours-Project | e21902934a11acfab2a357fba4f5538db1db1775 | 86fbfd1af49f7bece4b6fdf72d0c822eb49872b7 | refs/heads/main | 2023-07-19T05:06:01.286077 | 2021-09-07T15:52:01 | 2021-09-07T15:52:01 | 316,050,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,125 | cpp | #include "SwordBladeMesh.h"
#define DEBUG_SCALE_FACTOR 25.0f
SwordBladeMesh::SwordBladeMesh(ID3D11Device* device, ID3D11DeviceContext* deviceContext, ParameterSet* a_set, int lresolution)
{
set = a_set;
resolution = lresolution;
initBuffers(device);
}
SwordBladeMesh::~SwordBladeMesh()
{
BaseMesh::~BaseMesh();
}
void SwordBladeMesh::initBuffers(ID3D11Device* device)
{
VertexType* vertices;
unsigned long* indices;
D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
D3D11_SUBRESOURCE_DATA vertexData, indexData;
// 6 vertices per quad, res*res is face, times 6 for each face
vertexCount = 40;
indexCount = 400;
// Create the vertex and index array.
vertices = new VertexType[vertexCount];
indices = new unsigned long[indexCount];
vertices[0].position = XMFLOAT3(0, -((set->getBBreadth() / DEBUG_SCALE_FACTOR) * 0.5) , 0);
vertices[0].texture = XMFLOAT2(0, 0);
vertices[0].normal = XMFLOAT3(0.0f, -1.0f, 0.0f);
vertices[1].position = XMFLOAT3((set->getBWidth() / DEBUG_SCALE_FACTOR) * 0.5, -((set->getBBreadth() / DEBUG_SCALE_FACTOR) * 0.5) + (set->getFWidth() / DEBUG_SCALE_FACTOR), 0);
vertices[1].texture = XMFLOAT2(0, 0);
vertices[1].normal = XMFLOAT3(1.0f, -1.0f, 0.0f);
vertices[2].position = XMFLOAT3(0, ((set->getBBreadth() / DEBUG_SCALE_FACTOR) * 0.5), 0);
vertices[2].texture = XMFLOAT2(0, 0);
vertices[2].normal = XMFLOAT3(0.0f, 1.0f, 0.0f);
vertices[3].position = XMFLOAT3(-((set->getBWidth() / DEBUG_SCALE_FACTOR) * 0.5), -((set->getBBreadth() / DEBUG_SCALE_FACTOR) * 0.5) + (set->getFWidth() / DEBUG_SCALE_FACTOR), 0);
vertices[3].texture = XMFLOAT2(0, 0);
vertices[3].normal = XMFLOAT3(-1.0f, -1.0f, 0.0f);
vertices[4].position = XMFLOAT3(0, -((set->getBBreadth() / DEBUG_SCALE_FACTOR) * 0.5), (set->getBLength() / DEBUG_SCALE_FACTOR));
vertices[4].texture = XMFLOAT2(0, 0);
vertices[4].normal = XMFLOAT3(0.0f, -1.0f, 1.0f);
vertices[5].position = XMFLOAT3((set->getBWidth() / DEBUG_SCALE_FACTOR) * 0.5, -((set->getBBreadth() / DEBUG_SCALE_FACTOR) * 0.5) + (set->getFWidth() / DEBUG_SCALE_FACTOR), (set->getBLength() / DEBUG_SCALE_FACTOR));
vertices[5].texture = XMFLOAT2(0, 0);
vertices[5].normal = XMFLOAT3(1.0f, -1.0f, 1.0f);
vertices[6].position = XMFLOAT3(0, ((set->getBBreadth() / DEBUG_SCALE_FACTOR) * 0.5), (set->getBLength() / DEBUG_SCALE_FACTOR));
vertices[6].texture = XMFLOAT2(0, 0);
vertices[6].normal = XMFLOAT3(0.0f, 1.0f, 1.0f);
vertices[7].position = XMFLOAT3(-((set->getBWidth() / DEBUG_SCALE_FACTOR) * 0.5), -((set->getBBreadth() / DEBUG_SCALE_FACTOR) * 0.5) + (set->getFWidth() / DEBUG_SCALE_FACTOR), (set->getBLength() / DEBUG_SCALE_FACTOR));
vertices[7].texture = XMFLOAT2(0, 0);
vertices[7].normal = XMFLOAT3(-1.0f, -1.0f, 1.0f);
vertices[4].position.y -= (set->getHCLength() / DEBUG_SCALE_FACTOR);
vertices[5].position.y -= (set->getHCLength() / DEBUG_SCALE_FACTOR);
vertices[6].position.y -= (set->getHCLength() / DEBUG_SCALE_FACTOR);
vertices[7].position.y -= (set->getHCLength() / DEBUG_SCALE_FACTOR);
vertices[4].position.z -= ((set->getHCLength() / DEBUG_SCALE_FACTOR) / 2);
vertices[5].position.z -= ((set->getHCLength() / DEBUG_SCALE_FACTOR) / 4);
vertices[7].position.z -= ((set->getHCLength() / DEBUG_SCALE_FACTOR) / 4);
//Now we interpolate
//Between P2 and 3
XMFLOAT3 distance, newPoint;
float m;
distance = XMFLOAT3(vertices[2].position.x - vertices[3].position.x, vertices[2].position.y - vertices[3].position.y, vertices[2].position.z - vertices[3].position.z);
m = sqrt(distance.x * distance.x + distance.y * distance.y + distance.z + distance.z);
distance.x /= m;
distance.y /= m;
distance.z /= m;
newPoint.x = ((float)vertices[3].position.x + distance.x * (m / 4));
newPoint.y = ((float)vertices[3].position.y + distance.y * (m / 4));
newPoint.z = ((float)vertices[3].position.z + distance.z * (m / 4));
vertices[8].position = newPoint;
vertices[8].texture = XMFLOAT2(0, 0);
vertices[8].normal = XMFLOAT3(0.0f, -1.0f, 0.0f);
newPoint.x = ((float)vertices[3].position.x + distance.x * (m / 2));
newPoint.y = ((float)vertices[3].position.y + distance.y * (m / 2));
newPoint.z = ((float)vertices[3].position.z + distance.z * (m / 2));
vertices[9].position = newPoint;
vertices[9].texture = XMFLOAT2(0, 0);
vertices[9].normal = XMFLOAT3(0.0f, -1.0f, 0.0f);
newPoint.x = ((float)vertices[3].position.x + distance.x * (m * 3 / 4));
newPoint.y = ((float)vertices[3].position.y + distance.y * (m * 3 / 4));
newPoint.z = ((float)vertices[3].position.z + distance.z * (m * 3 / 4));
vertices[10].position = newPoint;
vertices[10].texture = XMFLOAT2(0, 0);
vertices[10].normal = XMFLOAT3(0.0f, -1.0f, 0.0f);
distance = XMFLOAT3(vertices[9].position.x - 0, vertices[9].position.y - vertices[9].position.y, vertices[9].position.z - vertices[9].position.z);
m = sqrt(distance.x * distance.x + distance.y * distance.y + distance.z + distance.z);
distance.x /= m;
distance.y /= m;
distance.z /= m;
newPoint.x = ((float)vertices[8].position.x - distance.x * (m / 4));
newPoint.y = ((float)vertices[8].position.y - distance.y * (m / 4));
newPoint.z = ((float)vertices[8].position.z - distance.z * (m / 4));
vertices[11].position = newPoint;
vertices[11].texture = XMFLOAT2(0, 0);
vertices[11].normal = XMFLOAT3(-1.0f, 1.0f, 0.0f);
newPoint.x = ((float)vertices[9].position.x - distance.x * (m / 3));
newPoint.y = ((float)vertices[9].position.y - distance.y * (m / 3));
newPoint.z = ((float)vertices[9].position.z - distance.z * (m / 3));
vertices[12].position = newPoint;
vertices[12].texture = XMFLOAT2(0, 0);
vertices[12].normal = XMFLOAT3(-1.0f, 1.0f, 0.0f);
newPoint.x = ((float)vertices[10].position.x - distance.x * (m / 4));
newPoint.y = ((float)vertices[10].position.y - distance.y * (m / 4));
newPoint.z = ((float)vertices[10].position.z - distance.z * (m / 4));
vertices[13].position = newPoint;
vertices[13].texture = XMFLOAT2(0, 0);
vertices[13].normal = XMFLOAT3(-1.0f, 1.0f, 0.0f);
vertices[14].position = vertices[11].position;
vertices[14].position.x = -vertices[11].position.x;
vertices[14].texture = XMFLOAT2(0, 0);
vertices[14].normal = XMFLOAT3(1.0f, 1.0f, 0.0f);
vertices[15].position = vertices[12].position;
vertices[15].position.x = -vertices[12].position.x;
vertices[15].texture = XMFLOAT2(0, 0);
vertices[15].normal = XMFLOAT3(1.0f, 1.0f, 0.0f);
vertices[16].position = vertices[13].position;
vertices[16].position.x = -vertices[13].position.x;
vertices[16].texture = XMFLOAT2(0, 0);
vertices[16].normal = XMFLOAT3(1.0f, 1.0f, 0.0f);
vertices[17].position = vertices[11].position;
vertices[17].position.z = set->getBLength() / DEBUG_SCALE_FACTOR;
vertices[17].texture = XMFLOAT2(0, 0);
vertices[17].normal = vertices[11].normal;
vertices[18].position = vertices[12].position;
vertices[18].position.z = set->getBLength() / DEBUG_SCALE_FACTOR;
vertices[18].texture = XMFLOAT2(0, 0);
vertices[18].normal = vertices[12].normal;
vertices[19].position = vertices[13].position;
vertices[19].position.z = set->getBLength() / DEBUG_SCALE_FACTOR;
vertices[19].texture = XMFLOAT2(0, 0);
vertices[19].normal = vertices[13].normal;
vertices[20].position = vertices[14].position;
vertices[20].position.z = set->getBLength() / DEBUG_SCALE_FACTOR;
vertices[20].texture = XMFLOAT2(0, 0);
vertices[20].normal = vertices[14].normal;
vertices[21].position = vertices[15].position;
vertices[21].position.z = set->getBLength() / DEBUG_SCALE_FACTOR;
vertices[21].texture = XMFLOAT2(0, 0);
vertices[21].normal = vertices[15].normal;
vertices[22].position = vertices[16].position;
vertices[22].position.z = set->getBLength() / DEBUG_SCALE_FACTOR;
vertices[22].texture = XMFLOAT2(0, 0);
vertices[22].normal = vertices[16].normal;
//Now between 3 and 0
distance = XMFLOAT3(vertices[3].position.x - vertices[0].position.x, vertices[3].position.y - vertices[0].position.y, vertices[3].position.z - vertices[0].position.z);
m = sqrt(distance.x * distance.x + distance.y * distance.y + distance.z + distance.z);
distance.x /= m;
distance.y /= m;
distance.z /= m;
newPoint.x = ((float)vertices[3].position.x - distance.x * (m / 4));
newPoint.y = ((float)vertices[3].position.y - distance.y * (m / 4));
newPoint.z = ((float)vertices[3].position.z - distance.z * (m / 4));
vertices[23].position = newPoint;
vertices[23].texture = XMFLOAT2(0, 0);
vertices[23].normal = XMFLOAT3(0.0f, -1.0f, 0.0f);
newPoint.x = ((float)vertices[3].position.x - distance.x * (m / 2));
newPoint.y = ((float)vertices[3].position.y - distance.y * (m / 2));
newPoint.z = ((float)vertices[3].position.z - distance.z * (m / 2));
vertices[24].position = newPoint;
vertices[24].texture = XMFLOAT2(0, 0);
vertices[24].normal = XMFLOAT3(0.0f, -1.0f, 0.0f);
newPoint.x = ((float)vertices[3].position.x - distance.x * (m * 3 / 4));
newPoint.y = ((float)vertices[3].position.y - distance.y * (m * 3 / 4));
newPoint.z = ((float)vertices[3].position.z - distance.z * (m * 3 / 4));
vertices[25].position = newPoint;
vertices[25].texture = XMFLOAT2(0, 0);
vertices[25].normal = XMFLOAT3(0.0f, -1.0f, 0.0f);
distance = XMFLOAT3(vertices[24].position.x - 0, vertices[24].position.y - vertices[24].position.y, vertices[24].position.z - vertices[24].position.z);
m = sqrt(distance.x * distance.x + distance.y * distance.y + distance.z + distance.z);
distance.x /= m;
distance.y /= m;
distance.z /= m;
newPoint.x = ((float)vertices[23].position.x - distance.x * (m / 6));
newPoint.y = ((float)vertices[23].position.y - distance.y * (m / 6));
newPoint.z = ((float)vertices[23].position.z - distance.z * (m / 6));
vertices[26].position = newPoint;
vertices[26].texture = XMFLOAT2(0, 0);
vertices[26].normal = XMFLOAT3(-1.0f, -1.0f, 0.0f);
newPoint.x = ((float)vertices[24].position.x - distance.x * (m / 4));
newPoint.y = ((float)vertices[24].position.y - distance.y * (m / 4));
newPoint.z = ((float)vertices[24].position.z - distance.z * (m / 4));
vertices[27].position = newPoint;
vertices[27].texture = XMFLOAT2(0, 0);
vertices[27].normal = XMFLOAT3(-1.0f, -1.0f, 0.0f);
newPoint.x = ((float)vertices[25].position.x - distance.x * (m / 6));
newPoint.y = ((float)vertices[25].position.y - distance.y * (m / 6));
newPoint.z = ((float)vertices[25].position.z - distance.z * (m / 6));
vertices[28].position = newPoint;
vertices[28].texture = XMFLOAT2(0, 0);
vertices[28].normal = XMFLOAT3(-1.0f, -1.0f, 0.0f);
vertices[29].position = vertices[26].position;
vertices[29].position.x = -vertices[26].position.x;
vertices[29].texture = XMFLOAT2(0, 0);
vertices[29].normal = XMFLOAT3(1.0f, -1.0f, 0.0f);
vertices[30].position = vertices[27].position;
vertices[30].position.x = -vertices[27].position.x;
vertices[30].texture = XMFLOAT2(0, 0);
vertices[30].normal = XMFLOAT3(1.0f, -1.0f, 0.0f);
vertices[31].position = vertices[28].position;
vertices[31].position.x = -vertices[28].position.x;
vertices[31].texture = XMFLOAT2(0, 0);
vertices[31].normal = XMFLOAT3(1.0f, -1.0f, 0.0f);
vertices[32].position = vertices[26].position;
vertices[32].position.z = set->getBLength() / DEBUG_SCALE_FACTOR;
vertices[32].texture = XMFLOAT2(0, 0);
vertices[32].normal = vertices[26].normal;
vertices[33].position = vertices[27].position;
vertices[33].position.z = set->getBLength() / DEBUG_SCALE_FACTOR;
vertices[33].texture = XMFLOAT2(0, 0);
vertices[33].normal = vertices[27].normal;
vertices[34].position = vertices[28].position;
vertices[34].position.z = set->getBLength() / DEBUG_SCALE_FACTOR;
vertices[34].texture = XMFLOAT2(0, 0);
vertices[34].normal = vertices[28].normal;
vertices[35].position = vertices[29].position;
vertices[35].position.z = set->getBLength() / DEBUG_SCALE_FACTOR;
vertices[35].texture = XMFLOAT2(0, 0);
vertices[35].normal = vertices[29].normal;
vertices[36].position = vertices[30].position;
vertices[36].position.z = set->getBLength() / DEBUG_SCALE_FACTOR;
vertices[36].texture = XMFLOAT2(0, 0);
vertices[36].normal = vertices[30].normal;
vertices[37].position = vertices[31].position;
vertices[37].position.z = set->getBLength() / DEBUG_SCALE_FACTOR;
vertices[37].texture = XMFLOAT2(0, 0);
vertices[37].normal = vertices[31].normal;
vertices[38].position = XMFLOAT3(0, vertices[4].position.y, vertices[4].position.z + (set->getPLength() / DEBUG_SCALE_FACTOR));
vertices[38].texture = XMFLOAT2(0, 0);
vertices[38].normal = XMFLOAT3(0.0f, 0.0f, 1.0f);
//face 1
/*indices[0] = 0;
indices[1] = 1;
indices[2] = 3;
indices[3] = 0;
indices[4] = 3;
indices[5] = 1;
indices[6] = 3;
indices[7] = 2;
indices[8] = 1;
indices[9] = 3;
indices[10] = 1;
indices[11] = 2;
//face 2
indices[12] = 4;
indices[13] = 5;
indices[14] = 7;
indices[15] = 4;
indices[16] = 7;
indices[17] = 5;
indices[18] = 7;
indices[19] = 6;
indices[20] = 5;
indices[21] = 7;
indices[22] = 5;
indices[23] = 6;*/
/*indices[24] = 6;
indices[25] = 8;
indices[26] = 3;
indices[27] = 6;
indices[28] = 3;
indices[29] = 8;
indices[30] = 6;
indices[31] = 8;
indices[32] = 9;
indices[33] = 6;
indices[34] = 9;
indices[35] = 8;
indices[36] = 6;
indices[37] = 10;
indices[38] = 9;
indices[39] = 6;
indices[40] = 9;
indices[41] = 10;
indices[42] = 6;
indices[43] = 10;
indices[44] = 2;
indices[45] = 6;
indices[46] = 2;
indices[47] = 10;*/
int iCounter = 0;
int a, b, c, d, e, f, g, h, i, j;
a = 2;
b = 3;
c = 13;
d = 12;
e = 11;
f = 6;
g = 7;
h = 19;
i = 18;
j = 17;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = g;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = g;
iCounter++;
a = 2;
b = 1;
c = 16;
d = 15;
e = 14;
f = 6;
g = 5;
h = 22;
i = 21;
j = 20;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = g;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = g;
iCounter++;
a = 3;
b = 0;
c = 26;
d = 27;
e = 28;
f = 7;
g = 4;
h = 32;
i = 33;
j = 34;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = g;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = g;
iCounter++;
a = 1;
b = 0;
c = 29;
d = 30;
e = 31;
f = 5;
g = 4;
h = 35;
i = 36;
j = 37;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = h;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = i;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = g;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = j;
iCounter++;
indices[iCounter] = g;
iCounter++;
//Sword Point
a = 38;
b = 6;
c = 7;
d = 19;
e = 18;
f = 17;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = c;
iCounter++;
b = 6;
c = 7;
d = 19;
e = 18;
f = 17;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = c;
iCounter++;
b = 4;
c = 7;
d = 34;
e = 33;
f = 32;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = c;
iCounter++;
b = 4;
c = 5;
d = 37;
e = 36;
f = 35;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = b;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = d;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = e;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = c;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = a;
iCounter++;
indices[iCounter] = f;
iCounter++;
indices[iCounter] = c;
iCounter++;
// Set up the description of the static vertex buffer.
vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(VertexType)* vertexCount;
vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;
vertexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the vertex data.
vertexData.pSysMem = vertices;
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;
// Now create the vertex buffer.
device->CreateBuffer(&vertexBufferDesc, &vertexData, &vertexBuffer);
// Set up the description of the static index buffer.
indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long)* indexCount;
indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;
indexBufferDesc.StructureByteStride = 0;
// Give the subresource structure a pointer to the index data.
indexData.pSysMem = indices;
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;
// Create the index buffer.
device->CreateBuffer(&indexBufferDesc, &indexData, &indexBuffer);
// Release the arrays now that the vertex and index buffers have been created and loaded.
delete[] vertices;
vertices = 0;
delete[] indices;
indices = 0;
}
| [
"1600045@uad.ac.uk"
] | 1600045@uad.ac.uk |
40b067488a1dcbbb0c1c6addb79c6aa5d057a0a1 | 9be33fe923f68f0738fc0fa1da3a24609e53801f | /jump_search/jump_search.cpp | 7e613f798f1c7e9e78c323766a72ceda1c11e20e | [] | no_license | rohitsh16/CP_mathematics | 807a1ca00f13c6b982dc880032eeaef2d4db7382 | 909226b24d0449e33e62e288469eefb9feda7341 | refs/heads/master | 2021-07-12T08:31:51.846353 | 2020-07-14T16:10:59 | 2020-07-14T16:10:59 | 212,121,573 | 3 | 72 | null | 2023-03-29T19:59:19 | 2019-10-01T14:45:07 | C++ | UTF-8 | C++ | false | false | 825 | cpp | #include <bits/stdc++.h>
using namespace std;
int jumpSearch(int arr[], int x, int n)
{
int step = sqrt(n);
int prev = 0;
while (arr[min(step, n)-1] < x)
{
prev = step;
step += sqrt(n);
if (prev >= n)
return -1;
}
while (arr[prev] < x)
{
prev++;
if (prev == min(step, n))
return -1;
}
if (arr[prev] == x)
return prev;
return -1;
}
int main()
{
int n,i;
cout<<"Eneter size of array : ";
cin>>n;
cout<<"Enter elements of array"<<endl;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
cout<<"Enter key to be searched : ";
int key;
cin>>key;
int index = jumpSearch(a, key, n);
cout << "\nNumber " << key << " is at index " << index;
return 0;
}
| [
"himanshu.shekharjha.272@gmail.com"
] | himanshu.shekharjha.272@gmail.com |
8c4f854425be2156558d5f7874dd04d6cdcac524 | 8b2182e95b5441c3ed7497b8443cff5b0237f35c | /C5Dlg.cpp | d8afcdf44213060ad3d21a3dd211455aa89dbf37 | [] | no_license | Jeremy-625/C-plus-project | 9b850a86a1a6ce67353114514c5cef2da77bd482 | f0c03efaae83f54a4ef870b65915c87d499ea3f2 | refs/heads/master | 2022-04-19T01:56:35.756217 | 2020-04-10T07:22:32 | 2020-04-10T07:22:32 | 254,570,894 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,223 | cpp |
// C5Dlg.cpp: 实现文件
//
#include "pch.h"
#include "framework.h"
#include "C5.h"
#include "C5Dlg.h"
#include "afxdialogex.h"
#include "CDialogLogin.h"
#include <iostream>
#include <fstream>
#include "course.h"
#include "student.h"
using namespace std;
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
int isg = 0; //判断是否为研究生
int order = 0; //学生序号
Student* tmp; //登录学生
extern Course cou[12]; //课程信息
extern Ugstudent ugstu[30]; //本科生信息
extern Gstudent gstu[15]; //研究生信息
CDialogLogin login; //登录窗口
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CC5Dlg 对话框
CC5Dlg::CC5Dlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_C5_DIALOG, pParent)
, m_name(_T(""))
, m_id(_T(""))
, m_type(_T(""))
, m_credit(0)
, m_tuition(0)
, m_select(0)
, m_quit(0)
, m_numall(0)
, m_teacher(_T(""))
{
m_hIcon = AfxGetApp()->LoadIcon(IDI_ICON1);
//更改图标
}
void CC5Dlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, m_name);
DDX_Text(pDX, IDC_EDIT2, m_id);
DDX_Text(pDX, IDC_EDIT3, m_type);
DDX_Text(pDX, IDC_EDIT4, m_credit);
DDX_Text(pDX, IDC_EDIT5, m_tuition);
DDX_Control(pDX, IDC_LIST2, m_list);
DDX_Control(pDX, IDC_LIST3, m_list2);
DDX_Text(pDX, IDC_EDIT6, m_select);
DDX_Text(pDX, IDC_EDIT7, m_quit);
DDX_Text(pDX, IDC_EDIT8, m_numall);
DDX_Text(pDX, IDC_EDIT9, m_teacher);
}
BEGIN_MESSAGE_MAP(CC5Dlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST2, &CC5Dlg::OnLvnItemchangedList2)
ON_EN_CHANGE(IDC_EDIT7, &CC5Dlg::OnEnChangeEdit7)
ON_BN_CLICKED(IDC_BUTTON6, &CC5Dlg::OnBnClickedButton6)
ON_BN_CLICKED(IDC_BUTTON3, &CC5Dlg::OnBnClickedButton3)
ON_BN_CLICKED(IDC_BUTTON4, &CC5Dlg::OnBnClickedButton4)
ON_BN_CLICKED(IDC_BUTTON5, &CC5Dlg::OnBnClickedButton5)
END_MESSAGE_MAP()
// CC5Dlg 消息处理程序
BOOL CC5Dlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != nullptr)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
cou[0].initial();
ugstu[0].initial();
gstu[0].initial(); //初始化
login.DoModal(); //打开登录窗口
if (isg)
tmp = &gstu[order];
else
tmp = &ugstu[order]; //切换对象
CString name(tmp->getname());
m_name = name; //获取学生姓名
CString id(tmp->getid());
m_id = id; //获取学生学号
if (isg)
{
m_type = TEXT("研究生"); //获取学生类别
}
else
{
m_type = TEXT("本科生");
}
m_credit = tmp->getcredit(); //获取学生学分
m_tuition = tmp->calculate(); //获取学生学费
m_numall = cou->courseNumAll; //获取总选课数
CString teacher(tmp->getteachername());
m_teacher = teacher;
//更新列表1
CString list[] = { TEXT("序号"),TEXT("类型"),TEXT("名称"),TEXT("学分"),TEXT("人数") };
m_list.InsertColumn(0, list[0], LVCFMT_LEFT, 50);
m_list.InsertColumn(1, list[1], LVCFMT_LEFT, 80);
m_list.InsertColumn(2, list[2], LVCFMT_LEFT, 120);
m_list.InsertColumn(3, list[3], LVCFMT_LEFT, 50);
m_list.InsertColumn(4, list[4], LVCFMT_LEFT, 80);
for (int i = 0; i < 12; i++)
{
CString index;
index.Format(TEXT("%d"), cou[i].courseOrder);
m_list.InsertItem(i, index);//序号
CString type(cou[i].courseType);
m_list.SetItemText(i, 1,type);//类型
CString name(cou[i].courseName);
m_list.SetItemText(i, 2, name);//名称
CString credit;
credit.Format(TEXT("%d"), cou[i].courseCredit);
m_list.SetItemText(i, 3, credit);//学分
CString num;
num.Format(TEXT("%d/%d"), cou[i].courseNum,15);
m_list.SetItemText(i, 4, num);//人数
}
//更新列表2
CString list2[] = { TEXT("课程序号"),TEXT("名称"),TEXT("学分") };
m_list2.InsertColumn(0, list2[0], LVCFMT_LEFT, 80);
m_list2.InsertColumn(1, list2[1], LVCFMT_LEFT, 110);
m_list2.InsertColumn(2, list2[2], LVCFMT_LEFT, 50);
for (int i = 0; i < tmp->studentSelect; i++)
{
CString index;
index.Format(TEXT("%d"), tmp->studentCourse[i]->courseOrder);
m_list2.InsertItem(i, index);//序号
CString name(tmp->studentCourse[i]->courseName);
m_list2.SetItemText(i, 1, name);//名称
CString credit;
credit.Format(TEXT("%d"), tmp->studentCourse[i]->courseCredit);
m_list2.SetItemText(i, 2, credit);//学分
}
UpdateData(false);
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CC5Dlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CC5Dlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CC5Dlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CC5Dlg::OnLvnItemchangedList2(NMHDR* pNMHDR, LRESULT* pResult)
{
LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
// TODO: 在此添加控件通知处理程序代码
*pResult = 0;
}
void CC5Dlg::OnEnChangeEdit7()
{
// TODO: 如果该控件是 RICHEDIT 控件,它将不
// 发送此通知,除非重写 CDialogEx::OnInitDialog()
// 函数并调用 CRichEditCtrl().SetEventMask(),
// 同时将 ENM_CHANGE 标志“或”运算到掩码中。
// TODO: 在此添加控件通知处理程序代码
}
void CC5Dlg::OnBnClickedButton6()
{
// TODO: 在此添加控件通知处理程序代码
exit(0);
}
void CC5Dlg::OnBnClickedButton3() //选课
{
// TODO: 在此添加控件通知处理程序代码
UpdateData(true);
for (int i = 0; i < tmp->studentSelect; i++)
if (tmp->studentCourse[i]->courseOrder == m_select)
{
MessageBox(TEXT("重复选课"));
return;
}
if (tmp->studentSelect == 5)
{
MessageBox(TEXT("选课数已达上限"));
return;
}
if (cou[m_select - 1].courseNum == 15)
{
MessageBox(TEXT("该课程人数已满"));
return;
}
tmp->studentCourse[tmp->studentSelect] = &cou[m_select-1];
cou[m_select-1].addNum();
tmp->studentSelect++;
m_list2.DeleteAllItems();
for (int i = 0; i < tmp->studentSelect; i++)
{
CString index;
index.Format(TEXT("%d"), tmp->studentCourse[i]->courseOrder);
m_list2.InsertItem(i, index);//序号
CString name(tmp->studentCourse[i]->courseName);
m_list2.SetItemText(i, 1, name);//名称
CString credit;
credit.Format(TEXT("%d"), tmp->studentCourse[i]->courseCredit);
m_list2.SetItemText(i, 2, credit);//学分
}
m_list.DeleteAllItems();
for (int i = 0; i < 12; i++)
{
CString index;
index.Format(TEXT("%d"), cou[i].courseOrder);
m_list.InsertItem(i, index);//序号
CString type(cou[i].courseType);
m_list.SetItemText(i, 1, type);//类型
CString name(cou[i].courseName);
m_list.SetItemText(i, 2, name);//名称
CString credit;
credit.Format(TEXT("%d"), cou[i].courseCredit);
m_list.SetItemText(i, 3, credit);//学分
CString num;
num.Format(TEXT("%d/%d"), cou[i].courseNum, 15);
m_list.SetItemText(i, 4, num);//人数
}
m_credit = tmp->getcredit();
m_tuition = tmp->calculate();
m_numall = cou->courseNumAll;
UpdateData(false);
}
void CC5Dlg::OnBnClickedButton4()//退课
{
// TODO: 在此添加控件通知处理程序代码
int flag = 1;
UpdateData(true);
for (int i = 0; i < tmp->studentSelect; i++)
if (tmp->studentCourse[i]->courseOrder == m_quit)
{
flag = 0;
break;
}
if (flag)
{
MessageBox(TEXT("退课错误"));
return;
}
for(int i=0;i<tmp->studentSelect;i++)
if (tmp->studentCourse[i]->courseOrder == m_quit)
{
int j = i + 1;
for (j; j < tmp->studentSelect; j++)
tmp->studentCourse[j - 1] = tmp->studentCourse[j];
tmp->studentSelect--;
cou[m_quit-1].subNum();
}
m_list2.DeleteAllItems();
for (int i = 0; i < tmp->studentSelect; i++)
{
CString index;
index.Format(TEXT("%d"), tmp->studentCourse[i]->courseOrder);
m_list2.InsertItem(i, index);//序号
CString name(tmp->studentCourse[i]->courseName);
m_list2.SetItemText(i, 1, name);//名称
CString credit;
credit.Format(TEXT("%d"), tmp->studentCourse[i]->courseCredit);
m_list2.SetItemText(i, 2, credit);//学分
}
m_list.DeleteAllItems();
for (int i = 0; i < 12; i++)
{
CString index;
index.Format(TEXT("%d"), cou[i].courseOrder);
m_list.InsertItem(i, index);//序号
CString type(cou[i].courseType);
m_list.SetItemText(i, 1, type);//类型
CString name(cou[i].courseName);
m_list.SetItemText(i, 2, name);//名称
CString credit;
credit.Format(TEXT("%d"), cou[i].courseCredit);
m_list.SetItemText(i, 3, credit);//学分
CString num;
num.Format(TEXT("%d/%d"), cou[i].courseNum, 15);
m_list.SetItemText(i, 4, num);//人数
}
m_credit = tmp->getcredit();
m_tuition = tmp->calculate();
m_numall = cou->courseNumAll;
UpdateData(false);
}
void CC5Dlg::OnOK()
{
// TODO: 在此添加专用代码和/或调用基类
//CDialogEx::OnOK();
}
void CC5Dlg::OnBnClickedButton5()
{
// TODO: 在此添加控件通知处理程序代码
login.DoModal();
m_list.DeleteAllItems();
m_list2.DeleteAllItems();
if (isg)
tmp = &gstu[order];
else
tmp = &ugstu[order];
CString name(tmp->getname());
m_name = name;
CString id(tmp->getid());
m_id = id;
if (isg)
m_type = TEXT("研究生");
else
m_type = TEXT("本科生");
m_credit = tmp->getcredit();
m_tuition = tmp->calculate();
m_numall = cou->courseNumAll;
CString teacher(tmp->getteachername());
m_teacher = teacher;
m_select = 0;
m_quit = 0;
for (int i = 0; i < 12; i++)
{
CString index;
index.Format(TEXT("%d"), cou[i].courseOrder);
m_list.InsertItem(i, index);//序号
CString type(cou[i].courseType);
m_list.SetItemText(i, 1, type);//类型
CString name(cou[i].courseName);
m_list.SetItemText(i, 2, name);//名称
CString credit;
credit.Format(TEXT("%d"), cou[i].courseCredit);
m_list.SetItemText(i, 3, credit);//学分
CString num;
num.Format(TEXT("%d/%d"), cou[i].courseNum, 15);
m_list.SetItemText(i, 4, num);//人数
}
for (int i = 0; i < tmp->studentSelect; i++)
{
CString index;
index.Format(TEXT("%d"), tmp->studentCourse[i]->courseOrder);
m_list2.InsertItem(i, index);//序号
CString name(tmp->studentCourse[i]->courseName);
m_list2.SetItemText(i, 1, name);//名称
CString credit;
credit.Format(TEXT("%d"), tmp->studentCourse[i]->courseCredit);
m_list2.SetItemText(i, 2, credit);//学分
}
UpdateData(false);
}
| [
"15225100519@163.com"
] | 15225100519@163.com |
da5000a3d0d1c9d8b316cea434f266bf0706aea6 | 1e6ce42f127c99be9946f46fc0f1ed135c847d5b | /casnake/casnake/Casnake_Main.cpp | 78b4338e64d33d0468b30e998938c03478d0c961 | [] | no_license | OchaParadise/casnake | 5f48376e3c3af1efdb6984d278e46b64cfb7e979 | 2e47b542db6fa95f22e3c75330b80e6f7a0c572d | refs/heads/master | 2016-09-06T18:56:10.198226 | 2012-10-08T13:11:58 | 2012-10-08T13:11:58 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,672 | cpp | #include "DxLib.h"
#include "Variable.h"
#include "Calc.h"
#include "Init.h"
#include "MapMake.h"
#include "Display.h"
#include "Character.h"
#include "Item.h"
#include <Windows.h>
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow )
{
Init init;
Display Disp;
MapMake mapmake;
Character character;
Variable variable;
Item item;
int IsContinue = IDYES;
///// メニュー画面 /////
init.Dxlib_init();
init.Load_init_menu();
////////////////////////
WaitTimer(100);
Disp.Introduction();
////// 画像読み込み /////
if(IsQuarter == IDNO){
init.Load_init();
}else{
init.Load_init_Q();
}
/////////////////////////
// エンターキー入力待ち
while(CheckHitKey(KEY_INPUT_RETURN) == 0){
if(ProcessMessage() == -1){
break;
}
}
//WaitKey();
while(IsContinue == IDYES)
{
///// 初期化 /////
mapmake.map_init();
item.item_init();
//////////////////
////// mapを作る /////
_rect first_split_rect = {0, 0, MAP_W -1, MAP_H -1};
mapmake.rect_split(&first_split_rect, 3);
mapmake.room_make();
mapmake.list_to_map();
//////////////////////
////// アイテム設置 //////
item.set_item();
//////////////////////////
////// 入力検知や描画処理(ゲーム本体) //////
IsContinue = Disp.game_loop(IsContinue);
////////////////////////////////
////// コンテナ等の中身をカラに //////
variable.VariableClear();
//////////////////////////////////////
}
// 感謝!
Disp.Thanks();
WaitKey();
DxLib_End();
return 0;
} | [
"mcmlxxxvi.viii.xvii+github@gmail.com"
] | mcmlxxxvi.viii.xvii+github@gmail.com |
bf64dacbf6f17fa835de1c079445ebfc3bdea269 | c16d1e8a2dc835f73306a209f3b2da2cbcc7ae54 | /201604-1.cpp | b51de454c5b0ee09573ef4d85903137b92b63fc0 | [] | no_license | starkwj/OJ_CSP | 20b6082d993996d4171e11c84f7be67c1a0cca93 | 77152af997710c05272da5532a74a48c99a95222 | refs/heads/master | 2020-03-29T01:26:06.427653 | 2018-09-19T03:47:10 | 2018-09-19T03:47:10 | 149,388,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 293 | cpp | #include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
int cnt = 0;
for (int i = 1; i < n - 1; i++)
{
if ((a[i] - a[i - 1]) * (a[i + 1] - a[i]) < 0)
{
cnt++;
}
}
cout << cnt << endl;
return 0;
}
| [
"792732547@qq.com"
] | 792732547@qq.com |
64796bf4204162244f2258a8e42616405e5c5257 | e212b4b554bb80664dd25c3213f981c18bbdf0bf | /backup/rotate.cpp | 0ded67fe6e092704c0e75b8295f4b224258616eb | [] | no_license | DavidLoftus/kattis | 60fd7ea22252e2553cceb68dbc9c8d545c390108 | 27a558529f00a0bc5337048fd0b0855a40e00295 | refs/heads/master | 2020-04-01T20:26:41.236098 | 2020-01-07T21:13:09 | 2020-01-07T21:13:09 | 153,604,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 550 | cpp | #include <iostream>
#include <string>
#include <algorithm>
int main()
{
int N;
std::string s;
while(std::cin >> N >> s)
{
std::reverse(s.begin(), s.end());
for(char& c : s)
{
if(c == '_')
c = 'Z'+1;
else if(c == '.')
c = 'Z'+2;
c = (c - 'A' + N) % 28 + 'A';
if(c == 'Z'+1)
c = '_';
else if(c == 'Z'+2)
c = '.';
}
std::cout << s << std::endl;
}
return 0;
}
| [
"43099493+DavidLoftus@users.noreply.github.com"
] | 43099493+DavidLoftus@users.noreply.github.com |
a8fdb3f3a2f956206218816f0399805eec9a4ce8 | 1777a7938f9ae00a731aa9afcfdbf83246e41c67 | /gtkproto2/src/shootingcontrol.cpp | 159375e1a1c0c6462d5f28d751cb8c22922a218e | [] | no_license | NaggieOgasawara/gtk3 | 38d03417678335c86c5b682f9baa559a895a3ac5 | fc5cb77b2bbcec4906ce160bb535c26efc25b3a2 | refs/heads/master | 2020-12-02T23:50:12.559888 | 2020-01-01T00:45:42 | 2020-01-01T00:45:42 | 231,091,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 876 | cpp | #include "shootingcontrol.h"
#include <cairomm/context.h>
ShootingControl::ShootingControl()
{
m_background = new BackGround;
m_StarLayer = new StarLayer;
m_EnemyLayer = new EnemyLayer;
/*
m_enemy[ 0 ] = new EnemyTemplate( 0, 2 );
for( int i = 1; i < ENEMY_NUM; i++ )
{
m_enemy[ i ] = new EnemyTemplate( i );
// m_enemy[ i ]->setNo(i);
}
*/
}
ShootingControl::~ShootingControl()
{
}
void ShootingControl::Draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
// draw BackGround
m_background->Draw( cr );
// draw Star
m_StarLayer->Draw( cr );
// draw Enemy
m_EnemyLayer->Draw( cr );
/*
for( int i = 0; i < ENEMY_NUM; i++)
m_enemy[ i ]->Draw( cr );
*/
}
void ShootingControl::Move()
{
// 星を動かす
m_StarLayer->Move();
m_EnemyLayer->Move();
/*
for( int i = 0; i < ENEMY_NUM; i++)
m_enemy[ i ]->Move();
*/
}
| [
"nagakazu.ogasawara@gmail.com"
] | nagakazu.ogasawara@gmail.com |
541cddf8bcde88f63b414626ffb4b4aea5f8abba | 8b5a558fac20370c650d758fe19b3d411ca985ea | /Ejercicios 2ª Evaluación Funciones/Ejercicio_4.cpp | 9fb1d28deadd7df9f885f42a5b419b4c6a1e23ed | [] | no_license | DanielCoduras/2-Evaluacion | b26df0b719bf62837fd27a75a7b4d694d6dd7562 | 87ae4ee1393352d4b74fd29ac28817e33826b407 | refs/heads/master | 2020-04-21T00:53:47.567664 | 2019-02-28T15:47:13 | 2019-02-28T15:47:13 | 169,208,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 622 | cpp | #include<stdio.h>
int main(){
int mes;
printf("Escribe un numero entre 1-12: ");scanf("%i",&mes);
switch(mes){
case 1: printf("Enero");break;
case 2:printf("Febrero");break;
case 3:printf("Marzo");break;
case 4:printf("Abril");break;
case 5:printf("Mayo");break;
case 6:printf("Junio");break;
case 7:printf("Julio");break;
case 8:printf("Agosto");break;
case 9:printf("Septiembre");break;
case 10:printf("Octubre");break;
case 11:printf("Noviembre");break;
case 12:printf("Diciembre");break;
default: printf("Numero no valido para mes");
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
b5aa4cdb22f3435efce2e6fac8883efd34c2b891 | 64a1533f4541b76181cd6d3cec3b28876c969250 | /LADS/ValC/GUI/FMXTemplates.cpp | 4cfcb182b928b4affd0aeec80e9eb71fb5f85040 | [] | no_license | drkvogel/retrasst | df1db3330115f6e2eea7afdb869e070a28c1cae8 | ee952fe39cf1a00998b00a09ca361fc7c83fa336 | refs/heads/master | 2020-05-16T22:53:26.565996 | 2014-08-01T16:52:16 | 2014-08-01T16:52:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 359 | cpp | #include "FMXTemplates.h"
#include "Require.h"
namespace valcui
{
void setText( TStyledControl* control, const char* textSubcomponentName, const std::string& text )
{
TText* textSubcomponent = (TText*) control->FindStyleResource(textSubcomponentName);
throwUnless(textSubcomponent);
textSubcomponent->Text = text.c_str();
}
}
| [
"chris.bird@ctsu.ox.ac.uk"
] | chris.bird@ctsu.ox.ac.uk |
245e7d3e6bb0177d1836e8aea42dc0e63c5525cc | 7d814cf427952e2c81e0768a7c36b15c5af21262 | /kernel/algorithms/loader.cpp | bd75dae7fa81e5c80d54bf3de168551dd671ce2d | [] | no_license | komorowskilab/Parallel-ROSETTA | e2b9ee90a4bbe4f79546026e9d00abcc38ae3f5d | 60112009f4cc29f943e37d0fda86d1b28344fd3c | refs/heads/master | 2020-08-18T05:18:18.000368 | 2019-10-22T13:12:53 | 2019-10-22T13:12:53 | 215,751,254 | 2 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,152 | cpp | //-------------------------------------------------------------------
// Author........: Aleksander šhrn
// Date..........:
// Description...:
// Revisions.....: Aš 000211: Full rewrite.
//===================================================================
#include <stdafx.h> // Precompiled headers.
#include <copyright.h>
#include <kernel/algorithms/loader.h>
#include <kernel/algorithms/keyword.h>
#include <kernel/structures/structure.h>
//-------------------------------------------------------------------
// Methods for class Loader.
//===================================================================
//-------------------------------------------------------------------
// Constructors/destructor.
//===================================================================
Loader::Loader() {
filename_ = Undefined::String();
}
Loader::~Loader() {
}
//-------------------------------------------------------------------
// Methods inherited from Identifier.
//===================================================================
IMPLEMENTIDMETHODS(Loader, LOADER, ScriptAlgorithm)
//-------------------------------------------------------------------
// Methods inherited from Algorithm.
//===================================================================
//-------------------------------------------------------------------
// Method........: GetParameters
// Author........: Aleksander šhrn
// Date..........:
// Description...:
// Comments......:
// Revisions.....:
//===================================================================
String
Loader::GetParameters() const {
String parameters;
// Filename.
parameters += Keyword::Filename();
parameters += Keyword::Assignment();
parameters += GetFilename();
return parameters;
}
//-------------------------------------------------------------------
// Method........: SetParameter
// Author........: Aleksander šhrn
// Date..........:
// Description...:
// Comments......:
// Revisions.....:
//===================================================================
bool
Loader::SetParameter(const String &keyword, const String &value) {
// Filename.
if (keyword == Keyword::Filename())
return SetFilename(value);
return false;
}
//-------------------------------------------------------------------
// Method........: IsApplicable
// Author........: Aleksander šhrn
// Date..........:
// Description...:
// Comments......:
// Revisions.....:
//===================================================================
bool
Loader::IsApplicable(const Structure &/*structure*/, bool /*warn*/) const {
return true;
}
//-------------------------------------------------------------------
// Method........: Apply
// Author........: Aleksander šhrn
// Date..........:
// Description...:
// Comments......:
// Revisions.....:
//===================================================================
Structure *
Loader::Apply(Structure &structure) const {
// Check applicability.
if (!IsApplicable(structure))
return NULL;
// Load.
if (!structure.Load(GetFilename()))
return NULL;
return &structure;
}
Loader *
Loader::Clone() {
return new Loader;
}
| [
"Komorowskilab@gmail.com"
] | Komorowskilab@gmail.com |
bf03e3baae7fcf97fab4904c78779aaa46795b55 | 905f9d0efaedaf2f80892bd1e08b28d717629668 | /client.h | 22c3a91c949e65bbfd6aa58ecbdd6d0b9ee526c2 | [] | no_license | mirub/Client-Server-app | c3583846b0bc5c9998f518bb6b3c51821627b9a1 | 1b3225b61dfc5c4652651f97365ad67536944c11 | refs/heads/master | 2022-04-27T02:45:42.681331 | 2020-04-26T22:14:49 | 2020-04-26T22:14:49 | 259,022,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 829 | h | #ifndef CLIENT_H
#define CLIENT_H
#include <bits/stdc++.h>
#include "udp_message.h"
struct client {
// The client ID
char clientID[10];
// The file descriptor of the client
int cliFD;
// State of the user
bool online;
// Messages that had not been sent due to
// disconnection
std::queue<UDP_Message> pendingMessages;
// The SF state of each topic
std::map<std::string, int> sfTopic;
client() {}
client(int new_cliFD, bool new_online, std::map<std::string, int> new_sfTopic,
std::queue<UDP_Message> new_pendingMessages, char* new_clientID) {
strcpy(clientID, new_clientID);
cliFD = new_cliFD;
online = new_online;
sfTopic = new_sfTopic;
pendingMessages = new_pendingMessages;
}
};
#endif // CLIENT_H | [
"miru.b99@gmail.com"
] | miru.b99@gmail.com |
bc72f936387297d7bcc11017bfeb584c07ae4a98 | d2e8412c50ed287b77f75d2a418ec5f58c1d5a15 | /src/qt/guiutil.cpp | ccc531785243eb96c2cab01f3ac6061fbab76aa1 | [
"MIT"
] | permissive | Onlax/onlax-project | ff0a79d82c14ade0d401bf3565d80b4d0066532d | 22fd576e28adc2ca5efbeacbc16f1a011f37145b | refs/heads/master | 2020-03-07T20:43:34.794343 | 2018-04-05T19:38:07 | 2018-04-05T19:38:07 | 127,705,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,083 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017-2018 The Solaris developers
// Copyright (c) 2017-2018 The Onlax developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "bitcoinunits.h"
#include "qvalidatedlineedit.h"
#include "walletmodel.h"
#include "init.h"
#include "main.h"
#include "primitives/transaction.h"
#include "protocol.h"
#include "script/script.h"
#include "script/standard.h"
#include "util.h"
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shellapi.h"
#include "shlobj.h"
#include "shlwapi.h"
#endif
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#if BOOST_FILESYSTEM_VERSION >= 3
#include <boost/filesystem/detail/utf8_codecvt_facet.hpp>
#endif
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QDateTime>
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QDoubleValidator>
#include <QFileDialog>
#include <QFont>
#include <QLineEdit>
#include <QSettings>
#include <QTextDocument> // for Qt::mightBeRichText
#include <QThread>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
#if BOOST_FILESYSTEM_VERSION >= 3
static boost::filesystem::detail::utf8_codecvt_facet utf8;
#endif
#if defined(Q_OS_MAC)
extern double NSAppKitVersionNumber;
#if !defined(NSAppKitVersionNumber10_8)
#define NSAppKitVersionNumber10_8 1187
#endif
#if !defined(NSAppKitVersionNumber10_9)
#define NSAppKitVersionNumber10_9 1265
#endif
#endif
#define URI_SCHEME "onlax"
namespace GUIUtil
{
QString dateTimeStr(const QDateTime& date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
#if QT_VERSION >= 0x040800
font.setStyleHint(QFont::Monospace);
#else
font.setStyleHint(QFont::TypeWriter);
#endif
return font;
}
void setupAddressWidget(QValidatedLineEdit* widget, QWidget* parent)
{
parent->setFocusProxy(widget);
widget->setFont(bitcoinAddressFont());
#if QT_VERSION >= 0x040700
// We don't want translators to use own addresses in translations
// and this is the only place, where this address is supplied.
widget->setPlaceholderText(QObject::tr("Enter a Onlax address (e.g. %1)").arg("sKdojfasIfjISwiIi53il1sSd25kLoZtWY"));
#endif
widget->setValidator(new BitcoinAddressEntryValidator(parent));
widget->setCheckValidator(new BitcoinAddressCheckValidator(parent));
}
void setupAmountWidget(QLineEdit* widget, QWidget* parent)
{
QDoubleValidator* amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl& uri, SendCoinsRecipient* out)
{
// return if URI is not valid or is no Onlax: URI
if (!uri.isValid() || uri.scheme() != QString(URI_SCHEME))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
// Trim any following forward slash which may have been added by the OS
if (rv.address.endsWith("/")) {
rv.address.truncate(rv.address.length() - 1);
}
rv.amount = 0;
#if QT_VERSION < 0x050000
QList<QPair<QString, QString> > items = uri.queryItems();
#else
QUrlQuery uriQuery(uri);
QList<QPair<QString, QString> > items = uriQuery.queryItems();
#endif
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) {
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-")) {
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label") {
rv.label = i->second;
fShouldReturnFalse = false;
}
if (i->first == "message") {
rv.message = i->second;
fShouldReturnFalse = false;
} else if (i->first == "amount") {
if (!i->second.isEmpty()) {
if (!BitcoinUnits::parse(BitcoinUnits::ONL, i->second, &rv.amount)) {
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if (out) {
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient* out)
{
// Convert onlax:// to onlax:
//
// Cannot handle this later, because onlax:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if (uri.startsWith(URI_SCHEME "://", Qt::CaseInsensitive)) {
uri.replace(0, std::strlen(URI_SCHEME) + 3, URI_SCHEME ":");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString formatBitcoinURI(const SendCoinsRecipient& info)
{
QString ret = QString(URI_SCHEME ":%1").arg(info.address);
int paramCount = 0;
if (info.amount) {
ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::ONL, info.amount, false, BitcoinUnits::separatorNever));
paramCount++;
}
if (!info.label.isEmpty()) {
QString lbl(QUrl::toPercentEncoding(info.label));
ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
paramCount++;
}
if (!info.message.isEmpty()) {
QString msg(QUrl::toPercentEncoding(info.message));
ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
paramCount++;
}
return ret;
}
bool isDust(const QString& address, const CAmount& amount)
{
CTxDestination dest = CBitcoinAddress(address.toStdString()).Get();
CScript script = GetScriptForDestination(dest);
CTxOut txOut(amount, script);
return txOut.IsDust(::minRelayTxFee);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
#if QT_VERSION < 0x050000
QString escaped = Qt::escape(str);
#else
QString escaped = str.toHtmlEscaped();
#endif
escaped = escaped.replace(" ", " ");
if (fMultiLine) {
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView* view, int column, int role)
{
if (!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if (!selection.isEmpty()) {
// Copy first item
setClipboard(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget* parent, const QString& caption, const QString& dir, const QString& filter, QString* selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if (dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
} else {
myDir = dir;
}
/* Directly convert path to native OS path separators */
QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter));
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if (filter_re.exactMatch(selectedFilter)) {
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if (!result.isEmpty()) {
if (info.suffix().isEmpty() && !selectedSuffix.isEmpty()) {
/* No suffix specified, add selected suffix */
if (!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if (selectedSuffixOut) {
*selectedSuffixOut = selectedSuffix;
}
return result;
}
QString getOpenFileName(QWidget* parent, const QString& caption, const QString& dir, const QString& filter, QString* selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if (dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
} else {
myDir = dir;
}
/* Directly convert path to native OS path separators */
QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter));
if (selectedSuffixOut) {
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if (filter_re.exactMatch(selectedFilter)) {
selectedSuffix = filter_re.cap(1);
}
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if (QThread::currentThread() != qApp->thread()) {
return Qt::BlockingQueuedConnection;
} else {
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint& p, const QWidget* w)
{
QWidget* atW = QApplication::widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget* w)
{
return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDebug)));
}
void openConfigfile()
{
boost::filesystem::path pathConfig = GetConfigFile();
/* Open onlax.conf with the associated application */
if (boost::filesystem::exists(pathConfig))
QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig)));
}
void openMNConfigfile()
{
boost::filesystem::path pathConfig = GetMasternodeConfigFile();
/* Open masternode.conf with the associated application */
if (boost::filesystem::exists(pathConfig))
QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig)));
}
void showBackups()
{
boost::filesystem::path pathBackups = GetDataDir() / "backups";
/* Open folder with default browser */
if (boost::filesystem::exists(pathBackups))
QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathBackups)));
}
void SubstituteFonts(const QString& language)
{
#if defined(Q_OS_MAC)
// Background:
// OSX's default font changed in 10.9 and QT is unable to find it with its
// usual fallback methods when building against the 10.7 sdk or lower.
// The 10.8 SDK added a function to let it find the correct fallback font.
// If this fallback is not properly loaded, some characters may fail to
// render correctly.
//
// The same thing happened with 10.10. .Helvetica Neue DeskInterface is now default.
//
// Solution: If building with the 10.7 SDK or lower and the user's platform
// is 10.9 or higher at runtime, substitute the correct font. This needs to
// happen before the QApplication is created.
#if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8) {
if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9)
/* On a 10.9 - 10.9.x system */
QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
else {
/* 10.10 or later system */
if (language == "zh_CN" || language == "zh_TW" || language == "zh_HK") // traditional or simplified Chinese
QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Heiti SC");
else if (language == "ja") // Japanesee
QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Songti SC");
else
QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Lucida Grande");
}
}
#endif
#endif
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject* parent) : QObject(parent),
size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject* obj, QEvent* evt)
{
if (evt->type() == QEvent::ToolTipChange) {
QWidget* widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if (tooltip.size() > size_threshold && !tooltip.startsWith("<qt")) {
// Escape the current message as HTML and replace \n by <br> if it's not rich text
if (!Qt::mightBeRichText(tooltip))
tooltip = HtmlEscape(tooltip, true);
// Envelop with <qt></qt> to make sure Qt detects every tooltip as rich text
// and style='white-space:pre' to preserve line composition
tooltip = "<qt style='white-space:pre'>" + tooltip + "</qt>";
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
void TableViewLastColumnResizingFixer::connectViewHeadersSignals()
{
connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(on_sectionResized(int, int, int)));
connect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
}
// We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.
void TableViewLastColumnResizingFixer::disconnectViewHeadersSignals()
{
disconnect(tableView->horizontalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(on_sectionResized(int, int, int)));
disconnect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
}
// Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.
// Refactored here for readability.
void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
{
#if QT_VERSION < 0x050000
tableView->horizontalHeader()->setResizeMode(logicalIndex, resizeMode);
#else
tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode);
#endif
}
void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width)
{
tableView->setColumnWidth(nColumnIndex, width);
tableView->horizontalHeader()->resizeSection(nColumnIndex, width);
}
int TableViewLastColumnResizingFixer::getColumnsWidth()
{
int nColumnsWidthSum = 0;
for (int i = 0; i < columnCount; i++) {
nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i);
}
return nColumnsWidthSum;
}
int TableViewLastColumnResizingFixer::getAvailableWidthForColumn(int column)
{
int nResult = lastColumnMinimumWidth;
int nTableWidth = tableView->horizontalHeader()->width();
if (nTableWidth > 0) {
int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column);
nResult = std::max(nResult, nTableWidth - nOtherColsWidth);
}
return nResult;
}
// Make sure we don't make the columns wider than the tables viewport width.
void TableViewLastColumnResizingFixer::adjustTableColumnsWidth()
{
disconnectViewHeadersSignals();
resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex));
connectViewHeadersSignals();
int nTableWidth = tableView->horizontalHeader()->width();
int nColsWidth = getColumnsWidth();
if (nColsWidth > nTableWidth) {
resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));
}
}
// Make column use all the space available, useful during window resizing.
void TableViewLastColumnResizingFixer::stretchColumnWidth(int column)
{
disconnectViewHeadersSignals();
resizeColumn(column, getAvailableWidthForColumn(column));
connectViewHeadersSignals();
}
// When a section is resized this is a slot-proxy for ajustAmountColumnWidth().
void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize)
{
adjustTableColumnsWidth();
int remainingWidth = getAvailableWidthForColumn(logicalIndex);
if (newSize > remainingWidth) {
resizeColumn(logicalIndex, remainingWidth);
}
}
// When the tabless geometry is ready, we manually perform the stretch of the "Message" column,
// as the "Stretch" resize mode does not allow for interactive resizing.
void TableViewLastColumnResizingFixer::on_geometriesChanged()
{
if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0) {
disconnectViewHeadersSignals();
resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));
connectViewHeadersSignals();
}
}
/**
* Initializes all internal variables and prepares the
* the resize modes of the last 2 columns of the table and
*/
TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth) : tableView(table),
lastColumnMinimumWidth(lastColMinimumWidth),
allColumnsMinimumWidth(allColsMinimumWidth)
{
columnCount = tableView->horizontalHeader()->count();
lastColumnIndex = columnCount - 1;
secondToLastColumnIndex = columnCount - 2;
tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth);
setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive);
setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive);
}
/**
* Class constructor.
* @param[in] seconds Number of seconds to convert to a DHMS string
*/
DHMSTableWidgetItem::DHMSTableWidgetItem(const int64_t seconds) : QTableWidgetItem(),
value(seconds)
{
this->setText(QString::fromStdString(DurationToDHMS(seconds)));
}
/**
* Comparator overload to ensure that the "DHMS"-type durations as used in
* the "active-since" list in the masternode tab are sorted by the elapsed
* duration (versus the string value being sorted).
* @param[in] item Right hand side of the less than operator
*/
bool DHMSTableWidgetItem::operator<(QTableWidgetItem const& item) const
{
DHMSTableWidgetItem const* rhs =
dynamic_cast<DHMSTableWidgetItem const*>(&item);
if (!rhs)
return QTableWidgetItem::operator<(item);
return value < rhs->value;
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "Onlax.lnk";
}
bool GetStartOnSystemStartup()
{
// check for Onlax.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart) {
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres)) {
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres)) {
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(Q_OS_LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "onlax.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof()) {
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else {
char pszExePath[MAX_PATH + 1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath) - 1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out | std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a onlax.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=Onlax\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#elif defined(Q_OS_MAC)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
// based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl);
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)
{
// loop through the list of startup items and try to find the onlax app
CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL);
for (int i = 0; i < CFArrayGetCount(listSnapshot); i++) {
LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);
UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
CFURLRef currentItemURL = NULL;
#if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100
if(&LSSharedFileListItemCopyResolvedURL)
currentItemURL = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, NULL);
#if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100
else
LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, NULL);
#endif
#else
LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, NULL);
#endif
if(currentItemURL && CFEqual(currentItemURL, findUrl)) {
// found
CFRelease(currentItemURL);
return item;
}
if (currentItemURL) {
CFRelease(currentItemURL);
}
}
return NULL;
}
bool GetStartOnSystemStartup()
{
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
return !!foundItem; // return boolified object
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
if (fAutoStart && !foundItem) {
// add onlax app to startup item list
LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL);
} else if (!fAutoStart && foundItem) {
// remove item
LSSharedFileListItemRemove(loginItems, foundItem);
}
return true;
}
#pragma GCC diagnostic pop
#else
bool GetStartOnSystemStartup()
{
return false;
}
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
void saveWindowGeometry(const QString& strSetting, QWidget* parent)
{
QSettings settings;
settings.setValue(strSetting + "Pos", parent->pos());
settings.setValue(strSetting + "Size", parent->size());
}
void restoreWindowGeometry(const QString& strSetting, const QSize& defaultSize, QWidget* parent)
{
QSettings settings;
QPoint pos = settings.value(strSetting + "Pos").toPoint();
QSize size = settings.value(strSetting + "Size", defaultSize).toSize();
if (!pos.x() && !pos.y()) {
QRect screen = QApplication::desktop()->screenGeometry();
pos.setX((screen.width() - size.width()) / 2);
pos.setY((screen.height() - size.height()) / 2);
}
parent->resize(size);
parent->move(pos);
}
// Check whether a theme is not build-in
bool isExternal(QString theme)
{
if (theme.isEmpty())
return false;
return (theme.operator!=("default"));
}
// Open CSS when configured
QString loadStyleSheet()
{
QString styleSheet;
QSettings settings;
QString cssName;
QString theme = settings.value("theme", "").toString();
if (isExternal(theme)) {
// External CSS
settings.setValue("fCSSexternal", true);
boost::filesystem::path pathAddr = GetDataDir() / "themes/";
cssName = pathAddr.string().c_str() + theme + "/css/theme.css";
} else {
// Build-in CSS
settings.setValue("fCSSexternal", false);
if (!theme.isEmpty()) {
cssName = QString(":/css/") + theme;
} else {
cssName = QString(":/css/default");
settings.setValue("theme", "default");
}
}
QFile qFile(cssName);
if (qFile.open(QFile::ReadOnly)) {
styleSheet = QLatin1String(qFile.readAll());
}
return styleSheet;
}
void setClipboard(const QString& str)
{
QApplication::clipboard()->setText(str, QClipboard::Clipboard);
QApplication::clipboard()->setText(str, QClipboard::Selection);
}
#if BOOST_FILESYSTEM_VERSION >= 3
boost::filesystem::path qstringToBoostPath(const QString& path)
{
return boost::filesystem::path(path.toStdString(), utf8);
}
QString boostPathToQString(const boost::filesystem::path& path)
{
return QString::fromStdString(path.string(utf8));
}
#else
#warning Conversion between boost path and QString can use invalid character encoding with boost_filesystem v2 and older
boost::filesystem::path qstringToBoostPath(const QString& path)
{
return boost::filesystem::path(path.toStdString());
}
QString boostPathToQString(const boost::filesystem::path& path)
{
return QString::fromStdString(path.string());
}
#endif
QString formatDurationStr(int secs)
{
QStringList strList;
int days = secs / 86400;
int hours = (secs % 86400) / 3600;
int mins = (secs % 3600) / 60;
int seconds = secs % 60;
if (days)
strList.append(QString(QObject::tr("%1 d")).arg(days));
if (hours)
strList.append(QString(QObject::tr("%1 h")).arg(hours));
if (mins)
strList.append(QString(QObject::tr("%1 m")).arg(mins));
if (seconds || (!days && !hours && !mins))
strList.append(QString(QObject::tr("%1 s")).arg(seconds));
return strList.join(" ");
}
QString formatServicesStr(quint64 mask)
{
QStringList strList;
// Just scan the last 8 bits for now.
for (int i = 0; i < 8; i++) {
uint64_t check = 1 << i;
if (mask & check) {
switch (check) {
case NODE_NETWORK:
strList.append(QObject::tr("NETWORK"));
break;
case NODE_BLOOM:
case NODE_BLOOM_WITHOUT_MN:
strList.append(QObject::tr("BLOOM"));
break;
default:
strList.append(QString("%1[%2]").arg(QObject::tr("UNKNOWN")).arg(check));
}
}
}
if (strList.size())
return strList.join(" & ");
else
return QObject::tr("None");
}
QString formatPingTime(double dPingTime)
{
return dPingTime == 0 ? QObject::tr("N/A") : QString(QObject::tr("%1 ms")).arg(QString::number((int)(dPingTime * 1000), 10));
}
} // namespace GUIUtil
| [
"onlaxproject@protonmail.com"
] | onlaxproject@protonmail.com |
6dc841f1a885415d572ddd76c2df5c60c85bc16c | dd3d11771fd5affedf06f9fcf174bc83a3f2b139 | /BotCore/DofusProtocol/HaapiBufferListMessage.h | df8f60c216a1743903270d6c48bc9dd91efb575a | [] | no_license | Arkwell9112/arkwBot | d3f77ad3874e831594bd5712705983618e94f258 | 859f78dd5c777077b3005870800cb62eec1a9587 | refs/heads/master | 2023-03-17T12:45:07.560436 | 2021-03-16T11:22:35 | 2021-03-16T11:22:35 | 338,042,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 506 | h | #ifndef HAAPIBUFFERLISTMESSAGE
#define HAAPIBUFFERLISTMESSAGE
#include "../IO/ICustomDataInput.h"
#include "../NetworkInterface.h"
#include <vector>
#include "BufferInformation.h"
class HaapiBufferListMessage : public NetworkInterface {
public:
std::vector<BufferInformation> buffers;
unsigned int protocolId = 115;
void deserialize(ICustomDataInput &input);
void deserializeAs_HaapiBufferListMessage(ICustomDataInput &input);
void _buffersFunc(ICustomDataInput &input);
};
#endif | [
"arkwell9112@nowhere.com"
] | arkwell9112@nowhere.com |
0ea50825c68c06a2d4dd1a2db2f2709637aeb50d | e23634f5b5f127baf7b213373311d0ff38e86ebe | /Source/Core/Network/CurlShare.cpp | 6183f8fe432a34fdfefeb03b4dd3525b52dcecd9 | [
"Apache-2.0"
] | permissive | YuriPet/image-uploader | aca4292d8cc26eb74b02985d58e837198a54338a | db4a39368797b413cd2aa6d287b760584b04d078 | refs/heads/master | 2023-03-19T18:17:52.778857 | 2022-12-24T08:54:11 | 2022-12-24T08:54:11 | 192,969,982 | 0 | 0 | Apache-2.0 | 2019-06-20T18:37:31 | 2019-06-20T18:37:31 | null | UTF-8 | C++ | false | false | 1,546 | cpp | #include "CurlShare.h"
#include "Core/Logging.h"
CurlShare::CurlShare()
{
share_ = curl_share_init();
CURLSHcode shareError;
curl_share_setopt(share_, CURLSHOPT_USERDATA, this);
shareError = curl_share_setopt(share_, CURLSHOPT_LOCKFUNC, lockData);
if (shareError){
LOG(ERROR) << "share set opt wrong" ;
return;
}
shareError = curl_share_setopt(share_, CURLSHOPT_UNLOCKFUNC, unlockData);
if (shareError){
LOG(ERROR) << "share set opt wrong";
return;
}
shareError = curl_share_setopt(share_, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
if (shareError){
LOG(ERROR) << "share set opt wrong";
return;
}
shareError = curl_share_setopt(share_, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
if (shareError){
LOG(ERROR) << "share set opt wrong";
return;
}
shareError = curl_share_setopt(share_, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);
if (shareError){
LOG(ERROR) << "share set opt wrong";
return;
}
}
CurlShare::~CurlShare()
{
curl_share_cleanup(share_);
}
CURLSH* CurlShare::getHandle() const
{
return share_;
}
void CurlShare::lockData(CURL *handle, curl_lock_data data, curl_lock_access, void *useptr){
auto pthis = reinterpret_cast<CurlShare*>(useptr);
pthis->mutexes_[data].lock();
}
/* unlock callback */
void CurlShare::unlockData(CURL *handle, curl_lock_data data, void *useptr){
auto pthis = reinterpret_cast<CurlShare*>(useptr);
pthis->mutexes_[data].unlock();
} | [
"zenden2k@gmail.com"
] | zenden2k@gmail.com |
10c1f2292cc34665cf3e154278193b48a62d8518 | a909df0ba2abf695df4a7d15350312d4c6463c48 | /UVa/11947.cpp | 66a494160bd8b1e4513382c59bfa6ab376a622f8 | [] | no_license | SayaUrobuchi/uvachan | 1dadd767a96bb02c7e9449c48e463847480e98ec | c213f5f3dcfc72376913a21f9abe72988a8127a1 | refs/heads/master | 2023-07-23T03:59:50.638063 | 2023-07-16T04:31:23 | 2023-07-16T04:31:23 | 94,064,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,251 | cpp | #include <stdio.h>
const char *s[12] = {"aquarius", "pisces", "aries", "taurus", "gemini", "cancer", "leo",
"virgo", "libra", "scorpio", "sagittarius", "capricorn"};
int calc(int m, int y)
{
if(m == 2)
{
return 28+(!(y&3) && (y%100||y%400==0));
}
if(m < 8)
{
return 30+(m&1);
}
return 31-(m&1);
}
const char *get_str(int m, int d)
{
int t;
t = m*100+d;
if(t < 121)
{
return s[11];
}
else if(t < 220)
{
return s[0];
}
else if(t < 321)
{
return s[1];
}
else if(t < 421)
{
return s[2];
}
else if(t < 522)
{
return s[3];
}
else if(t < 622)
{
return s[4];
}
else if(t < 723)
{
return s[5];
}
else if(t < 822)
{
return s[6];
}
else if(t < 924)
{
return s[7];
}
else if(t < 1024)
{
return s[8];
}
else if(t < 1123)
{
return s[9];
}
else if(t < 1223)
{
return s[10];
}
return s[11];
}
int main()
{
int cas, count, mon, day, year, i;
cas = 0;
scanf("%d", &count);
while(count--)
{
scanf("%2d%2d%4d", &mon, &day, &year);
for(i=0; i<280; i++)
{
day++;
if(day > calc(mon, year))
{
day = 1;
mon++;
if(mon > 12)
{
year++;
mon = 1;
}
}
}
printf("%d %02d/%02d/%04d %s\n", ++cas, mon, day, year, get_str(mon, day));
}
return 0;
}
| [
"sa072688@gmail.com"
] | sa072688@gmail.com |
e0fd4996c43ba7b4cc2509efccc32312121a3200 | ab5c19cf7af83931cdf7acf11b6a1dbe3ea96eb6 | /CookieRun/Classes/PlayerCookie.h | 11d7c956bce26d936c28f5ee42b411f49754ad3e | [] | no_license | rkddlsgh1234/MyGameSource | ecc4f16d94017834fd3695241cc052baf43beee3 | 54c15d457f26608b9e9f02368d10febaa3f01a2d | refs/heads/master | 2020-07-02T03:39:20.417188 | 2019-08-09T08:37:47 | 2019-08-09T08:37:47 | 201,403,584 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,984 | h | #pragma once
#include "cocos2d.h"
#include "ObjectManager.h"
class PlayerCookie
{
private:
cocos2d::Sprite* m_pPlayer;
cocos2d::SpriteFrameCache* m_pCharacterCache;
cocos2d::SpriteFrameCache* m_pEffectCache;
cocos2d::Vector <cocos2d::Sprite*> m_vcEffect;
cocos2d::Vector <cocos2d::Sprite*> m_vcCoinEffect;
cocos2d::Scene* m_pScene;
ObjectManager* m_pObjectManager;
bool m_bJump;
bool m_bDubbleJump;
bool m_bSlide;
bool m_bDie;
bool m_bGod;
bool m_bControl;
bool m_bItemBig;
bool m_bItemBoost;
bool m_bFever;
bool m_bFeverAction;
bool m_bPush;
public:
PlayerCookie();
virtual ~PlayerCookie();
virtual void Init(cocos2d::Scene* pScene, cocos2d::SpriteFrameCache* pJumpSpriteFrame, ObjectManager* pObject);
bool Updata(ObjectManager* pObject);
virtual void UpdataCharacter();
virtual void Input();
virtual void InputPush();
virtual void StartGame();
virtual void SetRunAni();
virtual bool CheckCrash();
void UpdataItem();
bool SetGravity(ObjectManager* pObject);
void InputFever();
void SetRunAnimate();
void ResetState();
void SetVisible();
void SetHealthCookie();
void ChangeGodMode();
void ShowCookie();
void SetItem(string Item);
void ResetItem(string Item);
void ShowEffect();
void SetFeverMode();
void UnFeverMode();
void SetJump();
void SetDubbleJump();
void UnPush();
void ActionFever();
virtual inline cocos2d::Sprite* GetSprite()
{
return m_pPlayer;
}
virtual inline bool GetGodMode()
{
return m_bGod;
}
virtual inline bool GetJumpState()
{
if (m_bJump)
return false;
if (m_bDubbleJump)
return false;
return true;
}
virtual inline bool GetFever()
{
return m_bFever;
}
virtual inline bool GetDubbleJump()
{
return m_bDubbleJump;
}
virtual inline bool GetJump()
{
return m_bJump;
}
virtual inline bool GetSlide()
{
return m_bSlide;
}
virtual inline cocos2d::SpriteFrameCache* GetCache()
{
return m_pCharacterCache;
}
virtual inline bool GetSkil()
{
return false;
}
}; | [
"inho2456@naver.com"
] | inho2456@naver.com |
296ce0e08e4d1eee12a78cc965ba82e5fe7bd120 | 8ac88c00345f74201ac97c7a658fb8555c8ee5e0 | /widget.cpp | b96f3638e0f8720d3e24e8fab6d1eb4fef4ad7d2 | [] | no_license | huanghaizilu/saoma | ee13c4958bf55defd1877426ea01ec43b48bc2ad | ca80f745ce18f26ebb39c49c270b4d8f7dd57f73 | refs/heads/master | 2020-03-25T15:29:15.935514 | 2018-08-08T15:39:16 | 2018-08-08T15:39:16 | 143,885,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 72,279 | cpp | #include "widget.h"
#include "ui_widget.h"
#include <QSqlQueryModel>
#include <QTableView>
#include <QDebug>
#include <QMessageBox>
#include <QSqlError>
#include <QDateTime>
#include <QKeyEvent>
#include <QSqlQuery>
#include <QDateTimeEdit>
#include <QPrintDialog>
#include <QPrintPreviewDialog>
#include <QFileDialog>
#include <QFileInfo>
#include <QPrinter>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
// setWindowFlags (Qt::Window | Qt::FramelessWindowHint);
// showFullScreen();
// showMaximized();
// showNormal();
setFixedSize(1024,768);
// setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);
ui->printPButton_stock->setVisible(false);
ui->showAllPButton_stock->setVisible(false);
ui->printTableWidgetPButton->setVisible(false);
ui->tableWidget_table->setColumnCount(4);
ui->tableWidget_table->setRowCount(0);
ui->tableWidget_table->setColumnWidth(0,200);
ui->tableWidget_table->setColumnWidth(3,200);
ui->tableWidget_table->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"备注");
ui->tableWidget_table->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget_table->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
ui->tableWidget_import->setColumnCount(7);
ui->tableWidget_import->setRowCount(0);
ui->tableWidget_import->setColumnWidth(0,160);
ui->tableWidget_import->setColumnWidth(6,160);
ui->tableWidget_import->setHorizontalHeaderLabels(QStringList()<<"ImportID"<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_import->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget_import->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
ui->tableWidget_export->setColumnCount(7);
ui->tableWidget_export->setRowCount(0);
ui->tableWidget_export->setColumnWidth(0,160);
ui->tableWidget_export->setColumnWidth(6,160);
ui->tableWidget_export->setHorizontalHeaderLabels(QStringList()<<"ExportID"<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_export->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget_export->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
ui->tableWidget_statistics->setColumnCount(6);
ui->tableWidget_statistics->setRowCount(0);
ui->tableWidget_statistics->setColumnWidth(0,200);
ui->tableWidget_statistics->setColumnWidth(5,200);
ui->tableWidget_statistics->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_statistics->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget_statistics->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
ui->tableWidget_stock->setColumnCount(7);
ui->tableWidget_stock->setRowCount(0);
ui->tableWidget_stock->setColumnWidth(0,160);
ui->tableWidget_stock->setColumnWidth(6,160);
ui->tableWidget_stock->setHorizontalHeaderLabels(QStringList()<<"StockID"<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_stock->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget_stock->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
ui->tableWidget_alart->setColumnCount(9);
ui->tableWidget_alart->setRowCount(0);
ui->tableWidget_alart->setColumnWidth(0,200);
// ui->tableWidget_alart->setColumnWidth(6,200);
ui->tableWidget_alart->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"统计数量"<<"单位"<<"盘点数量"<<"最小值"<<"最大值"<<"备注");
ui->tableWidget_alart->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget_alart->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
ui->radioButton->setChecked(true);
ui->checkBox->setChecked(true);
ui->tableWidget_search->setColumnCount(7);
ui->tableWidget_search->setRowCount(0);
ui->tableWidget_search->setColumnWidth(0,160);
ui->tableWidget_search->setColumnWidth(6,160);
ui->tableWidget_search->setHorizontalHeaderLabels(QStringList()<<"表单ID"<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_search->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget_search->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
ui->search_dateEdit->setDate(QDate::currentDate());
ui->dateTimeEdit->setDateTime(QDateTime::currentDateTime());
ui->dateTimeEdit_2->setDateTime(QDateTime::currentDateTime());
ui->dateTimeEdit_3->setDateTime(QDateTime::currentDateTime());
int stockNumber;
QString sql_select = "select * from stock ";
QSqlQuery query ;
query.prepare(sql_select);
if(!query.exec())
{
qDebug() << query.lastError();
}
qDebug() << query.last();
if(query.last())
{
QString stockDate = query.value(6).toString().mid(0,10);
if(stockDate == QDate::currentDate().toString("yyyy-MM-dd"))
{
QString stockId = query.value(0).toString();
stockNumber = stockId.mid(11,3).toInt();
qDebug() <<"stockNumber" <<stockNumber;
ui->spinBox->setValue(stockNumber + 1);
}
}
else
{ stockNumber = 1;
ui->spinBox->setValue(stockNumber);
}
int exportNumber;
sql_select = "select * from export ";
query.prepare(sql_select);
if(!query.exec())
{
qDebug() << query.lastError();
}
qDebug() << query.last();
if(query.last())
{
QString exportDate = query.value(6).toString().mid(0,10);
if(exportDate == QDate::currentDate().toString("yyyy-MM-dd"))
{
QString exportId = query.value(0).toString();
exportNumber = exportId.mid(11,3).toInt();
qDebug() <<"exportNumber" <<exportNumber;
ui->spinBox_2->setValue(exportNumber + 1);
}
}
else
{ exportNumber = 1;
ui->spinBox_2->setValue(exportNumber);
}
int importNumber;
sql_select = "select * from import ";
query.prepare(sql_select);
if(!query.exec())
{
qDebug() << query.lastError();
}
qDebug() << query.last();
if(query.last())
{
QString importDate = query.value(6).toString().mid(0,10);
if(importDate == QDate::currentDate().toString("yyyy-MM-dd"))
{
QString importId = query.value(0).toString();
importNumber = importId.mid(11,3).toInt();
qDebug() <<"importNumber" <<importNumber;
ui->spinBox_3->setValue(importNumber + 1);
}
}
else
{ importNumber = 1;
ui->spinBox_3->setValue(importNumber);
}
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_addPButton_table_clicked()
{
ui->label_show->text().clear();
ui->tableWidget_table->setEditTriggers(QAbstractItemView::DoubleClicked);
ui->tableWidget_table->setShowGrid(true);
ui->tableWidget_table->setColumnWidth(0,200);
// ui->tableWidget_table->setRowHeight(3,60);
if(ui->lineEdit_id->text() == "")
{
ui->lineEdit_id->setFocus();
QMessageBox::information(this,"Title","Please input id!",QMessageBox::Yes,QMessageBox::Yes);
return;
}
if(ui->lineEdit_name->text() == "")
{
QMessageBox::information(this,"Title","Please input name!",QMessageBox::Yes,QMessageBox::Yes);
ui->lineEdit_name->setFocus();
return;
}
QString str_id = ui->lineEdit_id->text();
QString sql_query = "select * from goods where id = ?";
QSqlQuery query;
query.prepare(sql_query);
query.addBindValue(str_id);
if(!query.exec())
{
query.lastError();
}
if(query.first())
{
ui->label_show->setText("该商品已经录入名称!");
QFont ft;
ft.setPointSize(12);
ft.setBold(true);
ui->label_show->setFont(ft);
QPalette pal;
pal.setColor(QPalette::WindowText,Qt::red);
ui->label_show->setPalette(pal);
ui->lineEdit_id->setFocus();
return;
}
int rowNum = ui->tableWidget_table->rowCount();
ui->tableWidget_table->insertRow(rowNum);
ui->tableWidget_table->setItem(rowNum,0,new QTableWidgetItem(ui->lineEdit_id->text()));
ui->tableWidget_table->setItem(rowNum,1,new QTableWidgetItem(ui->lineEdit_name->text()));
ui->tableWidget_table->setItem(rowNum,2,new QTableWidgetItem(ui->lineEdit_kind->text()));
ui->tableWidget_table->setItem(rowNum,3,new QTableWidgetItem(ui->lineEdit_remark->text()));
for(int i=0;i<rowNum;i++)
{
if(ui->tableWidget_table->item(i,0)->text() == ui->lineEdit_id->text())
{
qDebug() <<" has same record" ;
ui->tableWidget_table->removeRow(rowNum);
ui->tableWidget_table->selectRow(i);
ui->lineEdit_id->setFocus();
}
}
ui->lineEdit_id->setText("");
ui->lineEdit_id->setFocus();
ui->lineEdit_name->setText("");
ui->lineEdit_kind->setText("");
ui->lineEdit_remark->setText("");
}
void Widget::on_delPButton_table_clicked()
{
int curRow = ui->tableWidget_table->currentIndex().row();
if(curRow == -1) return;
int ok = QMessageBox::warning(this,tr("删除当前行!"),
tr("你确定删除当前行吗?"),QMessageBox::Yes, QMessageBox::No);
if(ok == QMessageBox::No)
{
}
else
{
ui->tableWidget_table->removeRow(curRow);
}
ui->lineEdit_id->setText("");
ui->lineEdit_id->setFocus();
ui->lineEdit_name->setText("");
// ui->lineEdit_kind->setText("");
// ui->lineEdit_remark->setText("");
}
void Widget::on_showPButton_table_clicked()
{
ui->tableWidget_table->clear();
ui->tableWidget_table->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableWidget_table->setColumnWidth(0,200);
ui->tableWidget_table->setShowGrid(true);
QSqlQuery query;
int i = 0, j = 0, iColumn, iRow;
query.prepare("select * from goods");
query.exec();
query.last();
iRow = query.at() + 1;
ui->tableWidget_table->setRowCount(iRow);
iColumn = ui->tableWidget_table->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_table->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_table->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称");
ui->tableWidget_table->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
}
void Widget::on_showPButton_import_clicked()
{
ui->tableWidget_import->clear();
ui->tableWidget_import->setEditTriggers(QAbstractItemView::NoEditTriggers); //禁止修改
// ui->tableWidget_import->resizeColumnsToContents();
// ui->tableWidget_import->resizeRowsToContents();
ui->tableWidget_import->setColumnWidth(0,200);
ui->tableWidget_import->setColumnWidth(5,200);
ui->tableWidget_import->setShowGrid(true);
QSqlQuery query;
int i = 0, j = 0, iColumn, iRow;
query.prepare("select * from import");
query.exec();
query.last();
iRow = query.at() + 1;
ui->tableWidget_import->setRowCount(iRow);
iColumn = ui->tableWidget_import->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_import->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_import->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_import->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget_import->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
int rowCount = ui->tableWidget_import->rowCount();
ui->tableWidget_import->selectRow(rowCount-1);
}
void Widget::on_delPButton_import_clicked()
{
// int rowNum = ui->tableWidget_import->rowCount();
int curRow = ui->tableWidget_import->currentIndex().row();
qDebug() << "curRow" << curRow;
if(curRow == -1) return;
int ok = QMessageBox::warning(this,tr("删除当前行!"),
tr("你确定删除当前行吗?"),QMessageBox::Yes, QMessageBox::No);
if(ok == QMessageBox::No)
{
}
else
{
ui->tableWidget_import->removeRow(curRow);
}
}
void Widget::on_addPButton_import_clicked()
{
ui->tableWidget_import->setEditTriggers(QAbstractItemView::DoubleClicked);
ui->tableWidget_import->setColumnWidth(0,200);
ui->tableWidget_import->setColumnWidth(5,200);
int rowNum = ui->tableWidget_import->rowCount();
ui->tableWidget_import->insertRow(rowNum);
QModelIndex mdidx = ui->tableWidget_import->model()->index(rowNum,0);
ui->tableWidget_import->setFocus();
ui->tableWidget_import->setCurrentIndex(mdidx);
ui->tableWidget_import->edit(mdidx);
}
void Widget::keyPressEvent(QKeyEvent *event)
{
if((event->key() == Qt::Key_Return)||(event->key() == Qt::Key_Enter))
// setWindowState(Qt::WindowMaximized);
qDebug() << "key enter return event" ;
}
void Widget::keyReleaseEvent(QKeyEvent *event)
{
if(ui->tabWidget->currentIndex()==0)
{
if((event->key() == Qt::Key_Return)||(event->key() == Qt::Key_Enter))
{
qDebug() << "key release event import" ;
int rowNum = ui->tableWidget_import->rowCount();
QString str_id = ui->lineEdit_import->text();
if(str_id == "") return;
QSqlQuery query ;
QString sql_query = "select * from goods where id = ? ";
query.prepare(sql_query);
query.addBindValue(str_id);
if(!query.exec())
{
query.lastError();
}
query.first();
QString name1 = query.value(1).toString();
qDebug() <<"name1 import" <<name1;
if(name1 == "")
{
ui->lineEdit_import->setText("");
return;
}
QString kind1 = query.value(2).toString();
qDebug() <<"kind1 import" <<kind1;
// if(kind1 == "")
// {
// ui->lineEdit_import->setText("");
// return;
// }
QString import,import1,import2,import3,import4;
import1 = "I";//means import
import2 = QDate::currentDate().toString("yyyy-MM-dd");
// import3 = "xxx";//999条表单
// import3 = ui->lineEdit_number->text();
QString buling = "0";
int importNumber = ui->spinBox_3->value();
if((0<importNumber)&&(importNumber<10))
{
import3 = buling + buling + QString::number(importNumber,10);
} else if(((9<importNumber)&&(importNumber<100)))
{
import3 = buling + QString::number(importNumber,10);
}else {
import3 = QString::number(importNumber,10);
}
int importListnumber = ui->tableWidget_import->rowCount() + 1;
if((0<importListnumber)&&(importListnumber<10))
{
import4 = buling + buling + buling + buling + QString::number(importListnumber,10);
}else if(((9<importListnumber)&&(importListnumber<100)))
{
import4 = buling + buling + buling + QString::number(importListnumber,10);
}else if(((99<importListnumber)&&(importListnumber<1000))){
import4 = buling + buling + QString::number(importListnumber,10);
}else if(((999<importListnumber)&&(importListnumber<10000))){
import4 = buling + QString::number(importListnumber,10);
}else if(((9999<importListnumber)&&(importListnumber<100000))){
import4 = QString::number(importListnumber,10);
}
// import4 = "xxxxx";//99999记录
import = import1 +import2 +import3 + import4;
QTableWidgetItem *importId = new QTableWidgetItem();
QTableWidgetItem *id = new QTableWidgetItem();
QTableWidgetItem *name = new QTableWidgetItem();
QTableWidgetItem *kind = new QTableWidgetItem();
QTableWidgetItem *number = new QTableWidgetItem();
QTableWidgetItem *unit = new QTableWidgetItem();
QTableWidgetItem *dateTime = new QTableWidgetItem();
importId->setText(import);
id->setText(str_id);
name->setText(name1);
kind->setText(kind1);
number->setText("1");
unit->setText("份");
QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss zzz");
dateTime->setText(strDateTime);
ui->tableWidget_import->insertRow(rowNum);
ui->tableWidget_import->setItem(rowNum,0,importId);
ui->tableWidget_import->setItem(rowNum,1,id);
ui->tableWidget_import->setItem(rowNum,2,name);
ui->tableWidget_import->setItem(rowNum,3,kind);
ui->tableWidget_import->setItem(rowNum,4,number);
ui->tableWidget_import->setItem(rowNum,5,unit);
ui->tableWidget_import->setItem(rowNum,6,dateTime);
int rowNum1 = ui->tableWidget_import->rowCount();
for(int i=0;i<rowNum1-1;i++)
{
if(ui->lineEdit_import->text() == ui->tableWidget_import->item(i,1)->text() )
{
qDebug() <<"import has same record!";
int n = ui->tableWidget_import->item(i,4)->text().toInt();
n= n + 1;
QString str_n = QString::number(n,10);
QTableWidgetItem *number1 = new QTableWidgetItem();
number1->setText(str_n);
ui->tableWidget_import->setItem(i,4,number1);
int rowNum2 = ui->tableWidget_import->rowCount();
ui->tableWidget_import->removeRow(rowNum2-1);
break;
}
}
ui->lineEdit_import->setText("");
}
}
if(ui->tabWidget->currentIndex()==1)
{
if((event->key() == Qt::Key_Return)||(event->key() == Qt::Key_Enter))
{
qDebug() << "key release event export" ;
int rowNum = ui->tableWidget_export->rowCount();
QString str_id = ui->lineEdit_export->text();
if(str_id == "") return;
QSqlQuery query ;
QString sql_query = "select * from goods where id = ? ";
query.prepare(sql_query);
query.addBindValue(str_id);
if(!query.exec())
{
query.lastError();
}
query.first();
QString name1 = query.value(1).toString();
qDebug() <<"name1 export" <<name1;
if(name1 == "")
{
ui->lineEdit_export->setText("");
return;
}
QString kind1 = query.value(2).toString();
qDebug() <<"kind1 export" <<kind1;
if(kind1 == "")
{
// ui->lineEdit_export->setText("");
return;
}
QString export0,export1,export2,export3,export4;
export1 = "E";//means export
export2 = QDate::currentDate().toString("yyyy-MM-dd");
// export3 = "xxx";//999条表单
// export3 = ui->lineEdit_number->text();
QString buling = "0";
int exportNumber = ui->spinBox_2->value();
if((0<exportNumber)&&(exportNumber<10))
{
export3 = buling + buling + QString::number(exportNumber,10);
} else if(((9<exportNumber)&&(exportNumber<100)))
{
export3 = buling + QString::number(exportNumber,10);
}else {
export3 = QString::number(exportNumber,10);
}
int exportListnumber = ui->tableWidget_export->rowCount() + 1;
if((0<exportListnumber)&&(exportListnumber<10))
{
export4 = buling + buling + buling + buling + QString::number(exportListnumber,10);
}else if(((9<exportListnumber)&&(exportListnumber<100)))
{
export4 = buling + buling + buling + QString::number(exportListnumber,10);
}else if(((99<exportListnumber)&&(exportListnumber<1000))){
export4 = buling + buling + QString::number(exportListnumber,10);
}else if(((999<exportListnumber)&&(exportListnumber<10000))){
export4 = buling + QString::number(exportListnumber,10);
}else if(((9999<exportListnumber)&&(exportListnumber<100000))){
export4 = QString::number(exportListnumber,10);
}
// export4 = "xxxxx";//99999记录
export0 = export1 +export2 +export3 + export4;
QTableWidgetItem *exportId = new QTableWidgetItem();
QTableWidgetItem *id = new QTableWidgetItem();
QTableWidgetItem *name = new QTableWidgetItem();
QTableWidgetItem *kind = new QTableWidgetItem();
QTableWidgetItem *number = new QTableWidgetItem();
QTableWidgetItem *unit = new QTableWidgetItem();
QTableWidgetItem *dateTime = new QTableWidgetItem();
exportId->setText(export0);
id->setText(str_id);
name->setText(name1);
kind->setText(kind1);
number->setText("1");
unit->setText("份");
QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss zzz");
dateTime->setText(strDateTime);
ui->tableWidget_export->insertRow(rowNum);
ui->tableWidget_export->setItem(rowNum,0,exportId);
ui->tableWidget_export->setItem(rowNum,1,id);
ui->tableWidget_export->setItem(rowNum,2,name);
ui->tableWidget_export->setItem(rowNum,3,kind);
ui->tableWidget_export->setItem(rowNum,4,number);
ui->tableWidget_export->setItem(rowNum,5,unit);
ui->tableWidget_export->setItem(rowNum,6,dateTime);
int rowNum1 = ui->tableWidget_export->rowCount();
for(int i=0;i<rowNum1-1;i++)
{
if(ui->lineEdit_export->text() == ui->tableWidget_export->item(i,1)->text() )
{
qDebug() <<"export has same record!";
int n = ui->tableWidget_export->item(i,4)->text().toInt();
n= n + 1;
QString str_n = QString::number(n,10);
QTableWidgetItem *number1 = new QTableWidgetItem();
number1->setText(str_n);
ui->tableWidget_export->setItem(i,4,number1);
int rowNum2 = ui->tableWidget_export->rowCount();
ui->tableWidget_export->removeRow(rowNum2-1);
break;
}
}
ui->lineEdit_export->setText("");
}
}
if(ui->tabWidget->currentIndex()==5)
{
if((event->key() == Qt::Key_Return)||(event->key() == Qt::Key_Enter))
{
qDebug() << "key release event table" ;
ui->lineEdit_id->text() = "";
ui->lineEdit_name->text() = "";
ui->lineEdit_kind->text() = "";
ui->lineEdit_remark->text() = "";
QString str_id = ui->lineEdit_id->text();
if(str_id == "") return;
QString sql_query = "select * from goods where id = ?";
QSqlQuery query;
query.prepare(sql_query);
query.addBindValue(str_id);
if(!query.exec())
{
query.lastError();
}
if(query.first())
{
ui->label_show->setText("该商品已经录入名称!");
QFont ft;
ft.setPointSize(12);
ft.setBold(true);
ui->label_show->setFont(ft);
QPalette pal;
pal.setColor(QPalette::WindowText,Qt::red);
ui->label_show->setPalette(pal);
QString name = query.value(1).toString();
ui->lineEdit_name->setText(name);
QString kind = query.value(2).toString();
ui->lineEdit_kind->setText(kind);
QString remark = query.value(3).toString();
ui->lineEdit_remark->setText(remark);
}
else
{
ui->label_show->setText("该商品还没有录入名称!");
QFont ft;
ft.setPointSize(12);
ft.setBold(true);
ui->label_show->setFont(ft);
QPalette pal;
pal.setColor(QPalette::WindowText,Qt::red);
ui->label_show->setPalette(pal);
ui->lineEdit_name->setText("");
ui->lineEdit_name->setFocus();
ui->lineEdit_kind->setText("");
ui->lineEdit_remark->setText("");
}
}
}
if(ui->tabWidget->currentIndex()==2)
{
if((event->key() == Qt::Key_Return)||(event->key() == Qt::Key_Enter))
{
qDebug() << "key release event stock" ;
int rowNum = ui->tableWidget_stock->rowCount();
QString str_id = ui->lineEdit_ID->text();
if(str_id == "") return;
QSqlQuery query ;
QString sql_query = "select * from goods where id = ? ";
query.prepare(sql_query);
query.addBindValue(str_id);
if(!query.exec())
{
query.lastError();
}
query.first();
QString name1 = query.value(1).toString();
qDebug() <<"name1 stock" <<name1;
if(name1 == "")
{
ui->lineEdit_ID->setText("");
ui->lineEdit_ID->setFocus();
// QMessageBox::setText("Please input the name");
return;
}
QString kind1 = query.value(2).toString();
qDebug() <<"kind1 stock" <<kind1;
if(kind1 == "")
{
// ui->lineEdit_import->setText("");
// QMessageBox::setText("Please input the kind ");
return;
}
QString stock,stock1,stock2,stock3,stock4;
stock1 = "S";//means stock
stock2 = QDate::currentDate().toString("yyyy-MM-dd");
// stock3 = "xxx";//999条表单
// stock3 = ui->lineEdit_number->text();
QString buling = "0";
int stockNumber = ui->spinBox->value();
if((0<stockNumber)&&(stockNumber<10))
{
stock3 = buling + buling + QString::number(stockNumber,10);
} else if(((9<stockNumber)&&(stockNumber<100)))
{
stock3 = buling + QString::number(stockNumber,10);
}else {
stock3 = QString::number(stockNumber,10);
}
int stockListnumber = ui->tableWidget_stock->rowCount() + 1;
if((0<stockListnumber)&&(stockListnumber<10))
{
stock4 = buling + buling + buling + buling + QString::number(stockListnumber,10);
}else if(((9<stockListnumber)&&(stockListnumber<100)))
{
stock4 = buling + buling + buling + QString::number(stockListnumber,10);
}else if(((99<stockListnumber)&&(stockListnumber<1000))){
stock4 = buling + buling + QString::number(stockListnumber,10);
}else if(((999<stockListnumber)&&(stockListnumber<10000))){
stock4 = buling + QString::number(stockListnumber,10);
}else if(((9999<stockListnumber)&&(stockListnumber<100000))){
stock4 = QString::number(stockListnumber,10);
}
// stock4 = "xxxxx";//99999记录
stock = stock1 +stock2 +stock3 + stock4;
QTableWidgetItem *stockID = new QTableWidgetItem();
QTableWidgetItem *id = new QTableWidgetItem();
QTableWidgetItem *name = new QTableWidgetItem();
QTableWidgetItem *kind = new QTableWidgetItem();
QTableWidgetItem *number = new QTableWidgetItem();
QTableWidgetItem *unit = new QTableWidgetItem();
QTableWidgetItem *dateTime = new QTableWidgetItem();
stockID->setText(stock);
id->setText(str_id);
name->setText(name1);
kind->setText(kind1);
number->setText("1");
unit->setText("份");
QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss zzz");
dateTime->setText(strDateTime);
ui->tableWidget_stock->insertRow(rowNum);
ui->tableWidget_stock->setItem(rowNum,0,stockID);
ui->tableWidget_stock->setItem(rowNum,1,id);
ui->tableWidget_stock->setItem(rowNum,2,name);
ui->tableWidget_stock->setItem(rowNum,3,kind);
ui->tableWidget_stock->setItem(rowNum,4,number);
ui->tableWidget_stock->setItem(rowNum,5,unit);
ui->tableWidget_stock->setItem(rowNum,6,dateTime);
for(int i=0;i<rowNum;i++)
{
if(ui->lineEdit_ID->text() == ui->tableWidget_stock->item(i,1)->text() )
{
qDebug() <<"stock has same record!";
int n = ui->tableWidget_stock->item(i,4)->text().toInt();
n= n + 1;
QString str_n = QString::number(n,10);
QTableWidgetItem *number1 = new QTableWidgetItem();
number1->setText(str_n);
ui->tableWidget_stock->setItem(i,4,number1);
ui->tableWidget_stock->removeRow(rowNum);
break;
}
}
ui->lineEdit_ID->setText("");
}
}
}
void Widget::on_commitPButton_table_clicked()
{
ui->tableWidget_table->setEditTriggers(QAbstractItemView::DoubleClicked);
int rowNum = ui->tableWidget_table->rowCount();
if(rowNum == 0) return;
for(int i=0;i<rowNum;i++)
{
// int id;
QString id,name,kind,remark;
id = ui->tableWidget_table->item(i,0)->text();
name = ui->tableWidget_table->item(i,1)->text();
kind = ui->tableWidget_table->item(i,2)->text();
remark = ui->tableWidget_table->item(i,3)->text();
QString sql_insert;
sql_insert = "insert into goods values (?,?,?,?)";
QSqlQuery query;
query.prepare(sql_insert);
query.addBindValue(id);
query.addBindValue(name);
query.addBindValue(kind);
query.addBindValue(remark);
if(!query.exec())
{
qDebug() << query.lastError();
// QString error = query.lastError().text();
// QMessageBox::critical(this,"title",error,QMessageBox::Yes);
}
}
ui->tableWidget_table->setRowCount(0);
ui->lineEdit_id->setText("");
ui->lineEdit_id->setFocus();
ui->lineEdit_name->setText("");
ui->lineEdit_kind->setText("");
ui->lineEdit_remark->setText("");
}
void Widget::on_commitPButton_import_clicked()
{
ui->tableWidget_import->setEditTriggers(QAbstractItemView::DoubleClicked);
int rowNum;
rowNum = ui->tableWidget_import->rowCount();
for(int i=0;i<rowNum;i++)
{
int id,number;
QString importId,name,kind,unit,strDateTime;
importId = ui->tableWidget_import->item(i,0)->text();
id = ui->tableWidget_import->item(i,1)->text().toInt();
name = ui->tableWidget_import->item(i,2)->text();
kind = ui->tableWidget_import->item(i,3)->text();
number = ui->tableWidget_import->item(i,4)->text().toInt();
unit = ui->tableWidget_import->item(i,5)->text();
strDateTime = ui->tableWidget_import->item(i,6)->text();
QString sql_insert;
sql_insert = "insert into import values (?,?,?,?,?,?,?)";
QSqlQuery query;
query.prepare(sql_insert);
query.addBindValue(importId);
query.addBindValue(id);
query.addBindValue(name);
query.addBindValue(kind);
query.addBindValue(number);
query.addBindValue(unit);
query.addBindValue(strDateTime);
if(!query.exec())
{
qDebug() << query.lastError();
}
}
ui->tableWidget_import->clear();
ui->tableWidget_import->setRowCount(0);
ui->tableWidget_import->setHorizontalHeaderLabels(QStringList()<<"ImportID"<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_import->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget_import->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
QString import,import1,import2,import3;
import1 = "S";//means import
import2 = QDate::currentDate().toString("yyyy-MM-dd");
QString buling = "0";
int importNumber = ui->spinBox_3->value();
if((0<importNumber)&&(importNumber<10))
{
import3 = buling + buling + QString::number(importNumber,10);
} else if(((9<importNumber)&&(importNumber<100)))
{
import3 = buling + QString::number(importNumber,10);
}else {
import3 = QString::number(importNumber,10);
}
import = import1 + import2 + import3 ;
qDebug() << "import" <<import;
QString sql_insert1;
sql_insert1 = "insert into importSheet values (?)";
QSqlQuery query;
query.prepare(sql_insert1);
query.addBindValue(import);
if(!query.exec())
{
qDebug() << query.lastError();
}
int importNumber1 = ui->spinBox_3->value() + 1;
ui->spinBox_3->setValue(importNumber1);
}
void Widget::on_addPButton_export_clicked()
{
ui->tableWidget_export->setEditTriggers(QAbstractItemView::DoubleClicked);
// ui->tableWidget_import->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableWidget_export->setColumnWidth(0,200);
ui->tableWidget_export->setColumnWidth(5,200);
int rowNum ;
rowNum = ui->tableWidget_export->rowCount();
ui->tableWidget_export->insertRow(rowNum);
QModelIndex mdidx = ui->tableWidget_export->model()->index(rowNum,0);
ui->tableWidget_export->setFocus();
ui->tableWidget_export->setCurrentIndex(mdidx);
ui->tableWidget_export->edit(mdidx);
}
void Widget::on_delPButton_export_clicked()
{
int rowNum = ui->tableWidget_export->rowCount();
int curRow = ui->tableWidget_export->currentIndex().row();
if(curRow == rowNum -1 )
{
qDebug() << "select the last record , no delete !";
int rowNum1 = ui->tableWidget_export->rowCount();
QModelIndex mdidx = ui->tableWidget_export->model()->index(rowNum1-1,0);
ui->tableWidget_export->setFocus();
ui->tableWidget_export->setCurrentIndex(mdidx);
ui->tableWidget_export->edit(mdidx);
return;
}
int ok = QMessageBox::warning(this,tr("删除当前行!"),
tr("你确定删除当前行吗?"),QMessageBox::Yes, QMessageBox::No);
if(ok == QMessageBox::No)
{
}
else
{
ui->tableWidget_export->removeRow(curRow);
}
}
void Widget::on_showPButton_export_clicked()
{
ui->tableWidget_export->clear();
ui->tableWidget_export->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableWidget_export->setColumnWidth(0,200);
ui->tableWidget_export->setColumnWidth(5,200);
ui->tableWidget_export->setShowGrid(true);
QSqlQuery query;
int i = 0, j = 0, iColumn, iRow;
query.prepare("select * from export");
query.exec();
query.last();
iRow = query.at() + 1;
ui->tableWidget_export->setRowCount(iRow);
iColumn = ui->tableWidget_export->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_export->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_export->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_export->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget_export->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
int rowCount = ui->tableWidget_export->rowCount();
ui->tableWidget_export->selectRow(rowCount-1);
}
void Widget::on_commitPButton_export_clicked()
{
ui->tableWidget_export->setEditTriggers(QAbstractItemView::DoubleClicked);
int rowNum = ui->tableWidget_export->rowCount();
qDebug() <<"rowNum" <<rowNum;
if(rowNum == 0) return;
for(int i=0;i<rowNum;i++)
{
int id,number;
QString exportId,name,kind,unit,strDateTime;
exportId = ui->tableWidget_export->item(i,0)->text();
id = ui->tableWidget_export->item(i,1)->text().toInt();
name = ui->tableWidget_export->item(i,2)->text();
kind = ui->tableWidget_export->item(i,3)->text();
number = ui->tableWidget_export->item(i,4)->text().toInt();
unit = ui->tableWidget_export->item(i,5)->text();
strDateTime = ui->tableWidget_export->item(i,6)->text();
QString sql_insert;
sql_insert = "insert into export values (?,?,?,?,?,?,?)";
qDebug() << sql_insert;
QSqlQuery query;
query.prepare(sql_insert);
query.addBindValue(exportId);
query.addBindValue(id);
query.addBindValue(name);
query.addBindValue(kind);
query.addBindValue(number);
query.addBindValue(unit);
query.addBindValue(strDateTime);
if(!query.exec())
{
qDebug() << query.lastError();
}
}
ui->tableWidget_export->clear();
ui->tableWidget_export->setRowCount(0);
ui->tableWidget_export->setHorizontalHeaderLabels(QStringList()<<"ExportID"<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_export->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget_export->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
QString export0,export1,export2,export3;
export0 = "E";//means export
export2 = QDate::currentDate().toString("yyyy-MM-dd");
QString buling = "0";
int exportNumber = ui->spinBox_2->value();
if((0<exportNumber)&&(exportNumber<10))
{
export3 = buling + buling + QString::number(exportNumber,10);
} else if(((9<exportNumber)&&(exportNumber<100)))
{
export3 = buling + QString::number(exportNumber,10);
}else {
export3 = QString::number(exportNumber,10);
}
export0 = export1 + export2 + export3 ;
qDebug() << "export0" <<export0;
QString sql_insert1;
sql_insert1 = "insert into exportSheet values (?)";
QSqlQuery query;
query.prepare(sql_insert1);
query.addBindValue(export0);
if(!query.exec())
{
qDebug() << query.lastError();
}
int exportNumber1 = ui->spinBox_2->value() + 1;
ui->spinBox_2->setValue(exportNumber1);
}
void Widget::on_import_day_PButton_clicked()
{
ui->tableWidget_statistics->clear();
ui->tableWidget_statistics->setRowCount(0);
ui->tableWidget_statistics->setEditTriggers(QAbstractItemView::NoEditTriggers);
QSqlQuery query;
QString sql_select ="select importId,name,kind,sum(number),unit,importTime from import where importTime between ? and ? group by importId";
QDateTime startDateTime,endDateTime;
QDate startDate,endDate;
startDate = ui->calendarWidget->selectedDate().addDays(-1);
endDate = ui->calendarWidget->selectedDate();
QString str_startDateTime,str_endDateTime,str_startDate,str_endDate;
str_startDate = startDate.toString("yyyy-MM-dd");
str_startDateTime = str_startDate + " 00:00:00 000";
startDateTime =QDateTime::fromString(str_startDateTime,"yyyy-MM-dd HH:mm:ss zzz");
str_endDate = endDate.toString("yyyy-MM-dd");
str_endDateTime = str_endDate + " 00:00:00 000";
endDateTime = QDateTime::fromString(str_endDateTime,"yyyy-MM-dd HH:mm:ss zzz");
query.prepare(sql_select);
query.addBindValue(startDateTime);
query.addBindValue(endDateTime);
if(!query.exec())
{
qDebug() << query.lastError();
}
query.last();
int i = 0, j = 0, iColumn, iRow;
iRow = query.at() + 1;
ui->tableWidget_statistics->setRowCount(iRow);
iColumn = ui->tableWidget_statistics->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_statistics->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_statistics->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_statistics->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
// ui->tableWidget_statistics->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
int rowCount = ui->tableWidget_statistics->rowCount();
ui->tableWidget_statistics->selectRow(rowCount-1);
}
void Widget::on_import_week_PButton_clicked()
{
ui->tableWidget_statistics->clear();
ui->tableWidget_statistics->setRowCount(0);
ui->tableWidget_statistics->setEditTriggers(QAbstractItemView::NoEditTriggers);
int dayOfWeek = ui->calendarWidget->selectedDate().dayOfWeek();
QDate startDate,endDate;
QDateTime startDateTime,endDateTime;
startDate = ui->calendarWidget->selectedDate().addDays(-dayOfWeek);
endDate = ui->calendarWidget->selectedDate().addDays(+7-dayOfWeek);
QString str_startDateTime,str_endDateTime,str_startDate,str_endDate;
str_startDate = startDate.toString("yyyy-MM-dd");
str_startDateTime = str_startDate + " 00:00:00 000";
startDateTime =QDateTime::fromString(str_startDateTime,"yyyy-MM-dd HH:mm:ss zzz");
str_endDate = endDate.toString("yyyy-MM-dd");
str_endDateTime = str_endDate + " 00:00:00 000";
endDateTime = QDateTime::fromString(str_endDateTime,"yyyy-MM-dd HH:mm:ss zzz");
qDebug() << "startDateTime" << startDateTime << "endDateTime" << endDateTime;
QSqlQuery query;
int i = 0, j = 0, iColumn, iRow;
QString sql_select ="select importId,name,kind,sum(number),unit,importTime from import where importTime between ? and ? group by importId";
query.prepare(sql_select);
query.addBindValue(startDateTime);
query.addBindValue(endDateTime);
if(!query.exec())
{
qDebug() << query.lastError();
}
query.last();
iRow = query.at() + 1;
ui->tableWidget_statistics->setRowCount(iRow);
iColumn = ui->tableWidget_statistics->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_statistics->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_statistics->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_statistics->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
int rowCount = ui->tableWidget_statistics->rowCount();
ui->tableWidget_statistics->selectRow(rowCount-1);
}
void Widget::on_import_month_PButton_clicked()
{
ui->tableWidget_statistics->clear();
ui->tableWidget_statistics->setRowCount(0);
ui->tableWidget_statistics->setEditTriggers(QAbstractItemView::NoEditTriggers);
int daysInMonth = ui->calendarWidget->selectedDate().daysInMonth();
qDebug() << "daysInMonth" <<daysInMonth;
int day = ui->calendarWidget->selectedDate().day();
qDebug() << "day" <<day;
QDate startDate,endDate;
startDate = ui->calendarWidget->selectedDate().addDays(-day);
endDate = ui->calendarWidget->selectedDate().addDays(daysInMonth-day);
qDebug() << "startDate" <<startDate;
qDebug() << "endDate" <<endDate;
QString str_startDateTime,str_endDateTime;
str_startDateTime = startDate.toString("yyyy-MM-dd") + " 00:00:00 000";
str_endDateTime = endDate.toString("yyyy-MM-dd") + " 00:00:00 000";
qDebug() << "str_startDateTime" <<str_startDateTime;
qDebug() << "str_endDateTime" <<str_endDateTime;
QDateTime startDateTime,endDateTime;
startDateTime = QDateTime::fromString(str_startDateTime,"yyyy-MM-dd HH:mm:ss zzz");
endDateTime = QDateTime::fromString(str_endDateTime,"yyyy-MM-dd HH:mm:ss zzz");
qDebug() << "startDateTime" <<startDateTime;
qDebug() << "endDateTime" <<endDateTime;
QSqlQuery query;
int i = 0, j = 0, iColumn, iRow;
QString sql_select ="select importId,name,kind,sum(number),unit,importTime from import where importTime between ? and ? group by importId";
qDebug() <<"sql_select" <<sql_select;
// bool runNian;
// if(((year%4 == 0 )&&(year%100 != 0))||(year%400 == 0))
// runNian = true;
// else
// runNian = false;
// int daysOfMonth;
// switch (month) {
// case 1:daysOfMonth = 31;
// break;
// case 2:
// if(runNian)
// daysOfMonth = 29;
// else
// daysOfMonth =28;
// break;
// case 3:daysOfMonth = 31;
// break;
// case 4:daysOfMonth = 30;
// break;
// case 5:daysOfMonth = 31;
// break;
// case 6:daysOfMonth = 30;
// break;
// case 7:daysOfMonth = 31;
// break;
// case 8:daysOfMonth = 31;
// break;
// case 9:daysOfMonth = 30;
// break;
// case 10:daysOfMonth = 31;
// break;
// case 11:daysOfMonth = 30;
// break;
// case 12:daysOfMonth = 31;
// break;
// default:
// break;
// }
query.prepare(sql_select);
query.addBindValue(startDateTime);
query.addBindValue(endDateTime);
if(!query.exec())
{
qDebug() << query.lastError();
}
query.last();
iRow = query.at() + 1;
ui->tableWidget_statistics->setRowCount(iRow);
iColumn = ui->tableWidget_statistics->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_statistics->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_statistics->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_statistics->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
// ui->tableWidget_statistics->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
int rowCount = ui->tableWidget_statistics->rowCount();
ui->tableWidget_statistics->selectRow(rowCount-1);
}
void Widget::on_import_season_Button_clicked()
{
ui->tableWidget_statistics->clear();
ui->tableWidget_statistics->setRowCount(0);
ui->tableWidget_statistics->setEditTriggers(QAbstractItemView::NoEditTriggers); //禁止修改
ui->tableWidget_statistics->setColumnWidth(0,200);
ui->tableWidget_statistics->setColumnWidth(5,200);
ui->tableWidget_statistics->setShowGrid(true);
QSqlQuery query;
int i = 0, j = 0, iColumn, iRow;
query.prepare("select * from import");
query.exec();
query.last();
iRow = query.at() + 1;
ui->tableWidget_statistics->setRowCount(iRow);
iColumn = ui->tableWidget_statistics->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_statistics->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_statistics->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_statistics->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
// ui->tableWidget_statistics->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
int rowCount = ui->tableWidget_statistics->rowCount();
ui->tableWidget_statistics->selectRow(rowCount-1);
}
void Widget::on_import_year_PButton_clicked()
{
ui->tableWidget_statistics->clear();
ui->tableWidget_statistics->setRowCount(0);
ui->tableWidget_statistics->setEditTriggers(QAbstractItemView::NoEditTriggers);
QSqlQuery query;
int i = 0, j = 0, iColumn, iRow;
QString sql_select ="select importId,name,kind,sum(number),unit,importTime from import where importTime between ? and ? group by importId";
int daysInYear = ui->calendarWidget->selectedDate().daysInYear();
int dayOfYear = ui->calendarWidget->selectedDate().dayOfYear();
QDate startDate,endDate;
QDateTime startDateTime,endDateTime;
startDate = ui->calendarWidget->selectedDate().addDays(-dayOfYear);
endDate = ui->calendarWidget->selectedDate().addDays(daysInYear-dayOfYear);
QString str_startDateTime,str_endDateTime;
str_startDateTime = startDate.toString("yyyy-MM-dd") + " 00:00:00 000";
str_endDateTime = endDate.toString("yyyy-MM-dd") + " 00:00:00 000";
startDateTime = QDateTime::fromString(str_startDateTime,"yyyy-MM-dd HH:mm:ss zzz");
endDateTime = QDateTime::fromString(str_endDateTime ,"yyyy-MM-dd HH:mm:ss zzz");
qDebug() <<"startDateTime" <<startDateTime;
qDebug() <<"endDateTime" <<endDateTime;
query.prepare(sql_select);
query.addBindValue(startDateTime);
query.addBindValue(endDateTime);
if(!query.exec())
{
qDebug() << query.lastError();
}
query.last();
iRow = query.at() + 1;
ui->tableWidget_statistics->setRowCount(iRow);
iColumn = ui->tableWidget_statistics->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_statistics->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_statistics->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_statistics->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
// ui->tableWidget_statistics->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
int rowCount = ui->tableWidget_statistics->rowCount();
ui->tableWidget_statistics->selectRow(rowCount-1);
}
void Widget::on_export_season_PButton_clicked()
{
ui->tableWidget_statistics->clear();
ui->tableWidget_statistics->setRowCount(0);
ui->tableWidget_statistics->setEditTriggers(QAbstractItemView::NoEditTriggers);
QSqlQuery query;
int i = 0, j = 0, iColumn, iRow;
QString sql_select ="select exportId,name,kind,sum(number),unit,exportTime from export where exportTime between ? and ? group by exportId";
qDebug() << sql_select;
QDateTime startDateTime,endDateTime;
QDate startDate,endDate;
startDate = ui->calendarWidget->selectedDate().addDays(-1);
endDate = ui->calendarWidget->selectedDate();
QString str_startDateTime,str_endDateTime,str_startDate,str_endDate;
str_startDate = startDate.toString("yyyy-MM-dd");
str_startDateTime = str_startDate + " " + "00:00:00 000";
startDateTime =QDateTime::fromString(str_startDateTime,"yyyy-MM-dd HH:mm:ss zzz");
str_endDate = endDate.toString("yyyy-MM-dd");
str_endDateTime = str_endDate + " " + "00:00:00 000";
endDateTime = QDateTime::fromString(str_endDateTime,"yyyy-MM-dd HH:mm:ss zzz");
query.prepare(sql_select);
query.addBindValue(startDateTime);
query.addBindValue(endDateTime);
if(!query.exec())
{
qDebug() << query.lastError();
}
query.last();
iRow = query.at() + 1;
ui->tableWidget_statistics->setRowCount(iRow);
iColumn = ui->tableWidget_statistics->columnCount();
// iColumn = 3;
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_statistics->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_statistics->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_statistics->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget_statistics->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
int rowCount = ui->tableWidget_statistics->rowCount();
ui->tableWidget_statistics->selectRow(rowCount-1);
}
void Widget::on_export_day_PButton_clicked()
{
ui->tableWidget_statistics->clear();
ui->tableWidget_statistics->setRowCount(0);
ui->tableWidget_statistics->setEditTriggers(QAbstractItemView::NoEditTriggers);
QSqlQuery query;
QString sql_select ="select exportId,name,kind,sum(number),unit,exportTime from export where exportTime between ? and ? group by exportId";
QDateTime startDateTime,endDateTime;
QDate startDate,endDate;
startDate = ui->calendarWidget->selectedDate().addDays(-1);
endDate = ui->calendarWidget->selectedDate();
QString str_startDateTime,str_endDateTime,str_startDate,str_endDate;
str_startDate = startDate.toString("yyyy-MM-dd");
str_startDateTime = str_startDate + " 00:00:00 000";
startDateTime =QDateTime::fromString(str_startDateTime,"yyyy-MM-dd HH:mm:ss zzz");
str_endDate = endDate.toString("yyyy-MM-dd");
str_endDateTime = str_endDate + " 00:00:00 000";
endDateTime = QDateTime::fromString(str_endDateTime,"yyyy-MM-dd HH:mm:ss zzz");
query.prepare(sql_select);
query.addBindValue(startDateTime);
query.addBindValue(endDateTime);
if(!query.exec())
{
qDebug() << query.lastError();
}
query.last();
int i = 0, j = 0, iColumn, iRow;
iRow = query.at() + 1;
ui->tableWidget_statistics->setRowCount(iRow);
iColumn = ui->tableWidget_statistics->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_statistics->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_statistics->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_statistics->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
int rowCount = ui->tableWidget_statistics->rowCount();
ui->tableWidget_statistics->selectRow(rowCount-1);
}
void Widget::on_export_week_PButton_clicked()
{
ui->tableWidget_statistics->clear();
ui->tableWidget_statistics->setRowCount(0);
ui->tableWidget_statistics->setEditTriggers(QAbstractItemView::NoEditTriggers);
int dayOfWeek = ui->calendarWidget->selectedDate().dayOfWeek();
QDate startDate,endDate;
QDateTime startDateTime,endDateTime;
startDate = ui->calendarWidget->selectedDate().addDays(-dayOfWeek);
endDate = ui->calendarWidget->selectedDate().addDays(+7-dayOfWeek);
QString str_startDateTime,str_endDateTime,str_startDate,str_endDate;
str_startDate = startDate.toString("yyyy-MM-dd");
str_startDateTime = str_startDate + " 00:00:00 000";
startDateTime =QDateTime::fromString(str_startDateTime,"yyyy-MM-dd HH:mm:ss zzz");
str_endDate = endDate.toString("yyyy-MM-dd");
str_endDateTime = str_endDate + " 00:00:00 000";
endDateTime = QDateTime::fromString(str_endDateTime,"yyyy-MM-dd HH:mm:ss zzz");
QSqlQuery query;
int i = 0, j = 0, iColumn, iRow;
QString sql_select ="select exportId,name,kind,sum(number),unit,exportTime from export where exportTime between ? and ? group by exportId";
query.prepare(sql_select);
query.addBindValue(startDateTime);
query.addBindValue(endDateTime);
if(!query.exec())
{
qDebug() << query.lastError();
}
query.last();
iRow = query.at() + 1;
ui->tableWidget_statistics->setRowCount(iRow);
iColumn = ui->tableWidget_statistics->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_statistics->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_statistics->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_statistics->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
int rowCount = ui->tableWidget_statistics->rowCount();
ui->tableWidget_statistics->selectRow(rowCount-1);
}
void Widget::on_export_month_PButton_clicked()
{
ui->tableWidget_statistics->clear();
ui->tableWidget_statistics->setRowCount(0);
ui->tableWidget_statistics->setEditTriggers(QAbstractItemView::NoEditTriggers);
int daysInMonth = ui->calendarWidget->selectedDate().daysInMonth();
int day = ui->calendarWidget->selectedDate().day();
QDate startDate,endDate;
startDate = ui->calendarWidget->selectedDate().addDays(-day);
endDate = ui->calendarWidget->selectedDate().addDays(daysInMonth-day);
QString str_startDateTime,str_endDateTime;
str_startDateTime = startDate.toString("yyyy-MM-dd") + " 00:00:00 000";
str_endDateTime = endDate.toString("yyyy-MM-dd") + " 00:00:00 000";
QDateTime startDateTime,endDateTime;
startDateTime = QDateTime::fromString(str_startDateTime,"yyyy-MM-dd HH:mm:ss zzz");
endDateTime = QDateTime::fromString(str_endDateTime,"yyyy-MM-dd HH:mm:ss zzz");
QSqlQuery query;
int i = 0, j = 0, iColumn, iRow;
QString sql_select ="select exportId,name,kind,sum(number),unit,exportTime from export where exportTime between ? and ? group by exportId";
query.prepare(sql_select);
query.addBindValue(startDateTime);
query.addBindValue(endDateTime);
if(!query.exec())
{
qDebug() << query.lastError();
}
query.last();
iRow = query.at() + 1;
ui->tableWidget_statistics->setRowCount(iRow);
iColumn = ui->tableWidget_statistics->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_statistics->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_statistics->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_statistics->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
int rowCount = ui->tableWidget_statistics->rowCount();
ui->tableWidget_statistics->selectRow(rowCount-1);
}
void Widget::on_export_year_PButton_clicked()
{
ui->tableWidget_statistics->clear();
ui->tableWidget_statistics->setRowCount(0);
ui->tableWidget_statistics->setEditTriggers(QAbstractItemView::NoEditTriggers);
QSqlQuery query;
int i = 0, j = 0, iColumn, iRow;
QString sql_select ="select exportId,name,kind,sum(number),unit,exportTime from export where exportTime between ? and ? group by exportId";
int daysInYear = ui->calendarWidget->selectedDate().daysInYear();
int dayOfYear = ui->calendarWidget->selectedDate().dayOfYear();
QDate startDate,endDate;
QDateTime startDateTime,endDateTime;
startDate = ui->calendarWidget->selectedDate().addDays(-dayOfYear);
endDate = ui->calendarWidget->selectedDate().addDays(daysInYear-dayOfYear);
QString str_startDateTime,str_endDateTime;
str_startDateTime = startDate.toString("yyyy-MM-dd") + " 00:00:00 000";
str_endDateTime = endDate.toString("yyyy-MM-dd") + " 00:00:00 000";
startDateTime = QDateTime::fromString(str_startDateTime,"yyyy-MM-dd HH:mm:ss zzz");
endDateTime = QDateTime::fromString(str_endDateTime ,"yyyy-MM-dd HH:mm:ss zzz");
query.prepare(sql_select);
query.addBindValue(startDateTime);
query.addBindValue(endDateTime);
if(!query.exec())
{
qDebug() << query.lastError();
}
query.last();
iRow = query.at() + 1;
ui->tableWidget_statistics->setRowCount(iRow);
iColumn = ui->tableWidget_statistics->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_statistics->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_statistics->setHorizontalHeaderLabels(QStringList()<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_statistics->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
int rowCount = ui->tableWidget_statistics->rowCount();
ui->tableWidget_statistics->selectRow(rowCount-1);
}
void Widget::on_modPButton_table_clicked()
{
ui->label_show->clear();
if(ui->lineEdit_id->text() == "") return;
if(ui->lineEdit_name->text() == "") return;
QSqlQuery query;
QString sql_search;
sql_search = "select * from goods where id = ?";
query.prepare(sql_search);
QString idValue = ui->lineEdit_id->text();
query.addBindValue(idValue);
if(!query.exec())
{
qDebug() <<query.lastError();
}
if(!query.first())
{
ui->lineEdit_name->setFocus();
ui->label_show->setText("没有该商品信息!");
QFont ft;
ft.setPointSize(12);
ft.setBold(true);
ui->label_show->setFont(ft);
QPalette pal;
pal.setColor(QPalette::WindowText,Qt::red);
ui->label_show->setPalette(pal);
return;
}
QString sql_update;
sql_update = "update goods set name = ?,kind = ?,remark = ? where id = ?";
query.prepare(sql_update);
QString nameValue = ui->lineEdit_name->text();
query.addBindValue(nameValue);
QString kindValue = ui->lineEdit_kind->text();
query.addBindValue(kindValue);
QString remarkValue = ui->lineEdit_remark->text();
query.addBindValue(remarkValue);
query.addBindValue(idValue);
if(!query.exec())
{
qDebug() <<query.lastError();
}
ui->label_show->setText("更新成功!");
QFont ft;
ft.setPointSize(12);
ft.setBold(true);
ui->label_show->setFont(ft);
QPalette pal;
pal.setColor(QPalette::WindowText,Qt::red);
ui->label_show->setPalette(pal);
ui->lineEdit_id->setFocus();
}
void Widget::createPdf()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("导出PDF文件"),
QString(), "*.pdf");
if (!fileName.isEmpty()) {
// 如果文件后缀为空,则默认使用.pdf
if (QFileInfo(fileName).suffix().isEmpty())
fileName.append(".pdf");
QPrinter printer;
// 指定输出格式为pdf
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(fileName);
// ui->widget->render(&printer);
ui->widget->render(&printer);
// ui->textEdit->print(&printer);
}
}
void Widget::on_delPButton_stock_clicked()
{
int curRow = ui->tableWidget_stock->currentIndex().row();
if(curRow == -1) return;
int ok = QMessageBox::warning(this,tr("删除当前行!"),
tr("你确定删除当前行吗?"),QMessageBox::Yes, QMessageBox::No);
if(ok == QMessageBox::No)
{
}
else
{
ui->tableWidget_stock->removeRow(curRow);
}
}
void Widget::on_commitPButton_stock_clicked()
{
ui->tableWidget_stock->setEditTriggers(QAbstractItemView::DoubleClicked);
int rowNum = ui->tableWidget_stock->rowCount();
if(rowNum == 0) return;
for(int i=0;i<rowNum;i++)
{
int number;
QString stockId,id,name,kind,unit,stockTime;
stockId = ui->tableWidget_stock->item(i,0)->text();
id = ui->tableWidget_stock->item(i,1)->text();
name = ui->tableWidget_stock->item(i,2)->text();
kind = ui->tableWidget_stock->item(i,3)->text();
number = ui->tableWidget_stock->item(i,4)->text().toInt();
unit = ui->tableWidget_stock->item(i,5)->text();
stockTime= ui->tableWidget_stock->item(i,6)->text();
QString sql_insert;
sql_insert = "insert into stock values (?,?,?,?,?,?,?)";
QSqlQuery query;
query.prepare(sql_insert);
query.addBindValue(stockId);
query.addBindValue(id);
query.addBindValue(name);
query.addBindValue(kind);
query.addBindValue(number);
query.addBindValue(unit);
query.addBindValue(stockTime);
if(!query.exec())
{
qDebug() << query.lastError();
// QString error = query.lastError().text();
// QMessageBox::critical(this,"title",error,QMessageBox::Yes);
}
}
ui->tableWidget_stock->setRowCount(0);
ui->lineEdit_ID->setText("");
ui->lineEdit_ID->setFocus();
QString stock,stock1,stock2,stock3;
stock1 = "S";//means stock
stock2 = QDate::currentDate().toString("yyyy-MM-dd");
QString buling = "0";
int stockNumber = ui->spinBox->value();
if((0<stockNumber)&&(stockNumber<10))
{
stock3 = buling + buling + QString::number(stockNumber,10);
} else if(((9<stockNumber)&&(stockNumber<100)))
{
stock3 = buling + QString::number(stockNumber,10);
}else {
stock3 = QString::number(stockNumber,10);
}
stock = stock1 + stock2 + stock3 ;
qDebug() << "stock" <<stock;
QString sql_insert1;
sql_insert1 = "insert into stockSheet values (?)";
QSqlQuery query;
query.prepare(sql_insert1);
query.addBindValue(stock);
if(!query.exec())
{
qDebug() << query.lastError();
}
int stockNumber1 = ui->spinBox->value() + 1;
ui->spinBox->setValue(stockNumber1);
}
void Widget::on_printPButton_stock_clicked()
{
createPdf();
}
void Widget::on_showAllPButton_stock_clicked()
{
ui->tableWidget_stock->clear();
ui->tableWidget_stock->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableWidget_stock->setColumnWidth(0,200);
ui->tableWidget_stock->setColumnWidth(6,200);
ui->tableWidget_stock->setShowGrid(true);
QSqlQuery query;
int i = 0, j = 0, iColumn, iRow;
query.prepare("select * from stock");
query.exec();
query.last();
iRow = query.at() + 1;
ui->tableWidget_stock->setRowCount(iRow);
iColumn = ui->tableWidget_stock->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_stock->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
ui->tableWidget_stock->setHorizontalHeaderLabels(QStringList()<<"StockID"<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
ui->tableWidget_stock->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget_stock->setSelectionMode(QAbstractItemView::SingleSelection); //设置为可以选中单个
int rowCount = ui->tableWidget_stock->rowCount();
ui->tableWidget_stock->selectRow(rowCount-1);
}
void Widget::on_printTableWidgetPButton_clicked()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("导出PDF文件"),
QString(), "*.pdf");
if (!fileName.isEmpty()) {
// 如果文件后缀为空,则默认使用.pdf
if (QFileInfo(fileName).suffix().isEmpty())
fileName.append(".pdf");
QPrinter printer;
// 指定输出格式为pdf
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(fileName);
ui->tableWidget_stock->render(&printer);
}
}
void Widget::on_clear_sta_PButton_clicked()
{
ui->tableWidget_statistics->setRowCount(0);
}
void Widget::on_search_PButton_alart_clicked()
{
if((ui->radioButton->isChecked())&&(ui->checkBox->isChecked()))
qDebug() <<"radioButton checkbox";
QString str_id = ui->lineEdit_alart->text();
QString sql_query = "select * from goods where id = ?";
QSqlQuery query;
query.prepare(sql_query);
query.addBindValue(str_id);
if(!query.exec())
{
query.lastError();
}
query.first();
int rowNum = ui->tableWidget_alart->rowCount();
ui->tableWidget_alart->insertRow(rowNum);
ui->tableWidget_alart->setItem(rowNum,0,new QTableWidgetItem(str_id));
ui->tableWidget_alart->setItem(rowNum,1,new QTableWidgetItem(query.value(1).toString()));
ui->tableWidget_alart->setItem(rowNum,2,new QTableWidgetItem(query.value(2).toString()));
query.prepare(sql_query);
query.addBindValue(str_id);
if(!query.exec())
{
query.lastError();
}
query.first();
sql_query = "select sum(number) from import where importId = ?";
query.prepare(sql_query);
query.addBindValue(str_id);
if(!query.exec())
{
query.lastError();
}
query.first();
int import_Number,export_Number;
import_Number = query.value(0).toInt();
qDebug() <<"import_Number" <<import_Number;
sql_query = "select sum(number) from export where exportId = ?";
query.prepare(sql_query);
query.addBindValue(str_id);
if(!query.exec())
{
query.lastError();
}
query.first();
export_Number = query.value(0).toInt();
qDebug() <<"export_Number" <<export_Number;
QString str_number = QString::number(import_Number-export_Number);
ui->tableWidget_alart->setItem(rowNum,3,new QTableWidgetItem(str_number));
sql_query = "select * from number where id = ?";
query.prepare(sql_query);
query.addBindValue(str_id);
if(!query.exec())
{
query.lastError();
}
query.first();
QString str_minNumber = query.value(1).toString();
QString str_maxNumber = query.value(2).toString();
ui->tableWidget_alart->setItem(rowNum,6,new QTableWidgetItem(str_minNumber));
ui->tableWidget_alart->setItem(rowNum,7,new QTableWidgetItem(str_maxNumber));
}
void Widget::on_searchPButton_clicked()
{
ui->listWidget->clear();
QString stock,stock1,stock2;
stock1 = "S";//means stock
stock2 = ui->search_dateEdit->text();
qDebug() <<stock2;
stock = stock1 + stock2 + "%";
qDebug() <<"stock" <<stock;
QString sql_search = "select * from stockSheet where stockSheetId like :stock ";
qDebug() << sql_search;
QSqlQuery query ;
query.prepare(sql_search);
query. addBindValue(stock);
if(!query.exec())
{
query.lastError();
}
while (query.next())
{
ui->listWidget->addItem(query.value(0).toString());
}
}
void Widget::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
ui->tableWidget_search->clear();
ui->tableWidget_search->setRowCount(0);
ui->tableWidget_search->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableWidget_search->setHorizontalHeaderLabels(QStringList()<<"StockID"<<"ID"<<"名称"<<"种类"<<"数量"<<"单位"<<"日期和时间");
// QString stock = ui->listWidget->currentItem()->text();
QString stock = ui->listWidget->currentItem()->text();
stock = stock + "%";
QString sql_search = "select * from stock where stockId like :stock ";
QSqlQuery query ;
query.prepare(sql_search);
query. addBindValue(stock);
if(!query.exec())
{
query.lastError();
}
query.last();
int i = 0, j = 0, iColumn, iRow;
iRow = query.at() + 1;
ui->tableWidget_search->setRowCount(iRow);
iColumn = ui->tableWidget_search->columnCount();
query.first();
while(i<iRow)
{
for (j = 0; j<iColumn; j++)
ui->tableWidget_search->setItem(i, j, new QTableWidgetItem(query.value(j).toString()));
i++;
query.next();
}
}
| [
"huanghaizilu@163.com"
] | huanghaizilu@163.com |
cf2c63cb9df521a55a05ff13cee379f26bd9d7ed | b997482f96a2db288dc3459b45f0ddd06279a18d | /source/common/utls.h | 278290b5038d45e6416863c428b7f2001d9b8fa9 | [
"Apache-2.0"
] | permissive | roger912/breeze | bc7f9c3df6c99b63e0f5cbf3c9daa1c9cb4b665f | d0262c63044fa7828316fbbd12bbd8c1a4578f5f | refs/heads/master | 2021-01-17T23:54:53.758781 | 2016-01-31T17:32:24 | 2016-01-31T17:32:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,200 | h |
/*
* breeze License
* Copyright (C) 2016 YaweiZhang <yawei.zhang@foxmail.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _UTLS_H_
#define _UTLS_H_
#include <defined.h>
#include <single.h>
//file
//==========================================================================
//isBinary if false it's will auto fix UTF-8 BOM. only this.
std::string readFileContent(const std::string & filename, bool isBinary = false, size_t limitSize = 1024 * 1024, size_t beginIndex = 0);
size_t writeFileContent(const std::string & filename, const char * buff, size_t buffLen, bool isAppend = true);
bool isDirectory(const std::string & path);
bool createRecursionDir(std::string path);
bool removeFile(const std::string &pathfile);
bool removeDir(const std::string &path);
//md5
class MD5Data;
std::string genFileMD5(std::string filename);
//string
//==========================================================================
template<class T>
std::string toString(const T &t);
template<class RET>
RET fromString(const std::string & t, RET def);
//tonumber
//both 1 left, 2right, 3 both
void trim(std::string &str, std::string ign, int both = 3);
std::vector<std::string> splitString(const std::string & text, std::string deli, std::string ign);
std::string toUpperString(std::string org);
std::string toLowerString(std::string org);
bool compareStringIgnCase(const std::string & left, const std::string & right, bool canTruncate = false);
//date, time, tick
//==========================================================================
//----- sleep thread ------
void sleepMillisecond(unsigned int ms);
//----- time check ------
//check used time. don't used it as datetime.
inline double getNow();
inline double getSteadyNow();
inline long long getNowTick();
inline long long getSteadyNowTick();
//-----date time---------
//the second through 1900-01-01 00:00:00
inline time_t getCurTime();
inline time_t getTZZoneFixTime();
//the day through 1900-01-01 00:00:00
inline time_t getCurDay();
//the day through t
inline time_t getDay(time_t t);
//get struct tm via safe method
inline tm gettm(time_t ts);
//to print date time
inline std::string getDateString(time_t ts);
inline std::string getTimeString(time_t ts);
inline std::string getDateTimeString(time_t ts);
//default offset set 0
//example method isSameDay: if 03:00::00 is the day bound you can set offset = -3*3600
inline bool isSameYear(time_t first, time_t second, time_t offset = 0);
inline bool isSameMonth(time_t first, time_t second, time_t offset = 0);
inline bool isSameWeak(time_t first, time_t second, time_t offset = 0);
inline bool isSameDay(time_t first, time_t second, time_t offset = 0);
//float
//==========================================================================
const double POINT_DOUBLE = 1e-14;
const double PI = 3.14159265358979323;
inline bool isEqual(double f1, double f2, double acc = POINT_DOUBLE);
inline bool isZero(double f, double acc = POINT_DOUBLE);
inline double getDistance(double org, double dst);
inline double getDistance(double orgx, double orgy, double dstx, double dsty);
inline double getRadian(double orgx, double orgy, double dstx, double dsty);
inline std::tuple<double, double> getFarPoint(double orgx, double orgy, double radian, double distance);
inline std::tuple<double, double> getFarOffset(double orgx, double orgy, double dstx, double dsty, double distance);
inline std::tuple<double, double> rotatePoint(double orgx, double orgy, double orgrad, double distance, double radian);
//process
//==========================================================================
std::string getProcessID();
std::string getProcessName();
#include "utlsImpl.h"
#endif | [
"yawei.zhang@foxmail.com"
] | yawei.zhang@foxmail.com |
c3dee88f64404b4c7115ab73d480e4191f2f77aa | 3784495ba55d26e22302a803861c4ba197fd82c7 | /venv/lib/python3.6/site-packages/tensorflow_core/include/external/aws/aws-cpp-sdk-s3/include/aws/s3/model/ListBucketAnalyticsConfigurationsResult.h | b3e48018119ad46985fe5d654d1b931043a26f0a | [
"MIT",
"Apache-2.0"
] | permissive | databill86/HyperFoods | cf7c31f5a6eb5c0d0ddb250fd045ca68eb5e0789 | 9267937c8c70fd84017c0f153c241d2686a356dd | refs/heads/master | 2021-01-06T17:08:48.736498 | 2020-02-11T05:02:18 | 2020-02-11T05:02:18 | 241,407,659 | 3 | 0 | MIT | 2020-02-18T16:15:48 | 2020-02-18T16:15:47 | null | UTF-8 | C++ | false | false | 8,737 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/s3/S3_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/s3/model/AnalyticsConfiguration.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Xml
{
class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace S3
{
namespace Model
{
class AWS_S3_API ListBucketAnalyticsConfigurationsResult
{
public:
ListBucketAnalyticsConfigurationsResult();
ListBucketAnalyticsConfigurationsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
ListBucketAnalyticsConfigurationsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
/**
* <p>Indicates whether the returned list of analytics configurations is complete.
* A value of true indicates that the list is not complete and the
* NextContinuationToken will be provided for a subsequent request.</p>
*/
inline bool GetIsTruncated() const{ return m_isTruncated; }
/**
* <p>Indicates whether the returned list of analytics configurations is complete.
* A value of true indicates that the list is not complete and the
* NextContinuationToken will be provided for a subsequent request.</p>
*/
inline void SetIsTruncated(bool value) { m_isTruncated = value; }
/**
* <p>Indicates whether the returned list of analytics configurations is complete.
* A value of true indicates that the list is not complete and the
* NextContinuationToken will be provided for a subsequent request.</p>
*/
inline ListBucketAnalyticsConfigurationsResult& WithIsTruncated(bool value) { SetIsTruncated(value); return *this;}
/**
* <p>The ContinuationToken that represents where this request began.</p>
*/
inline const Aws::String& GetContinuationToken() const{ return m_continuationToken; }
/**
* <p>The ContinuationToken that represents where this request began.</p>
*/
inline void SetContinuationToken(const Aws::String& value) { m_continuationToken = value; }
/**
* <p>The ContinuationToken that represents where this request began.</p>
*/
inline void SetContinuationToken(Aws::String&& value) { m_continuationToken = std::move(value); }
/**
* <p>The ContinuationToken that represents where this request began.</p>
*/
inline void SetContinuationToken(const char* value) { m_continuationToken.assign(value); }
/**
* <p>The ContinuationToken that represents where this request began.</p>
*/
inline ListBucketAnalyticsConfigurationsResult& WithContinuationToken(const Aws::String& value) { SetContinuationToken(value); return *this;}
/**
* <p>The ContinuationToken that represents where this request began.</p>
*/
inline ListBucketAnalyticsConfigurationsResult& WithContinuationToken(Aws::String&& value) { SetContinuationToken(std::move(value)); return *this;}
/**
* <p>The ContinuationToken that represents where this request began.</p>
*/
inline ListBucketAnalyticsConfigurationsResult& WithContinuationToken(const char* value) { SetContinuationToken(value); return *this;}
/**
* <p>NextContinuationToken is sent when isTruncated is true, which indicates that
* there are more analytics configurations to list. The next request must include
* this NextContinuationToken. The token is obfuscated and is not a usable
* value.</p>
*/
inline const Aws::String& GetNextContinuationToken() const{ return m_nextContinuationToken; }
/**
* <p>NextContinuationToken is sent when isTruncated is true, which indicates that
* there are more analytics configurations to list. The next request must include
* this NextContinuationToken. The token is obfuscated and is not a usable
* value.</p>
*/
inline void SetNextContinuationToken(const Aws::String& value) { m_nextContinuationToken = value; }
/**
* <p>NextContinuationToken is sent when isTruncated is true, which indicates that
* there are more analytics configurations to list. The next request must include
* this NextContinuationToken. The token is obfuscated and is not a usable
* value.</p>
*/
inline void SetNextContinuationToken(Aws::String&& value) { m_nextContinuationToken = std::move(value); }
/**
* <p>NextContinuationToken is sent when isTruncated is true, which indicates that
* there are more analytics configurations to list. The next request must include
* this NextContinuationToken. The token is obfuscated and is not a usable
* value.</p>
*/
inline void SetNextContinuationToken(const char* value) { m_nextContinuationToken.assign(value); }
/**
* <p>NextContinuationToken is sent when isTruncated is true, which indicates that
* there are more analytics configurations to list. The next request must include
* this NextContinuationToken. The token is obfuscated and is not a usable
* value.</p>
*/
inline ListBucketAnalyticsConfigurationsResult& WithNextContinuationToken(const Aws::String& value) { SetNextContinuationToken(value); return *this;}
/**
* <p>NextContinuationToken is sent when isTruncated is true, which indicates that
* there are more analytics configurations to list. The next request must include
* this NextContinuationToken. The token is obfuscated and is not a usable
* value.</p>
*/
inline ListBucketAnalyticsConfigurationsResult& WithNextContinuationToken(Aws::String&& value) { SetNextContinuationToken(std::move(value)); return *this;}
/**
* <p>NextContinuationToken is sent when isTruncated is true, which indicates that
* there are more analytics configurations to list. The next request must include
* this NextContinuationToken. The token is obfuscated and is not a usable
* value.</p>
*/
inline ListBucketAnalyticsConfigurationsResult& WithNextContinuationToken(const char* value) { SetNextContinuationToken(value); return *this;}
/**
* <p>The list of analytics configurations for a bucket.</p>
*/
inline const Aws::Vector<AnalyticsConfiguration>& GetAnalyticsConfigurationList() const{ return m_analyticsConfigurationList; }
/**
* <p>The list of analytics configurations for a bucket.</p>
*/
inline void SetAnalyticsConfigurationList(const Aws::Vector<AnalyticsConfiguration>& value) { m_analyticsConfigurationList = value; }
/**
* <p>The list of analytics configurations for a bucket.</p>
*/
inline void SetAnalyticsConfigurationList(Aws::Vector<AnalyticsConfiguration>&& value) { m_analyticsConfigurationList = std::move(value); }
/**
* <p>The list of analytics configurations for a bucket.</p>
*/
inline ListBucketAnalyticsConfigurationsResult& WithAnalyticsConfigurationList(const Aws::Vector<AnalyticsConfiguration>& value) { SetAnalyticsConfigurationList(value); return *this;}
/**
* <p>The list of analytics configurations for a bucket.</p>
*/
inline ListBucketAnalyticsConfigurationsResult& WithAnalyticsConfigurationList(Aws::Vector<AnalyticsConfiguration>&& value) { SetAnalyticsConfigurationList(std::move(value)); return *this;}
/**
* <p>The list of analytics configurations for a bucket.</p>
*/
inline ListBucketAnalyticsConfigurationsResult& AddAnalyticsConfigurationList(const AnalyticsConfiguration& value) { m_analyticsConfigurationList.push_back(value); return *this; }
/**
* <p>The list of analytics configurations for a bucket.</p>
*/
inline ListBucketAnalyticsConfigurationsResult& AddAnalyticsConfigurationList(AnalyticsConfiguration&& value) { m_analyticsConfigurationList.push_back(std::move(value)); return *this; }
private:
bool m_isTruncated;
Aws::String m_continuationToken;
Aws::String m_nextContinuationToken;
Aws::Vector<AnalyticsConfiguration> m_analyticsConfigurationList;
};
} // namespace Model
} // namespace S3
} // namespace Aws
| [
"luis20dr@gmail.com"
] | luis20dr@gmail.com |
723f2a826c199c9ad1af7998027537297fa6facc | 5c76780083714014fe9029bb457490af472401ee | /include/franka_force_control/force_example_controller.h | f3abfbac5b2cb7cfce72be479e89143ed876ef1f | [] | no_license | marselap/franka_force_control | 0d963d1b7a151ad80a3ec9f207549cf0bd1eedb7 | 602ef46b90f5fb9cd4f438bef59abcd191da0f76 | refs/heads/master | 2023-02-16T20:52:53.680034 | 2021-01-14T20:30:10 | 2021-01-14T20:30:10 | 207,261,054 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,680 | h | // Copyright (c) 2017 Franka Emika GmbH
// Use of this source code is governed by the Apache-2.0 license, see LICENSE
#pragma once
#include <memory>
#include <string>
#include <vector>
#include <cmath>
#include <time.h>
#include <controller_interface/multi_interface_controller.h>
#include <dynamic_reconfigure/server.h>
#include <franka_hw/franka_model_interface.h>
#include <franka_hw/franka_state_interface.h>
#include <hardware_interface/joint_command_interface.h>
#include <hardware_interface/robot_hw.h>
#include <ros/node_handle.h>
#include <ros/time.h>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/Geometry>
#include <Eigen/QR>
#include <franka_force_control/desired_mass_paramConfig.h>
#include <franka_hw/franka_cartesian_command_interface.h>
#include "std_msgs/Float32MultiArray.h"
#include "std_msgs/Bool.h"
#include "geometry_msgs/WrenchStamped.h"
#include "geometry_msgs/Point.h"
#include "visualization_msgs/Marker.h"
#include <franka_msgs/ErrorRecoveryAction.h>
#include <franka_msgs/ErrorRecoveryActionGoal.h>
#include <franka_force_control/median_filter.h>
#include <franka_force_control/pid.h>
#define MAX_FILTER_SAMPLES_NUM 100
namespace franka_force_control {
class ForceExampleController : public controller_interface::MultiInterfaceController<
franka_hw::FrankaModelInterface,
hardware_interface::EffortJointInterface,
franka_hw::FrankaStateInterface,
franka_hw::FrankaPoseCartesianInterface> {
public:
bool init(hardware_interface::RobotHW* robot_hw, ros::NodeHandle& node_handle) override;
void starting(const ros::Time&) override;
void update(const ros::Time&, const ros::Duration& period) override;
private:
// Saturation
Eigen::Matrix<double, 7, 1> saturateTorqueRate(
const Eigen::Matrix<double, 7, 1>& tau_d_calculated,
const Eigen::Matrix<double, 7, 1>& tau_J_d); // NOLINT (readability-identifier-naming)
ros::Publisher tau_ext_pub, tau_d_pub, tau_cmd_pub, force_ext_pub,
force_des_pub, force_pid_pub, force_nof_pub, force_ref_pub,
force_cor_pub;
ros::Publisher pos_ref_glob_pub, pos_glob_pub;
ros::Publisher marker_pos_, marker_pip_;
ros::Subscriber reset_sub_, force_torque_ref_, impedance_pos_ref_, gripper_type_sub_;
std::unique_ptr<franka_hw::FrankaModelHandle> model_handle_;
std::unique_ptr<franka_hw::FrankaStateHandle> state_handle_;
std::vector<hardware_interface::JointHandle> joint_handles_;
ros::Publisher ori_pid_roll_msg_pub_, ori_pid_pitch_msg_pub_, ori_pid_yaw_msg_pub_;
ros::Publisher wrench_pid_pub_[6];
ros::Publisher state_handle_pub_, model_handle_pub_;
std::unique_ptr<franka_hw::FrankaCartesianPoseHandle> cartesian_pose_handle_;
double desired_mass_{0.0};
double desired_x_{0.0};
double desired_y_{0.0};
double desired_z_{0.0};
double desired_tx_{0.0};
double desired_ty_{0.0};
double desired_tz_{0.0};
double target_mass_{0.0};
double target_x_{0.0};
double target_y_{0.0};
double target_z_{0.0};
double target_tx_{3.14};
double target_ty_{0.0};
double target_tz_{0.0};
double k_p_{0.0};
double k_i_{0.0};
bool starting_ = true;
double target_k_p_{0.0};
double target_k_i_{0.0};
Eigen::Matrix<double, 6, 3> ft_pid;
Eigen::Matrix<double, 6, 3> ft_pid_target;
Eigen::Matrix<double, 1, 3> pid_ori_x_target, pid_ori_x;
Eigen::Matrix<double, 1, 3> pid_ori_y_target, pid_ori_y;
Eigen::Matrix<double, 1, 3> pid_ori_z_target, pid_ori_z;
double f_p_x_{1.0};
double f_i_x_{0.2};
double f_d_x_{0.0};
double f_p_y_{1.0};
double f_i_y_{0.2};
double f_d_y_{0.0};
double f_p_z_{1.0};
double f_i_z_{0.2};
double f_d_z_{0.0};
double t_p_x_{0.3};
double t_i_x_{0.0};
double t_d_x_{0.0};
double t_p_y_{0.3};
double t_i_y_{0.02};
double t_d_y_{0.0};
double t_p_z_{0.4};
double t_i_z_{0.0};
double t_d_z_{0.0};
double integrator_limit_{10.0};
Eigen::Matrix<double, 6, 1> f_err_prev_;
Eigen::Matrix<double, 6, 1> f_err_int_;
double filter_gain_{0.001};
Eigen::Matrix<double, 7, 1> tau_ext_initial_;
Eigen::Matrix<double, 6, 1> ext_force_initial_;
Eigen::Matrix<double, 7, 1> tau_error_;
static constexpr double kDeltaTauMax{1.0};
// Dynamic reconfigure
std::unique_ptr<dynamic_reconfigure::Server<franka_force_control::desired_mass_paramConfig>>
dynamic_server_desired_mass_param_;
ros::NodeHandle dynamic_reconfigure_desired_mass_param_node_;
void desiredMassParamCallback(franka_force_control::desired_mass_paramConfig& config,
uint32_t level);
void reset_callback(const franka_msgs::ErrorRecoveryActionGoal& msg);
void ft_ref_callback(const geometry_msgs::WrenchStamped::ConstPtr& msg);
void imp_pos_ref_callback(const geometry_msgs::Point::ConstPtr& msg);
void gripper_type_callback(const std_msgs::Bool::ConstPtr& msg);
void getAnglesFromRotationTranslationMatrix(Eigen::Matrix4d &rotationTranslationMatrix, float *angles);
void rviz_markers_plot(Eigen::VectorXd position);
void filter_new_params();
void wrapErrToPi(float* orientation_meas);
void debug_publish_force(Eigen::Matrix<double, 6, 1> force_imp, Eigen::Matrix<double, 6, 1> force_meas,
Eigen::VectorXd desired_force_torque, Eigen::Matrix<double, 6, 1> force_pid, Eigen::Matrix<double, 6, 1> force_cor);
void debug_publish_tau(Eigen::VectorXd tau_ext, Eigen::VectorXd tau_d, Eigen::VectorXd tau_cmd_pid);
bool gripper_rigid_{false};
Eigen::Matrix<double, 6, 1> PID_ft(Eigen::Matrix<double, 6, 1> measured,
Eigen::Matrix<double, 6, 1> desired,
const ros::Duration& period);
Eigen::Matrix<double, 6, 1> antiWindup(Eigen::Matrix<double, 6, 1> u);
median_filter filter_x_, filter_y_, filter_z_;
median_filter force_filter_[6];
float force_filt_x_, force_filt_y_, force_filt_z_;
std::array<double, 6> force_filtered_;
Eigen::Matrix<double, 6, 1> force_meas_init_;
int median_size_;
// impedance
double pos_step_{0.01}, time_step_{0.0};
double loc_d_x_{0.0}, loc_d_y_{0.0}, loc_d_z_{0.0};
double count_time_{0.0};
Eigen::Matrix<double, 3, 1> pos_global_prev_, vel_global_prev_;
Eigen::Matrix<double, 4, 1> dXglobal_;
double imp_f_{0.1}, imp_m_{3.}, imp_d_{31.6228}, imp_k_{50.}, imp_scale_{5.0}, imp_scale_m_{0.0}, imp_scale_m_i_{0.0};
double target_imp_f_{0.}, target_imp_m_{0.}, target_imp_d_{10.}, target_imp_k_{2.5}, target_imp_scale_{4.0}, target_imp_scale_m_{0.0}, target_imp_scale_m_i_{0.0};
Eigen::Matrix<double, 6, 1> impedanceOpenLoop(const ros::Duration& period,
Eigen::Matrix<double, 6, 1> f_ext,
Eigen::VectorXd incline);
Eigen::Matrix<double, 4, 1> posGlEE_prev_;
int wiggle_timer_{0};
Eigen::Matrix<double, 3, 1> wiggle_moments_;
float vel_ampl_prev_{0.};
Eigen::Matrix<double, 3, 1> wiggle(float velocity_amplitude);
Eigen::VectorXd polyfit(Eigen::VectorXd xvals, Eigen::VectorXd yvals,int order);
int polyfit_history{0};
Eigen::MatrixXd history_pos_;
Eigen::VectorXd directionPrediction(Eigen::VectorXd position);
int flag_reset_{10};
Eigen::VectorXd incline_, target_incline_;
Eigen::VectorXd moments_integrate_;
Eigen::VectorXd cummulative_dist_, distances_;
int marker_id_{0};
int count_markers_{0};
int pipe_dir_freq_{20};
PID orientation_pid_roll, orientation_pid_pitch, orientation_pid_yaw;
PID wrench_pid[6];
};
} // namespace franka_force_control
| [
"marselapolic@gmail.com"
] | marselapolic@gmail.com |
3a783f6e650f356bd0ef1135ff973df842be0ed5 | ca1d841700e3d4112df65a2b504d9ee7aa65a922 | /src/main.cpp | 69d5ba521834b9a922c0ea149f1c92fc6c1bd012 | [] | no_license | roop/onrakan | c2bb560552e584099853f7899f2e882b07ae557c | b484e622d84fe5e00aeaf4e34541cd2f565998cf | refs/heads/master | 2016-09-06T14:51:22.153096 | 2010-07-11T11:44:40 | 2010-07-11T11:44:40 | 32,131,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 260 | cpp | #include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
#if defined(Q_WS_S60) || defined(Q_WS_MAEMO_5)
w.showMaximized();
#else
w.show();
#endif
return a.exec();
}
| [
"roopesh.chander@408eb158-d1f9-561f-b18b-a7d84d174abe"
] | roopesh.chander@408eb158-d1f9-561f-b18b-a7d84d174abe |
937c51d9f9b24dec74975d7ea02824875fcd2d82 | 7bc675e2c9be16985f0c05d63fd081e0a597e930 | /Tests/TracesFeeder/TracesFeeder/sources/TracesTableRow.hpp | a5971823e1a73988a74d991978ba915a85611bba | [] | no_license | cobreti/TracingUtilities | eddc78f3976830d6a0943234ebbba8080a03f8a9 | d31c7e31f289b9b9eb86cf4dfc960ac1ea49e4e4 | refs/heads/master | 2021-01-10T13:04:53.596744 | 2016-04-06T00:49:28 | 2016-04-06T00:49:28 | 49,793,233 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,515 | hpp | #ifndef TracesTableRow_HPP
#define TracesTableRow_HPP
#include <qtcore>
#include <QTableWidget>
#include "sources/outputitem.hpp"
#include "sources/iconset.hpp"
class TracesTableRow
{
friend class TracesTable;
public:
using RowIdT = OutputItem::OutputItemIdT;
enum State
{
eState_Stopped,
eState_Playing,
eState_Stoping,
eState_Starting
};
using RowIconSet = IconSet<State>;
public:
~TracesTableRow();
TracesTableRow(const TracesTableRow&) = delete;
TracesTableRow& operator = (const TracesTableRow&) = delete;
RowIdT id() const noexcept { return rowId_; }
State state() const noexcept { return state_; }
const OutputItem& item() const noexcept { return item_; }
void setState(State state);
void setError();
void clearError();
protected:
TracesTableRow( int insertRow, const OutputItem& item, QTableWidget *pTableWidget, const RowIconSet& iconSet, const QIcon& errorIcon );
void updateFromState();
protected:
QTableWidget *pTableWidget_;
OutputItem item_;
QTableWidgetItem *pModuleNameWidgetItem_;
QTableWidgetItem *pFrequencyWidgetItem_;
QTableWidgetItem *pTraceContentWidgetItem_;
QTableWidgetItem *pStartStopWidgetItem_;
QTableWidgetItem *pErrorIndicatorWidgetItem;
RowIdT rowId_;
State state_;
const RowIconSet& icons_;
const QIcon& errorIcon_;
};
#endif // TracesTableRow_HPP
| [
"dannyt@DarksunMac.local"
] | dannyt@DarksunMac.local |
832eeef5e72e34f8986300e01ef0526e9d26ca6a | 5bfa95aefa3039d72e169905e56974c12447e6aa | /core/cpp/yijinjing/src/nanomsg/socket.cpp | 9e5021d257cf1f336b8f499acb23646a68a5f22a | [
"Apache-2.0"
] | permissive | lf-shaw/kungfu | c955b29038f7c30f2cbbe57da5a89deda4416844 | 22a9ec192f4129e61697fdbdbfe1326b5f2886d4 | refs/heads/master | 2023-04-04T06:20:01.977670 | 2021-04-02T07:57:00 | 2021-04-02T07:57:00 | 138,162,932 | 0 | 0 | Apache-2.0 | 2021-04-02T07:57:01 | 2018-06-21T11:43:41 | C++ | UTF-8 | C++ | false | false | 4,287 | cpp | //
// Created by Keren Dong on 2019-05-25.
//
#include <spdlog/spdlog.h>
#include <kungfu/yijinjing/util/util.h>
#include <kungfu/yijinjing/nanomsg/socket.h>
using namespace kungfu::yijinjing::nanomsg;
static const char *symbol (int i, int *value)
{
return nn_symbol (i, value);
}
static void term ()
{
nn_term ();
}
const char *nn_exception::what () const throw ()
{
return nn_strerror (errno_);
}
int nn_exception::num () const
{
return errno_;
}
socket::socket (int domain, protocol p, int buffer_size): protocol_(p), buf_(buffer_size)
{
sock_ = nn_socket (domain, static_cast<int>(p));
if (sock_ < 0)
{
SPDLOG_DEBUG("can not create socket");
throw nn_exception ();
}
}
socket::~socket ()
{
nn_close (sock_);
}
void socket::setsockopt (int level, int option, const void *optval,
size_t optvallen)
{
int rc = nn_setsockopt (sock_, level, option, optval, optvallen);
if (rc != 0)
{
SPDLOG_DEBUG("can not setsockopt");
throw nn_exception ();
}
}
void socket::setsockopt_str (int level, int option, std::string value)
{
setsockopt(level, option, value.c_str(), value.length());
}
void socket::setsockopt_int (int level, int option, int value)
{
setsockopt(level, option, &value, sizeof(value));
}
void socket::getsockopt (int level, int option, void *optval,
size_t *optvallen)
{
int rc = nn_getsockopt (sock_, level, option, optval, optvallen);
if (rc != 0)
{
SPDLOG_DEBUG("can not getsockopt");
throw nn_exception ();
}
}
int socket::getsockopt_int (int level, int option)
{
int rc;
size_t s = sizeof(rc);
getsockopt(level, option, &rc, &s);
return rc;
}
int socket::bind (const std::string &path)
{
url_ = "ipc://" + path;
int rc = nn_bind (sock_, url_.c_str());
if (rc < 0)
{
SPDLOG_ERROR("can not bind to {}", url_);
throw nn_exception ();
}
return rc;
}
int socket::connect (const std::string &path)
{
url_ = "ipc://" + path;
int rc = nn_connect (sock_, url_.c_str());
if (rc < 0)
{
SPDLOG_ERROR("can not connect to {}", url_);
throw nn_exception ();
}
return rc;
}
void socket::shutdown (int how)
{
int rc = nn_shutdown (sock_, how);
if (rc != 0)
{
SPDLOG_DEBUG("can not shutdown");
throw nn_exception ();
}
}
void socket::close ()
{
int rc = nn_close (sock_);
if (rc != 0)
{
SPDLOG_DEBUG("can not close");
throw nn_exception ();
}
}
int socket::send (const std::string& msg, int flags) const
{
int rc = nn_send (sock_, msg.c_str(), msg.length(), flags);
if (rc < 0) {
if (nn_errno () != EAGAIN)
{
SPDLOG_ERROR("can not send to {} errno [{}] {}", url_, nn_errno(), nn_strerror(nn_errno()));
throw nn_exception ();
}
return -1;
}
return rc;
}
int socket::recv (int flags)
{
int rc = nn_recv (sock_, buf_.data(), buf_.size(), flags);
if (rc < 0) {
switch (nn_errno())
{
case ETIMEDOUT:
case EAGAIN:
break;
case EINTR:
{
SPDLOG_WARN("interrupted when receiving from {}", url_);
break;
}
default:
{
SPDLOG_ERROR("can not recv from {} errno [{}] {}", url_, nn_errno(), nn_strerror(nn_errno()));
throw nn_exception ();
}
}
message_.assign(buf_.data(), 0);
return 0;
} else
{
message_.assign(buf_.data(), rc);
return rc;
}
}
const std::string& socket::recv_msg(int flags)
{
recv(flags);
return message_;
}
int socket::send_json (const nlohmann::json &msg, int flags) const
{
return send(msg.dump(), flags);
}
nlohmann::json socket::recv_json (int flags)
{
int rc = 0;
if ((rc = recv(flags)) > 0)
{
SPDLOG_INFO("parsing json {} {}", rc, message_);
return nlohmann::json::parse(message_);
}
else
{
return nlohmann::json();
}
}
const std::string& socket::request(const std::string &json_message)
{
send(json_message);
return recv_msg();
}
| [
"dongkeren@gmail.com"
] | dongkeren@gmail.com |
9642bccf8e591ca22a82551905a813308ccd9f80 | a11aa0a45ffd68ba87e9381c2615d08fc31b3f51 | /Atlas Engine/Source/New/Managers/Mesh/3D/Mesh3DManager.cpp | 307a0ca1676ee3463735c4797636c27c7853cee9 | [] | no_license | YanniSperon/Atlas-Engine | 7e2c17ddd84cdb0800054ec24f64e3cd67fd62d4 | b6f12e445e8342c2c5625d023a7fca8e253d78a5 | refs/heads/master | 2023-01-31T01:40:34.648755 | 2020-12-07T10:58:57 | 2020-12-07T10:58:57 | 277,727,067 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,532 | cpp | #include "Mesh3DManager.h"
#include "New/Rendering/3D/Object/Object3D.h"
#include "New/System/Console/Console.h"
#include "New/Mesh/Shared/Generator/MeshGenerator.h"
Atlas::VRAMHandle* Atlas::Mesh3DManager::LoadIntoVRAM(Mesh3D* mesh)
{
VRAMHandle* handle = new VRAMHandle();
glGenBuffers(1, &handle->vbo);
glBindBuffer(GL_ARRAY_BUFFER, handle->vbo);
glBufferData(GL_ARRAY_BUFFER, mesh->VertexBufferSize(), mesh->vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (char*)(sizeof(float) * 3));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (char*)(sizeof(float) * 5));
glGenBuffers(1, &handle->ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, handle->ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mesh->IndexBufferSize(), mesh->indices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glFinish();
return handle;
}
void Atlas::Mesh3DManager::UnloadFromVRAM(VRAMHandle* handle)
{
glDeleteBuffers(1, &handle->vbo);
glDeleteBuffers(1, &handle->vbo);
}
Atlas::Mesh3DManager::Mesh3DManager()
: Updatable(60), loadedMeshes(), vramReference()
{
}
Atlas::Mesh3DManager::~Mesh3DManager()
{
for (auto it : vramReference) {
UnloadFromVRAM(it.second);
delete it.second;
}
vramReference.clear();
for (auto it : loadedMeshes) {
it.second->DeleteMesh();
delete it.second;
}
loadedMeshes.clear();
}
void Atlas::Mesh3DManager::Update(float deltaTime)
{
Updatable::Update(deltaTime);
if (Updatable::ShouldUpdate()) {
for (auto it = loadedMeshes.begin(); it != loadedMeshes.end();) {
Mesh3D* mesh = it->second;
if (mesh->referencingObjects.size() == 0) {
VRAMHandle* ref = vramReference[mesh];
UnloadFromVRAM(ref);
vramReference.erase(mesh);
delete ref;
mesh->DeleteMesh();
it = loadedMeshes.erase(it);
delete mesh;
}
else {
it++;
}
}
}
}
Atlas::Mesh3D* Atlas::Mesh3DManager::LoadMesh(const std::string& filepath)
{
Mesh3D* tempMesh = nullptr;
for (auto it : loadedMeshes) {
if (it.second->filepath == filepath) {
tempMesh = it.second;
}
}
if (tempMesh) {
return tempMesh;
}
else {
Mesh3D* mesh = MeshGenerator::Generate3D(filepath);
return GetMesh(mesh);
}
}
Atlas::Mesh3D* Atlas::Mesh3DManager::GetMesh(Mesh3D* mesh)
{
if (loadedMeshes.find(mesh->name) == loadedMeshes.end()) {
// doesnt exist
loadedMeshes[mesh->name] = mesh;
vramReference[mesh] = LoadIntoVRAM(mesh);
}
else {
// does exist
int count = 0;
while (loadedMeshes.find(mesh->name + std::to_string(count)) != loadedMeshes.end()) {
count++;
}
std::string newName = mesh->name + std::to_string(count);
mesh->name = newName;
loadedMeshes[newName] = mesh;
vramReference[mesh] = LoadIntoVRAM(mesh);
}
return mesh;
}
void Atlas::Mesh3DManager::DeleteReference(Object* obj)
{
for (auto it : loadedMeshes) {
Object3D* obj3d = (Object3D*)obj;
if (it.second == obj3d->GetMesh()) {
it.second->referencingObjects.erase(obj);
}
}
}
void Atlas::Mesh3DManager::AddReference(Object* obj)
{
Object3D* obj3d = (Object3D*)obj;
obj3d->GetMesh()->referencingObjects.insert(obj);
}
void Atlas::Mesh3DManager::DeleteMesh(const std::string& name)
{
if (loadedMeshes.find(name) == loadedMeshes.end()) {
// doesnt exist
// do nothing
Console::Warning("Attempting to delete mesh that does not exist");
}
else {
Mesh3D* mesh = loadedMeshes[name];
VRAMHandle* ref = vramReference[mesh];
UnloadFromVRAM(ref);
vramReference.erase(mesh);
delete ref;
mesh->DeleteMesh();
loadedMeshes.erase(mesh->name);
delete mesh;
}
}
void Atlas::Mesh3DManager::DeleteMesh(Mesh3D* mesh)
{
if (loadedMeshes.find(mesh->name) == loadedMeshes.end()) {
Console::Warning("Attempting to delete unloaded mesh");
}
else {
Mesh3D* mesh = loadedMeshes[mesh->name];
VRAMHandle* ref = vramReference[mesh];
UnloadFromVRAM(ref);
vramReference.erase(mesh);
delete ref;
mesh->DeleteMesh();
loadedMeshes.erase(mesh->name);
delete mesh;
}
}
void Atlas::Mesh3DManager::SetMesh(Mesh3D* newMesh)
{
int count = 0;
while (loadedMeshes.find(newMesh->name + std::to_string(count)) != loadedMeshes.end()) {
count++;
}
std::string newName = newMesh->name + std::to_string(count);
newMesh->name = newName;
loadedMeshes[newName] = newMesh;
vramReference[newMesh] = LoadIntoVRAM(newMesh);
}
void Atlas::Mesh3DManager::ReplaceMesh(Mesh3D* newMesh)
{
if (loadedMeshes.find(newMesh->name) == loadedMeshes.end()) {
// Does not exist
loadedMeshes[newMesh->name] = newMesh;
vramReference[newMesh] = LoadIntoVRAM(newMesh);
}
else {
// Does exist
Mesh3D* mesh = loadedMeshes[newMesh->name];
VRAMHandle* ref = vramReference[mesh];
UnloadFromVRAM(ref);
vramReference.erase(mesh);
delete ref;
std::set<Object*> referencingObjects = std::set<Object*>(mesh->referencingObjects);
mesh->DeleteMesh();
loadedMeshes.erase(mesh->name);
delete mesh;
loadedMeshes[newMesh->name] = newMesh;
newMesh->referencingObjects = referencingObjects;
vramReference[newMesh] = LoadIntoVRAM(newMesh);
for (auto obj : newMesh->referencingObjects) {
Object3D* obj3d = (Object3D*)obj;
obj3d->SetMesh(newMesh);
obj3d->SetVRAMHandle(vramReference[newMesh]);
}
}
}
Atlas::VRAMHandle* Atlas::Mesh3DManager::GetVRAMHandle(Mesh3D* mesh)
{
return vramReference[mesh];
}
| [
"yannisperon@gmail.com"
] | yannisperon@gmail.com |
7a200595b8e2ab09c8f8ca2febeebb0b526fd1e8 | 66af1a552d9ff89fac0c717cc96e7e5e2c08b98d | /examples/GroveUltrasonicRanger/GroveUltrasonicRanger.ino | 31f8ae22023b925f7988dcc77f8cec5cf087db10 | [] | no_license | matsujirushi/MjGrove | 3daf0ed14d283bd9c02acfacb36b88e8672329e1 | 298828eb140abb85a8f1ac985c6b079e9619cf7a | refs/heads/master | 2021-06-16T13:04:55.431245 | 2019-09-08T05:10:51 | 2019-09-08T05:10:51 | 140,291,890 | 10 | 5 | null | 2019-06-22T11:01:37 | 2018-07-09T13:47:26 | C++ | UTF-8 | C++ | false | false | 383 | ino | // BOARD Seeed Wio 3G
// GROVE D38 <-> Grove - Ultrasonic Ranger (SKU#101020010)
#include <MjGrove.h>
#define INTERVAL (100)
GroveBoard Board;
GroveUltrasonicRanger Ranger(&Board.D38);
void setup() {
delay(200);
SerialUSB.begin(115200);
Board.D38.Enable();
Ranger.Init();
}
void loop() {
Ranger.Read();
SerialUSB.println(Ranger.Distance);
delay(INTERVAL);
}
| [
"matsujirushi@live.jp"
] | matsujirushi@live.jp |
ab6fc96410f77bc1ec47318cea426d91db3fae0e | b1b3d00f9e4200e77eec6a98e292af3fc7a04cc6 | /C++/Week_10/Assignment_1/evaluator_jin/evaluator_jin.hpp | a53743f15f574dfd57c0ff11d9c0bdfab1e4461e | [] | no_license | wjdwls0630/Software_Lab | 79f29889d083b50104e398ca12d0bfb6efbaa13f | 3e219d416e186b7814f2577548b5477407d9d36f | refs/heads/master | 2020-09-05T06:46:32.859494 | 2019-12-01T11:13:26 | 2019-12-01T11:13:26 | 220,014,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | hpp | //
// Created by ParkJungJin on 2019-11-07.
//
#ifndef _EVALUATOR_JIN_HPP
#define _EVALUATOR_JIN_HPP
#include <cmath>
#include <Eigen/Dense>
#include "../file_stream/file_stream.hpp"
class evaluator_jin {
private:
int m_nbits;
int m_nsamplespersymbol;
int m_nbitspersymbol;
int m_eb;
double m_no;
int m_k;
double m_BER; //bit per error
Eigen::MatrixXi m_data; //from the sender
Eigen::MatrixXi m_decoded_data;//from the receiver
public:
evaluator_jin(int mNbits, int mNsamplespersymbol, int mNbitspersymbol, int mEb, double mNo, double mk);
void evaluate();
void receiveData();
};
#endif //_EVALUATOR_JIN_HPP
| [
"wjdwls0630@gmail.com"
] | wjdwls0630@gmail.com |
0370ade33ae0b0570d5fb0fa65718ba640906d8a | 31f5cddb9885fc03b5c05fba5f9727b2f775cf47 | /thirdparty/physx/physx/source/lowleveldynamics/src/DyThreadContext.h | a2327825bc44b84c514549f59c42eb27cf2e8c32 | [
"MIT"
] | permissive | timi-liuliang/echo | 2935a34b80b598eeb2c2039d686a15d42907d6f7 | d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24 | refs/heads/master | 2023-08-17T05:35:08.104918 | 2023-08-11T18:10:35 | 2023-08-11T18:10:35 | 124,620,874 | 822 | 102 | MIT | 2021-06-11T14:29:03 | 2018-03-10T04:07:35 | C++ | UTF-8 | C++ | false | false | 7,919 | h | //
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef DY_THREADCONTEXT_H
#define DY_THREADCONTEXT_H
#include "foundation/PxTransform.h"
#include "PxvConfig.h"
#include "CmBitMap.h"
#include "CmMatrix34.h"
#include "PxcThreadCoherentCache.h"
#include "DyThresholdTable.h"
#include "PsAllocator.h"
#include "PsAllocator.h"
#include "GuContactBuffer.h"
#include "DySolverConstraintDesc.h"
#include "PxvDynamics.h"
#include "DyArticulation.h"
#include "DyFrictionPatchStreamPair.h"
#include "PxcConstraintBlockStream.h"
#include "DyCorrelationBuffer.h"
namespace physx
{
struct PxsIndexedContactManager;
namespace Dy
{
//Needed by all constraints
struct PxTGSSolverBodyVel
{
PX_ALIGN(16, PxVec3) linearVelocity; //12
PxU16 nbStaticInteractions; //14 Used to accumulate the number of static interactions
PxU16 maxDynamicPartition; //16 Used to accumualte the max partition of dynamic interactions
PxVec3 angularVelocity; //28
PxU32 partitionMask; //32 Used in partitioning as a bit-field
PxVec3 deltaAngDt; //44
PxReal maxAngVel; //48
PxVec3 deltaLinDt; //60
PxU16 lockFlags; //62
bool isKinematic; //63
PxU8 pad; //64
PX_FORCE_INLINE PxReal projectVelocity(const PxVec3& lin, const PxVec3& ang) const
{
return linearVelocity.dot(lin) + angularVelocity.dot(ang);
}
};
//Needed only by prep, integration and 1D constraints
struct PxTGSSolverBodyTxInertia
{
PxTransform deltaBody2World;
PxMat33 sqrtInvInertia;
};
struct PxStepSolverBodyData
{
PX_ALIGN(16, PxVec3) originalLinearVelocity;
PxReal maxContactImpulse;
PxVec3 originalAngularVelocity;
PxReal penBiasClamp;
PxReal invMass;
PxU32 nodeIndex;
PxReal reportThreshold;
PxU32 pad;
PxReal projectVelocity(const PxVec3& linear, const PxVec3& angular) const
{
return originalLinearVelocity.dot(linear) + originalAngularVelocity.dot(angular);
}
};
/*!
Cache information specific to the software implementation(non common).
See PxcgetThreadContext.
Not thread-safe, so remember to have one object per thread!
TODO! refactor this and rename(it is a general per thread cache). Move transform cache into its own class.
*/
class ThreadContext :
public PxcThreadCoherentCache<ThreadContext, PxcNpMemBlockPool>::EntryBase
{
PX_NOCOPY(ThreadContext)
public:
#if PX_ENABLE_SIM_STATS
struct ThreadSimStats
{
void clear()
{
numActiveConstraints = 0;
numActiveDynamicBodies = 0;
numActiveKinematicBodies = 0;
numAxisSolverConstraints = 0;
}
PxU32 numActiveConstraints;
PxU32 numActiveDynamicBodies;
PxU32 numActiveKinematicBodies;
PxU32 numAxisSolverConstraints;
};
#endif
//TODO: tune cache size based on number of active objects.
ThreadContext(PxcNpMemBlockPool* memBlockPool);
void reset();
void resizeArrays(PxU32 frictionConstraintDescCount, PxU32 articulationCount);
PX_FORCE_INLINE Ps::Array<ArticulationSolverDesc>& getArticulations() { return mArticulations; }
#if PX_ENABLE_SIM_STATS
PX_FORCE_INLINE ThreadSimStats& getSimStats()
{
return mThreadSimStats;
}
#endif
Gu::ContactBuffer mContactBuffer;
// temporary buffer for correlation
PX_ALIGN(16, CorrelationBuffer mCorrelationBuffer);
FrictionPatchStreamPair mFrictionPatchStreamPair; // patch streams
PxsConstraintBlockManager mConstraintBlockManager; // for when this thread context is "lead" on an island
PxcConstraintBlockStream mConstraintBlockStream; // constraint block pool
// this stuff is just used for reformatting the solver data. Hopefully we should have a more
// sane format for this when the dust settles - so it's just temporary. If we keep this around
// here we should move these from public to private
PxU32 mNumDifferentBodyConstraints;
PxU32 mNumDifferentBodyFrictionConstraints;
PxU32 mNumSelfConstraints;
PxU32 mNumSelfFrictionConstraints;
PxU32 mNumSelfConstraintBlocks;
PxU32 mNumSelfConstraintFrictionBlocks;
Ps::Array<PxU32> mConstraintsPerPartition;
Ps::Array<PxU32> mFrictionConstraintsPerPartition;
Ps::Array<PxU32> mPartitionNormalizationBitmap;
PxsBodyCore** mBodyCoreArray;
PxsRigidBody** mRigidBodyArray;
ArticulationV** mArticulationArray;
Cm::SpatialVector* motionVelocityArray;
PxU32* bodyRemapTable;
PxU32* mNodeIndexArray;
//Constraint info for normal constraint sovler
PxSolverConstraintDesc* contactConstraintDescArray;
PxU32 contactDescArraySize;
PxSolverConstraintDesc* orderedContactConstraints;
PxConstraintBatchHeader* contactConstraintBatchHeaders;
PxU32 numContactConstraintBatches;
//Constraint info for partitioning
PxSolverConstraintDesc* tempConstraintDescArray;
//Additional constraint info for 1d/2d friction model
Ps::Array<PxSolverConstraintDesc> frictionConstraintDescArray;
Ps::Array<PxConstraintBatchHeader> frictionConstraintBatchHeaders;
//Info for tracking compound contact managers (temporary data - could use scratch memory!)
Ps::Array<CompoundContactManager> compoundConstraints;
//Used for sorting constraints. Temporary, could use scratch memory
Ps::Array<const PxsIndexedContactManager*> orderedContactList;
Ps::Array<const PxsIndexedContactManager*> tempContactList;
Ps::Array<PxU32> sortIndexArray;
Ps::Array<Cm::SpatialVectorF> mZVector;
Ps::Array<Cm::SpatialVectorF> mDeltaV;
PxU32 numDifferentBodyBatchHeaders;
PxU32 numSelfConstraintBatchHeaders;
PxU32 mOrderedContactDescCount;
PxU32 mOrderedFrictionDescCount;
PxU32 mConstraintSize;
PxU32 mAxisConstraintCount;
SelfConstraintBlock* mSelfConstraintBlocks;
SelfConstraintBlock* mSelfConstraintFrictionBlocks;
PxU32 mMaxPartitions;
PxU32 mMaxFrictionPartitions;
PxU32 mMaxSolverPositionIterations;
PxU32 mMaxSolverVelocityIterations;
PxU32 mMaxArticulationLength;
PxU32 mMaxArticulationSolverLength;
PxU32 mMaxArticulationLinks;
PxSolverConstraintDesc* mContactDescPtr;
PxSolverConstraintDesc* mStartContactDescPtr;
PxSolverConstraintDesc* mFrictionDescPtr;
private:
Ps::Array<ArticulationSolverDesc> mArticulations;
#if PX_ENABLE_SIM_STATS
ThreadSimStats mThreadSimStats;
#endif
public:
};
}
}
#endif //DY_THREADCONTEXT_H
| [
"qq79402005@gmail.com"
] | qq79402005@gmail.com |
1c2aa1cf9ad02fad24309e8178f40497b0548d8e | 752e7de00864c846cdf77d5d36d76923e0383f97 | /Praticas/aeda1920_fp02/Tests/veiculo.cpp | 88a676af2a172234cd830b0f272ba538954afc85 | [] | no_license | andrenasx/FEUP-AEDA | 6064f30e2c6b00af991c377010895bdf71ada160 | eb9423b0bdffd78fc4048198540b8d66e013fc96 | refs/heads/master | 2021-01-09T15:31:32.120948 | 2020-03-01T12:55:11 | 2020-03-01T12:55:11 | 242,346,613 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,132 | cpp | #include "veiculo.h"
#include <iostream>
#include <utility>
using namespace std;
Veiculo::Veiculo(string mc, int m, int a): marca(mc), mes(m), ano(a){}
int Veiculo::getAno() const {
return ano;
}
string Veiculo::getMarca() const {
return marca;
}
Motorizado::Motorizado(string mc, int m, int a, string c, int cil): Veiculo(mc,m,a), combustivel(c), cilindrada(cil) {}
string Motorizado::getCombustivel() const {
return combustivel;
}
Automovel::Automovel(string mc, int m, int a, string c, int cil): Motorizado(mc,m,a,c,cil){}
Camiao::Camiao(string mc, int m, int a, string c, int cil, int cm): Motorizado(mc,m,a,c,cil), carga_maxima(cm) {}
Bicicleta::Bicicleta(string mc, int m, int a, string t): Veiculo(mc,m,a), tipo(t) {}
int Veiculo::info() const {
cout<<"Marca do veiculo: "<<marca<<endl;
cout<<"Mes do veiculo: "<<mes<<endl;
cout<<"Ano do veiculo: "<<ano<<endl;
return 3;
}
int Motorizado::info() const {
int n=Veiculo::info();
cout<<"Combustivel: "<<combustivel<<endl;
cout<<"Cilindrada: "<<cilindrada<<endl;
return 2+n;
}
int Automovel::info() const {
int n=Motorizado::info();
return n;
}
int Camiao::info() const {
int n=Motorizado::info();
cout<<"Carga maxima do camiao: "<<carga_maxima<<endl;
return 1+n;
}
int Bicicleta::info() const {
int n= Veiculo::info();
cout<<"Tipo da bicicleta: "<<tipo<<endl;
return 1+n;
}
bool Veiculo::operator<(const Veiculo &v) const {
if(ano == v.ano)
return mes<v.mes;
return ano<v.ano;
}
float Veiculo::calcImposto() const {
return 0;
}
float Motorizado::calcImposto() const{
if((combustivel == "gasolina" && cilindrada<=1000) || (combustivel != "gasolina" && cilindrada <=1500)) {
if (ano > 1995)
return 14.56;
else
return 8.10;
}
else if ((combustivel == "gasolina" && cilindrada>1000 && cilindrada<=1300) || (combustivel != "gasolina" && cilindrada > 1500 && cilindrada<=2000)) {
if (ano > 1995)
return 29.06;
else
return 14.56;
}
else if ((combustivel == "gasolina" && cilindrada>1300 && cilindrada<=1750) || (combustivel != "gasolina" && cilindrada > 2000 && cilindrada<=3000)) {
if (ano > 1995)
return 45.15;
else
return 22.65;
}
else if ((combustivel == "gasolina" && cilindrada>1750 && cilindrada<=2600) || (combustivel != "gasolina" && cilindrada > 3000)) {
if (ano > 1995)
return 113.98;
else
return 54.89;
}
else if (combustivel == "gasolina" && cilindrada>2600 && cilindrada<=3500) {
if (ano > 1995)
return 181.17;
else
return 87.13;
}
else if (combustivel == "gasolina" && cilindrada>3500) {
if (ano > 1995)
return 320.89;
else
return 148.37;
}
return Veiculo::calcImposto();
}
float Bicicleta::calcImposto() const {
return Veiculo::calcImposto();
}
| [
"andrenas@ubuntu.Home"
] | andrenas@ubuntu.Home |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.