hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
299160c92bbd0348f74755701eabc56a7b45c07e | 1,402 | h | C | PiHardwareAbstractionLayer/sensors/i2c/CCS811Definitions.h | disaster0203/PiDashboard | 31570be97893663af2695621c9a558a101637d20 | [
"MIT"
] | null | null | null | PiHardwareAbstractionLayer/sensors/i2c/CCS811Definitions.h | disaster0203/PiDashboard | 31570be97893663af2695621c9a558a101637d20 | [
"MIT"
] | null | null | null | PiHardwareAbstractionLayer/sensors/i2c/CCS811Definitions.h | disaster0203/PiDashboard | 31570be97893663af2695621c9a558a101637d20 | [
"MIT"
] | null | null | null | #pragma once
namespace hal
{
namespace sensors
{
namespace i2c
{
namespace ccs811
{
enum class OperationMode : uint8_t
{
SLEEP = 0,
PULSE_60_S = 1,
PULSE_10_S = 2,
CONSTANT_POWER_1_S = 3,
CONSTANT_POWER_250_MS = 4
};
enum class State : uint8_t
{
BOOT = 0,
READY = 1,
};
struct DeviceInfo
{
uint8_t device_id;
uint8_t hardware_id;
std::string hardware_version;
std::string firmware_version;
std::string application_version;
};
struct Thresholds
{
uint16_t low_medium_threshold;
uint16_t medium_high_threshold;
uint8_t hysteresis_threshold;
};
struct NTC
{
uint16_t v_over_resistor;
uint16_t v_over_ntc;
};
struct Status
{
uint8_t raw_status_info;
State current_state;
bool firmware_loaded;
bool data_ready;
bool has_error;
std::vector<std::string> error_message;
};
struct ModeInfo
{
uint8_t raw_mode_info;
OperationMode current_mode;
bool interrupt_generation;
bool use_threshold;
};
struct RawData
{
uint8_t current; // in micro ampere
uint16_t voltage; // in micro V
};
struct ResultData
{
uint16_t eco2_value;
uint16_t tvoc_value;
uint8_t status;
uint8_t error_id;
RawData raw_data;
};
}
}
}
}
| 16.690476 | 44 | 0.613409 | [
"vector"
] |
2995926f66d73a1e04b86edfb40dd0ce39e69697 | 391 | h | C | geode/random/permute.h | jjqcat/geode | 157cc904c113cc5e29a1ffe7c091a83b8ec2cf8e | [
"BSD-3-Clause"
] | 75 | 2015-02-08T22:04:31.000Z | 2022-02-26T14:31:43.000Z | geode/random/permute.h | bantamtools/geode | d906f1230b14953b68af63aeec2f7b0418d5fdfd | [
"BSD-3-Clause"
] | 15 | 2015-01-08T15:11:38.000Z | 2021-09-05T13:27:22.000Z | geode/random/permute.h | bantamtools/geode | d906f1230b14953b68af63aeec2f7b0418d5fdfd | [
"BSD-3-Clause"
] | 22 | 2015-03-11T16:43:13.000Z | 2021-02-15T09:37:51.000Z | // Random access pseudorandom permutations
#pragma once
#include <geode/math/uint128.h>
#include <geode/vector/Vector.h>
namespace geode {
// Apply a pseudorandom permutation to the range [0,n-1]
GEODE_CORE_EXPORT uint64_t random_permute(uint64_t n, uint128_t key, uint64_t x) GEODE_CONST;
GEODE_CORE_EXPORT uint64_t random_unpermute(uint64_t n, uint128_t key, uint64_t x) GEODE_CONST;
}
| 30.076923 | 95 | 0.800512 | [
"vector"
] |
299f44332cacdd0a4be213fb4deea28a7391f7b2 | 4,497 | h | C | OgreMain/include/OgreRenderOperation.h | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | null | null | null | OgreMain/include/OgreRenderOperation.h | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | null | null | null | OgreMain/include/OgreRenderOperation.h | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | null | null | null | /*
-----------------------------------------------------------------------------
This source file is part of OGRE-Next
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef _RenderOperation_H__
#define _RenderOperation_H__
#include "OgrePrerequisites.h"
#include "OgreAtomicScalar.h"
#include "OgreVertexIndexData.h"
#include "OgreHeaderPrefix.h"
namespace Ogre
{
namespace v1
{
/** \addtogroup Core
* @{
*/
/** \addtogroup RenderSystem
* @{
*/
/** 'New' rendering operation using vertex buffers. */
class _OgrePrivate RenderOperation
{
public:
static AtomicScalar<uint32> MeshIndexId;
/// This index is set to 0 by default. The RenderQueue will sort by mesh using this index.
/// Two different RenderOperations may have the same meshIndex, but if so, performance could
/// be degraded (it would hinder auto instancing, forces rebinding of the vertex & index
/// buffer per Renderable, etc) It is the implementation's responsability to assign a (unique
/// if possible) index. The static variable MeshIndexId is provided as an incrementing ID,
/// but you're not forced to use it
uint32 meshIndex;
/// Vertex source data
VertexData *vertexData;
/// The type of operation to perform
OperationType operationType;
/** Specifies whether to use indexes to determine the vertices to use as input. If false, the
vertices are simply read in sequence to define the primitives. If true, indexes are used
instead to identify vertices anywhere in the buffer, and allowing vertices to be used more
than once. If true, then the indexBuffer, indexStart and numIndexes properties must be
valid. */
bool useIndexes;
/// Index data - only valid if useIndexes is true
IndexData *indexData;
#if OGRE_DEBUG_MODE
/// Debug pointer back to renderable which created this
const Renderable *srcRenderable;
#endif
/// The number of instances for the render operation - this option is supported
/// in only a part of the render systems.
size_t numberOfInstances;
/// Specifies whether rendering to the vertex buffer.
bool renderToVertexBuffer;
/** A flag to indicate that it is possible for this operation to use a global
vertex instance buffer if available.*/
bool useGlobalInstancingVertexBufferIsAvailable;
RenderOperation() :
meshIndex( 0 ),
vertexData( 0 ),
operationType( OT_TRIANGLE_LIST ),
useIndexes( true ),
indexData( 0 ),
#if OGRE_DEBUG_MODE
srcRenderable( 0 ),
#endif
numberOfInstances( 1 ),
renderToVertexBuffer( false ),
useGlobalInstancingVertexBufferIsAvailable( true )
{
}
};
/** @} */
/** @} */
} // namespace v1
} // namespace Ogre
#include "OgreHeaderSuffix.h"
#endif
| 38.435897 | 105 | 0.625306 | [
"mesh",
"render",
"object"
] |
29a9c1cf93c0482450af795901a79a9edbefb59e | 4,342 | h | C | exotica/include/exotica/Problems/UnconstrainedTimeIndexedProblem.h | LongfeiProjects/exotica | 206b296edf9bf3b653ca3984b1449151ca17d374 | [
"BSD-3-Clause"
] | 1 | 2019-04-12T20:26:59.000Z | 2019-04-12T20:26:59.000Z | exotica/include/exotica/Problems/UnconstrainedTimeIndexedProblem.h | LongfeiProjects/exotica | 206b296edf9bf3b653ca3984b1449151ca17d374 | [
"BSD-3-Clause"
] | null | null | null | exotica/include/exotica/Problems/UnconstrainedTimeIndexedProblem.h | LongfeiProjects/exotica | 206b296edf9bf3b653ca3984b1449151ca17d374 | [
"BSD-3-Clause"
] | null | null | null | /*
* Author: Vladimir Ivan
*
* Copyright (c) 2017, University Of Edinburgh
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef UNCONSTRAINEDTIMEINDEXEDPROBLEM_H_
#define UNCONSTRAINEDTIMEINDEXEDPROBLEM_H_
#include <exotica/PlanningProblem.h>
#include <exotica/Tasks.h>
#include <exotica/UnconstrainedTimeIndexedProblemInitializer.h>
namespace exotica
{
/**
* \brief Unconstrained time-indexed problem.
*/
class UnconstrainedTimeIndexedProblem : public PlanningProblem, public Instantiable<UnconstrainedTimeIndexedProblemInitializer>
{
public:
UnconstrainedTimeIndexedProblem();
virtual ~UnconstrainedTimeIndexedProblem();
virtual void Instantiate(UnconstrainedTimeIndexedProblemInitializer& init);
double getDuration();
void Update(Eigen::VectorXdRefConst x_in, int t);
void setGoal(const std::string& task_name, Eigen::VectorXdRefConst goal, int t = 0);
void setRho(const std::string& task_name, const double rho, int t = 0);
Eigen::VectorXd getGoal(const std::string& task_name, int t = 0);
double getRho(const std::string& task_name, int t = 0);
std::vector<Eigen::VectorXd> getInitialTrajectory();
void setInitialTrajectory(const std::vector<Eigen::VectorXd> q_init_in);
virtual void preupdate();
int getT() const { return T; }
void setT(int T_in);
double getTau() const { return tau; }
void setTau(double tau_in);
double getScalarTaskCost(int t);
Eigen::VectorXd getScalarTaskJacobian(int t);
double getScalarTransitionCost(int t);
Eigen::VectorXd getScalarTransitionJacobian(int t);
double ct; //!< Normalisation of scalar cost and Jacobian over trajectory length
TimeIndexedTask Cost;
Eigen::MatrixXd W;
std::vector<TaskSpaceVector> Phi;
std::vector<Eigen::MatrixXd> J;
std::vector<Hessian> H;
std::vector<Eigen::VectorXd> x; // current internal problem state
std::vector<Eigen::VectorXd> xdiff; // equivalent to dx = x(t)-x(t-1)
int PhiN;
int JN;
int NumTasks;
TaskSpaceVector CostPhi; // passed to the TimeIndexedTask, needs to be kept for reinitialisation
std::vector<std::shared_ptr<KinematicResponse>> getKinematicSolutions() { return KinematicSolutions; }
private:
int T; //!< Number of time steps
double tau; //!< Time step duration
double W_rate; //!< Kinematic system transition error covariance multiplier (constant throughout the trajectory)
std::vector<Eigen::VectorXd> InitialTrajectory;
UnconstrainedTimeIndexedProblemInitializer init_;
void reinitializeVariables();
TaskSpaceVector yref; //!< Stores task Phi reference value, to be assigned to Phi
std::vector<std::shared_ptr<KinematicResponse>> KinematicSolutions;
};
typedef std::shared_ptr<exotica::UnconstrainedTimeIndexedProblem> UnconstrainedTimeIndexedProblem_ptr;
}
#endif
| 40.203704 | 127 | 0.747351 | [
"vector"
] |
29ad1636a3f0ce33b3695195410f4bfed91ac821 | 960 | c | C | SampleQuestion2/abstract.c | LingboTang/Cpp-Study | 66cbf858691b26b072233bb8d1f19749d0a6ef20 | [
"MIT"
] | null | null | null | SampleQuestion2/abstract.c | LingboTang/Cpp-Study | 66cbf858691b26b072233bb8d1f19749d0a6ef20 | [
"MIT"
] | null | null | null | SampleQuestion2/abstract.c | LingboTang/Cpp-Study | 66cbf858691b26b072233bb8d1f19749d0a6ef20 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
//C-structs are types consisting of a collection of data items
struct Point
{
int x,y;
};
struct Poing p; //define point variable p
p.x=p.y=0; //initialize its data members
//In C, global functions act on structs; usually a pointer to
// a struct object is passed as first argument.
//C Abstract Data Type = Struct & Global Functions
//Eg.
void Point_init (struct Point *p)
{
p.x = p.y = 0;
}
// write it to file
//bool Point_write (struct Point *p, FILE *fp);
// read it from file
//bool Point_read (struct Point *p, FILE *fp);
// free resources (memory,files,locks,...)
//void Point_cleanup(struct Point *p)
// C function naming convention: struct name _operation
//Error-prone!
// What if we forget to call struct_init or struct_cleanup?
// Data will not be initialized properly or our program may leak resources,
// such as memory and file descriptors, eventually resulting in program termination.
| 20.869565 | 84 | 0.717708 | [
"object"
] |
29b4f04b4c390333eb96784cb2878b6253a8ada7 | 7,832 | c | C | impl/src/histtests.c | findvid/main | dd9bd14255af8c642b39b08d59e64cbfa314d908 | [
"MIT"
] | null | null | null | impl/src/histtests.c | findvid/main | dd9bd14255af8c642b39b08d59e64cbfa314d908 | [
"MIT"
] | null | null | null | impl/src/histtests.c | findvid/main | dd9bd14255af8c642b39b08d59e64cbfa314d908 | [
"MIT"
] | null | null | null | #include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavutil/mem.h>
#include <math.h>
typedef struct {
uint8_t *data;
int w;
int h;
} Image;
int loadImage(Image *img, char *filename) {
FILE *pFile;
pFile = fopen(filename, "rb");
if (pFile == NULL) {
return -1;
}
fscanf(pFile, "P6\n%d %d\n255\n", &(img->w), &(img->h));
img->data = (uint8_t*) av_malloc(3*img->w*img->h*sizeof(uint8_t));
fread(img->data, 1, 3*img->w*img->h, pFile);
return 0;
}
int saveImage(Image *img, char *filename) {
FILE *pFile;
pFile = fopen(filename, "wb");
if (pFile == NULL) {
return -1;
}
fprintf(pFile, "P6\n%d %d\n255\n", img->w, img->h);
fwrite(img->data, 1, 3*img->w*img->h, pFile);
return 0;
}
/*
* Calculates the position a pixel has in the histogram (4x4x4)
*
* img: uint8_t* with rgb color values
* x: int giving the start position for a pixel
* the next 3 values of img are the rgb-values of that pixel
*/
#define HISTPOS4(img, x) ((img[x+2] >> 6) + 4 * ((img[x+1] >> 6) + 4 * (img[x] >> 6)))
/*
* Allocates a 4x4x4 histogram and returns the pointer to it
* It will not be inizilized with 0
*/
uint32_t* newHist4() {
return (uint32_t *)av_malloc(sizeof(uint32_t) *4*4*4);
}
/*
* Calculates a 4x4x4 histogram for img and returns the results in hist
* hist is an array with 64 elements while it's index is orginized
* like this: 0bRRGGBB
*
* img: Image with pixel data and a width/height
* hist: array for the calculated histogram
*/
void calcHist4(Image *img, uint32_t *hist) {
int i;
for (i = 0; i < 4*4*4; i++) {
hist[i] = 0;
}
for (i = 0; i < img->w*img->h; i++) {
hist[HISTPOS4(img->data, i*3)] += 1;
}
}
/*
* Calculates the difference between two 4x4x4 histograms
*
* h1: First histogram
* h2: Second histogram
*/
uint32_t histDiff(uint32_t *h1, uint32_t *h2) {
int i;
int diff = 0;
for (i = 0; i < 4*4*4; i++) {
diff += abs(h1[i] - h2[i]);
}
return diff;
}
/*
* Draw a bar on an image
*/
void drawBar(Image *img, int pos, int h) {
if (h < 0) h = 0;
if (h >= img->h) h = img->h-1;
int x = pos;
int y = 0;
for (y = 0; y <= h; y++) {
img->data[3*(((img->h-1)-y)*img->w + x)] = 255;
}
}
#define MAX(x, y) (x > y) ? x : y
#define MIN(x, y) (x < y) ? x : y
/*
* Draw a bar on an image
*/
void drawBar2(Image *img, int pos, int h) {
h += (img->h/2);
if (h < 0) h = 0;
if (h >= img->h) h = img->h-1;
int x = pos;
int y = MIN(h,img->h/2);
int y2 = MAX(h, img->h/2);
for (; y <= y2; y++) {
img->data[3*(((img->h-1)-y)*img->w + x)] = 255;
}
}
int main(int argc, char** argv) {
// Registers all available codecs
av_register_all();
// Struct holding information about container-file
AVFormatContext * pFormatCtx = NULL;
if (argc < 2) {
printf("Usage: %s <videofile>\n", argv[0]);
return -1;
}
// Read format information into struct
if(avformat_open_input(&pFormatCtx, argv[1], NULL, NULL) != 0)
return -1;
// Retrieve stream information
if(avformat_find_stream_info(pFormatCtx, NULL)<0)
return -1; // Couldn't find stream information
// Search for a video stream, assuming there's only one, we pick the first and continue
int i;
int videoStream = -1;
for (i = 0; i < pFormatCtx->nb_streams; i++ ) {
if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
videoStream = i;
break;
}
}
// Could not find a video stream
if (videoStream == -1)
return -1;
// Retrieve CodecContext
AVCodecContext *pCodecCtx = pFormatCtx->streams[videoStream]->codec;
// Get the appropiate Decoder for the video stream
AVCodec *pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL) {
printf("Unsupported Codec\n");
return -1;
}
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
return -1;
}
// Allocate frame to read packets into
AVFrame *pFrame = av_frame_alloc();
// Allocate frame to read conversion into
AVFrame *pFrameRGB = av_frame_alloc();
if (pFrame == NULL || pFrameRGB == NULL)
return -1;
avpicture_alloc((AVPicture *)pFrameRGB, PIX_FMT_RGB24, pCodecCtx->width, pCodecCtx->height);
pFrameRGB->width = pCodecCtx->width;
pFrameRGB->height = pCodecCtx->height;
// Object needed to perform conversions from a source dimension to a destination dimension using certain filters
struct SwsContext *img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL);
// Finally, start reading packets from the file
int frameCount = 0;
int frameFinished = 0;
AVPacket packet;
#define MAX_FRAMES 1024
#define HEIGHT 200
uint32_t *last = newHist4();
uint32_t *this = newHist4();
uint32_t *diff = (uint32_t *)av_malloc(sizeof(uint32_t) * MAX_FRAMES);
Image graph;
graph.data = (uint8_t *)av_malloc(sizeof(uint8_t) * MAX_FRAMES * 3 * HEIGHT);
graph.w = MAX_FRAMES;
graph.h = HEIGHT;
Image graph2;
graph2.data = (uint8_t *)av_malloc(sizeof(uint8_t) * MAX_FRAMES * 3 * HEIGHT);
graph2.w = MAX_FRAMES;
graph2.h = HEIGHT;
for (i = 0; i < graph.h * graph.w * 3; i++) {
graph.data[i] = 0;
graph2.data[i] = 0;
}
// Mind that we read from pFormatCtx, which is the general container file...
while (av_read_frame(pFormatCtx, &packet) >= 0 && frameCount < MAX_FRAMES) {
// ... therefore, not every packet belongs to our video stream!
if (packet.stream_index == videoStream) {
// Packet is part of the video stream previously found
// therefore use the CodecContext previously retrieved with
// avcodec_find_decoder2 to read the packet into pFrame
int len = avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
if (len < 0) return -1;
// frameFinished is set be avcodec_decode_video2 accordingly
if (frameFinished) {
// Convert pFrame into a simple bitmap format
sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize);
// and save the first 5 frames to disk. Because we can
//SaveFrame(pFrameRGB, pCodecCtx->width, pCodecCtx->height, frameCount);
// Swap pointers
uint32_t *tmp = last;
last = this;
this = tmp;
// put the frame into Image struct
Image img;
img.data = pFrameRGB->data[0];
img.h = pCodecCtx->height;
img.w = pCodecCtx->width;
// calculate the histogram
calcHist4(&img, this);
// calculate the diffrence between this and the last frame
diff[frameCount] = histDiff(last, this);
// draw the bar in the graph
drawBar(&graph, frameCount, diff[frameCount] / 10000);
if (frameCount > 0) drawBar2(&graph2, frameCount, ((int)diff[frameCount] - (int)diff[frameCount-1]) / 10000);
frameCount++;
}
}
av_free_packet(&packet);
}
saveImage(&graph, "graph.ppm");
saveImage(&graph2, "graph2.ppm");
free(graph.data);
free(graph2.data);
free(last);
free(this);
free(diff);
// av_free(buffer);
av_free(pFrameRGB);
av_free(pFrame);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
}
/*int main(int argc, char** argv) {
if (argc < 3) {
printf("Usage: %s <infile> <outfile>\n", argv[0]);
return -1;
}
Image img;
loadImage(&img, argv[1]);
uint32_t *hist = createHistogram(&img);
int r,g,b,i;
int count = 0;
for (r = 0; r < 4; r++)
for (g = 0; g < 4; g++)
for (b = 0; b < 4; b++) {
printf("%d : [%d][%d][%d] : %u\n", r+2*g+4*b, r, g, b, hist[r+2*(g+2*b)]);
count += hist[r+2*g+4*b];
for (i=0; i*100 < hist[r+2*g+4*b]; i += 1) img.data[(r+2*g+4*b)+i*img.w+0] = r << 6;
for (i=0; i*100 < hist[r+2*g+4*b]; i += 1) img.data[(r+2*g+4*b)+i*img.w+1] = g << 6;
for (i=0; i*100 < hist[r+2*g+4*b]; i += 1) img.data[(r+2*g+4*b)+i*img.w+2] = b << 6;
}
printf("%d\n", count);
saveImage(&img, argv[2]);
free(img.data);
}*/
| 27.194444 | 193 | 0.641216 | [
"object"
] |
73b24933afca134554c56c6222f6be0cff7bffa5 | 1,539 | h | C | escort/src/typedarray/Int8ArrayImp.h | rvedam/es-operating-system | 32d3e4791c28a5623744800f108d029c40c745fc | [
"Apache-2.0"
] | 2 | 2020-11-30T18:38:20.000Z | 2021-06-07T07:44:03.000Z | escort/src/typedarray/Int8ArrayImp.h | LambdaLord/es-operating-system | 32d3e4791c28a5623744800f108d029c40c745fc | [
"Apache-2.0"
] | 1 | 2019-01-14T03:09:45.000Z | 2019-01-14T03:09:45.000Z | escort/src/typedarray/Int8ArrayImp.h | LambdaLord/es-operating-system | 32d3e4791c28a5623744800f108d029c40c745fc | [
"Apache-2.0"
] | null | null | null | // Generated by esidl 0.2.1.
// This file is expected to be modified for the Web IDL interface
// implementation. Permission to use, copy, modify and distribute
// this file in any software license is hereby granted.
#ifndef ORG_W3C_DOM_BOOTSTRAP_INT8ARRAYIMP_H_INCLUDED
#define ORG_W3C_DOM_BOOTSTRAP_INT8ARRAYIMP_H_INCLUDED
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <org/w3c/dom/typedarray/Int8Array.h>
#include "ArrayBufferViewImp.h"
#include <org/w3c/dom/typedarray/ArrayBuffer.h>
#include <org/w3c/dom/typedarray/ArrayBufferView.h>
#include <org/w3c/dom/typedarray/Int8Array.h>
namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{
class Int8ArrayImp : public ObjectMixin<Int8ArrayImp, ArrayBufferViewImp>
{
public:
// Int8Array
unsigned int getLength();
signed char get(unsigned int index);
void set(unsigned int index, signed char value);
void set(typedarray::Int8Array array);
void set(typedarray::Int8Array array, unsigned int offset);
void set(ObjectArray<signed char> array);
void set(ObjectArray<signed char> array, unsigned int offset);
typedarray::Int8Array subarray(int start, int end);
// Object
virtual Any message_(uint32_t selector, const char* id, int argc, Any* argv)
{
return typedarray::Int8Array::dispatch(this, selector, id, argc, argv);
}
static const char* const getMetaData()
{
return typedarray::Int8Array::getMetaData();
}
};
}
}
}
}
#endif // ORG_W3C_DOM_BOOTSTRAP_INT8ARRAYIMP_H_INCLUDED
| 27 | 80 | 0.74204 | [
"object"
] |
73b44f66a696bceaadc9a49f7b26c4b6dd7f39a1 | 1,836 | h | C | iPhoneOS14.2.sdk/System/Library/Frameworks/CoreNFC.framework/Headers/NFCNDEFMessage.h | Zi0P4tch0/sdks | 96951a2b5a0c0a58963a8f9c37bc44ec9991153b | [
"MIT"
] | 416 | 2016-08-20T03:40:59.000Z | 2022-03-30T14:27:47.000Z | iPhoneOS14.4.sdk/System/Library/Frameworks/CoreNFC.framework/Headers/NFCNDEFMessage.h | haoict/sdks | 40a7cee1dc15ae097d867ae0c5133709fa103040 | [
"MIT"
] | 41 | 2016-08-22T14:41:42.000Z | 2022-02-25T11:38:16.000Z | iPhoneOS14.4.sdk/System/Library/Frameworks/CoreNFC.framework/Headers/NFCNDEFMessage.h | haoict/sdks | 40a7cee1dc15ae097d867ae0c5133709fa103040 | [
"MIT"
] | 173 | 2016-08-28T15:09:18.000Z | 2022-03-23T15:42:52.000Z | //
// NFCNDEFMessage.h
// CoreNFC
//
// Copyright © 2018 Apple. All rights reserved.
//
#ifndef NFCNDEFMessage_h
#define NFCNDEFMessage_h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class NFCNDEFPayload;
/*!
* @class NFCNDEFMessage
*
* @discussion A NDEF message consists of payload records. The maximum size of the NDEF message is limited to 128KB.
*/
NS_EXTENSION_UNAVAILABLE("Not available to extensions") API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, macos, tvos)
@interface NFCNDEFMessage : NSObject<NSSecureCoding>
/*!
* @property records
*
* @discussion Array of NFCNDEFPayload records contained in this message.
*/
@property (nonatomic, copy) NSArray<NFCNDEFPayload *> *records API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, macos, tvos);
/*!
* @property length
*
* @discussion Length of the resulting NDEF message in bytes as it would be stored on a NFC tag.
*/
@property (nonatomic, readonly) NSUInteger length API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, macos, tvos);
- (instancetype)init NS_UNAVAILABLE;
/*!
* @method initWithNDEFRecords:
*
* @param records NSArray of NFCNDEFPayload object. An empty array will create an empty NDEF message.
*/
- (instancetype)initWithNDEFRecords:(NSArray<NFCNDEFPayload *> *)records API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, macos, tvos);
/*!
* @method ndefMessageWithData:
*
* @param data NSData storing raw bytes of a complete NDEF message. The data content will be validated; all NDEF payloads must
* be valid according to the NFC Forum NDEF RTD specification and it shall only contain a single NDEF message.
*
*/
+ (_Nullable instancetype)ndefMessageWithData:(NSData *)data API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, macos, tvos);
@end
NS_ASSUME_NONNULL_END
#endif /* NFCNDEFMessage_h */
| 30.6 | 136 | 0.751634 | [
"object"
] |
73c09bcc49a6aabc228b98b069b414a4536535e0 | 14,564 | h | C | db/db_impl.h | ruihong123/NovaLSM | 8a661197ce5b993f2baeef608f34192d1ef0adf5 | [
"BSD-3-Clause"
] | 14 | 2020-09-25T00:12:46.000Z | 2022-03-24T12:11:03.000Z | db/db_impl.h | ruihong123/NovaLSM | 8a661197ce5b993f2baeef608f34192d1ef0adf5 | [
"BSD-3-Clause"
] | null | null | null | db/db_impl.h | ruihong123/NovaLSM | 8a661197ce5b993f2baeef608f34192d1ef0adf5 | [
"BSD-3-Clause"
] | 6 | 2020-12-01T23:21:47.000Z | 2022-03-03T07:47:53.000Z | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#ifndef STORAGE_LEVELDB_DB_DB_IMPL_H_
#define STORAGE_LEVELDB_DB_DB_IMPL_H_
#include <atomic>
#include <deque>
#include <queue>
#include <set>
#include <string>
#include <list>
#include <map>
#include <fmt/core.h>
#include <semaphore.h>
#include "common/nova_common.h"
#include "leveldb/db_profiler.h"
#include "leveldb/cache.h"
#include "ltc/stoc_file_client_impl.h"
#include "db/dbformat.h"
#include "leveldb/log_writer.h"
#include "db/snapshot.h"
#include "leveldb/db.h"
#include "leveldb/env.h"
#include "port/port.h"
#include "port/thread_annotations.h"
#include "memtable.h"
#include "leveldb/subrange.h"
#include "subrange_manager.h"
#include "compaction.h"
#include "lookup_index.h"
#include "range_index.h"
#include "log/log_recovery.h"
namespace leveldb {
class MemTable;
class TableCache;
class Version;
class VersionEdit;
class VersionSet;
class DBImpl : public DB {
public:
DBImpl(const Options &options, const std::string &dbname);
DBImpl(const DBImpl &) = delete;
DBImpl &operator=(const DBImpl &) = delete;
~DBImpl() override;
void QueryFailedReplicas(uint32_t failed_stoc_id,
bool is_stoc_failed,
std::unordered_map<uint32_t, std::vector<ReplicationPair>> *stoc_repl_pairs,
int level,
ReconstructReplicasStats *stats) override;
// Implementations of the DB interface
Status Put(const WriteOptions &, const Slice &key,
const Slice &value) override;
void EvictFileFromCache(uint64_t file_number) override;
uint32_t FlushMemTables(bool flush_active_memtable) override;
Status Delete(const WriteOptions &, const Slice &key) override;
Status WriteMemTablePool(const WriteOptions &options, const Slice &key,
const Slice &val) override;
Status WriteStaticPartition(const WriteOptions &options,
const Slice &key,
const Slice &val);
Status WriteSubrange(const WriteOptions &options,
const Slice &key,
const Slice &val);
Status Get(const ReadOptions &options, const Slice &key,
std::string *value) override;
void TestCompact(EnvBGThread *bg_thread,
const std::vector<EnvBGTask> &tasks) override;
Iterator *NewIterator(const ReadOptions &) override;
const Snapshot *GetSnapshot() override;
void StartTracing() override;
void ReleaseSnapshot(const Snapshot *snapshot) override;
bool GetProperty(const Slice &property, std::string *value) override;
void GetApproximateSizes(const Range *range, int n,
uint64_t *sizes) override;
void PerformCompaction(EnvBGThread *bg_thread,
const std::vector<EnvBGTask> &tasks) override;
void PerformSubRangeReorganization() override;
void QueryDBStats(DBStats *db_stats) override;
Status Recover() override;
Status
RecoverLogFile(
const std::unordered_map<std::string, uint64_t> &logfile_buf,
uint32_t *recovered_log_records,
timeval *rdma_read_complete);
void
CoordinateMajorCompaction() override;
void GenerateLogRecord(const WriteOptions &options,
SequenceNumber last_sequence,
const Slice &key, const Slice &val,
uint32_t memtable_id);
void GenerateLogRecord(const WriteOptions &options,
const std::vector<LevelDBLogRecord> &log_records,
uint32_t memtable_id);
void StartCoordinatedCompaction();
void StopCoordinatedCompaction();
void StopCompaction();
uint32_t EncodeMemTablePartitions(char *buf);
void
DecodeMemTablePartitions(Slice *buf, std::unordered_map<uint32_t, leveldb::MemTableLogFilePair> *mid_table_map);
const std::string &dbname() override;
uint32_t EncodeDBMetadata(char *buf, nova::StoCInMemoryLogFileManager *log_manager, uint32_t cfg_id);
void
RecoverDBMetadata(const Slice &buf, uint32_t version_id, uint64_t last_sequence, uint64_t next_file_number,
uint64_t memtable_id_seq, nova::StoCInMemoryLogFileManager *log_manager,
std::unordered_map<uint32_t, leveldb::MemTableLogFilePair> *mid_table_map);
void ScheduleFlushMemTableTask(
int thread_id,
uint32_t memtable_id,
MemTable *imm,
uint32_t partition_id, uint32_t imm_slot,
unsigned int *rand_seed, bool merge_memtables_without_flushing);
const Options options_; // options_.comparator == &internal_comparator_
nova::StoCInMemoryLogFileManager *log_manager_ = nullptr;
std::vector<EnvBGThread *> bg_flush_memtable_threads_;
void ScheduleFileDeletionTask();
void UpdateFileMetaReplicaLocations(
const std::vector<leveldb::ReplicationPair> &results, uint32_t stoc_server_id, int level, StoCClient* client) override ;
std::atomic_bool is_loading_db_;
private:
void ObtainStoCFilesOfSSTable(std::vector<std::string> *files_to_delete,
std::unordered_map<uint32_t, std::vector<SSTableStoCFilePair>> *server_pairs,
const FileMetaData &meta) const;
Status GetWithLookupIndex(const ReadOptions &options, const Slice &key,
std::string *value);
Status GetWithRangeIndex(const ReadOptions &options, const Slice &key,
std::string *value);
std::atomic_bool start_compaction_;
std::atomic_bool start_coordinated_compaction_;
std::atomic_bool terminate_coordinated_compaction_;
void CleanupLSMCompaction(CompactionState *state,
VersionEdit &edit,
RangeIndexVersionEdit &range_edit,
std::unordered_map<uint32_t, MemTableL0FilesEdit> &edits,
CompactionRequest *compaction_req,
uint32_t compacting_version_id);
bool ComputeCompactions(Version *current,
std::vector<Compaction *> *compactions,
VersionEdit *edit,
RangeIndexVersionEdit *range_edit,
bool *delete_due_to_low_overlap,
std::unordered_map<uint32_t, leveldb::MemTableL0FilesEdit> *memtableid_l0fns);
class NovaCCRecoveryThread {
public:
NovaCCRecoveryThread(
uint32_t client_id,
std::vector<leveldb::MemTable *> memtables,
MemManager *mem_manager);
void Recover();
sem_t sem_;
uint32_t recovered_log_records = 0;
uint64_t recovery_time = 0;
uint64_t new_memtable_time = 0;
uint64_t max_sequence_number = 0;
std::vector<char *> log_replicas_;
private:
std::vector<leveldb::MemTable *> memtables_;
uint32_t client_id_ = 0;
MemManager *mem_manager_;
};
// Compact the in-memory write buffer to disk. Switches to a new
// log-file/memtable and writes a new descriptor iff successful.
// Errors are recorded in bg_error_.
void CompactMemTableStaticPartition(EnvBGThread *bg_thread,
const std::vector<EnvBGTask> &tasks,
VersionEdit *edit,
bool prune_memtable);
bool CompactMultipleMemTablesStaticPartitionToMemTable(
int partition_id,
EnvBGThread *bg_thread,
const std::vector<EnvBGTask> &tasks,
std::vector<uint32_t> *closed_memtable_log_files);
friend class DB;
struct Writer;
DBProfiler *db_profiler_ = nullptr;
void StealMemTable(const WriteOptions &options);
// Information for a manual compaction
struct ManualCompaction {
int level;
bool done;
const InternalKey *begin; // null means beginning of key range
const InternalKey *end; // null means end of key range
InternalKey tmp_storage; // Used to keep track of compaction progress
};
Iterator *NewInternalIterator(const ReadOptions &,
SequenceNumber *latest_snapshot,
uint32_t *seed);
// Delete any unneeded files and stale in-memory entries.
void
ObtainObsoleteFiles(EnvBGThread *bg_thread,
std::vector<std::string> *files_to_delete,
std::unordered_map<uint32_t, std::vector<SSTableStoCFilePair>> *server_pairs,
uint32_t compacting_version_id);
void DeleteFiles(EnvBGThread *bg_thread,
std::vector<std::string> &files_to_delete,
std::unordered_map<uint32_t, std::vector<SSTableStoCFilePair>> &server_pairs);
void
ObtainLookupIndexEdits(CompactionState *state,
std::unordered_map<uint32_t, MemTableL0FilesEdit> *memtableid_l0fns);
void UpdateLookupIndex(uint32_t version_id,
const std::unordered_map<uint32_t, MemTableL0FilesEdit> &edits);
void
DeleteObsoleteVersions(EnvBGThread *bg_thread) EXCLUSIVE_LOCKS_REQUIRED(mutex_);
// Compact the in-memory write buffer to disk. Switches to a new
// log-file/memtable and writes a new descriptor iff successful.
// Errors are recorded in bg_error_.
bool CompactMemTable(EnvBGThread *bg_thread,
const std::vector<EnvBGTask> &tasks) EXCLUSIVE_LOCKS_REQUIRED(mutex_);
void RecordBackgroundError(const Status &s);
void ScheduleCompactionTask(int thread_id, void *compaction);
void ScheduleFileDeletionTask(int thread_id);
Status
InstallCompactionResults(CompactionState *compact, VersionEdit *edit, int target_level);
const Comparator *user_comparator() const {
return internal_comparator_.user_comparator();
}
FlushOrder *flush_order_;
// Constant after construction
Env *const env_;
uint32_t server_id_;
uint32_t dbid_;
const Comparator *user_comparator_;
const InternalKeyComparator internal_comparator_;
const InternalFilterPolicy internal_filter_policy_;
const bool owns_info_log_;
const bool owns_cache_;
const std::string dbname_;
// table_cache_ provides its own synchronization
TableCache *const table_cache_;
// Lock over the persistent DB state. Non-null iff successfully acquired.
FileLock *db_lock_;
// Range lock.
port::Mutex range_lock_;
port::CondVar memtable_available_signal_;
int number_of_available_pinned_memtables_ = 2;
const int min_memtables_ = 2;
port::Mutex mutex_;
std::atomic<bool> shutting_down_;
port::Mutex l0_stop_write_mutex_;
port::CondVar l0_stop_write_signal_;
std::vector<EnvBGThread *> bg_compaction_threads_;
EnvBGThread *reorg_thread_;
EnvBGThread *compaction_coordinator_thread_;
std::atomic_int_fast32_t memtable_id_seq_;
SubRangeManager *subrange_manager_ = nullptr;
// key -> memtable-id.
LookupIndex *lookup_index_ = nullptr;
RangeIndexManager *range_index_manager_ = nullptr;
// memtable pool.
std::vector<AtomicMemTable *> active_memtables_;
// partitioned memtables.
std::vector<MemTablePartition *> partitioned_active_memtables_ GUARDED_BY(mutex_);
std::vector<uint32_t> partitioned_imms_ GUARDED_BY(mutex_); // Memtable being compacted
uint32_t seed_ GUARDED_BY(mutex_); // For sampling.
SnapshotList snapshots_ GUARDED_BY(mutex_);
// Set of table files to protect from deletion because they are
// part of ongoing compactions.
std::unordered_map<uint64_t, FileMetaData> compacted_tables_ GUARDED_BY(mutex_);
bool is_major_compaciton_running_ = false;
ManualCompaction *manual_compaction_ GUARDED_BY(mutex_);
VersionSet *const versions_ GUARDED_BY(mutex_);
port::Mutex mutex_compacting_tables;
std::set<uint64_t> compacting_tables_;
// Have we encountered a background error in paranoid mode?
Status bg_error_ GUARDED_BY(mutex_);
std::string current_log_file_name_ GUARDED_BY(mutex_);
std::vector<uint32_t> closed_memtable_log_files_ GUARDED_BY(range_lock_);
bool WriteStaticPartition(const leveldb::WriteOptions &options,
const leveldb::Slice &key,
const leveldb::Slice &value,
uint32_t partition_id,
bool should_wait, uint64_t last_sequence,
SubRange *subrange);
StoCWritableFileClient *manifest_file_ = nullptr;
unsigned int rand_seed_ = 0;
};
// Sanitize db options. The caller should delete result.info_log if
// it is not equal to src.info_log.
Options SanitizeOptions(const std::string &db,
const InternalKeyComparator *icmp,
const InternalFilterPolicy *ipolicy,
const Options &src);
} // namespace leveldb
#endif // STORAGE_LEVELDB_DB_DB_IMPL_H_ | 37.439589 | 136 | 0.61501 | [
"vector"
] |
73c8b8f412c567682152ad41e956a80946b0201f | 1,185 | h | C | FEM/Constrained.h | ThieJan/ogs5 | a05837cac4de890db18845b5bc0cb002d1ca5829 | [
"BSD-4-Clause"
] | null | null | null | FEM/Constrained.h | ThieJan/ogs5 | a05837cac4de890db18845b5bc0cb002d1ca5829 | [
"BSD-4-Clause"
] | null | null | null | FEM/Constrained.h | ThieJan/ogs5 | a05837cac4de890db18845b5bc0cb002d1ca5829 | [
"BSD-4-Clause"
] | null | null | null | /**
* \copyright
* Copyright (c) 2018, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#ifndef CONSTRAINED_H_
#define CONSTRAINED_H_
#include "FEMEnums.h"
struct Constrained
{
double constrainedValue;
FiniteElement::ProcessType constrainedProcessType;
FiniteElement::PrimaryVariable constrainedPrimVar;
ConstrainedType::type constrainedDirection;
ConstrainedVariable::type constrainedVariable;
bool _isCompleteConstrained;
bool _completeConstrainedStateOff;
std::vector<bool> _constrainedNodes;
bool _isConstrainedVelStable;
bool _isSeepageBC;
Constrained()
: constrainedValue(0.0), constrainedProcessType(FiniteElement::INVALID_PROCESS),
constrainedPrimVar(FiniteElement::INVALID_PV),
constrainedDirection(ConstrainedType::INVALID_CONSTRAINED_TYPE),
constrainedVariable(ConstrainedVariable::INVALID_CONSTRAINED_VARIABLE), _isCompleteConstrained(false),
_completeConstrainedStateOff(false), _isConstrainedVelStable(false), _isSeepageBC(false)
{
}
};
#endif
| 30.384615 | 109 | 0.772996 | [
"vector"
] |
73deb5d40370488c4f8973f0a7035a6c8587658b | 32,369 | h | C | include/diplib/library/dimension_array.h | DIPlib/diplib | eaf03372264f050bcda2d49bdf443702308ba303 | [
"Apache-2.0"
] | 140 | 2017-04-04T23:10:16.000Z | 2022-03-24T18:21:34.000Z | include/diplib/library/dimension_array.h | DIPlib/diplib | eaf03372264f050bcda2d49bdf443702308ba303 | [
"Apache-2.0"
] | 98 | 2018-01-13T23:16:00.000Z | 2022-03-14T14:45:37.000Z | include/diplib/library/dimension_array.h | DIPlib/diplib | eaf03372264f050bcda2d49bdf443702308ba303 | [
"Apache-2.0"
] | 40 | 2017-04-11T20:41:58.000Z | 2022-03-24T18:21:36.000Z | /*
* DIPlib 3.0
* This file contains the definition for the dip::DimensionArray template class.
*
* (c)2016-2021, Cris Luengo.
*
* 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.
*/
//
// NOTE!
// This file is included through diplib.h -- no need to include directly
//
#ifndef DIP_DIMENSIONARRAY_H
#define DIP_DIMENSIONARRAY_H
#include <cstdlib> // std::malloc, std::realloc, std::free, std::size_t
#include <initializer_list>
#include <iterator>
#include <algorithm>
#include <utility>
#include <iostream>
#include <type_traits>
#include <cmath>
#include "diplib/library/error.h"
/// \file
/// \brief The \ref dip::DimensionArray template class. This file is always included through \ref "diplib.h".
/// See \ref supporttypes.
namespace dip {
/// \addtogroup supporttypes
/// \brief A dynamic array type optimized for few elements.
///
/// `dip::DimensionArray` is similar to `std::vector` but optimized for one particular
/// use within the *DIPlib* library: hold one element per image dimension. Most images have
/// only two or three dimensions, and for internal processing we might add the
/// tensor dimension to the mix, yielding up to four dimensions for most
/// applications. However, *DIPlib* does not limit image dimensionality, and we
/// need to be able to hold more than four dimensions if the user needs to do
/// so. We want the array holding the image dimensions to be as efficient in
/// use as a static array of size 4, but without the limitation of a static
/// array. So this version of `std::vector` has a static array of size 4, which
/// is used if that is sufficient, and also a pointer we can use if we need to
/// allocate space on the heap.
///
/// It also differs from std::vector in that it doesn't grow or shrink
/// efficiently, don't use this type when repeatedly using `push_back()` or
/// similar functionality. The *DIPlib* codebase uses dip::DimensionArray only
/// where the array holds one value per image dimension, or when more often
/// than not the array will have very few elements, and `std::vector` everywhere
/// else.
///
/// The interface tries to copy that of the STL containers, but only partially.
/// We do not include some of the `std::vector` functionality, and do include
/// some custom functionality useful for the specific application of the container.
/// We also have some custom algorithms such as dip::DimensionArray::sort() that
/// assumes the array is short.
///
/// This container can only be used with trivially copyable types (this means that
/// the destructor performs no action, and the object can be copied by copying its
/// bit pattern).
///
/// An array of size 0 has space for writing four values in it, `data()` won't
/// return a `nullptr`, and nothing will break if you call front(). But don't
/// do any of these things! The implementation could change. Plus, you're just
/// being silly and making unreadable code.
template< typename T >
class DIP_NO_EXPORT DimensionArray {
static_assert( std::is_trivially_copyable<T>::value, "DimensionArray can only be used with trivially copyable types." );
public:
// Types for consistency with STL containers
/// Type of values stored in container
using value_type = T;
/// Type of container's iterator
using iterator = T*;
/// Type of container's const iterator
using const_iterator = T const*;
/// Type of container's reverse iterator
using reverse_iterator = std::reverse_iterator< iterator >;
/// Type of container's const reverse iterator
using const_reverse_iterator = std::reverse_iterator< const_iterator >;
/// Type of index into container
using size_type = std::size_t;
/// The default-initialized array has zero size.
DimensionArray() {}; // Using `=default` causes weird sequence of "constructor required before non-static data member for ‘dip::Histogram::Configuration::lowerBound’ has been parsed" in GCC
/// Like `std::vector`, you can initialize with a size and a default value.
explicit DimensionArray( size_type sz, T newval = T() ) {
resize( sz, newval );
}
/// Like `std::vector`, you can initialize with a set of values in braces.
DimensionArray( std::initializer_list< T > const init ) {
resize( init.size() );
std::copy( init.begin(), init.end(), data_ );
}
/// Copy constructor, initializes with a copy of `other`.
DimensionArray( DimensionArray const& other ) {
resize( other.size_ );
std::copy( other.data_, other.data_ + size_, data_ );
}
/// \brief Cast constructor, initializes with a copy of `other`.
/// Casting done as default in C++, not through `dip::clamp_cast`.
template< typename O >
explicit DimensionArray( DimensionArray< O > const& other ) {
resize( other.size() );
std::transform( other.data(), other.data() + size_, data_, []( O const& v ) { return static_cast< value_type >( v ); } );
}
/// Move constructor, initializes by stealing the contents of `other`.
DimensionArray( DimensionArray&& other ) noexcept {
steal_data_from( other );
}
// Destructor, no need for documentation
~DimensionArray() noexcept {
free_array(); // no need to keep status consistent...
}
/// Copy assignment, copies over data from `other`.
DimensionArray& operator=( DimensionArray const& other ) {
if( this != &other ) {
resize( other.size_ );
std::copy( other.data_, other.data_ + size_, data_ );
}
return *this;
}
/// Move assignment, steals the contents of `other`.
DimensionArray& operator=( DimensionArray&& other ) noexcept {
// Self-assignment is not valid for move assignment, not testing for it here.
free_array();
steal_data_from( other );
return *this;
}
/// Swaps the contents of two arrays.
void swap( DimensionArray& other ) noexcept {
using std::swap;
if( is_dynamic() ) {
if( other.is_dynamic() ) {
// both have dynamic memory
swap( data_, other.data_ );
} else {
// *this has dynamic memory, other doesn't
other.data_ = data_;
data_ = stat_;
std::move( other.stat_, other.stat_ + other.size_, stat_ );
}
} else {
if( other.is_dynamic() ) {
// other has dynamic memory, *this doesn't
data_ = other.data_;
other.data_ = other.stat_;
std::move( stat_, stat_ + size_, other.stat_ );
} else {
// both have static memory
std::swap_ranges( stat_, stat_ + std::max( size_, other.size_ ), other.stat_ );
}
}
swap( size_, other.size_ );
}
/// \brief Resizes the array, making it either larger or smaller. Initializes
/// new elements with `newval`.
void resize( size_type newsz, T newval = T() ) {
if( newsz == size_ ) { return; } // NOP
if( newsz > static_size_ ) {
if( is_dynamic() ) {
// expand or contract heap data
T* tmp = static_cast< T* >( std::realloc( data_, newsz * sizeof( T )));
//std::cout << " DimensionArray realloc\n";
if( tmp == nullptr ) {
throw std::bad_alloc();
}
data_ = tmp;
if( newsz > size_ ) {
std::fill( data_ + size_, data_ + newsz, newval );
}
size_ = newsz;
} else {
// move from static to heap data
// We use malloc because we want to be able to use realloc; new cannot do this.
T* tmp = static_cast< T* >( std::malloc( newsz * sizeof( T )));
//std::cout << " DimensionArray malloc\n";
if( tmp == nullptr ) {
throw std::bad_alloc();
}
std::move( stat_, stat_ + size_, tmp );
data_ = tmp;
std::fill( data_ + size_, data_ + newsz, newval );
size_ = newsz;
}
} else {
if( is_dynamic() ) {
// move from heap to static data
if( newsz > 0 ) {
std::move( data_, data_ + newsz, stat_ );
}
free_array();
size_ = newsz;
data_ = stat_;
} else {
// expand or contract static data
if( newsz > size_ ) {
std::fill( stat_ + size_, stat_ + newsz, newval );
}
size_ = newsz;
}
}
}
/// Clears the contents of the array, set its length to 0.
void clear() noexcept {
free_array();
reset();
}
/// Checks whether the array is empty (size is 0).
DIP_NODISCARD bool empty() const noexcept { return size_ == 0; }
/// Returns the size of the array.
size_type size() const noexcept { return size_; }
/// Accesses an element of the array
T& operator[]( size_type index ) { return *( data_ + index ); }
/// Accesses an element of the array
T const& operator[]( size_type index ) const { return *( data_ + index ); }
/// Accesses the first element of the array
T& front() { return *data_; }
/// Accesses the first element of the array
T const& front() const { return *data_; }
/// Accesses the last element of the array
T& back() { return *( data_ + size_ - 1 ); }
/// Accesses the last element of the array
T const& back() const { return *( data_ + size_ - 1 ); }
/// Returns a pointer to the underlying data
T* data() { return data_; };
/// Returns a pointer to the underlying data
T const* data() const { return data_; };
/// Returns an iterator to the beginning
iterator begin() { return data_; }
/// Returns an iterator to the beginning
const_iterator begin() const { return data_; }
/// Returns an iterator to the end
iterator end() { return data_ + size_; }
/// Returns an iterator to the end
const_iterator end() const { return data_ + size_; }
/// Returns a reverse iterator to the beginning
reverse_iterator rbegin() { return reverse_iterator( end() ); }
/// Returns a reverse iterator to the beginning
const_reverse_iterator rbegin() const { return const_reverse_iterator( end() ); }
/// Returns a reverse iterator to the end
reverse_iterator rend() { return reverse_iterator( begin() ); }
/// Returns a reverse iterator to the end
const_reverse_iterator rend() const { return const_reverse_iterator( begin() ); }
/// \brief Adds a value at the given location, moving the current value at that
/// location and subsequent values forward by one.
void insert( size_type index, T const& value ) {
DIP_ASSERT( index <= size_ );
resize( size_ + 1 ); // we're default-initializing one T here.
if( index < size_ - 1 ) {
std::move_backward( data_ + index, data_ + size_ - 1, data_ + size_ );
}
*( data_ + index ) = value;
}
/// \brief Adds a value to the back. Not efficient -- prefer `std::vector` if you need
/// to use this repeatedly.
void push_back( T const& value ) {
resize( size_ + 1, value );
}
/// Adds all values in source array to the back.
void append( DimensionArray const& values ) {
size_type index = size_;
resize( size_ + values.size_ );
for( size_type ii = 0; ii < values.size_; ++ii ) {
data_[ index + ii ] = values.data_[ ii ];
}
}
/// Removes the value at the given location, moving subsequent values forward by one.
void erase( size_type index ) {
DIP_ASSERT( index < size_ );
if( index < size_ - 1 ) {
std::move( data_ + index + 1, data_ + size_, data_ + index );
}
resize( size_ - 1 );
}
/// Removes the value at the back.
void pop_back() {
DIP_ASSERT( size_ > 0 );
resize( size_ - 1 );
}
/// Adds a constant to each element in the array.
DimensionArray& operator+=( T const& v ) {
for( size_type ii = 0; ii < size_; ++ii ) {
data_[ ii ] += v;
}
return *this;
}
/// \brief Adds an array to `this`, element-wise. `other` must have the same number of elements.
template< typename S >
DimensionArray< T >& operator+=( DimensionArray< S > const& other );
/// Subtracts a constant from each element in the array.
DimensionArray& operator-=( T const& v ) {
for( size_type ii = 0; ii < size_; ++ii ) {
data_[ ii ] -= v;
}
return *this;
}
/// \brief Subtracts an array from `this`, element-wise. `other` must have the same number of elements.
template< typename S >
DimensionArray< T >& operator-=( DimensionArray< S > const& other );
/// Sort the contents of the array from smallest to largest.
void sort() {
// Using insertion sort because we expect the array to be small.
for( size_type ii = 1; ii < size_; ++ii ) {
T elem = data_[ ii ];
size_type jj = ii;
while(( jj > 0 ) && ( data_[ jj - 1 ] > elem )) {
data_[ jj ] = data_[ jj - 1 ];
--jj;
}
data_[ jj ] = elem;
}
}
/// Multiplies each element in the array by a constant.
DimensionArray& operator*=( T const& v ) {
for( size_type ii = 0; ii < size_; ++ii ) {
data_[ ii ] *= v;
}
return *this;
}
/// Divides each element in the array by a constant.
DimensionArray& operator/=( T const& v ) {
for( size_type ii = 0; ii < size_; ++ii ) {
data_[ ii ] /= v;
}
return *this;
}
/// Sort the contents of the array from smallest to largest, and keeping `other` in the same order.
template< typename S >
void sort( DimensionArray< S >& other ) {
// We cannot access private members of `other` because it's a different class (if S != T).
DIP_ASSERT( size_ == other.size() );
// Using insertion sort because we expect the array to be small.
for( size_type ii = 1; ii < size_; ++ii ) {
T elem = data_[ ii ];
S otherelem = other[ ii ];
size_type jj = ii;
while(( jj > 0 ) && ( data_[ jj - 1 ] > elem )) {
data_[ jj ] = data_[ jj - 1 ];
other[ jj ] = other[ jj - 1 ];
--jj;
}
data_[ jj ] = elem;
other[ jj ] = otherelem;
}
}
/// Returns an array with indices into the array, sorted from smallest value to largest.
DIP_NODISCARD DimensionArray< size_type > sorted_indices() const {
DimensionArray< size_type > out( size_ );
for( size_type ii = 0; ii < size_; ++ii ) {
out[ ii ] = ii;
}
// Using insertion sort because we expect the array to be small.
for( size_type ii = 1; ii < size_; ++ii ) {
size_type elem = out[ ii ];
size_type jj = ii;
while(( jj > 0 ) && ( data_[ out[ jj - 1 ]] > data_[ elem ] )) {
out[ jj ] = out[ jj - 1 ];
--jj;
}
out[ jj ] = elem;
}
return out;
}
/// \brief Order the elements in the array according to the `order` array, such as returned by `sorted_indices`.
///
/// Postcondition:
///
/// ```cpp
/// out[ ii ] = (*this)[ order[ ii ] ];
/// ```
DIP_NODISCARD DimensionArray permute( DimensionArray< size_type > const& order ) const {
DimensionArray out( order.size() );
for( size_type ii = 0; ii < order.size(); ++ii ) {
out[ ii ] = data_[ order[ ii ]];
}
return out;
}
/// \brief Inverse orders the elements in the array according to the `order` array, such as returned by `sorted_indices`.
///
/// Postcondition:
///
/// ```cpp
/// out[ order[ ii ]] = (*this)[ ii ];
/// ```
///
/// Elements not indexed by `order` will be default-initialized.
DIP_NODISCARD DimensionArray inverse_permute( DimensionArray< size_type > const& order ) const {
size_type n = 0;
for( auto o : order ) {
n = std::max( n, o + 1 );
}
DimensionArray out( n );
for( size_type ii = 0; ii < order.size(); ++ii ) {
out[ order[ ii ]] = data_[ ii ];
}
return out;
}
/// Finds the first occurrence of `value` in the array, returns the index or `size()` if it is not present.
size_type find( T value ) {
// Like in `sort`, we expect the array to be small
size_type ii = 0;
while(( ii < size_ ) && ( data_[ ii ] != value )) {
++ii;
}
return ii;
}
/// Compute the sum of the elements in the array.
T sum() const {
T p = 0;
for( size_type ii = 0; ii < size_; ++ii ) {
p += data_[ ii ];
}
return p;
}
/// Compute the product of the elements in the array.
T product() const {
T p = 1;
for( size_type ii = 0; ii < size_; ++ii ) {
p *= data_[ ii ];
}
return p;
}
/// Compute the sum of the squares of the elements in the array.
double norm_square() const {
double p = 0;
for( size_type ii = 0; ii < size_; ++ii ) {
double d = static_cast< double >( data_[ ii ] );
p += d * d;
}
return p;
}
/// Find the minimum element in the array, returns the index or 0 if the array is empty.
size_type minimum() const {
if( size_ == 0 ) {
return 0;
}
size_type result = 0;
size_type ii = 0;
while( ++ii != size_ ) {
if( data_[ ii ] < data_[ result ] ) {
result = ii;
}
}
return result;
}
/// Find the maximum element in the array, returns the index or 0 if the array is empty.
size_type maximum() const {
if( size_ == 0 ) {
return 0;
}
size_type result = 0;
size_type ii = 0;
while( ++ii != size_ ) {
if( data_[ ii ] > data_[ result ] ) {
result = ii;
}
}
return result;
}
/// \brief Find the minimum element in the array, returns the value. The array must not be empty.
T minimum_value() const {
// If the array is empty, returns `data[0]`, which is OK but contains unspecified data.
return data_[ minimum() ];
}
/// \brief Find the minimum element in the array, returns the value. The array must not be empty.
T& minimum_value() {
return data_[ minimum() ];
}
/// \brief Find the maximum element in the array, returns the value. The array must not be empty.
T maximum_value() const {
return data_[ maximum() ];
}
/// \brief Find the maximum element in the array, returns the value. The array must not be empty.
T& maximum_value() {
return data_[ maximum() ];
}
/// True if all elements are non-zero.
bool all() const {
for( size_type ii = 0; ii < size_; ++ii ) {
if( data_[ ii ] == T( 0 )) {
return false;
}
}
return true;
}
/// True if one element is non-zero.
bool any() const {
for( size_type ii = 0; ii < size_; ++ii ) {
if( data_[ ii ] != T( 0 )) {
return true;
}
}
return false;
}
/// Count of number of elements that are non-zero.
size_type count() const {
size_type n = 0;
for( size_type ii = 0; ii < size_; ++ii ) {
if( data_[ ii ] != T( 0 )) {
++n;
}
}
return n;
}
/// Assigns one same value to each element in the array
void fill( T const& value ) {
for( size_type ii = 0; ii < size_; ++ii ) {
data_[ ii ] = value;
}
}
private:
constexpr static size_type static_size_ = 4;
size_type size_ = 0;
T* data_ = stat_;
T stat_[ static_size_ ];
// The alternate implementation, where data_ and stat_ are in a union
// to reduce the amount of memory used, requires a test for every data
// access. Data access is most frequent, it's worth using a little bit
// more memory to avoid that test.
bool is_dynamic() const noexcept {
return data_ != stat_;
}
void free_array() noexcept {
if( is_dynamic() ) {
std::free( data_ );
//std::cout << " DimensionArray free\n";
}
}
void reset() noexcept {
// This should be called only after `free_array()`.
size_ = 0;
data_ = stat_;
}
void steal_data_from( DimensionArray& other ) noexcept {
if( other.is_dynamic() ) {
size_ = other.size_;
data_ = other.data_; // move pointer
other.reset(); // leave other in consistent, empty state
} else {
size_ = other.size_;
data_ = stat_;
std::move( other.data_, other.data_ + size_, data_ );
}
}
};
//
// Compound assignment operator specializations
//
// The general case: cast rhs to type of lhs
template< typename T >
template< typename S >
DimensionArray< T >& DimensionArray< T >::operator+=( DimensionArray< S > const& other ) {
DIP_ASSERT( size_ == other.size() );
for( size_type ii = 0; ii < size_; ++ii ) {
data_[ ii ] += static_cast< T >( other[ ii ] );
}
return *this;
}
// A special case for adding a signed array to an unsigned array
template<>
template<>
inline DimensionArray< std::size_t >& DimensionArray< std::size_t >::operator+=( DimensionArray< std::ptrdiff_t > const& other ) {
DIP_ASSERT( size_ == other.size() );
for( size_type ii = 0; ii < size_; ++ii ) {
data_[ ii ] = static_cast< std::size_t >( static_cast< std::ptrdiff_t >( data_[ ii ] ) + other[ ii ] );
}
return *this;
}
template< typename T >
template< typename S >
DimensionArray< T >& DimensionArray< T >::operator-=( DimensionArray< S > const& other ) {
DIP_ASSERT( size_ == other.size() );
for( size_type ii = 0; ii < size_; ++ii ) {
data_[ ii ] -= static_cast< T >( other[ ii ] );
}
return *this;
}
// A special case for subtracting a signed array from an unsigned array
template<>
template<>
inline DimensionArray< std::size_t >& DimensionArray< std::size_t >::operator-=( DimensionArray< std::ptrdiff_t > const& other ) {
DIP_ASSERT( size_ == other.size() );
for( size_type ii = 0; ii < size_; ++ii ) {
data_[ ii ] = static_cast< std::size_t >( static_cast< std::ptrdiff_t >( data_[ ii ] ) - other[ ii ] );
}
return *this;
}
//
// Comparison operators, array vs array
//
/// \brief Compares two arrays, returns true only if they have the same size and contain the same values.
/// \relates dip::DimensionArray
template< typename T >
inline bool operator==( DimensionArray< T > const& lhs, DimensionArray< T > const& rhs ) {
if( lhs.size() != rhs.size() ) {
return false;
}
auto lhsp = lhs.begin();
auto rhsp = rhs.begin();
while( lhsp != lhs.end() ) {
if( *lhsp != *rhsp ) {
return false;
}
++lhsp;
++rhsp;
};
return true;
}
/// \brief Compares two arrays, returns true if they have different size and/or contain different values.
/// \relates dip::DimensionArray
template< typename T >
inline bool operator!=( DimensionArray< T > const& lhs, DimensionArray< T > const& rhs ) {
return !( lhs == rhs );
}
// Note on ordering operators: These have a non-standard meaning, because they all return false if the arrays
// are not of the same length. Therefore, it is not possible to define operator<= in terms of operator>, etc.
/// \brief Compares two arrays, returns true only if they have the same size and all `lhs` elements are larger
/// than all `rhs` elements.
/// \relates dip::DimensionArray
template< typename T >
inline bool operator>( DimensionArray< T > const& lhs, DimensionArray< T > const& rhs ) {
if( lhs.size() != rhs.size() ) {
return false;
}
auto lhsp = lhs.begin();
auto rhsp = rhs.begin();
while( lhsp != lhs.end() ) {
if( *lhsp <= *rhsp ) {
return false;
}
++lhsp;
++rhsp;
};
return true;
}
/// \brief Compares two arrays, returns true only if they have the same size and all `lhs` elements are smaller
/// than all `rhs` elements.
/// \relates dip::DimensionArray
template< typename T >
inline bool operator<( DimensionArray< T > const& lhs, DimensionArray< T > const& rhs ) {
if( lhs.size() != rhs.size() ) {
return false;
}
auto lhsp = lhs.begin();
auto rhsp = rhs.begin();
while( lhsp != lhs.end() ) {
if( *lhsp >= *rhsp ) {
return false;
}
++lhsp;
++rhsp;
};
return true;
}
/// \brief Compares two arrays, returns true only if they have the same size and all `lhs` elements are larger
/// or equal than all `rhs` elements.
/// \relates dip::DimensionArray
template< typename T >
inline bool operator>=( DimensionArray< T > const& lhs, DimensionArray< T > const& rhs ) {
if( lhs.size() != rhs.size() ) {
return false;
}
auto lhsp = lhs.begin();
auto rhsp = rhs.begin();
while( lhsp != lhs.end() ) {
if( *lhsp < *rhsp ) {
return false;
}
++lhsp;
++rhsp;
};
return true;
}
/// \brief Compares two arrays, returns true only if they have the same size and all `lhs` elements are smaller
/// or equal than all `rhs` elements.
/// \relates dip::DimensionArray
template< typename T >
inline bool operator<=( DimensionArray< T > const& lhs, DimensionArray< T > const& rhs ) {
if( lhs.size() != rhs.size() ) {
return false;
}
auto lhsp = lhs.begin();
auto rhsp = rhs.begin();
while( lhsp != lhs.end() ) {
if( *lhsp > *rhsp ) {
return false;
}
++lhsp;
++rhsp;
};
return true;
}
//
// Comparison operators, array vs scalar
//
/// \brief Compares an array to a scalar, returns a boolean array.
/// \relates dip::DimensionArray
template< typename T >
inline DimensionArray< bool > operator==( DimensionArray< T > const& lhs, T const& rhs ) {
DimensionArray< bool > out( lhs.size() );
auto lhsp = lhs.begin();
auto outp = out.begin();
while( lhsp != lhs.end() ) {
*outp = *lhsp == rhs;
++lhsp;
++outp;
};
return out;
}
/// \brief Compares an array to a scalar, returns a boolean array.
/// \relates dip::DimensionArray
template< typename T >
inline DimensionArray< bool > operator!=( DimensionArray< T > const& lhs, T const& rhs ) {
DimensionArray< bool > out( lhs.size() );
auto lhsp = lhs.begin();
auto outp = out.begin();
while( lhsp != lhs.end() ) {
*outp = *lhsp != rhs;
++lhsp;
++outp;
};
return out;
}
/// \brief Compares an array to a scalar, returns a boolean array.
/// \relates dip::DimensionArray
template< typename T >
inline DimensionArray< bool > operator>( DimensionArray< T > const& lhs, T const& rhs ) {
DimensionArray< bool > out( lhs.size() );
auto lhsp = lhs.begin();
auto outp = out.begin();
while( lhsp != lhs.end() ) {
*outp = *lhsp > rhs;
++lhsp;
++outp;
};
return out;
}
/// \brief Compares an array to a scalar, returns a boolean array.
/// \relates dip::DimensionArray
template< typename T >
inline DimensionArray< bool > operator<( DimensionArray< T > const& lhs, T const& rhs ) {
DimensionArray< bool > out( lhs.size() );
auto lhsp = lhs.begin();
auto outp = out.begin();
while( lhsp != lhs.end() ) {
*outp = *lhsp < rhs;
++lhsp;
++outp;
};
return out;
}
/// \brief Compares an array to a scalar, returns a boolean array.
/// \relates dip::DimensionArray
template< typename T >
inline DimensionArray< bool > operator>=( DimensionArray< T > const& lhs, T const& rhs ) {
DimensionArray< bool > out( lhs.size() );
auto lhsp = lhs.begin();
auto outp = out.begin();
while( lhsp != lhs.end() ) {
*outp = *lhsp >= rhs;
++lhsp;
++outp;
};
return out;
}
/// \brief Compares an array to a scalar, returns a boolean array.
/// \relates dip::DimensionArray
template< typename T >
inline DimensionArray< bool > operator<=( DimensionArray< T > const& lhs, T const& rhs ) {
DimensionArray< bool > out( lhs.size() );
auto lhsp = lhs.begin();
auto outp = out.begin();
while( lhsp != lhs.end() ) {
*outp = *lhsp <= rhs;
++lhsp;
++outp;
};
return out;
}
//
// Other operators and convenience functions
//
/// \brief Writes the array to a stream
/// \relates dip::DimensionArray
template< typename T >
inline std::ostream& operator<<(
std::ostream& os,
DimensionArray< T > const& array
) {
os << '{';
auto it = array.begin();
if( it != array.end() ) {
os << *it;
while( ++it != array.end() ) {
os << ", " << *it;
};
}
os << '}';
return os;
}
template< typename T >
inline void swap( DimensionArray< T >& v1, DimensionArray< T >& v2 ) {
v1.swap( v2 );
}
/// \brief Sorts the `indices` array with indices into the `data` array, from smallest to largest. The sort is stable.
/// \relates dip::DimensionArray
template< typename T >
inline void sortIndices( DimensionArray< typename DimensionArray< T >::size_type >& indices, DimensionArray< T > const& data ) {
using size_type = typename DimensionArray< T >::size_type;
#ifdef DIP_CONFIG_ENABLE_ASSERT
for( size_type ii = 0; ii < indices.size(); ++ii ) {
DIP_ASSERT( indices[ ii ] < data.size() );
}
#endif
// Using insertion sort because we expect the array to be small.
for( size_type ii = 1; ii < indices.size(); ++ii ) {
size_type elem = indices[ ii ];
size_type jj = ii;
while(( jj > 0 ) && ( data[ indices[ jj - 1 ]] > data[ elem ] )) {
indices[ jj ] = indices[ jj - 1 ];
--jj;
}
indices[ jj ] = elem;
}
}
/// \brief Computes the Square Euclidean distance between two points.
/// \relates dip::DimensionArray
template< typename T >
inline double SquareDistance( DimensionArray< T > const& v1, DimensionArray< T > const& v2 ) {
DIP_ASSERT( v1.size() == v2.size() );
using size_type = typename DimensionArray< T >::size_type;
double p = 0;
for( size_type ii = 0; ii < v1.size(); ++ii ) {
double d = static_cast< double >( v1[ ii ] ) - static_cast< double >( v2[ ii ] );
p += d * d;
}
return p;
}
/// \brief Computes the Square Euclidean distance between two points.
/// \relates dip::DimensionArray
template< typename T >
inline double Distance( DimensionArray< T > const& v1, DimensionArray< T > const& v2 ) {
return std::sqrt( SquareDistance( v1, v2 ));
}
/// \endgroup
} // namespace dip
#endif // DIP_DIMENSIONARRAY_H
| 34.216702 | 195 | 0.570948 | [
"object",
"vector",
"transform"
] |
73e7abdf4e820cb602b87fdf91db089094f5ae5d | 2,870 | h | C | actions/hdl_stringmatch/sw/postgresql/hook/mt/base/ThreadBase.h | hustsword/snap | 356e9ebcc49c205a791d2a990f694307252f8f35 | [
"Apache-2.0"
] | null | null | null | actions/hdl_stringmatch/sw/postgresql/hook/mt/base/ThreadBase.h | hustsword/snap | 356e9ebcc49c205a791d2a990f694307252f8f35 | [
"Apache-2.0"
] | null | null | null | actions/hdl_stringmatch/sw/postgresql/hook/mt/base/ThreadBase.h | hustsword/snap | 356e9ebcc49c205a791d2a990f694307252f8f35 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 International Business Machines
*
* 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 THREADBASE_H_h
#define THREADBASE_H_h
#include <iostream>
#include <deque>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include "JobBase.h"
#include "HardwareManager.h"
class ThreadBase
{
public:
// Constructor of thread base
ThreadBase();
ThreadBase (int in_id);
ThreadBase (int in_id, int in_timeout);
// Destructor of thread base
virtual ~ThreadBase();
// Get ID of this thread
int get_id();
// Set ID of this thread
void set_id (int in_id);
// Add a job to the queue
int add_job (JobPtr in_job);
// Delete a job from the queue
void delete_job (int job_id);
// Initialize each job in this thread
virtual int init() = 0;
// Start the thread, preparing for work
int start();
// The main thread of job handling
void work();
// Stop the job processing
int stop();
// Join the thread
void join();
// Work with the jobs
virtual void work_with_job (JobPtr in_job) = 0;
// Interrupt the thread execution
void interrupt();
// Wait for an interrupt to be invoked
int wait_interrupt();
// Get number of remaining jobs
int get_num_remaining_jobs();
// The mutex used to sync between threads
// (each thread would start a thread to work with all the jobs in queue))
// Make it static to share across all instances of ThreadBase
static boost::mutex m_global_mutex;
// Cleanup necessary resources
virtual void cleanup () = 0;
protected:
// The queue to hold all jobs of this thread
std::deque<JobPtr> m_jobs;
// The pointer to the thread instance
boost::shared_ptr<boost::thread> m_thread;
// The mutex used inside an object to sync between different calls within the object
boost::mutex m_mutex;
// The condition variable used to sync between different calls within the object
boost::condition_variable_any m_cond;
// ID of this thread
int m_id;
// The timeout value before waiting an job to finish
int m_timeout;
// If this thread has stopped work
bool m_stopped;
// Index to indicate the position of current jobs
int m_current_job_idx;
};
typedef boost::shared_ptr<ThreadBase> ThreadPtr;
#endif
| 25.175439 | 88 | 0.690941 | [
"object"
] |
73fe23bb20802e11a4be96ec6c802483580c2261 | 4,427 | h | C | src/gui/src/qt/walletcontroller.h | MatthewDarnell/iota-simplewallet | aa3449bae3023e292ad47a9fa72213e279367b7a | [
"MIT"
] | 1 | 2020-11-19T07:18:44.000Z | 2020-11-19T07:18:44.000Z | src/gui/src/qt/walletcontroller.h | MatthewDarnell/iota-simplewallet | aa3449bae3023e292ad47a9fa72213e279367b7a | [
"MIT"
] | null | null | null | src/gui/src/qt/walletcontroller.h | MatthewDarnell/iota-simplewallet | aa3449bae3023e292ad47a9fa72213e279367b7a | [
"MIT"
] | null | null | null | // Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_WALLETCONTROLLER_H
#define BITCOIN_QT_WALLETCONTROLLER_H
#include <sendcoinsrecipient.h>
#include <support/allocators/secure.h>
//#include <sync.h>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <QMessageBox>
#include <QMutex>
#include <QProgressDialog>
#include <QThread>
#include <QTimer>
#include <QString>
class OptionsModel;
class PlatformStyle;
class WalletModel;
namespace interfaces {
class Handler;
class Node;
class Wallet;
} // namespace interfaces
class AskPassphraseDialog;
class CreateWalletActivity;
class CreateWalletDialog;
class ImportAccountDialog;
class ImportWalletActivity;
class WalletControllerActivity;
/**
* Controller between interfaces::Node, WalletModel instances and the GUI.
*/
class WalletController : public QObject
{
Q_OBJECT
void removeAndDeleteWallet(WalletModel* wallet_model);
public:
WalletController(interfaces::Node& node, const PlatformStyle* platform_style, OptionsModel* options_model, QObject* parent);
~WalletController();
//! Returns wallet models currently open.
std::vector<WalletModel*> getOpenWallets() const;
WalletModel* getOrCreateWallet(std::unique_ptr<interfaces::Wallet> wallet);
//! Returns all wallet names in the wallet dir mapped to whether the wallet
//! is loaded.
std::map<std::string, bool> listWalletDir() const;
void closeWallet(WalletModel* wallet_model, QWidget* parent = nullptr);
Q_SIGNALS:
void walletAdded(WalletModel* wallet_model);
void walletRemoved(WalletModel* wallet_model);
void coinsSent(WalletModel* wallet_model, SendCoinsRecipient recipient, QByteArray transaction);
private:
QThread* const m_activity_thread;
QObject* const m_activity_worker;
interfaces::Node& m_node;
const PlatformStyle* const m_platform_style;
OptionsModel* const m_options_model;
mutable QMutex m_mutex;
std::vector<WalletModel*> m_wallets;
std::unique_ptr<interfaces::Handler> m_handler_load_wallet;
friend class WalletControllerActivity;
};
class WalletControllerActivity : public QObject
{
Q_OBJECT
public:
WalletControllerActivity(WalletController* wallet_controller, QWidget* parent_widget);
virtual ~WalletControllerActivity();
Q_SIGNALS:
void finished();
protected:
interfaces::Node& node() const { return m_wallet_controller->m_node; }
QObject* worker() const { return m_wallet_controller->m_activity_worker; }
void showProgressDialog(const QString& label_text);
WalletController* const m_wallet_controller;
QWidget* const m_parent_widget;
QProgressDialog* m_progress_dialog{nullptr};
WalletModel* m_wallet_model{nullptr};
std::string m_error_message;
std::vector<std::string> m_warning_message;
};
class CreateWalletActivity : public WalletControllerActivity
{
Q_OBJECT
public:
CreateWalletActivity(WalletController* wallet_controller, QWidget* parent_widget);
virtual ~CreateWalletActivity();
void create();
Q_SIGNALS:
void created(WalletModel* wallet_model);
private:
void askPassphrase();
void createWallet();
void finish();
SecureString m_passphrase;
CreateWalletDialog* m_create_wallet_dialog{nullptr};
AskPassphraseDialog* m_passphrase_dialog{nullptr};
};
class ImportWalletActivity : public WalletControllerActivity
{
Q_OBJECT
public:
ImportWalletActivity(WalletController* wallet_controller, QWidget* parent_widget);
void importFromSeed();
void importFromFile();
Q_SIGNALS:
void opened(WalletModel* wallet_model);
private:
void finish();
void import(QString path);
ImportAccountDialog* m_import_wallet_dialog { nullptr };
SecureString m_username;
SecureString m_passphrase;
SecureString m_seed;
};
class GenerateAddressesWalletActivity : public WalletControllerActivity
{
Q_OBJECT
public:
GenerateAddressesWalletActivity(WalletModel* walletModel, WalletController* wallet_controller,
QWidget* parent_widget);
void generate();
signals:
void generated(int count);
void failure(const QString &reason);
private:
WalletModel* m_walletModel;
};
#endif // BITCOIN_QT_WALLETCONTROLLER_H
| 25.442529 | 128 | 0.759205 | [
"vector"
] |
90bcdb0e5075294dc680cb15773351cb5188cafe | 5,198 | h | C | Builder/Builder/include/Voxelize.h | sglab/OpenIRT | 1a1522ed82f6bb26f1d40dc93024487869045ab2 | [
"BSD-2-Clause"
] | 2 | 2015-09-28T12:59:25.000Z | 2020-03-28T22:28:03.000Z | Builder/Builder/include/Voxelize.h | sglab/OpenIRT | 1a1522ed82f6bb26f1d40dc93024487869045ab2 | [
"BSD-2-Clause"
] | 2 | 2018-10-26T12:17:53.000Z | 2018-11-09T07:04:17.000Z | Builder/Builder/include/Voxelize.h | sglab/OpenIRT | 1a1522ed82f6bb26f1d40dc93024487869045ab2 | [
"BSD-2-Clause"
] | null | null | null | #ifndef VOXELIZE_H
#define VOXELIZE_H
#include "BVHNodeDefine.h"
#include "Vertex.h"
#include "Triangle.h"
#include "Photon.h"
#include "Voxel.h"
#include "BV.h"
#include "OOCFile6464.h"
#include "Progression.h"
#include "Octree.h"
#include "OOC_PCA.h"
#include "NewMaterial.h"
//#define BUILD_BOEING
#define BUILD_SPONZA
#define BVHNode BSPArrayTreeNode
#define OOC_FILE_CLASS OOCFile6464
#define N 2
#ifdef BUILD_BOEING
#define MAX_DEPTH 10
#define MAX_DEPTH2 12
#define MAX_LOW_DEPTH 5
#endif
#ifdef BUILD_SPONZA
#define MAX_DEPTH 8
#define MAX_DEPTH2 10
#define MAX_LOW_DEPTH 5
#endif
class VoxelMaterialExtra
{
public:
Vector3 summedKd;
Vector3 summedKs;
float summedD;
float summedNs;
int numElements;
VoxelMaterialExtra() : summedKd(Vector3(0.0f)), summedKs(Vector3(0.0f)), summedD(0), summedNs(0), numElements(0) {}
void addMaterial(const NewMaterial &material)
{
summedKd += material.getMatKd();
summedKs += material.getMatKs();
summedD += material.getMat_d();
summedNs += material.getMat_Ns();
numElements++;
}
static VoxelMaterialExtra getTransparentMaterial()
{
VoxelMaterialExtra mat;
mat.summedKs = Vector3(1.0f);
mat.summedNs = 2048.0f;
mat.numElements = 1;
return mat;
}
Vector3 getKd() {return summedKd / numElements;}
Vector3 getKs() {return summedKs / numElements;}
float getD() {return summedD / numElements;}
float getNs() {return summedNs / numElements;}
void normailize()
{
summedKd = getKd();
summedKs = getKs();
summedD = getD();
summedNs = getNs();
numElements = 1;
}
VoxelMaterialExtra operator + (const VoxelMaterialExtra &x) const
{
VoxelMaterialExtra sum;
sum.summedKd = summedKd + x.summedKd;
sum.summedKs = summedKs + x.summedKs;
sum.summedD = summedD + x.summedD;
sum.summedNs = summedNs + x.summedNs;
sum.numElements = numElements + x.numElements;
return sum;
}
};
class Voxelize
{
protected:
typedef struct OOCVoxel_t
{
int rootChildIndex;
int startDepth;
int offset;
int numVoxels;
AABB rootBB;
OOCVoxel_t(int rootChildIndex, int startDepth, const AABB &rootBB) :
rootChildIndex(rootChildIndex), startDepth(startDepth), rootBB(rootBB), offset(0), numVoxels(0) {}
} OOCVoxel;
typedef std::vector<OOCVoxel> OOCVoxelList;
protected:
FILE *m_fp;
OOC_FILE_CLASS<Vertex> *m_vertPtr;
OOC_FILE_CLASS<Triangle> *m_triPtr;
OOC_FILE_CLASS<BVHNode> *m_nodePtr;
OOC_FILE_CLASS<Vertex> m_vert;
OOC_FILE_CLASS<Triangle> m_tri;
OOC_FILE_CLASS<BVHNode> m_node;
AABB m_BB;
Vector3 m_voxelDelta;
float m_intersectEpsilon;
int m_lastIndex;
unsigned char *m_indexMap;
Octree m_octree;
COOCPCAwoExtent *m_PCAOctree;
VoxelMaterialExtra *m_leafVoxelMat;
NewMaterialList m_matList;
OOCVoxelList m_oocVoxelList;
BVHNode *m_oocVoxelBSPtree;
public:
Voxelize();
~Voxelize();
bool isIntersect(const AABB &box, const Triangle &tri);
bool isIntersect(const AABB &box, Vector3 *vert);
bool isIntersect(const AABB &a, const BVHNode *b);
bool isIntersect(const AABB &a);
void getIntersectVoxels(const BVHNode *tree, const Triangle &tri, std::vector<int> &list);
AABB computeSubBox(int x, int y, int z, const AABB &box);
void setGeomBitmap(Voxel &voxel, const AABB &box);
int createOctreeNode();
int createOctreeNode(FILE *fp, const OOCVoxel &voxel);
int createOctreeNode(FILE *fp, int parentIndex, int myIndex, int &lastIndex, const AABB &box, int depth, bool generateOOC = false, bool *isOOCPart = NULL);
float triArea(std::vector<Vector3> &verts, int pos);
void applyTri(int index, const AABB &bb, Vector3 *vert, const Vector3 &norm, const NewMaterial &material);
COOCPCAwoExtent computeGeomLOD(const AABB &bb, int index);
VoxelMaterialExtra computeMaterialLOD(int index);
void computeLOD(const char *fileName, int startDepth = 1);
void setGeomLOD(int index, const AABB &bb);
int Do(const char *filepath, int maxDepth = 0, int maxDepth2 = 0, int maxLowDepth = 0);
bool depthTest(int depth, const AABB &bb);
bool loadMaterialFromMTL(const char *fileName, NewMaterialList &matList);
typedef std::vector<unsigned int> TriangleIndexList;
typedef TriangleIndexList::iterator TriangleIndexListIterator;
FORCEINLINE void updateBB(Vector3 &min, Vector3 &max, const Vector3 &vec)
{
min.e[0] = ( min.e[0] < vec.e[0] ) ? min.e[0] : vec.e[0];
min.e[1] = ( min.e[1] < vec.e[1] ) ? min.e[1] : vec.e[1];
min.e[2] = ( min.e[2] < vec.e[2] ) ? min.e[2] : vec.e[2];
max.e[0] = ( max.e[0] > vec.e[0] ) ? max.e[0] : vec.e[0];
max.e[1] = ( max.e[1] > vec.e[1] ) ? max.e[1] : vec.e[1];
max.e[2] = ( max.e[2] > vec.e[2] ) ? max.e[2] : vec.e[2];
}
bool Subdivide(BVHNode *tree, const AABB &rootBB, int &numNodes, TriangleIndexList *triIDs, unsigned int left, unsigned int right, unsigned int myIndex, unsigned int nextIndex, int depth);
void buildBVH(int numTris, const AABB &bb, const char *fileName);
void buildVoxelBVH(const char *fileName, const AABB &rootBB);
void oocVoxelize(const char *filePath);
void buildOOCVoxelBSPTree();
bool SubdivideBSPTree(BVHNode *tree, const AABB &rootBB, int &numNodes, std::vector<int> *voxelIDs, unsigned int left, unsigned int right, unsigned int myIndex, unsigned int nextIndex, int depth);
};
#endif | 28.718232 | 197 | 0.727972 | [
"vector"
] |
90dece81099750dd8f1a20bcd099a27f37982886 | 2,729 | h | C | sling/nlp/parser/action-table.h | JDzvonik/sling | 3000f6ff7ae5c2d5ddcae13ad3599e35bf375ec5 | [
"Apache-2.0"
] | null | null | null | sling/nlp/parser/action-table.h | JDzvonik/sling | 3000f6ff7ae5c2d5ddcae13ad3599e35bf375ec5 | [
"Apache-2.0"
] | null | null | null | sling/nlp/parser/action-table.h | JDzvonik/sling | 3000f6ff7ae5c2d5ddcae13ad3599e35bf375ec5 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Google 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.
#ifndef SLING_NLP_PARSER_ACTION_TABLE_H_
#define SLING_NLP_PARSER_ACTION_TABLE_H_
#include <unordered_map>
#include <vector>
#include "sling/base/types.h"
#include "sling/frame/object.h"
#include "sling/frame/store.h"
#include "sling/nlp/parser/parser-action.h"
#include "sling/nlp/parser/parser-state.h"
namespace sling {
namespace nlp {
// The action table is a set of parser actions indexed by id.
class ActionTable {
public:
// Add action to the table.
void Add(const ParserAction &action);
// Return the index of action.
int Index(const ParserAction &action) const {
const auto &it = mapping_.find(action);
return it == mapping_.end() ? -1 : it->second;
}
// Return the number of parser actions.
int size() const { return actions_.size(); }
// Return the ith parser action.
const ParserAction &Action(int index) const { return actions_[index]; }
// Return list of actions.
const std::vector<ParserAction> &list() const { return actions_; }
// Saves the action table.
void Save(const Store *global, const string &file) const;
// Returns the serialization of the table.
string Serialize(const Store *global) const;
// Write action table in frame.
void Write(Builder *frame) const;
// Initialize the action table from store.
void Init(Store *store);
// Maximum number of actions per token.
int max_actions_per_token() const { return max_actions_per_token_; }
void set_max_actions_per_token(int m) {
if (max_actions_per_token_ < m) max_actions_per_token_ = m;
}
// Frame limit for source and target in parser actions.
int frame_limit() const { return frame_limit_; }
void set_frame_limit(int limit) { frame_limit_ = limit; }
private:
// List of actions.
std::vector<ParserAction> actions_;
// Mapping from parser action to index.
std::unordered_map<ParserAction, int, ParserActionHash> mapping_;
// Maximum index of source and target for actions.
int frame_limit_ = 5;
// Maximum number of actions taken per token.
int max_actions_per_token_ = -1;
};
} // namespace nlp
} // namespace sling
#endif // SLING_NLP_PARSER_ACTION_TABLE_H_
| 29.989011 | 75 | 0.727373 | [
"object",
"vector"
] |
90e625abdea5c97bba0653713c39442f8e2e3a89 | 2,384 | h | C | iit/YarpJS/include/YarpJS_Bottle.h | robotology/dialog-service | de9e08d8f364b49f5b5a545783be8d5a1fb10bc6 | [
"BSD-3-Clause"
] | 2 | 2019-07-10T13:55:31.000Z | 2020-04-09T17:13:15.000Z | iit/YarpJS/include/YarpJS_Bottle.h | robotology/dialog-service | de9e08d8f364b49f5b5a545783be8d5a1fb10bc6 | [
"BSD-3-Clause"
] | null | null | null | iit/YarpJS/include/YarpJS_Bottle.h | robotology/dialog-service | de9e08d8f364b49f5b5a545783be8d5a1fb10bc6 | [
"BSD-3-Clause"
] | 1 | 2019-07-12T13:51:03.000Z | 2019-07-12T13:51:03.000Z |
/*
Wrapper for the yarp Bottle object.
*/
#ifndef YARP_JS_BOTTLE_H
#define YARP_JS_BOTTLE_H
#include <nan.h>
#include <string>
#include "YarpJS_Wrapper.h"
#include <yarp/os/Bottle.h>
class YarpJS_Bottle: public YarpJS_Wrapper<yarp::os::Bottle>
{
private:
/* setJSMethods(v8::Local<v8::FunctionTemplate> &tpl)
Function in charge of registering the node.js methods (exposed to the user).
Called when creating the object.
The signature is
Nan::SetPrototypeMethod(tpl, "<JS function name>", <C++ function name>);
with
- <JS function name> the name of the function (method) to associate the JS object.
- <C++ function name> handle to the C++ class method to call when the JS function is called.
*/
static void setJSMethods(v8::Local<v8::FunctionTemplate> &tpl)
{
Nan::SetPrototypeMethod(tpl, "copy", Copy);
Nan::SetPrototypeMethod(tpl, "toArray", ToArray);
Nan::SetPrototypeMethod(tpl, "toString", ToString);
Nan::SetPrototypeMethod(tpl, "toObject", ToArray);
Nan::SetPrototypeMethod(tpl, "fromString", FromString);
Nan::SetPrototypeMethod(tpl, "getObjType", GetObjType);
}
public:
// Create the Bottle from a string (using the yarp implementation)
void fromString(const Nan::FunctionCallbackInfo<v8::Value> &info)
{
v8::String::Utf8Value _bottle_string(info[0]->ToString());
this->getYarpObj()->fromString(*_bottle_string);
}
// "Translating" the current Bottle to a standard javascript array
static void toArray(const yarp::os::Bottle *bObj, v8::Local<v8::Array> &bArr);
// Copy Constructor from a node.js bottle.
explicit YarpJS_Bottle(const Nan::FunctionCallbackInfo<v8::Value> &info)
{
this->setYarpObj(new yarp::os::Bottle());
this->fromString(info);
}
// Copy Constructor from a yarp Bottle.
explicit YarpJS_Bottle(yarp::os::Bottle &bottle)
{
this->setYarpObj(new yarp::os::Bottle(bottle));
}
// Destructor
~YarpJS_Bottle()
{}
// Actual
static NAN_METHOD(Copy);
static NAN_METHOD(ToArray);
static NAN_METHOD(ToString);
static NAN_METHOD(FromString);
static NAN_METHOD(GetObjType);
// NAN Stuff
YARPJS_INIT(YarpJS_Bottle,"Bottle",YarpJS)
};
#endif
| 22.923077 | 100 | 0.650587 | [
"object"
] |
90ea187c29a9ee65d1d6fb15243cd7a16b1eb3f1 | 838 | h | C | software/PSGTools/src/output/Chip.h | Yevgeniy-Olexandrenko/ay-ym-usb-streamer | 8dbc3972fb2cb653fa17d62d1481708ef2b534ae | [
"MIT"
] | null | null | null | software/PSGTools/src/output/Chip.h | Yevgeniy-Olexandrenko/ay-ym-usb-streamer | 8dbc3972fb2cb653fa17d62d1481708ef2b534ae | [
"MIT"
] | null | null | null | software/PSGTools/src/output/Chip.h | Yevgeniy-Olexandrenko/ay-ym-usb-streamer | 8dbc3972fb2cb653fa17d62d1481708ef2b534ae | [
"MIT"
] | null | null | null | #pragma once
#include <stdint.h>
#include <string>
struct Chip
{
public:
enum class Count
{
SingleChip, TurboSound
};
enum class Model
{
Unknown, AY, YM, Compatible
};
enum class Frequency
{
Unknown, F1000000, F1750000, F1773400, F2000000
};
enum class Channels
{
Unknown, MONO, ABC, ACB
};
public:
Chip();
std::string toString() const;
void count(Count count);
Count count() const;
void model(Model model);
Model model() const;
bool modelKnown() const;
void frequency(Frequency frequency);
void freqValue(uint32_t freqValue);
Frequency frequency() const;
uint32_t freqValue() const;
bool frequencyKnown() const;
void channels(Channels channels);
Channels channels() const;
bool channelsKnown() const;
private:
Count m_count;
Model m_model;
Frequency m_frequency;
Channels m_channels;
}; | 15.236364 | 49 | 0.717184 | [
"model"
] |
90f802bb873694d877114c7401bbcbb20fd5f6f6 | 7,408 | c | C | src/drawing/drawing.c | YclepticStudios/pebble-battery-plus | 3cc8cf1fb99202f966a7d7e25db671df15fb7b16 | [
"MIT"
] | 1 | 2019-09-11T01:52:42.000Z | 2019-09-11T01:52:42.000Z | src/drawing/drawing.c | YclepticStudios/pebble-battery-plus | 3cc8cf1fb99202f966a7d7e25db671df15fb7b16 | [
"MIT"
] | null | null | null | src/drawing/drawing.c | YclepticStudios/pebble-battery-plus | 3cc8cf1fb99202f966a7d7e25db671df15fb7b16 | [
"MIT"
] | null | null | null | // @file drawing_card.c
// @brief Base wrapper for controlling card layers
//
// This file contains wrapper code to manage all card layers.
// It controls refreshing, events, and everything which gets
// passed to the cards.
//
// @author Eric D. Phillips
// @date December 23, 2015
// @bugs No known bugs
#include "drawing.h"
#include "../animation/animation.h"
#include "card.h"
#include "cards/card_render.h"
#include "../utility.h"
// Constants
#define CARD_SLIDE_ANIMATION_DURATION 100
#define CARD_BOUNCE_ANIMATION_DURATION 70
#define CARD_BOUNCE_HEIGHT 10
#define ACTION_DOT_RADIUS 15
#define ACTION_DOT_OPEN_INSET PBL_IF_RECT_ELSE(5, 9)
#define ACTION_DOT_CLOSE_DURATION 150
// Main data struct
static struct {
Layer *card_layer[DRAWING_CARD_COUNT]; //< An array of pointers to the base card layers
Layer *top_layer; //< Topmost layer for drawing any extra content on
GRect window_bounds; //< The dimensions of the window
int32_t scroll_offset_ani; //< The true offset of the 0'th card
int32_t scroll_offset; //< The final offset of the 0'th card after animation
int32_t action_dot_inset_ani; //< The inset from the left of the screen for the
// dot
} drawing_data;
////////////////////////////////////////////////////////////////////////////////////////////////////
// Private Functions
//
// Position cards
static void prv_position_cards(void) {
GRect bounds = drawing_data.window_bounds;
for (int8_t ii = 0; ii < DRAWING_CARD_COUNT; ii++) {
bounds.origin.y = (drawing_data.scroll_offset_ani % (bounds.size.h * DRAWING_CARD_COUNT) +
(DRAWING_CARD_COUNT + ii) * bounds.size.h) %
(bounds.size.h * DRAWING_CARD_COUNT) - bounds.size.h;
layer_set_bounds(drawing_data.card_layer[ii], bounds);
}
}
// Topmost layer update proc handler
static void prv_top_layer_update_proc_handler(Layer *layer, GContext *ctx) {
// get bounds
GRect bounds = layer_get_bounds(layer);
GPoint center;
center.x = bounds.size.w + ACTION_DOT_RADIUS - drawing_data.action_dot_inset_ani;
center.y = bounds.size.h / 2;
// draw action dot
graphics_context_set_antialiased(ctx, true);
graphics_context_set_fill_color(ctx, GColorBlack);
graphics_fill_circle(ctx, center, ACTION_DOT_RADIUS);
}
// Animation callback handler
static void prv_animation_handler(void) {
// update card positions
prv_position_cards();
// check if out of view
for (int8_t ii = 0; ii < DRAWING_CARD_COUNT; ii++) {
card_free_cache_if_hidden(drawing_data.card_layer[ii], false);
}
// redraw topmost layer
layer_mark_dirty(drawing_data.top_layer);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// API Interface
//
// Refresh current card
void drawing_refresh(void) {
uint8_t card_index = (DRAWING_CARD_COUNT -
((drawing_data.scroll_offset / drawing_data.window_bounds.size.h) % DRAWING_CARD_COUNT - 1)) %
DRAWING_CARD_COUNT;
card_render(drawing_data.card_layer[card_index]);
}
// Free all card caches
void drawing_free_caches(void) {
// loop over cards and force them to free their cache
for (uint8_t ii = 0; ii < DRAWING_CARD_COUNT; ii++) {
card_free_cache_if_hidden(drawing_data.card_layer[ii], true);
}
}
// Set the visible state of the action menu dot
void drawing_set_action_menu_dot(bool visible) {
if (visible) {
drawing_data.action_dot_inset_ani = ACTION_DOT_OPEN_INSET;
} else {
animation_int32_start(&drawing_data.action_dot_inset_ani, 0,
ACTION_DOT_CLOSE_DURATION, 0, CurveSinEaseOut);
}
layer_mark_dirty(drawing_data.top_layer);
}
// Select click handler for current card
void drawing_select_click(void) {
// get current card
uint8_t card_index = (DRAWING_CARD_COUNT -
((drawing_data.scroll_offset / drawing_data.window_bounds.size.h) % DRAWING_CARD_COUNT - 1)) %
DRAWING_CARD_COUNT;
// send click event
card_select_click(drawing_data.card_layer[card_index]);
}
// Render the next or previous card
void drawing_render_next_card(bool up) {
// render the next card
uint8_t cur_card_index = (DRAWING_CARD_COUNT -
((drawing_data.scroll_offset / drawing_data.window_bounds.size.h) % DRAWING_CARD_COUNT - 1)) %
DRAWING_CARD_COUNT;
uint8_t next_card_index = (cur_card_index + (up ? -1 : 1) + DRAWING_CARD_COUNT) %
DRAWING_CARD_COUNT;
// free the previous cache on Aplite
#ifdef PBL_BW
card_free_cache_if_hidden(drawing_data.card_layer[cur_card_index], true);
#endif
// render the next card
card_render(drawing_data.card_layer[next_card_index]);
// move next card underneath current card to hide rendering
layer_insert_below_sibling(drawing_data.card_layer[next_card_index],
drawing_data.card_layer[cur_card_index]);
}
// Select next or previous card
void drawing_select_next_card(bool up) {
// move target card position
drawing_data.scroll_offset += (up ? 1 : -1) * drawing_data.window_bounds.size.h;
// animate slide
animation_int32_start(&drawing_data.scroll_offset_ani,
drawing_data.scroll_offset + (up ? 1 : -1) * CARD_BOUNCE_HEIGHT,
CARD_SLIDE_ANIMATION_DURATION, 0, CurveLinear);
// animate bounce
animation_int32_start(&drawing_data.scroll_offset_ani, drawing_data.scroll_offset,
CARD_BOUNCE_ANIMATION_DURATION, CARD_SLIDE_ANIMATION_DURATION, CurveSinEaseOut);
}
// Initialize all cards and add to window layer
void drawing_initialize(Layer *window_layer, DataAPI *data_api) {
// get params
drawing_data.window_bounds = layer_get_bounds(window_layer);
// initialize cards
// this must be done with the last initialized being the one which is selected first. As
// all the cards must initially be stacked on the screen so they can render themselves.
// When scrolling begins, they will reposition.
drawing_data.scroll_offset = drawing_data.scroll_offset_ani = -drawing_data.window_bounds.size.h;
drawing_data.card_layer[0] = card_initialize(drawing_data.window_bounds, CARD_PALETTE_RECORD_LIFE,
CARD_BACK_COLOR_RECORD_LIFE, card_render_record_life, data_api);
drawing_data.card_layer[1] = card_initialize(drawing_data.window_bounds, CARD_PALETTE_LINE_GRAPH,
CARD_BACK_COLOR_LINE_GRAPH, card_render_line_graph, data_api);
drawing_data.card_layer[2] = card_initialize(drawing_data.window_bounds, CARD_PALETTE_DASHBOARD,
CARD_BACK_COLOR_DASHBOARD, card_render_dashboard, data_api);
drawing_data.card_layer[3] = card_initialize(drawing_data.window_bounds, CARD_PALETTE_BAR_GRAPH,
CARD_BACK_COLOR_BAR_GRAPH, card_render_bar_graph, data_api);
prv_position_cards();
// add to window
for (uint8_t ii = 0; ii < DRAWING_CARD_COUNT; ii++) {
layer_add_child(window_layer, drawing_data.card_layer[ii]);
}
// create topmost layer
drawing_data.top_layer = layer_create(drawing_data.window_bounds);
ASSERT(drawing_data.top_layer);
layer_set_update_proc(drawing_data.top_layer, prv_top_layer_update_proc_handler);
layer_add_child(window_layer, drawing_data.top_layer);
// register animation handler
animation_register_update_callback(prv_animation_handler);
}
// Terminate all cards and free memory
void drawing_terminate(void) {
// destroy topmost layer
layer_destroy(drawing_data.top_layer);
// destroy cards
for (uint8_t ii = 0; ii < DRAWING_CARD_COUNT; ii++) {
card_terminate(drawing_data.card_layer[ii]);
}
}
| 38.38342 | 100 | 0.735961 | [
"render"
] |
90fa3ef97ae990b49266982adc39152b0ad02a26 | 5,577 | c | C | services/src/running_lock_mgr.c | openharmony-sig-ci/powermgr_powermgr_lite | 4f4f1c02494fe5610c5e736334fc3a44049e5a8f | [
"Apache-2.0"
] | null | null | null | services/src/running_lock_mgr.c | openharmony-sig-ci/powermgr_powermgr_lite | 4f4f1c02494fe5610c5e736334fc3a44049e5a8f | [
"Apache-2.0"
] | null | null | null | services/src/running_lock_mgr.c | openharmony-sig-ci/powermgr_powermgr_lite | 4f4f1c02494fe5610c5e736334fc3a44049e5a8f | [
"Apache-2.0"
] | 1 | 2021-09-13T12:05:38.000Z | 2021-09-13T12:05:38.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <common.h>
#include <ohos_errno.h>
#include <pthread.h>
#include <securec.h>
#include "hilog_wrapper.h"
#include "running_lock_entry.h"
#include "running_lock_handler.h"
static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
static Vector g_runningLocks[RUNNINGLOCK_BUTT];
static const char * const g_runningLockNames[RUNNINGLOCK_BUTT] = {
"OHOSPowerMgr.Screen",
"OHOSPowerMgr.Background",
"OHOSPowerMgr.Proximity",
};
static RunningLockEntry *DupRunningLockEntry(RunningLockEntry *entry)
{
RunningLockEntry *e = (RunningLockEntry *)malloc(sizeof(RunningLockEntry));
if (e == NULL) {
POWER_HILOGE("Failed allocate running lock entry");
return NULL;
}
if (memcpy_s(e, sizeof(RunningLockEntry), entry, sizeof(RunningLockEntry)) != EOK) {
POWER_HILOGE("Failed copy running lock entry");
free(e);
return NULL;
}
return e;
}
static BOOL AddRunningLockEntryLocked(Vector *vec, RunningLockEntry *entry)
{
int16_t pos = VECTOR_FindByKey(vec, (void *)&entry->identity);
if (pos >= 0) {
POWER_HILOGI("Already acquired: %s", entry->lock.name);
return TRUE;
}
RunningLockEntry *e = DupRunningLockEntry(entry);
if (e == NULL) {
POWER_HILOGE("Failed duplicate running lock entry");
return FALSE;
}
pos = VECTOR_Add(vec, (void *)e);
if (pos == INVALID_INDEX) {
POWER_HILOGE("Failed to add entry to vector for lock: %s", e->lock.name);
free(e);
return FALSE;
}
POWER_HILOGD("Add running lock entry, name: %s, type: %d", e->lock.name, e->lock.type);
if (VECTOR_Num(vec) == 1) {
RunningLockHandlerLock(g_runningLockNames[entry->lock.type]);
}
return TRUE;
}
static BOOL RemoveRunningLockEntryLocked(Vector *vec, RunningLockEntry *entry)
{
int16_t pos = VECTOR_FindByKey(vec, (void *)&entry->identity);
if (pos < 0) {
POWER_HILOGE("Non-existent running lock: %s", entry->lock.name);
return TRUE;
}
RunningLockEntry *e = (RunningLockEntry *)VECTOR_Swap(vec, pos, NULL);
free(e);
POWER_HILOGD("Remove running lock entry, name: %s, type: %d", entry->lock.name, entry->lock.type);
if (VECTOR_Num(vec) == 0) {
RunningLockHandlerUnlock(g_runningLockNames[entry->lock.type]);
}
return TRUE;
}
static void ShowLocks()
{
#ifdef OHOS_DEBUG
for (int32_t t = RUNNINGLOCK_SCREEN; t < RUNNINGLOCK_BUTT; t++) {
Vector *vec = &g_runningLocks[t];
int32_t size = VECTOR_Size(vec);
POWER_HILOGD("type: %d, lock num: %d", t, VECTOR_Num(vec));
for (int32_t i = 0; i < size; i++) {
RunningLockEntry* e = VECTOR_At(vec, i);
if (e != NULL) {
POWER_HILOGD("No.%d, name: %s, pid: %u, token: %llu",
i, e->lock.name, e->identity.pid, (long long)e->identity.token);
}
}
}
#endif
}
int32_t RunningLockMgrAcquireEntry(RunningLockEntry *entry, int32_t timeoutMs)
{
if (IsValidRunningLockEntry(entry) == FALSE) {
POWER_HILOGE("Invalid running lock entry");
return EC_INVALID;
}
pthread_mutex_lock(&g_mutex);
Vector *vec = &g_runningLocks[entry->lock.type];
BOOL ret = AddRunningLockEntryLocked(vec, entry);
ShowLocks();
pthread_mutex_unlock(&g_mutex);
return (ret == TRUE) ? EC_SUCCESS : EC_FAILURE;
}
int32_t RunningLockMgrReleaseEntry(RunningLockEntry *entry)
{
if (IsValidRunningLockEntry(entry) == FALSE) {
POWER_HILOGE("Invalid running lock entry");
return EC_INVALID;
}
pthread_mutex_lock(&g_mutex);
Vector *vec = &g_runningLocks[entry->lock.type];
BOOL ret = RemoveRunningLockEntryLocked(vec, entry);
ShowLocks();
pthread_mutex_unlock(&g_mutex);
return (ret == TRUE) ? EC_SUCCESS : EC_FAILURE;
}
uint32_t RunningLockMgrGetLockCount(RunningLockType type)
{
uint32_t cnt = 0;
if ((type >= 0) && (type < RUNNINGLOCK_BUTT)) {
pthread_mutex_lock(&g_mutex);
cnt = VECTOR_Num(&g_runningLocks[type]);
pthread_mutex_unlock(&g_mutex);
}
return cnt;
}
uint32_t RunningLockMgrGetTotalLockCount()
{
uint32_t cnt = 0;
pthread_mutex_lock(&g_mutex);
for (int32_t t = RUNNINGLOCK_SCREEN; t < RUNNINGLOCK_BUTT; t++) {
cnt += VECTOR_Num(&g_runningLocks[t]);
}
pthread_mutex_unlock(&g_mutex);
POWER_HILOGD("Total lock count: %u", cnt);
return cnt;
}
static RunningLockIdentity *GetRunningLockIdentity(const RunningLockEntry *entry)
{
return &entry->identity;
}
static int32_t RunningLockIdentityCmp(const RunningLockIdentity *a, const RunningLockIdentity *b)
{
return (IsSameRunningLockIdentity(a, b) == TRUE) ? 0 : -1;
}
void RunningLockMgrInit(void)
{
for (int32_t i = 0; i < RUNNINGLOCK_BUTT; i++) {
g_runningLocks[i] = VECTOR_Make((VECTOR_Key)GetRunningLockIdentity, (VECTOR_Compare)RunningLockIdentityCmp);
}
}
| 31.508475 | 116 | 0.66846 | [
"vector"
] |
29015c350c83e815e10131318d36e3b3ec6389d1 | 3,459 | h | C | EVT/EXAM/VoiceRcgExam/VoiceRcgExam/User/VoiceRcg.h | Taoyukai/ch32v307 | 62806cf743f6c0badad4b2df90a29b0bcfd75c92 | [
"Apache-2.0"
] | null | null | null | EVT/EXAM/VoiceRcgExam/VoiceRcgExam/User/VoiceRcg.h | Taoyukai/ch32v307 | 62806cf743f6c0badad4b2df90a29b0bcfd75c92 | [
"Apache-2.0"
] | null | null | null | EVT/EXAM/VoiceRcgExam/VoiceRcgExam/User/VoiceRcg.h | Taoyukai/ch32v307 | 62806cf743f6c0badad4b2df90a29b0bcfd75c92 | [
"Apache-2.0"
] | null | null | null | #ifndef __VOICERCG_H__
#define __VOICERCG_H__
#include "math.h"
#include "debug.h"
#ifndef NULL
#define NULL ((void *)0)
#endif
#define ERR_OK 0 //no error
#define ERR_FLASH 1 //error at flash operation
#define ERR_DETEC 2 //error at detecting
#define ERR_PARA 3 //error at calculating parameter
#define ERR_MATCH 0xFFFFFFFF //error at matching
#define DataSampleFrq 8000 //don't change because relate to fft
#define SampleTime 2000 //total sample time
#define SampleDataLen ((DataSampleFrq/1000)*SampleTime) //total data length
#define SampleNoiseTime 300 //noise Sample time, must be a multiple of 30
#define SampleNoiseLen ((DataSampleFrq/1000)*SampleNoiseTime) //noise data length
#define stime_energy 9.4 //short-time energy rate
#define stime_zerocross 0.2 //short-time zero cross
#define FLASH_PAGE_SIZE 256
#define MAGIC_DATA 0x55AA //magic data used to check
#define size_per_chara (8*1024) //sizes of a characteristic parameter
#define page_per_chara (size_per_chara/FLASH_PAGE_SIZE) //pages of a characteristic parameter
#define charaml_per_kw 2 //characteristic parameters of a key word
#define size_per_kw (charaml_per_kw*size_per_chara) //sizes of a key word
#define kw_num 4 //number of key words
#define charamls_size (size_per_kw*kw_num) //total sizes
/* we use non-zero waiting period spaces to storage parameters */
#define charamls_start_addr (charamls_end_addr-charamls_size) //start address at flash
#define charamls_end_addr 0x08070800 //end address at flash
/* real and image of complex */
typedef struct
{
float real;
float imag;
}vr_compx_d;
typedef struct
{
uint32_t average; //short-time average energy
uint32_t energy; //short-time energy
uint16_t noise; //background noise
uint16_t zerocross; //short-time zero cross rate
}vr_dtg_para;
typedef struct
{
uint16_t *act_start; //active segment start point
uint16_t *act_end; //active segment end point
}vr_act_seg;
typedef struct __attribute__((packed))
{
uint16_t magic; //check if overflow
uint16_t seg_cnt; //segment cnt
float chara_para[120*12];//characteristic parameter
}vr_chara_para ;
/* calculate background noise and shor time parameter */
void environment_noise( uint16_t *noise, uint16_t noise_length, vr_dtg_para *dtg_para );
/* get active segment from data buffer */
void active_segment_detect( uint16_t *data , uint16_t d_len, vr_act_seg *act_seg, vr_dtg_para *dtg_para);
/* calculate mfcc characteristic parameter */
void calc_mfcc_chara_para(vr_act_seg *act_seg, vr_chara_para *chara_para, vr_dtg_para *dtg_para);
/* save mfcc characteristic parameter to flash */
uint8_t save_mfcc_chara_para(vr_chara_para* chara_para, uint32_t addr);
/* calculate distance between input and model */
uint32_t calc_chara_para_match_dis(vr_chara_para *chara_para_src, vr_chara_para *chara_para_mdl);
#endif
| 38.865169 | 113 | 0.64296 | [
"model"
] |
2906f4ed53706b7256f96f0b8d8337d085e97624 | 1,106 | h | C | previewer/projector.h | hellux/3d-projection | e7568ed5e37400d00f3274ae5dac77fd05b16aa8 | [
"Unlicense"
] | 3 | 2016-12-07T16:44:21.000Z | 2020-05-14T13:22:49.000Z | previewer/projector.h | hellux/3d-projection | e7568ed5e37400d00f3274ae5dac77fd05b16aa8 | [
"Unlicense"
] | null | null | null | previewer/projector.h | hellux/3d-projection | e7568ed5e37400d00f3274ae5dac77fd05b16aa8 | [
"Unlicense"
] | null | null | null | #ifndef projector_h
#define projector_h
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h> /* uint8_t type for colors */
#include <limits.h> /* INT_MAX, INT_MIN */
#include <math.h> /* abs, trig */
#include <SDL2/SDL.h>
#include "../common/world.h"
#include "../common/camera.h"
#include "../common/object.h"
#include "../common/triangle.h"
#include "../common/vector.h"
#include "../common/image.h"
void painters_render_scene(SDL_Renderer* renderer,
struct World* W,
struct Camera* C);
void render_scene_vertex(SDL_Renderer* renderer, struct World* W, struct Camera* C);
void render_scene_surface(SDL_Renderer* renderer, struct World* W, struct Camera* C);
void render_vertex(SDL_Renderer* renderer, struct Camera* C, double vertex[]);
void render_triangle(SDL_Renderer* renderer, struct Camera* C, struct Triangle* T);
void render_fill_triangle(SDL_Renderer* renderer,
double v1[], double v2[], double v3[]);
void transform_point(struct Camera* C, double P[], double point_2d[]);
#endif
| 36.866667 | 86 | 0.668174 | [
"object",
"vector"
] |
291150f6df4fb30249b5c63c9b9781750769d033 | 4,108 | h | C | src/Functions/JSONPath/Generator/GeneratorJSONPath.h | pdv-ru/ClickHouse | 0ff975bcf3008fa6c6373cbdfed16328e3863ec5 | [
"Apache-2.0"
] | 15,577 | 2019-09-23T11:57:53.000Z | 2022-03-31T18:21:48.000Z | src/Functions/JSONPath/Generator/GeneratorJSONPath.h | pdv-ru/ClickHouse | 0ff975bcf3008fa6c6373cbdfed16328e3863ec5 | [
"Apache-2.0"
] | 16,476 | 2019-09-23T11:47:00.000Z | 2022-03-31T23:06:01.000Z | src/Functions/JSONPath/Generator/GeneratorJSONPath.h | pdv-ru/ClickHouse | 0ff975bcf3008fa6c6373cbdfed16328e3863ec5 | [
"Apache-2.0"
] | 3,633 | 2019-09-23T12:18:28.000Z | 2022-03-31T15:55:48.000Z | #pragma once
#include <Functions/JSONPath/Generator/IGenerator.h>
#include <Functions/JSONPath/Generator/VisitorJSONPathMemberAccess.h>
#include <Functions/JSONPath/Generator/VisitorJSONPathRange.h>
#include <Functions/JSONPath/Generator/VisitorJSONPathRoot.h>
#include <Functions/JSONPath/Generator/VisitorJSONPathStar.h>
#include <Functions/JSONPath/Generator/VisitorStatus.h>
#include <Functions/JSONPath/ASTs/ASTJSONPath.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
}
template <typename JSONParser>
class GeneratorJSONPath : public IGenerator<JSONParser>
{
public:
/**
* Traverses children ASTs of ASTJSONPathQuery and creates a vector of corresponding visitors
* @param query_ptr_ pointer to ASTJSONPathQuery
*/
GeneratorJSONPath(ASTPtr query_ptr_)
{
query_ptr = query_ptr_;
const auto * path = query_ptr->as<ASTJSONPath>();
if (!path)
{
throw Exception("Invalid path", ErrorCodes::LOGICAL_ERROR);
}
const auto * query = path->jsonpath_query;
for (auto child_ast : query->children)
{
if (typeid_cast<ASTJSONPathRoot *>(child_ast.get()))
{
visitors.push_back(std::make_shared<VisitorJSONPathRoot<JSONParser>>(child_ast));
}
else if (typeid_cast<ASTJSONPathMemberAccess *>(child_ast.get()))
{
visitors.push_back(std::make_shared<VisitorJSONPathMemberAccess<JSONParser>>(child_ast));
}
else if (typeid_cast<ASTJSONPathRange *>(child_ast.get()))
{
visitors.push_back(std::make_shared<VisitorJSONPathRange<JSONParser>>(child_ast));
}
else if (typeid_cast<ASTJSONPathStar *>(child_ast.get()))
{
visitors.push_back(std::make_shared<VisitorJSONPathStar<JSONParser>>(child_ast));
}
}
}
const char * getName() const override { return "GeneratorJSONPath"; }
/**
* This method exposes API of traversing all paths, described by JSONPath,
* to SQLJSON Functions.
* Expected usage is to iteratively call this method from inside the function
* and to execute custom logic with received element or handle an error.
* On each such call getNextItem will yield next item into element argument
* and modify its internal state to prepare for next call.
*
* @param element root of JSON document
* @return is the generator exhausted
*/
VisitorStatus getNextItem(typename JSONParser::Element & element) override
{
while (true)
{
/// element passed to us actually is root, so here we assign current to root
auto current = element;
if (current_visitor < 0)
{
return VisitorStatus::Exhausted;
}
for (int i = 0; i < current_visitor; ++i)
{
visitors[i]->apply(current);
}
VisitorStatus status = VisitorStatus::Error;
for (size_t i = current_visitor; i < visitors.size(); ++i)
{
status = visitors[i]->visit(current);
current_visitor = i;
if (status == VisitorStatus::Error || status == VisitorStatus::Ignore)
{
break;
}
}
updateVisitorsForNextRun();
if (status != VisitorStatus::Ignore)
{
element = current;
return status;
}
}
}
private:
bool updateVisitorsForNextRun()
{
while (current_visitor >= 0 && visitors[current_visitor]->isExhausted())
{
visitors[current_visitor]->reinitialize();
current_visitor--;
}
if (current_visitor >= 0)
{
visitors[current_visitor]->updateState();
}
return current_visitor >= 0;
}
int current_visitor = 0;
ASTPtr query_ptr;
VisitorList<JSONParser> visitors;
};
}
| 31.844961 | 105 | 0.601266 | [
"vector"
] |
291b9bfba1853bf8b54d237f38942944ca4e0e83 | 3,115 | h | C | libraries/nodes/include/MultiplexerNode.h | siddu1998/ELL | 993d5370f0f7a274e8dfd8f43220c792be46f314 | [
"MIT"
] | 1 | 2018-11-08T06:19:31.000Z | 2018-11-08T06:19:31.000Z | libraries/nodes/include/MultiplexerNode.h | vishnoitanuj/ELL | 993d5370f0f7a274e8dfd8f43220c792be46f314 | [
"MIT"
] | null | null | null | libraries/nodes/include/MultiplexerNode.h | vishnoitanuj/ELL | 993d5370f0f7a274e8dfd8f43220c792be46f314 | [
"MIT"
] | 1 | 2019-12-19T10:02:48.000Z | 2019-12-19T10:02:48.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: MultiplexerNode.h (node)
// Authors: Ofer Dekel
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
// model
#include "CompilableNode.h"
#include "IRMapCompiler.h"
#include "InputPort.h"
#include "MapCompiler.h"
#include "Node.h"
#include "OutputPort.h"
// utilities
#include "IArchivable.h"
#include "TypeName.h"
// stl
#include <exception>
#include <vector>
namespace ell
{
/// <summary> model namespace </summary>
namespace nodes
{
/// <summary> A node that outputs a dynamically specified element from an input array. </summary>
template <typename ValueType, typename SelectorType>
class MultiplexerNode : public model::CompilableNode
{
public:
/// @name Input and Output Ports
/// @{
static constexpr const char* elementsPortName = "elements";
static constexpr const char* selectorPortName = "selector";
const model::InputPort<ValueType>& elements = _elements;
const model::InputPort<SelectorType>& selector = _selector;
const model::OutputPort<ValueType>& output = _output;
/// @}
/// <summary> Default Constructor </summary>
MultiplexerNode();
/// <summary> Constructor </summary>
///
/// <param name="elements"> The input aray of values. </param>
/// <param name="selector"> The index of the chosen element </param>
MultiplexerNode(const model::OutputPort<ValueType>& elements, const model::OutputPort<SelectorType>& selector);
/// <summary> Gets the name of this type (for serialization). </summary>
///
/// <returns> The name of this type. </returns>
static std::string GetTypeName() { return utilities::GetCompositeTypeName<ValueType, SelectorType>("MultiplexerNode"); }
/// <summary> Gets the name of this type (for serialization). </summary>
///
/// <returns> The name of this type. </returns>
std::string GetRuntimeTypeName() const override { return GetTypeName(); }
protected:
void Compute() const override;
void Compile(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function) override;
void WriteToArchive(utilities::Archiver& archiver) const override;
void ReadFromArchive(utilities::Unarchiver& archiver) override;
bool HasState() const override { return false; }
private:
void Copy(model::ModelTransformer& transformer) const override;
void CompileMultiplexerBinary(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function);
void CompileUnrolled(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function);
// Inputs
model::InputPort<ValueType> _elements;
model::InputPort<SelectorType> _selector;
// Output
model::OutputPort<ValueType> _output;
};
}
}
#include "../tcc/MultiplexerNode.tcc"
| 35 | 128 | 0.623756 | [
"vector",
"model"
] |
292244e34570163576d55a7af6ba1835f0a2eb71 | 19,259 | h | C | lib/seismic/libseispp/GenericFileHandle.h | chad-iris/antelope_contrib | d4cb83d433f30fd76ee7416f3106a4074a7206d4 | [
"BSD-2-Clause",
"MIT"
] | 30 | 2015-02-20T21:44:29.000Z | 2021-09-27T02:53:14.000Z | lib/seismic/libseispp/GenericFileHandle.h | chad-iris/antelope_contrib | d4cb83d433f30fd76ee7416f3106a4074a7206d4 | [
"BSD-2-Clause",
"MIT"
] | 14 | 2015-07-07T19:17:24.000Z | 2020-12-19T19:18:53.000Z | lib/seismic/libseispp/GenericFileHandle.h | chad-iris/antelope_contrib | d4cb83d433f30fd76ee7416f3106a4074a7206d4 | [
"BSD-2-Clause",
"MIT"
] | 46 | 2015-02-06T16:22:41.000Z | 2022-03-30T11:46:37.000Z | #ifndef _LINEAR_FILE_HANDLE_
#define _LINEAR_FILE_HANDLE_
#include <fstream>
#include "Metadata.h"
#include "TimeSeries.h"
#include "ensemble.h"
#include "FixedFormatTrace.h"
#include "AttributeCrossReference.h"
namespace SEISPP
{
using namespace std;
using namespace SEISPP;
/* \brief Generic file handle for seismic data stored with fixed length headers.
Much multichannel processing was born from the concept of linear file
formats born of tape processing. This model remains useful for
many types of data processing. This object attempts to standardize
reading and writing of data into such file formats with the only
restriction being that the data have to have header data stored in
a fixed length structure. The header structure itself is defined in
the writer by constructors and is considered absolutely immutable.
*/
class GenericFileHandle
{
public:
/*! Full constructor.
This is a fully parameterized constructor that defines
all the components needed to make the object valid.
A file accessed by this handle is in either read or write
mode, but it cannot be both.
\param filename is the data file to be read or created.
\param tracetype is a unique data type identifier used
internally to define format (implementation dependent)
\param namemap is an object that provides a cross referencing
between the internal and external namespace.
\param orderkeys is a list of attributes used to define
internal groupings during reads. Ignored in writing
so writers can leave this empty.
\param ensmdlist is a list of internal names to be loaded
as global for the entire ensemble. These are extracted
for input and pushed to all headers in output.
\param tmdlist is a list of internal names for metadata to
be loaded for every object read or to be stored for
each object written.
\param read_only is true if as name implies this is to
be used only in read mode.
\param ns_key is a Metadata tag (internal name, not external
name for given file format) for number of samples.
\param dt_key is a Metadata tag (internal name, not external)
used to define sample interval in seconds.
\param dtscl is a scale factor to be applied to the external
files stored sample rate. This is necessary, for example,
with segy/su files where dt is defined in microseconds.
\param using_sample_interval is used as a flag to define
the physical meaning of the dt_key parameter. When
this parameter is true it is assumed the dt_key attribute
is the sample interval. When false it is assumed the
value stored is sampling frequency = 1/dt. (default true)
\param nowritedead defines how to handle traces maked dead.
When true (the default) traces marked dead (live=false)
are ignored. When false a zero pad version will be inserted.
The later, for example, is used by segy.
\exception A SeisppError can be thrown for a number of reasons.
There are the obvious ones of open failure, but a more
subtle issue needs to be recognized. The following must
be defined in the required metadata list or the constructor
will throw an excpetion: nsamp and dt.
*/
GenericFileHandle(string filename, string tracetype,
AttributeCrossReference& namemap, list<string> orderkeys,
list<string> ensmdlist, list<string> tmdlist,
bool read_only, string ns_key, string dt_key, double dtscl,
bool using_sample_interval=true,bool nowritedead=true);
/*! \brief Simplified constructor with file name and type only.
Children of this handle for particular trace formats
will normally use this constructor. It builds only core
components that have to be initialized by a "construction is
initialization" algorithm. Any use of this constructor
will require a later call to the protected method called
set_required. The object itself has
internal checks for validation of required parameters.
The intent is most uses of this object will use this
constructor in the standard colon syntax followed by calls
to set_required. This allows the details of how these
messy elements are constructed to be hidden behind the
interface.
\param filename is the data file to be read or created.
\param tracetype is a unique data type identifier used
internally to define format (implementation dependent)
\param read_only is boolean as the name implies.
*/
GenericFileHandle(string filename, string tracetype,
bool read_only=true);
/*! Copy constructor.
The current implementation does not actually allow this
handle to be copied. If you try to call this constructor
a SeisppError exception will be thrown. The idea is that
if you need to move copies of this handle around wrap the
master copy in a boost::shared_pointer or manage the
destruction of the object yourself. The problem is that
the handle maintains an open file that needs to be closed
and something like a shared_pointer is required for counting
to avoid closing the file prematurely. */
GenericFileHandle(const GenericFileHandle& parent);
~GenericFileHandle();
shared_ptr<TimeSeriesEnsemble> GetNextEnsemble();
TimeSeries GetNextSeismogram();
/* \brief Test for end of file during reading.
Data driven loops require a mechanism to inform the
caller when there is no more data to read. This method
is comparable to the eof method in the stardard
istream operator >>. That is, it returns true when
the last read touches eof. The bottom line is that
the read logic when using this handle should have
a while loop with a call to the eof method and
the top of the while loop should issue a call to one
of the read methods followed by code to do something
to data read. This allows proper handling of the last
object in the file.
*/
bool eof();
/*! Write one seismogram to output.
\param d is the TimeSeries object containing data to be written.
\return 1 on success (not normally useful)
\exception SeisppError can be thrown for a variety of potential
problems.
*/
int put(TimeSeries& d);
/*! Write ensemble of data.
\param d contains the data ensemble to be written to output.
\return number of traces written.
\exception SeisppError will be thrown if there are problems.
*/
int put(TimeSeriesEnsemble& d);
/*! Write a binary blob.
Some formats (e.g. true SEGY as opposed to Seismic Unix
format) have other stuff that needs to be written to
a file that does not match the fixed length record
model exactly on which this object is built. An example
are the so called reel headers of SEGY. We allow writing
such a thing through an opaque pointer that needs to
normally be cast by the caller to an const char
pointer. This has the universal warning that we
implicitly assume the pointer is directed at where
you think it is and chaos will result if it is anything
else. The only exception is that a NULL pointer will
create an exception.
\param b is a pointer to the first byte of the block
of data to be written to output at the current file position.
\param nb is the number of bytes from b to write.
\return number of bytes successfully written
\exception SeisppError is thrown if b is nill.
*/
int put(const char *b, int nb);
/* \brief Load and return a ThreeComponentSeismgram object.
Some formats can and should allow gathers of three component
seismgrams organized in one of two orders: channel order or
time frame order. The interface should take care of handling
this important detail in the constructor as is done in this
implementation. Since ThreeComponentSeismograms objects
contain a transformation matrix the interface and format
definition should define this and assume these attributes
in each member are initialized. In this implementation
the user can always assume the returned seismgrams have
been rotated to standard coordinates as describe in the
documentation for a ThreeComponentSeismgram object.
\exception can throw a SeisppError object for a range of
possible problems. */
shared_ptr<ThreeComponentEnsemble> GetNext3CEnsemble();
/* \brief read and load one ThreeComponentSeismogram object.
Some formats can and should allow simple reads of three component
seismgrams organized in one of two orders: channel order or
time frame order. The interface should take care of handling
this important detail in the constructor as is done in this
implementation. Since ThreeComponentSeismograms objects
contain a transformation matrix the interface and format
definition should define this and assume these attributes
in each member are initialized. In this implementation
the user can always assume the returned seismgram has
been rotated to standard coordinates as describe in the
documentation for a ThreeComponentSeismgram object.
\exception can throw a SeisppError object for a range of
*/
ThreeComponentSeismogram GetNext3CSeismogram();
/*! Write one three component seismogram to output.
Although this interface was designed to insulate users from
details of a format, the implmentation will force the output
to be written as a header followed by the sample data in
either time or channel order (a format variation).
\param d is the TimeSeries object containing data to be written.
\return 1 on success (not normally useful)
\exception SeisppError can be thrown for a variety of potential
problems.
*/
int put(ThreeComponentSeismogram& d);
/*! Write a full ensemble of ThreeComponentSeismogram objects.
In this implementation this amounts to only slightly more than a
loop over members of the input ensemble with members written
using the put(ThreeComponentSeismgram) method.
\param d is the ensemble to be written.
\exception a SeisppError object may be thrown for a variety
of possible errors.
*/
int put(ThreeComponentEnsemble& d);
/*! return current file size in bytes. */
long filesize();
/*! Position file pointer to beginning of file. */
void rewind();
protected:
/* \brief Sets all required format dependent variables.
This procedure is a companion to the partial constructor
above. It exists mainly to provide a way to build
simplified constructors for specific formats. This procedure
sets the required parameters and an internal boolean that
validates the handle is complete and in working order.
\param namemap is an object that provides a cross referencing
between the internal and external namespace.
\param orderkeys is a list of attributes used to define
internal groupings during reads. Ignored in writing
so writers can leave this empty.
\param ensmdlist is a list of internal names to be loaded
as global for the entire ensemble. These are extracted
for input and pushed to all headers in output.
\param tmdlist is a list of internal names for metadata to
be loaded for every object read or to be stored for
each object written.
\param ns_key is a Metadata tag (internal name, not external
name for given file format) for number of samples.
\param dt_key is a Metadata tag (internal name, not external)
used to define sample interval in seconds.
\param dtscl is a scale factor to be applied to the external
files stored sample rate. This is necessary, for example,
with segy/su files where dt is defined in microseconds.
\param using_sample_interval is used as a flag to define
the physical meaning of the dt_key parameter. When
this parameter is true it is assumed the dt_key attribute
is the sample interval. When false it is assumed the
value stored is sampling frequency = 1/dt. (default true)
\param nowritedead defines how to handle traces maked dead.
When true (the default) traces marked dead (live=false)
are ignored. When false a zero pad version will be inserted.
The later, for example, is used by segy.
*/
void set_required(AttributeCrossReference& namemap,
list<string> orderkeys,
list<string> ensmdlist,
list<string> tmdlist,
string ns_key,
string dt_key,
double dtscl,
bool using_sample_interval,
bool nowritedead);
private:
bool handle_not_ready;
/* This is little routine opens files and stores appropriate
handle in this object. Used by all constructors. */
void initialize_iohandle(string filename, bool read_only);
FixedFormatTrace dbuffer;
AttributeCrossReference xref;
/* Current implementation uses the file name to create an empty
lock file derived from the original file name. This string
holds the original file name, NOT the lock file name */
string fname;
bool readmode;
FILE *fp; // defined only when reading.
ofstream outstrm; // Defined only when writing
list<string> orderkeys;
list<string> ensemble_mdlist;
list<string> trace_mdlist;
/* File size in bytes. Cached during read for efficiency. */
long fsize;
/* Current file position */
long current_file_position;
/* These are needed by FixedFormatTrace constructors.
First are internal namespace */
string nsamp_keyword;
string dt_keyword;
/* These are cached external namespace for nsamp and dt respectively
that are stored for efficiency and so we don't have to constantly
trap errors for these absolutely required parameters */
string nskey_ext;
string dtkey_ext;
bool key_is_dt;
bool no_write_dead;
/* This is used only for 3c data. When true data in output are
presumed to be in channel order. This is effectively the
transpose of the dmatrix that holds data in 3c data objects.
For efficiency most 3c formats using the library should
put data in time multiplex order in which case this
attribute should be set false. */
bool channel_order;
/* Some external formats like segy store dt in nonstandard units.
This is a generic way to rescale the external dt to something
more appropriate for internal use. */
double dtscale; //WARNING: PERHAPS SHOULD BE IN FIXEFORMATTRACE OBJECT
/* The next two methods define common code for get methods.
First is a method that is the get equivalent of put_metadata_to_dbuffer
below. That is, this method standardizes loading of a list of
attributes defined by mdlist. Note that mdlist is a list of
internal metadata names NOT external. These are converted
to external names and extracted for the external representation
abstracted in dext*/
void LoadMetadata(FixedFormatTrace& dext,
Metadata& d, list<string> mdlist);
/* This is a comparable method for loading required BasicTimeSeries
attributes with a common set of code. */
void LoadCommonAttributes(FixedFormatTrace& d, BasicTimeSeries& bts);
/* This method is used to test order keys */
bool keys_match(Metadata& current, Metadata& previous);
/* private method to avoid repetitious code. Loads
a list of metadata from d (internal names) to
dbuffer (external names)*/
void put_metadata_to_dbuffer(Metadata& d,
list<string>& mdlist);
/* Because sample interval handling is variable with
format we use this private method to handle
if it is stored as dt of 1/dt and if there is a scaling
as in segy */
void put_sample_interval(BasicTimeSeries& d);
/* This file handle is designed to work in a multithreaded
environment as one of the primary goals was a way to read
and write data on a massively parallel machine.
A timeout method is used in trying to obtain a file lock
during write operations. Specifically, write methods all
call the lock function below. If a lock cannot be obtained
the process will sleep for sleep_interval seconds before
trying again. That processes is repeated up to retry_limit
before an exception is thrown. It may prove useful in the
future to use a finer granularity than the traditional
sleep (1 s intervals) but for now we use that. Note
these constants are set in the constructor.*/
int retry_limit;
unsigned int sleep_interval;
/* These two private methods are needed to avoid collisions
with multiple threads. C++ streams library stupidly does
not have a locking mechanism defined in the interface
considering it a system dependent issue - what do those
bozos thing an interface is for. Anyway, these methods
implement locking on the output stream. Retry limit is defined
above to avoid deadlocks. */
void lock();
void unlock();
};
} // end SEISPP namespace encapsulation
#endif
| 51.357333 | 82 | 0.652007 | [
"object",
"model"
] |
2926dbba0592af7709f356b5b02f0492c74d855e | 25,238 | c | C | tests/test.c | Lederstrumpf/substrate-c-tool | 999bc55ffa2f354b96c347ebb122c79baad812cc | [
"MIT"
] | null | null | null | tests/test.c | Lederstrumpf/substrate-c-tool | 999bc55ffa2f354b96c347ebb122c79baad812cc | [
"MIT"
] | null | null | null | tests/test.c | Lederstrumpf/substrate-c-tool | 999bc55ffa2f354b96c347ebb122c79baad812cc | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <sodium.h>
#include "../src/substrate.h"
#include "../src/substrate-methods.h"
#include "../lib/munit/munit.h"
#include "../src/substrate-address.h"
#include "../src/kusama.h"
// creates a `SubstrateTransaction` without checking if values are acceptable
// returns 1 if the creation fails
int mock_transaction(SubstrateTransaction* transaction, uint8_t* amount, size_t amount_len,
uint8_t* nonce, size_t nonce_len, uint8_t* tip, size_t tip_len, enum Chain chain, uint8_t version, uint8_t* recipient) {
int res_amount, res_nonce, res_tip;
res_amount = encode_scale(&(transaction->amount), amount, amount_len, type_compact);
res_nonce = encode_scale(&(transaction->nonce), nonce, nonce_len, type_compact);
res_tip = encode_scale(&(transaction->tip), tip, tip_len, type_compact);
if ( (res_amount != 0) || (res_nonce != 0) || (res_tip != 0))
return 1;
transaction->era.type = type_era;
transaction->era.elem.era.length =1;
transaction->era.elem.era.type = type_era;
transaction->era.elem.era.value[0] = 0x00;
transaction-> version = v4_signed;
SUBSTRATE_MEMCPY(transaction->recipient, recipient, ADDRESS_LEN);
return 0;
}
void print_bytes(uint8_t* in, size_t len) {
for (int i=0; i < len; i++) {
printf("%02x", in[i]);
}
printf("\n");
}
void mock_current_block(SubstrateBlock *current_block) {
uint8_t block_hash[SIZE_HASH_256] = {0xb0, 0xa8, 0xd4, 0x93, 0x28, 0x5c, 0x2d, 0xf7, 0x32, 0x90, 0xdf, 0xb7, 0xe6, 0x1f, 0x87, 0x0f, 0x17, 0xb4, 0x18, 0x01, 0x19, 0x7a, 0x14, 0x9c, 0xa9, 0x36, 0x54, 0x49, 0x9e, 0xa3, 0xda, 0xfe};
SUBSTRATE_MEMCPY(current_block->hash, block_hash, SIZE_HASH_256);
current_block->number = 0;
}
uint8_t * hexstring_to_array(const char *string, size_t *output_len) {
int s;
uint8_t *output = NULL;
if (string == NULL)
return NULL;
size_t len = strlen(string);
if((len % 2) != 0)
return NULL;
*output_len = len/2;
output = malloc(*output_len);
memset(output, 0, *output_len);
for (int i=0; i<len; i++) {
char c = string[i];
s = 0;
if(c >= '0' && c <= '9')
s = (c - '0');
else if (c >= 'A' && c <= 'F')
s = (10 + (c - 'A'));
else if (c >= 'a' && c <= 'f')
s = (10 + (c - 'a'));
else {
free(output);
return NULL;
}
output[(i/2)] += s << (((i + 1) % 2) * 4);
}
// success
return output;
}
static MunitResult encodes_era(const MunitParameter params[], void* data) {
uint8_t *expected_result;
uint8_t scale_len;
uint8_t *encoded_value;
ScaleElem era;
size_t len;
// immortal transaction
expected_result = hexstring_to_array("00", &len);
uint8_t v[1] = {0x00};
encode_scale(&era, v, 1, type_era);
scale_len = get_scale_length(&era);
encoded_value = malloc(scale_len*sizeof(uint8_t));
get_scale_value(&era, encoded_value, scale_len);
munit_assert_true(scale_len == 1);
munit_assert_memory_equal(scale_len, encoded_value, expected_result);
free((void*) expected_result);
free((void*) encoded_value);
// transaction of limited time
expected_result = hexstring_to_array("3c01", &len);
uint8_t v2[2] = {0x3c, 0x01};
encode_scale(&era, v2, 2, type_era);
scale_len = get_scale_length(&era);
encoded_value = malloc(scale_len*sizeof(uint8_t));
get_scale_value(&era, encoded_value, scale_len);
munit_assert_true(scale_len == 2);
munit_assert_memory_equal(scale_len, encoded_value, expected_result);
free((void*) expected_result);
free((void*) encoded_value);
return MUNIT_OK;
}
static MunitResult decodes_scale(const MunitParameter params[], void* data) {
uint8_t* raw_scale;
size_t raw_scale_len, decoded_value_len, consumed;
uint8_t decoded_value[SCALE_COMPACT_MAX];
int res;
size_t len;
// case 0b00u
raw_scale = hexstring_to_array("00", &len);
raw_scale_len = 1;
res = decode_stream(raw_scale, decoded_value, raw_scale_len, &decoded_value_len, &consumed, type_compact);
munit_assert_false(res);
free((void*) raw_scale);
memset(&decoded_value, 0, SCALE_COMPACT_MAX);
// case 0b01u, number 64
raw_scale = hexstring_to_array("0101", &len);
raw_scale_len = 2;
res = decode_stream(raw_scale, decoded_value, raw_scale_len, &decoded_value_len, &consumed, type_compact);
munit_assert_false(res);
free((void*) raw_scale);
memset(&decoded_value, 0, SCALE_COMPACT_MAX);
// case 0b01u, number (base 16) = 8000;
raw_scale = hexstring_to_array("02000200", &len);
raw_scale_len = 4;
res = decode_stream(raw_scale, decoded_value, raw_scale_len, &decoded_value_len, &consumed, type_compact);
munit_assert_false(res);
munit_assert_true(decoded_value_len == 4);
free((void*) raw_scale);
memset(&decoded_value, 0, SCALE_COMPACT_MAX);
// case 0b10u
// number 123456789, hex(number) = 0x75bcd15
char v3[4] = { 0x56, 0x34, 0x6f, 0x1d};
raw_scale = (uint8_t*) v3;
raw_scale_len = 4;
res = decode_stream(raw_scale, decoded_value, raw_scale_len, &decoded_value_len, &consumed, type_compact);
munit_assert_true(decoded_value_len == 4);
munit_assert_false(res);
memset(&decoded_value, 0, SCALE_COMPACT_MAX);
// case 0b11u
// number 1234567899, hex(number) = 0x499602db
char v[5] = { 0x03, 0xdb, 0x02, 0x96, 0x49};
raw_scale = (uint8_t*) v;
raw_scale_len = 5;
res = decode_stream(raw_scale, decoded_value, raw_scale_len, &decoded_value_len, &consumed, type_compact);
munit_assert_true(decoded_value_len == 4);
munit_assert_false(res);
memset(&decoded_value, 0, SCALE_COMPACT_MAX);
// case 0b11u;
// number: 123456789123456789123456789123456789, hex(number): 0x17c6e3c032f89045ad746684045f15
char v2[16] = { 0x2f, 0x15, 0x5f, 0x04, 0x84, 0x66, 0x74, 0xad, 0x45, 0x90, 0xf8, 0x32, 0xc0, 0xe3, 0xc6, 0x17};
raw_scale = (uint8_t*) v2;
raw_scale_len = 16;
res = decode_stream(raw_scale, decoded_value, raw_scale_len, &decoded_value_len, &consumed, type_compact);
munit_assert_true(decoded_value_len == 15);
munit_assert_false(res);
return MUNIT_OK;
}
// decode a transaction
// 290284fe6549bbf4dde68661a07690ffb908e9a586e3867a6a0c4066d451d3387d168300c168ac0902387ec587c054657bcfb6bcc1727e5380087bbe0f8b3f38e3dc80eea98366f8bd64abbfa25338f148fed4250645e11ad45ff38331e4958a0a2e5f060000000400fe6549bbf4dde68661a07690ffb908e9a586e3867a6a0c4066d451d3387d168300
static MunitResult decodes_raw_extrinsic(const MunitParameter params[], void* data) {
int res;
uint8_t* raw_extrinsic = NULL;
size_t raw_extrinsic_len;
SubstrateExtrinsicObject decodedExtrinsic;
// init a runtime
SubstrateRuntime kusamaRuntime;
init_kusama_runtime(&kusamaRuntime);
// must fail because blockNumber == 0
raw_extrinsic = hexstring_to_array("290284fe6549bbf4dde68661a07690ffb908e9a586e3867a6a0c4066d451d3387d1683", &raw_extrinsic_len);
res = decode_raw_extrinsic(raw_extrinsic, 1234, &kusamaRuntime, 0, &decodedExtrinsic);
munit_assert_true(res);
const unsigned long blockNumber = 1375087; // runtime 1050
// must fail getting `version`
raw_extrinsic = hexstring_to_array("2902", &raw_extrinsic_len);
res = decode_raw_extrinsic(raw_extrinsic, raw_extrinsic_len, &kusamaRuntime, blockNumber, &decodedExtrinsic);
munit_assert_true(res);
// must fail getting `version`
raw_extrinsic = hexstring_to_array("290284", &raw_extrinsic_len);
res = decode_raw_extrinsic(raw_extrinsic, raw_extrinsic_len, &kusamaRuntime, blockNumber, &decodedExtrinsic);
munit_assert_true(res);
// must fail getting `signature_type`
raw_extrinsic = hexstring_to_array("290284fe6549bbf4dde68661a07690ffb908e9a586e3867a6a0c4066d451d3387d1683", &raw_extrinsic_len);
res = decode_raw_extrinsic(raw_extrinsic, raw_extrinsic_len, &kusamaRuntime, blockNumber, &decodedExtrinsic);
munit_assert_true(res);
// must fail getting `era`
raw_extrinsic = hexstring_to_array("290284fe6549bbf4dde68661a07690ffb908e9a586e3867a6a0c4066d451d3387d168300c168ac0902387ec587c054657bcfb6bcc1727e5380087bbe0f8b3f38e3dc80eea98366f8bd64abbfa25338f148fed4250645e11ad45ff38331e4958a0a2e5f06", &raw_extrinsic_len);
res = decode_raw_extrinsic(raw_extrinsic, raw_extrinsic_len, &kusamaRuntime, blockNumber, &decodedExtrinsic);
munit_assert_true(res);
// must fail getting `era`
raw_extrinsic = hexstring_to_array("290284fe6549bbf4dde68661a07690ffb908e9a586e3867a6a0c4066d451d3387d168300c168ac0902387ec587c054657bcfb6bcc1727e5380087bbe0f8b3f38e3dc80eea98366f8bd64abbfa25338f148fed4250645e11ad45ff38331e4958a0a2e5f06", &raw_extrinsic_len);
res = decode_raw_extrinsic(raw_extrinsic, raw_extrinsic_len, &kusamaRuntime, blockNumber, &decodedExtrinsic);
munit_assert_true(res);
// must fail getting `tip`
raw_extrinsic = hexstring_to_array("290284fe6549bbf4dde68661a07690ffb908e9a586e3867a6a0c4066d451d3387d168300c168ac0902387ec587c054657bcfb6bcc1727e5380087bbe0f8b3f38e3dc80eea98366f8bd64abbfa25338f148fed4250645e11ad45ff38331e4958a0a2e5f060000", &raw_extrinsic_len);
res = decode_raw_extrinsic(raw_extrinsic, raw_extrinsic_len, &kusamaRuntime, blockNumber, &decodedExtrinsic);
munit_assert_true(res);
// must fail getting `module`
raw_extrinsic = hexstring_to_array("290284fe6549bbf4dde68661a07690ffb908e9a586e3867a6a0c4066d451d3387d168300c168ac0902387ec587c054657bcfb6bcc1727e5380087bbe0f8b3f38e3dc80eea98366f8bd64abbfa25338f148fed4250645e11ad45ff38331e4958a0a2e5f06000000", &raw_extrinsic_len);
res = decode_raw_extrinsic(raw_extrinsic, raw_extrinsic_len, &kusamaRuntime, blockNumber, &decodedExtrinsic);
munit_assert_true(res);
// must fail getting `call`
raw_extrinsic = hexstring_to_array("290284fe6549bbf4dde68661a07690ffb908e9a586e3867a6a0c4066d451d3387d168300c168ac0902387ec587c054657bcfb6bcc1727e5380087bbe0f8b3f38e3dc80eea98366f8bd64abbfa25338f148fed4250645e11ad45ff38331e4958a0a2e5f060000000400fe6549bbf4dde68661a07690ffb908e9a586e3867a6a0c4066d451d3387d1683", &raw_extrinsic_len);
res = decode_raw_extrinsic(raw_extrinsic, raw_extrinsic_len, &kusamaRuntime, blockNumber, &decodedExtrinsic);
munit_assert_true(res);
// must succeed
raw_extrinsic = hexstring_to_array("290284fe6549bbf4dde68661a07690ffb908e9a586e3867a6a0c4066d451d3387d168300c168ac0902387ec587c054657bcfb6bcc1727e5380087bbe0f8b3f38e3dc80eea98366f8bd64abbfa25338f148fed4250645e11ad45ff38331e4958a0a2e5f060000000400fe6549bbf4dde68661a07690ffb908e9a586e3867a6a0c4066d451d3387d168300", &raw_extrinsic_len);
res = decode_raw_extrinsic(raw_extrinsic, raw_extrinsic_len, &kusamaRuntime, blockNumber, &decodedExtrinsic);
munit_assert_false(res);
return MUNIT_OK;
}
static MunitResult address_is_correct(const MunitParameter params[], void* data) {
size_t address_len;
generate_Alices_test_keypair();
uint8_t* address = NULL;
ss58_encode(&address, &address_len, Alice.public_key, generic);
munit_assert_memory_equal(address_len, address, "5FA9nQDVg267DEd8m1ZypXLBnvN7SFxYwV7ndqSYGiN9TTpu");
free((void*) address);
return MUNIT_OK;
}
static MunitResult generates_polkadot_address(const MunitParameter params[], void* data) {
uint8_t* address = NULL;
size_t address_len;
generate_Alices_test_keypair();
uint8_t expected[] = "146SvjUZXoMaemdeiecyxgALeYMm8ZWh1yrGo8RtpoPfe7WL";
ss58_encode(&address, &address_len, Alice.public_key, polkadot);
munit_assert_memory_equal(address_len, address, expected);
free((void*) address);
return MUNIT_OK;
}
static MunitResult fails_for_unknown_chain(const MunitParameter params[], void* data) {
size_t address_len;
uint8_t *address = NULL;
generate_Alices_test_keypair();
ss58_encode(&address, &address_len, Alice.public_key, -1);
munit_assert_null((char*) address);
return MUNIT_OK;
}
static MunitResult constructs_balance_transfer_function(const MunitParameter params[], void* data) {
size_t len;
generate_Alices_test_keypair();
const uint8_t* expected_result = hexstring_to_array("040088dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee00", &len);
SubstrateTransaction transaction_data;
size_t call_len;
uint8_t* result;
// init a runtime
SubstrateRuntime kusamaRuntime;
init_kusama_runtime(&kusamaRuntime);
// construct transaction
uint8_t amount[1] = {0x00};
uint8_t nonce[1] = {0x01};
uint8_t tip[1] = {0x00};
if (mock_transaction(&transaction_data, amount, 1, nonce, 1, tip, 1, kusama, 4, Alice.public_key) != 0)
return MUNIT_ERROR;
// construct context
SubstrateBlock current_block;
mock_current_block(¤t_block);
result = construct_BalanceTransferFunction(&transaction_data, &kusamaRuntime, &call_len);
munit_assert_memory_equal(call_len, result, expected_result);
free((void*) expected_result);
return MUNIT_OK;
}
static MunitResult constructs_transaction_payload(const MunitParameter params[], void* data) {
size_t len;
generate_Alices_test_keypair();
const uint8_t* expected_result = hexstring_to_array("040088dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee000004001f040000b0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafeb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe", &len);
SubstrateTransaction transaction_data;
size_t payload_len;
// init a runtime
SubstrateRuntime kusamaRuntime;
init_kusama_runtime(&kusamaRuntime);
uint8_t* result;
// assume call is computed
uint8_t* call = hexstring_to_array("040088dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee00", &len);
// construct transaction
uint8_t amount[1] = {0x00};
uint8_t nonce[1] = {0x01};
uint8_t tip[1] = {0x00};
mock_transaction(&transaction_data, amount, 1, nonce, 1, tip, 1, kusama, 4, Alice.public_key);
// construct context
SubstrateBlock current_block;
mock_current_block(¤t_block);
result = construct_TransactionPayload(&transaction_data, &kusamaRuntime, ¤t_block, call, len, &payload_len);
munit_assert_memory_equal(payload_len, result, expected_result);
free((void*) expected_result);
return MUNIT_OK;
}
static MunitResult constructs_transaction_info(const MunitParameter params[], void* data) {
size_t len;
generate_Alices_test_keypair();
const uint8_t* expected_result = hexstring_to_array("88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee0015999702d5a1580bf8e7961385e3e487cbc462d2e553d5df100bbc48b1b1f1d18f9c2cc66a220c68f8e6bdec7357aa4da917e6d70c8f799ac1329a85a7100509000400", &len);
size_t transaction_info_len;
uint8_t* result;
// construct transaction
uint8_t amount[1] = {0x00};
uint8_t nonce[1] = {0x01};
uint8_t tip[1] = {0x00};
SubstrateTransaction transaction_data;
mock_transaction(&transaction_data, amount, 1, nonce, 1, tip, 1, kusama, 4, Alice.public_key);
// construct context
SubstrateBlock current_block;
mock_current_block(¤t_block);
// assume signature is computed
uint8_t * signature = hexstring_to_array("15999702d5a1580bf8e7961385e3e487cbc462d2e553d5df100bbc48b1b1f1d18f9c2cc66a220c68f8e6bdec7357aa4da917e6d70c8f799ac1329a85a7100509", &len);
result = construct_TransactionInfo(&transaction_data, Alice.public_key, signature, &transaction_info_len);
munit_assert_memory_equal(transaction_info_len, result, expected_result);
free((void*) signature);
free((void*) expected_result);
return MUNIT_OK;
}
static MunitResult constructs_extrinsic(const MunitParameter params[], void* data) {
size_t len, transaction_info_len, call_len, extrinsic_len;
uint8_t* transaction_info = hexstring_to_array("88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee0015999702d5a1580bf8e7961385e3e487cbc462d2e553d5df100bbc48b1b1f1d18f9c2cc66a220c68f8e6bdec7357aa4da917e6d70c8f799ac1329a85a7100509000400", &transaction_info_len);
const uint8_t* expected_result = hexstring_to_array("8488dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee0015999702d5a1580bf8e7961385e3e487cbc462d2e553d5df100bbc48b1b1f1d18f9c2cc66a220c68f8e6bdec7357aa4da917e6d70c8f799ac1329a85a71005090004000400e5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a00", &len);
uint8_t* result;
// assume call is computed
uint8_t* call = hexstring_to_array("0400e5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a00", &call_len);
extrinsic_len = get_extrinsic_length(transaction_info_len, call_len);
result = malloc(extrinsic_len);
if (result)
costruct_Extrinsic(result, transaction_info, transaction_info_len, call, call_len);
munit_assert_true( extrinsic_len == (1 +transaction_info_len + call_len) );
munit_assert_memory_equal(transaction_info_len, result, expected_result);
free((void*) transaction_info);
free((void*) call);
free((void*) expected_result);
return MUNIT_OK;
}
static MunitResult signs_transaction_v4(const MunitParameter params[], void* data) {
generate_Alices_test_keypair();
const uint8_t* expected_result;
SubstrateTransaction* transaction_data;
uint8_t* transaction;
size_t transaction_len, len;
SubstrateBlock current_block;
mock_current_block(¤t_block);
// init a runtime
SubstrateRuntime kusamaRuntime;
init_kusama_runtime(&kusamaRuntime);
// test amount = 0
expected_result = hexstring_to_array("21028488dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee00959ecca272c11cd3ea67cca328d558a322671a47d620080ab4f3329464d5d72081b58cae2f94b3b7b5dec9b69e8f012603fad3ffae952471964e8c8569044003000400040088dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee00", &len);
transaction_data = malloc(sizeof(SubstrateTransaction));
uint8_t amount[1] = {0x00};
uint8_t nonce[1] = {0x01};
uint8_t tip[1] = {0x00};
mock_transaction(transaction_data, amount, 1, nonce, 1, tip, 1, kusama, 4, Alice.public_key);
sign_transfer_with_secret(&transaction, &transaction_len, Alice.private_key, transaction_data, &kusamaRuntime, ¤t_block);
munit_assert_memory_equal(transaction_len, transaction, expected_result);
SUBSTRATE_FREE(expected_result);
SUBSTRATE_FREE(transaction);
SUBSTRATE_FREE(transaction_data);
// test amount = 69 (0x45) (Compact will have size 2)
expected_result = hexstring_to_array("25028488dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee003e2e6e9b865739cea7e07410abb2b71e8cc0b2d0641d33d954cad9cfc4cf1470ae2b6811a26684e50292fa8bbe03aa3eb41240e7011fc44e92e0fb52577f2104001000040088dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee1501", &len);
transaction_data = malloc(sizeof(SubstrateTransaction));
uint8_t amount2[2] = {0x45};
uint8_t nonce2[1] = {0x04};
mock_transaction(transaction_data, amount2, 2, nonce2, 1, tip, 1, kusama, 4, Alice.public_key);
sign_transfer_with_secret(&transaction, &transaction_len, Alice.private_key, transaction_data, &kusamaRuntime, ¤t_block);
munit_assert_memory_equal(transaction_len, transaction, expected_result);
SUBSTRATE_FREE(expected_result);
SUBSTRATE_FREE(transaction);
SUBSTRATE_FREE(transaction_data);
// test amount = 36893488147419103232
expected_result = hexstring_to_array("45028488dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee004cbef33b14ea981ae497476dda53ea0edb05761eda4ee76b571d86df2b28ff98ff2554126d5fcbccc7806afb06b914ad7d2baccc40ed0d62bd03842fdf062906000000040088dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee17000000000000000002", &len);
transaction_data = malloc(sizeof(SubstrateTransaction));
uint8_t amount3[9] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02};
uint8_t nonce3[1] = {0x00};
mock_transaction(transaction_data, amount3, 9, nonce3, 1, tip, 1, kusama, 4, Alice.public_key);
sign_transfer_with_secret(&transaction, &transaction_len, Alice.private_key, transaction_data, &kusamaRuntime, ¤t_block);
munit_assert_memory_equal(transaction_len, transaction, expected_result);
SUBSTRATE_FREE(expected_result);
SUBSTRATE_FREE(transaction);
SUBSTRATE_FREE(transaction_data);
return MUNIT_OK;
}
static MunitResult encode_compacts(const MunitParameter params[], void* data) {
uint8_t* expected_result;
uint8_t number;
size_t len;
ScaleElem* scale_elem;
uint8_t* result = NULL;
uint8_t scale_len;
// easy one - just 1 byte
expected_result = hexstring_to_array("04", &len);
number = 0x01;
scale_elem = malloc(sizeof(ScaleElem));
encode_scale(scale_elem, &number, sizeof(uint8_t), type_compact);
scale_len = get_scale_length(scale_elem);
result = malloc(scale_len*sizeof(uint8_t));
get_scale_value(scale_elem, result, scale_len);
munit_assert_memory_equal(1, result, expected_result);
free((void*) expected_result);
free((void*) scale_elem);
free((void*) result);
// also easy
expected_result = hexstring_to_array("a8", &len);
number = 42;
scale_elem = malloc(sizeof(ScaleElem));
encode_scale(scale_elem, &number, sizeof(uint8_t), type_compact);
result = malloc(scale_len*sizeof(uint8_t));
get_scale_value(scale_elem, result, scale_len);
munit_assert_memory_equal(1, result, expected_result);
free((void*) expected_result);
free((void*) scale_elem);
free((void*) result);
// compact type 2
expected_result = hexstring_to_array("0101", &len);
number = 64;
scale_elem = malloc(sizeof(ScaleElem));
encode_scale(scale_elem, &number, sizeof(uint8_t), type_compact);
scale_len = get_scale_length(scale_elem);
result = malloc(scale_len*sizeof(uint8_t));
get_scale_value(scale_elem, result, scale_len);
munit_assert_memory_equal(2, result, expected_result);
free((void*) expected_result);
free((void*) scale_elem);
free((void*) result);
// compact type 3
expected_result = hexstring_to_array("02000200", &len);
uint8_t number_32768[4] = {0x00, 0x80, 0x00, 0x00};
scale_elem = malloc(sizeof(ScaleElem));
encode_scale(scale_elem, (uint8_t*) number_32768, 4, type_compact);
scale_len = get_scale_length(scale_elem);
result = malloc(scale_len*sizeof(uint8_t));
get_scale_value(scale_elem, result, scale_len);
munit_assert_memory_equal(len, result, expected_result);
free((void*) expected_result);
free((void*) scale_elem);
free((void*) result);
// now the hard part: BigInteger compact
expected_result = hexstring_to_array("071234567899", &len);
uint8_t input[5] = {0x12, 0x34, 0x56, 0x78, 0x99};
scale_elem = malloc(sizeof(ScaleElem));
encode_scale(scale_elem, input, 5, type_compact);
scale_len = get_scale_length(scale_elem);
result = malloc(scale_len*sizeof(uint8_t));
get_scale_value(scale_elem, result, scale_len);
munit_assert_memory_equal(6, result, expected_result);
free((void*) expected_result);
free((void*) scale_elem);
free((void*) result);
// test a corner case (just in case)
len = 1000;
scale_elem = malloc(sizeof(ScaleElem));
int res = encode_scale(scale_elem, input, len, type_compact);
munit_assert_true(res);
free((void*) scale_elem);
return MUNIT_OK;
}
static MunitResult encodes_vector_u8(const MunitParameter params[], void* data) {
uint8_t* expected_result;
uint8_t* input;
uint8_t* result;
size_t len;
expected_result = hexstring_to_array("290284ff34602b88f60513f1c805d87ef52896934baf6a662bc37414dbdbf69356b1a69100236f9b56555b860ffa1c5271e42abca515d1a6c6b6174c368a3d114cf12e086963d4136373a5f0db211c9634a8d7e851f0b09d5b547eb5c3f87c153838e448030000000600ff34602b88f60513f1c805d87ef52896934baf6a662bc37414dbdbf69356b1a69100", &len);
input = hexstring_to_array("84ff34602b88f60513f1c805d87ef52896934baf6a662bc37414dbdbf69356b1a69100236f9b56555b860ffa1c5271e42abca515d1a6c6b6174c368a3d114cf12e086963d4136373a5f0db211c9634a8d7e851f0b09d5b547eb5c3f87c153838e448030000000600ff34602b88f60513f1c805d87ef52896934baf6a662bc37414dbdbf69356b1a69100", &len);
len = 138;
uint8_t s = get_vector_u8_size(len);
result = malloc(s);
as_scale_vector_u8(result, s, input, len);
munit_assert_memory_equal(s, result, expected_result);
free(result);
return MUNIT_OK;
}
static MunitTest test_suite_tests[] = {
{
"[scale] encodes Era",
encodes_era
},
{
"[scale] decodes Compact",
decodes_scale
},
{
"[scale] encodes Compact",
encode_compacts
},
{
"[scale] encodes Vector u8",
encodes_vector_u8
},
{
"[address] generates generic",
address_is_correct,
},
{
"[address] generates polkadot",
generates_polkadot_address
},
{
"[address] handles unknown chain",
fails_for_unknown_chain
},
{
"[transaction] constructs BalanceTransferFunction correctly",
constructs_balance_transfer_function
},
{
"[transaction] constructs TransactionPayload correctly",
constructs_transaction_payload
},
{
"[transaction] constructs TransactionInfo correctly",
constructs_transaction_info
},
{
"[transaction] constructs Extrinsic correctly",
constructs_extrinsic
},
{
"[transaction] transaction (v4) is correct",
signs_transaction_v4
},
{
"[extrinsic] decodes from raw",
decodes_raw_extrinsic
}
};
static const MunitSuite test_suite = {
(char*) "",
test_suite_tests,
NULL,
1,
MUNIT_SUITE_OPTION_NONE
};
int main(int argc, char* argv[MUNIT_ARRAY_PARAM(argc + 1)]) {
return munit_suite_main(&test_suite, (void*) "µnit", argc, argv);
}
| 39.189441 | 343 | 0.778112 | [
"vector"
] |
2928a8f16d76ce62a99e3ad22f86850f76dbcb4b | 5,893 | c | C | src/libEmu/regression.c | MADAI/MADAIEmulator | 7d926ad04a791c7694defd88db41c13f7ee4e6aa | [
"MIT"
] | 2 | 2015-04-02T17:37:42.000Z | 2017-06-02T00:34:49.000Z | src/libEmu/regression.c | MADAI/MADAIEmulator | 7d926ad04a791c7694defd88db41c13f7ee4e6aa | [
"MIT"
] | null | null | null | src/libEmu/regression.c | MADAI/MADAIEmulator | 7d926ad04a791c7694defd88db41c13f7ee4e6aa | [
"MIT"
] | null | null | null | #include "math.h"
#include "regression.h"
/* { */
/* makeHVector_linear(h_vector, x_location, nparams); */
/* } */
void makeHVector_trivial(gsl_vector *h_vector, gsl_vector *x_location, int nparams){
(void) x_location;
(void) nparams;
gsl_vector_set_zero(h_vector);
gsl_vector_set(h_vector, 0, 1);
}
void makeHVector_linear( gsl_vector *h_vector, gsl_vector *x_location, int nparams){
int i;
double temp_val;
gsl_vector_set(h_vector, 0, 1); // the first element is always a constant
for(i = 0; i < nparams; i++) {
temp_val = gsl_vector_get(x_location, i);
gsl_vector_set(h_vector, i+1, temp_val);
}
}
/**
* an example of a basis of more complicated regression functions,
* fiddling around with this might be useful if you *really* need prediction and
* you have some idea of what the regression spectrum should be like, i.e up to a certain
* order in polys etc,
*
* sticking with the linear model is probably fine
*/
void makeHVector_quadratic( gsl_vector *h_vector, gsl_vector *x_location, int nparams){
int i;
double temp_val;
gsl_vector_set(h_vector, 0, 1); // the first element is always a constant
for(i = 0; i < nparams; i++) {
temp_val = gsl_vector_get(x_location, i);
gsl_vector_set(h_vector, i+1, temp_val);
}
for(i = 0; i < nparams; i++){
temp_val = gsl_vector_get(x_location, i);
temp_val = temp_val * temp_val;
gsl_vector_set(h_vector, nparams+i+1, temp_val);
}
}
void makeHVector_cubic( gsl_vector *h_vector, gsl_vector *x_location, int nparams){
int i;
double temp_val;
gsl_vector_set(h_vector, 0, 1); // the first element is always a constant
for(i = 0; i < nparams; i++) {
temp_val = gsl_vector_get(x_location, i);
gsl_vector_set(h_vector, i+1, temp_val);
}
for(i = 0; i < nparams; i++){
temp_val = gsl_vector_get(x_location, i);
temp_val = temp_val * temp_val;
gsl_vector_set(h_vector, nparams+i+1, temp_val);
}
for(i = 0; i < nparams; i++){
temp_val = gsl_vector_get(x_location, i);
temp_val = temp_val*temp_val * temp_val;
gsl_vector_set(h_vector, 2*nparams+i+1, temp_val);
}
}
/**
* create the h_matrix, which is the a matrix of h_vectors evaluated at each
* design point from xmodel
* where h_matrix is defined to be n_model_points x nregression_fns
*
* not threadsafe: uses the global fnptr makeHVector(...)
*/
void makeHMatrix(gsl_matrix *h_matrix, gsl_matrix *xmodel, int nmodel_points, int nparams, int nregression_fns){
int i;
gsl_vector *h_vec = gsl_vector_alloc(nregression_fns);
gsl_vector_view xmodel_row_i;
for(i = 0; i < nmodel_points; i++){
xmodel_row_i = gsl_matrix_row(xmodel, i);
makeHVector(h_vec, &xmodel_row_i.vector, nparams);
gsl_matrix_set_row(h_matrix, i, h_vec);
}
gsl_vector_free(h_vec);
}
/**
* create the h_matrix, which is the a matrix of h_vectors evaluated at each
* design point from xmodel
* where h_matrix is defined to be n_model_points x nregression_fns
*
* threadsafe
*
* final arg is a ptr to a fn which will init the h_vector correctly
*/
void makeHMatrix_fnptr(gsl_matrix *h_matrix, gsl_matrix *xmodel, int nmodel_points, int nparams, int nregression_fns,
void (*makeHVector_ptr)(gsl_vector *h_vector, gsl_vector *x_location, int nparams)){
int i;
gsl_vector *h_vec = gsl_vector_alloc(nregression_fns);
gsl_vector_view xmodel_row_i;
for(i = 0; i < nmodel_points; i++){
xmodel_row_i = gsl_matrix_row(xmodel, i);
makeHVector_ptr(h_vec, &xmodel_row_i.vector, nparams);
gsl_matrix_set_row(h_matrix, i, h_vec);
}
gsl_vector_free(h_vec);
}
/**
* estimate the values of the coefficients beta for a given training vector and inverse covariance matrix
*
* beta = (h_matrix^{T}.cinverse.hmatrix)^{-1} . (h_matrix^{T}.cinverse.yvector)
*/
void estimateBeta(gsl_vector *beta_vector, gsl_matrix *h_matrix, gsl_matrix* cinverse, gsl_vector *trainingvector, int nmodel_points, int nregression_fns){
int i, j, cholesky_test;
gsl_error_handler_t *temp_handler;
gsl_matrix *htrans_cinverse = gsl_matrix_alloc(nregression_fns, nmodel_points);
gsl_matrix *temp_denominator = gsl_matrix_alloc(nregression_fns, nregression_fns);
gsl_vector *temp_numerator = gsl_vector_alloc(nregression_fns);
// first calculate h_matrix^{T}.cinverse (since we'll use this twice)
gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, h_matrix, cinverse, 0.0, htrans_cinverse);
// now calculate htrans_cinverse.hmatrix
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, htrans_cinverse, h_matrix, 0.0 ,temp_denominator);
temp_handler = gsl_set_error_handler_off();
cholesky_test = gsl_linalg_cholesky_decomp(temp_denominator);
if(cholesky_test == GSL_EDOM){
FILE *fptr;
fprintf(stderr, "# err: estimateBeta\n");
fprintf(stderr, "# trying to cholesky a non postive def matrix, sorry...\n");
fprintf(stderr, "# matrix dumped to chol-err.dat\n");
fptr = fopen("chol-err.dat", "w");
for(i = 0; i < nregression_fns; ++i){
for(j = 0; j < nregression_fns; ++j){
fprintf(fptr, "%lf ", gsl_matrix_get(temp_denominator, i, j));
}
fprintf(fptr, "\n");
}
fclose(fptr);
fptr = fopen("chol-err-cinverse.dat", "w");
for(i = 0; i < nmodel_points; ++i){
for(j = 0; j < nmodel_points; ++j){
fprintf(fptr, "%lf ", gsl_matrix_get(cinverse, i, j));
}
fprintf(fptr, "\n");
}
fclose(fptr);
exit(1);
}
gsl_set_error_handler(temp_handler);
gsl_linalg_cholesky_invert(temp_denominator); // temp_denominator = (h_matrix^{T}.cinverse.hmatrix)^{-1}
// temp_numerator = htrans_cinverse.trainingvector
gsl_blas_dgemv(CblasNoTrans, 1.0, htrans_cinverse, trainingvector,0.0, temp_numerator);
// and finally we set the value of the beta vector
// beta = temp_denominator.temp_numerator
gsl_blas_dgemv(CblasNoTrans, 1.0, temp_denominator, temp_numerator, 0.0, beta_vector);
gsl_vector_free(temp_numerator);
gsl_matrix_free(temp_denominator);
gsl_matrix_free(htrans_cinverse);
}
| 33.293785 | 155 | 0.726795 | [
"vector",
"model"
] |
29493d5a06af3655a07e3ef455963e54b1e50fb9 | 1,025 | h | C | facerecognizer.h | siavash9000/CamObserver | fddb28f44e2506adfa3938d734491f07c5449a30 | [
"MIT"
] | 1 | 2016-01-14T18:12:39.000Z | 2016-01-14T18:12:39.000Z | facerecognizer.h | siavash9000/CamObserver | fddb28f44e2506adfa3938d734491f07c5449a30 | [
"MIT"
] | null | null | null | facerecognizer.h | siavash9000/CamObserver | fddb28f44e2506adfa3938d734491f07c5449a30 | [
"MIT"
] | null | null | null | #ifndef FACERECOGNIZER_H
#define FACERECOGNIZER_H
#include "webcamwrapper.h"
#include "opencv2/core/core.hpp"
#include "opencv2/contrib/contrib.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include <opencv/cv.h>
#include <QObject>
#include <QDebug>
#include <QTime>
#include "opencv2/core/core.hpp"
#include "opencv2/contrib/contrib.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
using namespace std;
using namespace cv;
struct prediction {
int label;
double confidence;
};
namespace camobserver{
class FaceRecognizer
{
public:
FaceRecognizer(WebCamWrapper& cam);
~FaceRecognizer();
void trainFace(cv::Rect_<int> face);
vector<prediction> predictFromWebcam(vector<cv::Rect_<int> > faces);
vector<Mat> m_images;
vector<int> m_labels;
Ptr<cv::FaceRecognizer> model;
WebCamWrapper& m_webCamWrapper;
};
}
#endif // FACERECOGNIZER_H
| 22.282609 | 72 | 0.750244 | [
"vector",
"model"
] |
ad2f1b42574acc3f79725dd0512f8db0de7c812a | 6,156 | h | C | src/obproxy/iocore/eventsystem/ob_action.h | wangzelin19961202/obproxy | 61d08536c074eec98e0e64775600834348de2cb0 | [
"Apache-2.0"
] | 1 | 2021-06-01T01:59:48.000Z | 2021-06-01T01:59:48.000Z | src/obproxy/iocore/eventsystem/ob_action.h | wangzelin19961202/obproxy | 61d08536c074eec98e0e64775600834348de2cb0 | [
"Apache-2.0"
] | null | null | null | src/obproxy/iocore/eventsystem/ob_action.h | wangzelin19961202/obproxy | 61d08536c074eec98e0e64775600834348de2cb0 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (c) 2021 OceanBase
* OceanBase Database Proxy(ODP) is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#ifndef OBPROXY_ACTION_H
#define OBPROXY_ACTION_H
#include "iocore/eventsystem/ob_continuation.h"
namespace oceanbase
{
namespace obproxy
{
namespace event
{
/**
* Represents an operation initiated on a ObProcessor.
*
* The ObAction class is an abstract representation of an operation
* being executed by some ObProcessor. A reference to an ObAction object
* allows you to cancel an ongoing asynchronous operation before it
* completes. This means that the ObContinuation specified for the
* operation will not be called back.
*
* Actions or classes derived from ObAction are the typical return
* type of methods exposed by Processors in the ObEvent System and
* throughout the IO Core libraries.
*
* The canceller of an action must be the state machine that will
* be called back by the task and that state machine's lock must be
* held while calling cancel.
*
* ObProcessor implementers:
*
* You must ensure that no events are sent to the state machine after
* the operation has been cancelled appropriately.
*
* Returning an ObAction:
*
* ObProcessor functions that are asynchronous must return actions to
* allow the calling state machine to cancel the task before completion.
* Because some processor functions are reentrant, they can call
* back the state machine before the returning from the call that
* creates the actions. To handle this case, special values are
* returned in place of an action to indicate to the state machine
* that the action is already completed.
*
* - @b (ret = OB_SUCCESS && NULL == action) The processor has completed
* the task and called the state machine back inline.
* - @b (ret = OB_SUCCESS && NULL != action) asynchronous task.
* - @b (ret != OB_SUCCESS) failed.
*
* To make matters more complicated, it's possible if the result is
* (ret = OB_SUCCESS && NULL == action)that state machine deallocated itself on the
* reentrant callback. Thus, state machine implementers MUST either
* use a scheme to never deallocate their machines on reentrant
* callbacks OR immediately check the returned action when creating
* an asynchronous task and if it is (ret = OB_SUCCESS && NULL == action) neither read
* nor write any state variables. With either method, it's imperative
* that the returned action always be checked for special values and
* the value handled accordingly.
*
* Allocation policy:
*
* Actions are allocated by the ObProcessor performing the actions.
* It is the processor's responsibility to handle deallocation once
* the action is complete or cancelled. A state machine MUST NOT
* access an action once the operation that returned the ObAction has
* completed or it has cancelled the ObAction.
*/
class ObAction
{
public:
/**
* Constructor of the ObAction object. ObProcessor implementers are
* responsible for associating this action with the proper
* ObContinuation.
*/
ObAction() : continuation_(NULL), mutex_(NULL), cancelled_(false) { }
virtual ~ObAction() { }
/**
* Cancels the asynchronous operation represented by this action.<p>
* This method is called by state machines willing to cancel an
* ongoing asynchronous operation. Classes derived from ObAction may
* perform additional steps before flagging this action as cancelled.
* There are certain rules that must be followed in order to cancel
* an action (see the Remarks section).
*
* @param c ObContinuation associated with this ObAction.
*/
virtual int cancel(const ObContinuation *cont = NULL)
{
int ret = common::OB_SUCCESS;
if (OB_UNLIKELY(NULL != cont) && OB_UNLIKELY(cont != continuation_)) {
ret = common::OB_INVALID_ARGUMENT;
PROXY_EVENT_LOG(WARN, "invalid argument, it should not happened", K(cont), K_(continuation), K(this), K(ret));
} else if (OB_UNLIKELY(cancelled_)) {
ret = common::OB_ERR_UNEXPECTED;
PROXY_EVENT_LOG(WARN, "it has already be cancelled, it should not happened", K_(cancelled), K(this), K(ret));
} else {
cancelled_ = true;
}
return ret;
}
virtual ObContinuation *set_continuation(ObContinuation *cont)
{
continuation_ = cont;
if (OB_LIKELY(NULL != cont)) {
mutex_ = cont->mutex_;
} else {
mutex_ = NULL;
}
return cont;
}
int copy(ObAction &action)
{
int ret = common::OB_SUCCESS;
continuation_ = action.continuation_;
mutex_ = action.mutex_;
cancelled_ = action.cancelled_;
return ret;
}
public:
/**
* Continuation that initiated this action.
*
* The reference to the initiating continuation is only used to
* verify that the action is being cancelled by the correct
* continuation. This field should not be accessed or modified
* directly by the state machine.
*/
ObContinuation *continuation_;
/**
* Reference to the ObContinuation's lock.
*
* Keeps a reference to the ObContinuation's lock to preserve the
* access to the cancelled field valid even when the state machine
* has been deallocated. This field should not be accessed or
* modified directly by the state machine.
*/
common::ObPtr<ObProxyMutex> mutex_;
/**
* Internal flag used to indicate whether the action has been
* cancelled.
*
* This flag is set after a call to cancel or cancel_action and
* it should not be accessed or modified directly by the state
* machine.
*/
volatile bool cancelled_;
private:
DISALLOW_COPY_AND_ASSIGN(ObAction);
};
} // end of namespace event
} // end of namespace obproxy
} // end of namespace oceanbase
#endif // OBPROXY_ACTION_H
| 34.779661 | 116 | 0.723034 | [
"object"
] |
ad2ffe382f1ab923f8f268d33fa4b74f77cd0ac8 | 3,564 | h | C | test/e2e/test_master/ObjectArxHeaders/AcEdSteeringWheel.h | BlueCannonBall/cppparser | 9ae5f0c21268be6696532cf5b90c0384d6eb4940 | [
"MIT"
] | null | null | null | test/e2e/test_master/ObjectArxHeaders/AcEdSteeringWheel.h | BlueCannonBall/cppparser | 9ae5f0c21268be6696532cf5b90c0384d6eb4940 | [
"MIT"
] | null | null | null | test/e2e/test_master/ObjectArxHeaders/AcEdSteeringWheel.h | BlueCannonBall/cppparser | 9ae5f0c21268be6696532cf5b90c0384d6eb4940 | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
//
// Copyright 2018 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
//
//////////////////////////////////////////////////////////////////////////////
//
// Name: AcEdSteeringWheel.h
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include "acgs.h"
#include "dbNavSettings.h"
class AcEdSteeringWheelReactor;
class AcEdSteeringWheel;
AcEdSteeringWheel* acedCreateSteeringWheel();
void acedDestroySteeringWheel(AcEdSteeringWheel* pWheel);
///////////////////////////////////////////////////////////////////////////////
//
// Interface AcEdSteeringWheel
//
class AcEdSteeringWheel
{
public:
enum WheelType {
kExterior = 0, ///< View Object Wheel.
kInterior, ///< Tour Buiding Wheel.
kFull, ///< Full Navigation Wheel.
k2D, ///< 2D Steering Wheel.
kMini, ///< Mini View Object Wheel.
kMiniOther, ///< Mini Tour Building Wheel.
kMiniEight, ///< Mini Full Navigation Wheel.
kTotalCount, ///< Total number of SteeringWheel types.
kWheelNone ///< Marks a disabled SteeringWheel.
};
enum MenuType {
// Steering Wheel Menus
kMenuNone = 0,
kMenuInterior,
kMenuExterior,
kMenuFull,
kMenu2D
};
// Message handlers
virtual void onKeyDown(UINT nChar, UINT nRepCount, UINT nFlags) = 0;
virtual void onKeyUp(UINT nChar, UINT nRepCount, UINT nFlags) = 0;
virtual bool onMouseWheel(UINT nFlags, short zDelta, POINT pt) = 0;
virtual void onMouseMove(UINT nFlags, POINT pt) = 0;
virtual void onLButtonUp(UINT nFlags, POINT pt) = 0;
virtual void onLButtonDown(UINT nFlags, POINT pt) = 0;
virtual void onRButtonUp(UINT nFlags, POINT pt) = 0;
virtual void onRButtonDown(UINT nFlags, POINT pt) = 0;
virtual void onMButtonDown(UINT nFlags, POINT pt) = 0;
virtual void onMButtonUp(UINT nFlags, POINT pt) = 0;
virtual void setHomeCamera(const AcDbHomeView& home) = 0;
virtual bool setLargeWheelOpacity(int nOpacity) = 0;
virtual int getLargeWheelOpacity() = 0;
virtual bool setMiniWheelOpacity(int nOpacity) = 0;
virtual int getMiniWheelOpacity() = 0;
virtual bool setWalkSpeed(double speed) = 0;
virtual double getWalkSpeed() = 0;
virtual bool setActiveWheel(WheelType type) = 0;
virtual WheelType getActiveWheel() = 0;
virtual void enableWheel(bool enable) = 0;
virtual bool isWheelEnabled() = 0;
virtual AcGsModel* getModel() = 0;
virtual AcGsView* getView() = 0;
virtual HWND getDeviceHandle() = 0;
virtual bool attachView(HWND hDevice, AcGsView* pGsView) = 0;
virtual void detachView() = 0;
virtual void addReactor(AcEdSteeringWheelReactor* pReactor) = 0;
virtual void removeReactor(AcEdSteeringWheelReactor* pReactor) = 0;
};
///////////////////////////////////////////////////////////////////////////////
//
// Interface AcEdSteeringWheelReactor
//
class AcEdSteeringWheelReactor
{
public:
virtual void modifyContextMenu(HMENU hMenu) = 0;
virtual void onSetCursor(HCURSOR hCursor) = 0;
virtual void onBeginOperation() = 0;
virtual void onEndOperation() = 0;
virtual void onBeginShot() = 0;
virtual void onEndShot() = 0;
virtual void onClose() = 0;
};
| 37.515789 | 82 | 0.617284 | [
"object"
] |
ad3115eb01258c5c4e60d9897ffbb90d194344c2 | 15,079 | h | C | include/Aspose.Page.Cpp/xps/src_xps/Presentation/Image/ImageDevice_.h | kashifiqb/Aspose.Page-for-C | ac121edcf382d2543261f797d1dac108936ca69f | [
"MIT"
] | 3 | 2020-06-19T20:30:11.000Z | 2021-01-15T09:07:42.000Z | include/Aspose.Page.Cpp/xps/src_xps/Presentation/Image/ImageDevice_.h | kashifiqb/Aspose.Page-for-C | ac121edcf382d2543261f797d1dac108936ca69f | [
"MIT"
] | null | null | null | include/Aspose.Page.Cpp/xps/src_xps/Presentation/Image/ImageDevice_.h | kashifiqb/Aspose.Page-for-C | ac121edcf382d2543261f797d1dac108936ca69f | [
"MIT"
] | 1 | 2019-12-26T12:53:01.000Z | 2019-12-26T12:53:01.000Z | #pragma once
#include <system/collections/list.h>
#include "Aspose.Page.Cpp/IMultiPartitionDevice.h"
#include "Aspose.Page.Cpp/Device.h"
namespace Aspose { namespace Page { namespace Xps { namespace Presentation { namespace Aps { class ApsDevice; } } } } }
namespace Aspose { namespace Page { class SaveOptions; } }
namespace Aspose { namespace Page { class ITrFont; } }
namespace Aspose { namespace Page { class IMultiPageDevice; } }
namespace Aspose { namespace Rendering { class ApsGlyphsIndices; } }
namespace Aspose { namespace Rendering { class ApsPage; } }
namespace Aspose { namespace Page { namespace Xps { namespace Presentation { namespace Image { class ImageSaveOptions; } } } } }
namespace Aspose {
namespace Page {
namespace Xps {
namespace Presentation {
namespace Image {
/// <summary>
/// The <b>Aspose.Page.Xps.Presentation.Image</b> namespace provides classes for rendering XPS
/// document to an image.
/// </summary>
class NamespaceDoc : public System::Object
{
typedef NamespaceDoc ThisType;
typedef System::Object BaseType;
typedef ::System::BaseTypesInfo<BaseType> ThisTypeBaseTypesInfo;
RTTI_INFO_DECL();
};
/// <summary>
/// Class incapsulating image composing device.
/// </summary>
class ImageDevice : public Aspose::Page::Device, public Aspose::Page::IMultiPartitionDevice
{
typedef ImageDevice ThisType;
typedef Aspose::Page::Device BaseType;
typedef Aspose::Page::IMultiPartitionDevice BaseType1;
typedef ::System::BaseTypesInfo<BaseType, BaseType1> ThisTypeBaseTypesInfo;
ASPOSE_PAGE_SHARED_RTTI_INFO_DECL();
FRIEND_FUNCTION_System_MakeObject;
public:
/// <summary>
/// Initializes save options.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void set_SaveOptions(System::SharedPtr<Aspose::Page::SaveOptions> value);
/// <summary>
/// Gets/sets the device media size.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API System::Drawing::Size get_Size();
/// <summary>
/// Gets/sets the device media size.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void set_Size(System::Drawing::Size value);
/// <summary>
/// Gets/sets the background color.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API System::Drawing::Color get_Background();
/// <summary>
/// Gets/sets the background color.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void set_Background(System::Drawing::Color value);
/// <summary>
/// Gets/sets the opacity.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API float get_Opacity();
/// <summary>
/// Gets/sets the opacity.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void set_Opacity(float value);
/// <summary>
/// Gets/sets the stroke for drawing paths.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API System::SharedPtr<System::Drawing::Pen> get_Stroke();
/// <summary>
/// Gets/sets the stroke for drawing paths.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void set_Stroke(System::SharedPtr<System::Drawing::Pen> value);
/// <summary>
/// Gets/sets the brush for filling paths.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API System::SharedPtr<System::Drawing::Brush> get_Paint();
/// <summary>
/// Gets/sets the brush for filling paths.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void set_Paint(System::SharedPtr<System::Drawing::Brush> value);
/// <summary>
/// Gets/sets the brush for opacity mask. The mask applies over Paint or Strike.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API System::SharedPtr<System::Drawing::Brush> get_OpacityMask();
/// <summary>
/// Gets/sets the brush for opacity mask. The mask applies over Paint or Strike.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void set_OpacityMask(System::SharedPtr<System::Drawing::Brush> value);
/// <summary>
/// Gets/sets the current font.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API System::SharedPtr<ITrFont> get_Font();
/// <summary>
/// Gets/sets the current font.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void set_Font(System::SharedPtr<ITrFont> value);
/// <summary>
/// Returns the resulting images byte arrays.
/// The first dimension is for inner documents
/// and the second one is for pages within inner documents.
/// </summary>
ASPOSE_PAGE_SHARED_API System::ArrayPtr<System::ArrayPtr<System::ArrayPtr<uint8_t>>> get_Result();
/// <summary>
/// Returns the absolute number of the current page within the document.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API int32_t get_CurrentPageNumber();
/// <summary>
/// Returns the relative number of the current page within the current partition.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API int32_t get_CurrentRelativePageNumber();
/// <summary>
/// Creates the new instance.
/// </summary>
ASPOSE_PAGE_SHARED_API ImageDevice();
/// <summary>
/// Creates the new instance with specified media size.
/// </summary>
/// <param name="pageSize">The size of the device output media.</param>
ASPOSE_PAGE_SHARED_API ImageDevice(System::Drawing::Size pageSize);
/// <summary>
/// Sets the devices to the initial state.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void ReNew();
/// <summary>
/// Starts the document.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void StartDocument();
/// <summary>
/// Accomplishes the document.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void EndDocument();
/// <summary>
/// Resets the device.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void Reset();
/// <summary>
/// Initializes numbers of pages to output.
/// </summary>
ASPOSE_PAGE_SHARED_API void InitPageNumbers();
/// <summary>
/// Starts a new page with the specifies title.
/// </summary>
/// <param name="title">The title.</param>
/// <returns><c>True</c> if started page is to be output (it's number is contained in PageNumbers save options).
/// <c>False</c>, otherwise.</returns>
virtual ASPOSE_PAGE_SHARED_API bool OpenPage(System::String title);
/// <summary>
/// Starts a new page with the specified width and height.
/// </summary>
/// <param name="width">The width of the page.</param>
/// <param name="height">The height of the page.</param>
/// <returns><c>True</c> if started page is to be output (it's number is contained in PageNumbers save options).
/// <c>False</c>, otherwise.</returns>
virtual ASPOSE_PAGE_SHARED_API bool OpenPage(float width, float height);
/// <summary>
/// Accomplishes the page.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void ClosePage();
/// <summary>
/// Updates the current page parameters.
/// </summary>
/// <param name="device">The multipage device.</param>
virtual ASPOSE_PAGE_SHARED_API void UpdatePageParameters(System::SharedPtr<IMultiPageDevice> device);
/// <summary>
/// Starts a new document partition.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void OpenPartition();
/// <summary>
/// Accomplished the document partition.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void ClosePartition();
/// <summary>
/// Creates a new instance of the device based on this device instance.
/// Writes this device graphics state, i.e. creates <see cref="ApsCanvas"/> instance(s)
/// with corresponding RenderTransform and Clip properties.
/// </summary>
/// <returns>The new device instance.</returns>
virtual ASPOSE_PAGE_SHARED_API System::SharedPtr<Device> Create();
/// <summary>
/// Disposes this device instance. Finalizes this device instance graphics state,
/// i.e. switches APS composing context to the <see cref="ApsCanvas"/> of the level higher then this
/// device's graphics state <see cref="ApsCanvas"/>.
/// </summary>
virtual ASPOSE_PAGE_SHARED_API void Dispose();
/// <summary>
/// Returns the current transformation matrix.
/// </summary>
/// <returns>The current transformation matrix.</returns>
virtual ASPOSE_PAGE_SHARED_API System::SharedPtr<System::Drawing::Drawing2D::Matrix> GetTransform();
/// <summary>
/// Sets the current transformation matrix.
/// </summary>
/// <param name="transform">The new transformation matrix.</param>
virtual ASPOSE_PAGE_SHARED_API void SetTransform(System::SharedPtr<System::Drawing::Drawing2D::Matrix> transform);
/// <summary>
/// Multiplies the current transformation matrix by the specified <see cref="Matrix"/>.
/// </summary>
/// <param name="transform">The matrix by which the current transformation matrix is to be multiplied.</param>
virtual ASPOSE_PAGE_SHARED_API void Transform(System::SharedPtr<System::Drawing::Drawing2D::Matrix> transform);
/// <summary>
/// Applies the specified translation vector to the current transformation matrix.
/// </summary>
/// <param name="x">The x offset.</param>
/// <param name="y">The y offset.</param>
virtual ASPOSE_PAGE_SHARED_API void Translate(double x, double y);
/// <summary>
/// Applies a clockwise rotation about the origin to the current transformation matrix.
/// </summary>
/// <param name="theta">The angle of the rotation, in radians.</param>
virtual ASPOSE_PAGE_SHARED_API void Rotate(double theta);
/// <summary>
/// Applies the specified scale vector to the current transformation matrix.
/// </summary>
/// <param name="x">The x scale factor.</param>
/// <param name="y">The y scale factor.</param>
virtual ASPOSE_PAGE_SHARED_API void Scale(double x, double y);
/// <summary>
/// Applies the specified shear vector to the current transformation matrix.
/// </summary>
/// <param name="shx">The x shear factor.</param>
/// <param name="shy">The y shear factor.</param>
virtual ASPOSE_PAGE_SHARED_API void Shear(double shx, double shy);
/// <summary>
/// Adds the specified path to the current clip path.
/// </summary>
/// <param name="clipPath">The clip path to be added.</param>
virtual ASPOSE_PAGE_SHARED_API void SetClip(System::SharedPtr<System::Drawing::Drawing2D::GraphicsPath> clipPath);
/// <summary>
/// Draws the specified path.
/// </summary>
/// <param name="path">The path to draw.</param>
virtual ASPOSE_PAGE_SHARED_API void Draw(System::SharedPtr<System::Drawing::Drawing2D::GraphicsPath> path);
/// <summary>
/// Fills the specified path.
/// </summary>
/// <param name="path">The path to fill.</param>
virtual ASPOSE_PAGE_SHARED_API void Fill(System::SharedPtr<System::Drawing::Drawing2D::GraphicsPath> path);
/// <summary>
/// Draws a string at the specified position.
/// </summary>
/// <param name="str">The text to be drawn.</param>
/// <param name="x">The x-coordinate of the string position.</param>
/// <param name="y">The y-coordinate of the string position.</param>
virtual ASPOSE_PAGE_SHARED_API void DrawString(System::String str, double x, double y);
protected:
/// <summary>
/// The clone constructor. Initializes new instance of <see cref="ImageDevice"/> with existing device.
/// </summary>
/// <param name="device">Existing device.</param>
ImageDevice(System::SharedPtr<ImageDevice> device);
virtual ASPOSE_PAGE_SHARED_API void ApplyGraphicState(System::SharedPtr<System::Drawing::Drawing2D::Matrix> transform, System::SharedPtr<System::Drawing::Drawing2D::GraphicsPath> clip);
/// <summary>
/// Writes the line width.
/// </summary>
/// <param name="width">The line width.</param>
virtual ASPOSE_PAGE_SHARED_API void WriteWidth(float width);
/// <summary>
/// Writes the line cap.
/// </summary>
/// <param name="cap">The line cap.</param>
virtual ASPOSE_PAGE_SHARED_API void WriteCap(System::Drawing::Drawing2D::LineCap cap);
/// <summary>
/// Writes the line join.
/// </summary>
/// <param name="join">The line join.</param>
virtual ASPOSE_PAGE_SHARED_API void WriteJoin(System::Drawing::Drawing2D::LineJoin join);
/// <summary>
/// Writes the miter limit.
/// </summary>
/// <param name="limit">The miter limit.</param>
virtual ASPOSE_PAGE_SHARED_API void WriteMiterLimit(float limit);
/// <summary>
/// Writes dash parameters.
/// </summary>
/// <param name="dash">The dash/gap array.</param>
/// <param name="phase">The stroke phase.</param>
/// <param name="dashCap">The dash cap.</param>
virtual ASPOSE_PAGE_SHARED_API void WriteDash(System::ArrayPtr<double> dash, double phase, System::Drawing::Drawing2D::DashCap dashCap);
/// <summary>
/// Writes the stroke brush.
/// </summary>
/// <param name="brush">The <see cref="SolidBrush"/> instance.</param>
virtual ASPOSE_PAGE_SHARED_API void WritePaint(System::SharedPtr<System::Drawing::SolidBrush> brush);
/// <summary>
/// Writes the stroke brush.
/// </summary>
/// <param name="brush">The <see cref="LinearGradientBrush"/> instance.</param>
virtual ASPOSE_PAGE_SHARED_API void WritePaint(System::SharedPtr<System::Drawing::Drawing2D::LinearGradientBrush> brush);
/// <summary>
/// Writes the stroke brush.
/// </summary>
/// <param name="brush">The <see cref="TextureBrush"/> instance.</param>
virtual ASPOSE_PAGE_SHARED_API void WritePaint(System::SharedPtr<System::Drawing::TextureBrush> brush);
/// <summary>
/// Writes the stroke brush.
/// </summary>
/// <param name="brush">The brush.</param>
virtual ASPOSE_PAGE_SHARED_API void WritePaint(System::SharedPtr<System::Drawing::Brush> brush);
virtual ASPOSE_PAGE_SHARED_API void DrawString(System::String str, double x, double y, double width, System::SharedPtr<Aspose::Rendering::ApsGlyphsIndices> indices, bool isRtl = false);
ASPOSE_PAGE_SHARED_API System::Object::shared_members_type GetSharedMembers() override;
private:
System::SharedPtr<Aspose::Page::Xps::Presentation::Aps::ApsDevice> _apsDevice;
System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<System::Collections::Generic::List<System::ArrayPtr<uint8_t>>>>> _imagesBytes;
static void SaveApsAsImages(System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<Aspose::Rendering::ApsPage>>>>> apsPages, System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<System::Collections::Generic::List<System::ArrayPtr<uint8_t>>>>> _imagesBytes, System::SharedPtr<ImageSaveOptions> options);
static System::ArrayPtr<uint8_t> renderPage(System::SharedPtr<Aspose::Rendering::ApsPage> page, int32_t number, System::SharedPtr<ImageSaveOptions> options);
};
} // namespace Image
} // namespace Presentation
} // namespace Xps
} // namespace Page
} // namespace Aspose
| 43.962099 | 393 | 0.685059 | [
"object",
"vector",
"transform"
] |
ad3145a0d3616fddf524343992de615aa836e497 | 788 | h | C | src/services/pcn-loadbalancer-dsr/src/interface/BackendPoolInterface.h | mbertrone/polycube | b35a6aa13273c000237d53c5f1bf286f12e4b9bd | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-07-16T04:49:29.000Z | 2020-07-16T04:49:29.000Z | src/services/pcn-loadbalancer-dsr/src/interface/BackendPoolInterface.h | mbertrone/polycube | b35a6aa13273c000237d53c5f1bf286f12e4b9bd | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/services/pcn-loadbalancer-dsr/src/interface/BackendPoolInterface.h | mbertrone/polycube | b35a6aa13273c000237d53c5f1bf286f12e4b9bd | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /**
* lbdsr API
* LoadBalancer Direct Server Return Service
*
* OpenAPI spec version: 2.0.0
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/polycube-network/swagger-codegen.git
* branch polycube
*/
/* Do not edit this file manually */
/*
* BackendPoolInterface.h
*
*
*/
#pragma once
#include "../serializer/BackendPoolJsonObject.h"
using namespace io::swagger::server::model;
class BackendPoolInterface {
public:
virtual void update(const BackendPoolJsonObject &conf) = 0;
virtual BackendPoolJsonObject toJsonObject() = 0;
/// <summary>
/// id
/// </summary>
virtual uint32_t getId() = 0;
/// <summary>
/// MAC address of the backend server of the pool
/// </summary>
virtual std::string getMac() = 0;
};
| 17.511111 | 75 | 0.692893 | [
"model"
] |
ad356e610de3e5a27659d87d84d120a2f6196dac | 2,068 | h | C | src/tensor/EigenMap.h | NicoSchlw/tandem | 3a08b5a7ae391c1675c5cbfdad77260d4a0115cc | [
"BSD-3-Clause"
] | 4 | 2021-11-03T17:11:00.000Z | 2022-02-16T07:51:01.000Z | src/tensor/EigenMap.h | NicoSchlw/tandem | 3a08b5a7ae391c1675c5cbfdad77260d4a0115cc | [
"BSD-3-Clause"
] | 12 | 2020-05-18T14:51:13.000Z | 2021-12-16T12:56:31.000Z | src/tensor/EigenMap.h | NicoSchlw/tandem | 3a08b5a7ae391c1675c5cbfdad77260d4a0115cc | [
"BSD-3-Clause"
] | 2 | 2020-10-23T08:04:42.000Z | 2021-11-15T12:23:59.000Z | #ifndef EIGENMAP_20200609_H
#define EIGENMAP_20200609_H
#include "Tensor.h"
#include "TensorBase.h"
#include "util/Utility.h"
#include <Eigen/Core>
#include <type_traits>
namespace tndm {
namespace detail {
template <typename Tensor, int Rows, int Cols, std::size_t D> struct EigenMapFactory;
template <typename Vector, int Rows, int Cols> struct EigenMapFactory<Vector, Rows, Cols, 1u> {
auto operator()(Vector& vector) {
using real_t = std::remove_pointer_t<decltype(vector.data())>;
using vector_t = copy_const<real_t, Eigen::Matrix<std::decay_t<real_t>, Rows, 1>>;
if constexpr (detail::traits<Vector>::Packed) {
return Eigen::Map<vector_t>(vector.data(), vector.shape(0));
} else {
using stride_t = Eigen::InnerStride<>;
return Eigen::Map<vector_t, Eigen::Unaligned, stride_t>(vector.data(), vector.shape(0),
stride_t(vector.stride(0)));
}
}
};
template <typename Matrix, int Rows, int Cols> struct EigenMapFactory<Matrix, Rows, Cols, 2u> {
auto operator()(Matrix& matrix) {
using real_t = std::remove_pointer_t<decltype(matrix.data())>;
using matrix_t = copy_const<real_t, Eigen::Matrix<std::decay_t<real_t>, Rows, Cols>>;
if constexpr (detail::traits<Matrix>::Packed) {
return Eigen::Map<matrix_t>(matrix.data(), matrix.shape(0), matrix.shape(1));
} else {
using stride_t = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
return Eigen::Map<matrix_t, Eigen::Unaligned, stride_t>(
matrix.data(), matrix.shape(0), matrix.shape(1),
stride_t(matrix.stride(1), matrix.stride(0)));
}
}
};
} // namespace detail
template <typename Tensor, int Rows = Eigen::Dynamic, int Cols = Eigen::Dynamic>
auto EigenMap(Tensor& tensor) {
detail::EigenMapFactory<Tensor, Rows, Cols, detail::traits<Tensor>::Dim> factory;
return factory(tensor);
}
} // namespace tndm
#endif // EIGENMAP_20200609_H
| 36.280702 | 99 | 0.636847 | [
"shape",
"vector"
] |
ad3a7b8f04f8be4bf3b383f088eb1b034a90ff0a | 7,872 | h | C | shared/devdriver/apis/ddEvent/ddEventClient/inc/ddEventClientApi.h | GPUOpen-Drivers/pal | bcec463efe5260776d486a5e3da0c549bc0a75d2 | [
"MIT"
] | 268 | 2017-12-22T11:03:10.000Z | 2022-03-31T15:37:31.000Z | shared/devdriver/apis/ddEvent/ddEventClient/inc/ddEventClientApi.h | GPUOpen-Drivers/pal | bcec463efe5260776d486a5e3da0c549bc0a75d2 | [
"MIT"
] | 79 | 2017-12-22T12:26:52.000Z | 2022-03-30T13:06:30.000Z | shared/devdriver/apis/ddEvent/ddEventClient/inc/ddEventClientApi.h | GPUOpen-Drivers/pal | bcec463efe5260776d486a5e3da0c549bc0a75d2 | [
"MIT"
] | 92 | 2017-12-22T12:21:16.000Z | 2022-03-29T22:34:17.000Z | /* Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved. */
#ifndef DD_EVENT_CLIENT_API_HEADER
#define DD_EVENT_CLIENT_API_HEADER
#include <ddApi.h>
#ifdef __cplusplus
extern "C" {
#endif
/// Compile time version information
#define DD_EVENT_CLIENT_API_MAJOR_VERSION 0
#define DD_EVENT_CLIENT_API_MINOR_VERSION 2
#define DD_EVENT_CLIENT_API_PATCH_VERSION 0
#define DD_EVENT_CLIENT_API_VERSION_STRING DD_API_STRINGIFY_VERSION(DD_EVENT_CLIENT_API_MAJOR_VERSION, \
DD_EVENT_CLIENT_API_MINOR_VERSION, \
DD_EVENT_CLIENT_API_PATCH_VERSION)
/// Opaque handle to an event client
typedef struct DDEventClient_t* DDEventClient;
/// Used by "ReadEventData()" to return event data from the network to the application
///
/// NOTE: This callback may also be triggered indirectly during the execution of functions that interact with providers.
/// This is a consequence of the asynchronous nature of the event protocol. It's entirely possible that the server
/// could emit events while a remote client is attempting to interact with providers. In this case, the client may
/// end up receiving event data interleaved with its provider configuration messages. When this occurs, the
/// implementation is forced to immediately return the data to the application since there is no way to robustly
/// buffer the data until the next time the read function is called.
typedef void (*PFN_ddEventDataCallback)(
void* pUserdata, /// [in] Userdata pointer
const void* pData, /// [in] Pointer to a buffer that contains event data
size_t dataSize); /// Size of the buffer pointed to by pData
/// Helper structure for PFN_ddEventDataCallback
typedef struct DDEventDataCallback
{
void* pUserdata; /// [in] Userdata pointer
PFN_ddEventDataCallback pfnCallback; /// [in] Pointer to a data callback function
} DDEventDataCallback;
/// Structure that contains the information required to create a client
typedef struct DDEventClientCreateInfo
{
DDNetConnection hConnection; /// A handle to an existing connection object
DDClientId clientId; /// The ClientId on the network to connect to
DDEventDataCallback dataCb; /// Callback used to return event data to the application
uint32_t timeoutInMs; /// The maximum time that will be spent attempting to connect to the remote server
//< Connection occurs at creation time and creation will fail if a timeout is
//< encountered.
//< [Optional] Specify 0 to use a reasonable but implementation defined default.
} DDEventClientCreateInfo;
/// Get version of the loaded library to check interface compatibility
typedef DDApiVersion (*PFN_ddEventClientQueryVersion)(
void);
/// Get human-readable representation of the loaded library version
typedef const char* (*PFN_ddEventClientQueryVersionString)(
void);
/// Attempts to create a new client object with the provided creation information
typedef DD_RESULT(*PFN_ddEventClientCreate)(
const DDEventClientCreateInfo* pInfo, /// [in] Create info
DDEventClient* phClient); /// [out] Handle to the new client object
/// Destroys an existing client object
typedef void (*PFN_ddEventClientDestroy)(
DDEventClient hClient); /// [in] Handle to the existing client object
/// Attempts to read incoming event from the server
///
/// Any data received through the read operation will be returned via the event data callback that was provided during
/// client creation.
typedef DD_RESULT (*PFN_ddEventClientReadEventData)(
DDEventClient hClient, /// [in] Handle to an existing client object
uint32_t timeoutInMs); /// Timeout in milliseconds
/// Structure that generically describes enablement status
typedef struct DDEventEnabledStatus
{
uint8_t isEnabled : 1; /// Non-zero if enabled
uint8_t reserved : 7; /// Reserved for future use
} DDEventEnabledStatus;
/// Structure that describes a remote event provider
typedef struct DDEventProviderDesc
{
uint32_t providerId; /// Unique identifier
DDEventEnabledStatus providerStatus; /// Overall enablement status
uint32_t numEvents; /// Number of items in pEventStatus array
const DDEventEnabledStatus* pEventStatus; /// Enablement status for each event in the provider
} DDEventProviderDesc;
/// Used by "QueryProviders()" to return data about an individual provider to the caller
///
/// This callback will be called once per provider returned by the server
/// If this function returns non-success, iteration will be aborted
typedef DD_RESULT(*PFN_ddEventVisitProvider)(
void* pUserdata, /// [in] Userdata pointer
const DDEventProviderDesc* pProvider); /// [in] Pointer to a provider description
/// Helper structure for PFN_ddEventVisitProvider
typedef struct DDEventProviderVisitor
{
void* pUserdata; /// [in] Userdata pointer
PFN_ddEventVisitProvider pfnVisit; /// [in] Pointer to a visitor function that will be called once per provider
} DDEventProviderVisitor;
/// Attempts to query and return all known providers from the remote server
typedef DD_RESULT (*PFN_ddEventClientQueryProviders)(
DDEventClient hClient, /// [in] Handle to an existing client object
const DDEventProviderVisitor* pVisitor); /// [in] Provider visitor to return provider data through
/// Attempts to configure the state of the providers on the remote server
///
/// Providers on the remote server will be updated to reflect the new configuration
typedef DD_RESULT (*PFN_ddEventClientConfigureProviders)(
DDEventClient hClient, /// [in] Handle to an existing client object
size_t numProviders, /// Number of items in the pProviders array
const DDEventProviderDesc* pProviders); /// [in] Array of provider descriptions to send to the server
/// Attempts to fully enable all specified providers on the remote server
///
/// This will enable the providers themselves and all individual events supported by them
typedef DD_RESULT (*PFN_ddEventClientEnableProviders)(
DDEventClient hClient, /// [in] Handle to an existing client object
size_t numProviderIds, /// Number of items in the pProviderIds array
const uint32_t* pProviderIds); /// [in] Array of provider ids to send to the server
/// Attempts to fully disable all specified providers on the remote server
///
/// This will disable the providers themselves and all individual events supported by them
typedef DD_RESULT (*PFN_ddEventClientDisableProviders)(
DDEventClient hClient, /// [in] Handle to an existing client object
size_t numProviderIds, /// Number of items in the pProviderIds array
const uint32_t* pProviderIds); /// [in] Array of provider ids to send to the server
/// API structure
typedef struct DDEventClientApi
{
PFN_ddEventClientQueryVersion pfnQueryVersion;
PFN_ddEventClientQueryVersionString pfnQueryVersionString;
PFN_ddEventClientCreate pfnCreateClient;
PFN_ddEventClientDestroy pfnDestroyClient;
PFN_ddEventClientReadEventData pfnReadEventData;
PFN_ddEventClientQueryProviders pfnQueryProviders;
PFN_ddEventClientConfigureProviders pfnConfigureProviders;
PFN_ddEventClientEnableProviders pfnEnableProviders;
PFN_ddEventClientDisableProviders pfnDisableProviders;
} DDEventClientApi;
#ifdef __cplusplus
} // extern "C"
#endif
#endif // ! DD_EVENT_CLIENT_API_HEADER
| 48.89441 | 120 | 0.719766 | [
"object"
] |
ad46467cdd3404ad78b20d3e7e7f08295b407f95 | 1,835 | h | C | grr/client/minicomm/client_actions/find.h | mikecb/grr | 52fdd977729af2a09a147301c55b8b7f1eccfa67 | [
"Apache-2.0"
] | 5 | 2017-03-17T08:25:09.000Z | 2022-02-22T05:28:14.000Z | grr/client/minicomm/client_actions/find.h | mikecb/grr | 52fdd977729af2a09a147301c55b8b7f1eccfa67 | [
"Apache-2.0"
] | null | null | null | grr/client/minicomm/client_actions/find.h | mikecb/grr | 52fdd977729af2a09a147301c55b8b7f1eccfa67 | [
"Apache-2.0"
] | 3 | 2018-12-07T07:04:37.000Z | 2022-02-22T05:28:16.000Z | #ifndef GRR_CLIENT_MINICOMM_CLIENT_ACTIONS_FIND_H_
#define GRR_CLIENT_MINICOMM_CLIENT_ACTIONS_FIND_H_
#include <memory>
#include <vector>
#include "grr/client/minicomm/client_action.h"
#include "grr/client/minicomm/file_contents.h"
#include "grr/client/minicomm/file_operations.h"
namespace grr {
namespace actions {
class Find : public ClientAction {
public:
Find() {}
void ProcessRequest(ActionContext* context) override;
private:
// Each filter takes some information about a file and returns true if the
// file should be filtered.
typedef std::function<bool(const std::string&)> NameFilter;
typedef std::function<bool(const StatEntry&)> StatFilter;
typedef std::function<bool(FileContents*)> ContentsFilter;
// A full set of filters.
struct FilterSet {
std::vector<NameFilter> name;
std::vector<StatFilter> stat;
std::vector<ContentsFilter> contents;
};
// Recurse through the directory tree beginning at path, sending a FindSpec
// back to the server for each file or directory which is not
// filtered. Returns true on success. In case of error, sets an error message
// in context and returns false.
//
// remaining_depth: How deep to recurse, remaining_depth=1 indicates to check
// the direct contents of path, remaining_depths=2 indicates
// to check the direct contents of path, and the direct
// contents of any subdirectories within path.
// cross_devices: Whether to cross device boundaries while recursing.
bool ProcessRecursive(const FilterSet& filters,
std::unique_ptr<OpenedPath> path, int remaining_depth,
bool cross_devices, ActionContext* context);
};
} // namespace actions
} // namespace grr
#endif // GRR_CLIENT_MINICOMM_CLIENT_ACTIONS_FIND_H_
| 35.980392 | 79 | 0.719891 | [
"vector"
] |
ad48a7ee8fe3972c89f8b915d43ddfeca67e3c53 | 1,077 | c | C | lib/wizards/nalle/area/monsters/assassin.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/nalle/area/monsters/assassin.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/nalle/area/monsters/assassin.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | inherit "obj/monster";
reset(arg) {
string chat_str, a_chat_str;
object weapon;
::reset(arg);
if (arg) { return; }
set_level(21);
set_race("human");
set_gender(1);
set_name("The Assassin");
set_alias("assassin");
set_short("An assassin is inspecting the area here.");
set_long("The assassin is completely clad in black. He seems to be a\n" +
"somewhat skilled fighter.\n");
set_al(0);
set_aggressive(0);
set_move_at_random(0);
if (!chat_str) {
chat_str = allocate(3);
chat_str[0] =
"The assassin throws his dagger in the air and catches it skillfully.\n";
chat_str[1] =
"The assassin whispers: 'D'you know people you want to get rid of?' \n";
chat_str[2] =
"The assassin stuffs his garotte under his cloak. \n";
}
if (!a_chat_str) {
a_chat_str = allocate(1);
a_chat_str[0] = "The assassin prepares to thrust his dagger into your guts. \n"
;
}
load_chat(10, chat_str);
load_a_chat(10, a_chat_str);
}
| 28.342105 | 87 | 0.601671 | [
"object"
] |
ad64e9a99133ee157870ecd5bc842e7fe4bc8160 | 50,483 | h | C | modules/eddl/include/ecvl/augmentations.h | simleo/ecvl | 6e6088c45677892e347fb612ef4a6c81b48d2e08 | [
"MIT"
] | 9 | 2020-01-22T09:49:09.000Z | 2021-05-23T19:00:00.000Z | modules/eddl/include/ecvl/augmentations.h | simleo/ecvl | 6e6088c45677892e347fb612ef4a6c81b48d2e08 | [
"MIT"
] | 27 | 2020-01-21T17:20:12.000Z | 2022-03-29T18:15:42.000Z | modules/eddl/include/ecvl/augmentations.h | simleo/ecvl | 6e6088c45677892e347fb612ef4a6c81b48d2e08 | [
"MIT"
] | 3 | 2020-01-22T10:16:56.000Z | 2020-06-03T12:21:46.000Z | /*
* ECVL - European Computer Vision Library
* Version: 0.3.4
* copyright (c) 2021, Università degli Studi di Modena e Reggio Emilia (UNIMORE), AImageLab
* Authors:
* Costantino Grana (costantino.grana@unimore.it)
* Federico Bolelli (federico.bolelli@unimore.it)
* Michele Cancilla (michele.cancilla@unimore.it)
* Laura Canalini (laura.canalini@unimore.it)
* Stefano Allegretti (stefano.allegretti@unimore.it)
* All rights reserved.
*/
#ifndef AUGMENTATIONS_H_
#define AUGMENTATIONS_H_
#include "ecvl/core/arithmetic.h"
#include "ecvl/core/imgproc.h"
#include <array>
#include <map>
#include <memory>
#include <random>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <unordered_map>
#include <vector>
namespace ecvl
{
#define ECVL_ERROR_AUGMENTATION_NAME throw std::runtime_error(ECVL_ERROR_MSG "Cannot load augmentation name");
#define ECVL_ERROR_AUGMENTATION_FORMAT throw std::runtime_error(ECVL_ERROR_MSG "Format error while loading augmentation parameters");
class param_list;
class param
{
static std::istream& read_until(std::istream& is, std::string& s, const std::string& list)
{
s.clear();
while (is.peek() && is && list.find(is.peek()) == list.npos) {
s += is.get();
}
return is;
}
void read_vals(std::istream& is, char closing_char)
{
double val;
char next_char;
do {
is >> val;
if (!is) {
break;
}
vals_.push_back(val);
is >> next_char;
} while (next_char == ',');
if (!is || next_char != closing_char) {
std::cerr << "Error while reading values of parameter " << name_ << "\n"; // TODO: standardize
throw std::runtime_error("Cannot read parameter value"); // TODO: standardize
}
}
public:
enum class type { range, vector, number, string };
static const char* to_string(type t)
{
switch (t) {
case type::range: return "range";
case type::vector: return "vector";
case type::number: return "number";
case type::string: return "string";
default:
ECVL_ERROR_NOT_REACHABLE_CODE
}
}
std::string name_;
type type_;
std::vector<double> vals_;
std::string str_;
param() {}
param(std::istream& is)
{
is >> std::ws;
read_until(is, name_, " =");
char next_char;
is >> std::ws >> next_char;
if (next_char != '=') {
throw std::runtime_error("Cannot read parameter name"); // TODO: standardize
}
is >> std::ws;
next_char = is.peek();
if (next_char == '[') { // range
is.ignore();
type_ = type::range;
read_vals(is, ']');
} else if (next_char == '(') { // vector
is.ignore();
type_ = type::vector;
read_vals(is, ')');
} else if (next_char == '"') { // string
is.ignore();
type_ = type::string;
std::getline(is, str_, '"');
} else {
type_ = type::number;
vals_.resize(1);
is >> vals_[0];
}
if (!is) {
std::cerr << "Error while reading value of parameter " << name_ << "\n"; // TODO: standardize
throw std::runtime_error("Cannot read parameter value"); // TODO: standardize
}
}
friend class param_list;
static param_list read(std::istream& is, std::string fn_name_);
};
class param_list
{
std::unordered_map<std::string, param> m_;
const std::string fn_name_;
public:
param_list(std::string fn_name) : fn_name_(move(fn_name)) {}
auto& operator[](const std::string& s)
{
return m_[s];
}
bool Get(const std::string& name, param::type type, bool required, param& value)
{
auto it = m_.find(name);
if (it != end(m_)) {
auto& p = it->second;
if (p.type_ != type) {
throw std::runtime_error(fn_name_ + ": " + name + " parameter must be a " + param::to_string(type));
}
value = p;
return true;
}
if (required) {
throw std::runtime_error(fn_name_ + ": " + name + " is a required parameter");
}
return false;
}
bool GenericGet(const std::string& name, bool required, param& value)
{
auto it = m_.find(name);
if (it != end(m_)) {
auto& p = it->second;
value = p;
return true;
}
if (required) {
throw std::runtime_error(fn_name_ + ": " + name + " is a required parameter");
}
return false;
}
};
/** @brief Augmentations parameters.
This class represent the augmentations parameters which must be randomly generated in a specific range.
@anchor AugmentationParam
*/
class AugmentationParam
{
public:
double min_, max_, value_;
AugmentationParam() = default;
AugmentationParam(const double min, const double max) : min_(min), max_(max) {}
/** @brief Generate the random value between min_ and max_.
*/
void GenerateValue()
{
value_ = std::uniform_real_distribution<>(min_, max_)(re_);
}
static std::default_random_engine re_;
static constexpr unsigned seed_min = std::numeric_limits<unsigned>::min();
static constexpr unsigned seed_max = std::numeric_limits<unsigned>::max();
/** @brief Set a fixed seed for the random generated values. Useful to reproduce experiments with same augmentations.
@param[in] seed Value of the seed for the random engine.
*/
static void SetSeed(unsigned seed)
{
re_.seed(seed);
}
};
/** @brief Abstract class which represent a generic Augmentation function.
@anchor Augmentation
*/
class Augmentation
{
public:
std::unordered_map<std::string, AugmentationParam> params_;
/** @brief Generate the random value for each parameter and call the specialized augmentation functions.
@param[in,out] img Image on which apply the augmentations.
@param[in,out] gt Ground truth image on which apply the augmentations.
*/
void Apply(ecvl::Image& img, const ecvl::Image& gt = Image())
{
for (auto& x : params_) {
x.second.GenerateValue();
}
RealApply(img, gt);
}
virtual std::shared_ptr<Augmentation> Clone() const = 0;
virtual ~Augmentation() = default;
private:
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) = 0;
};
#define DEFINE_AUGMENTATION_CLONE(class_name) std::shared_ptr<Augmentation> Clone() const override { return std::make_shared<class_name>(*this); }
struct AugmentationFactory
{
static std::shared_ptr<Augmentation> create(std::istream& is)
{
std::string name;
is >> name;
if (!is) {
ECVL_ERROR_AUGMENTATION_NAME
}
return create(name, is);
}
static std::shared_ptr<Augmentation> create(const std::string& name, std::istream& is);
};
/** @brief SequentialAugmentationContainer.
This class represents a container for multiple augmentations which will be sequentially applied to the Dataset images.
@anchor SequentialAugmentationContainer
*/
class SequentialAugmentationContainer : public Augmentation
{
/** @brief Call the specialized augmentation functions.
@param[in] img Image on which apply the augmentations.
@param[in] gt Ground truth image on which apply the augmentations.
*/
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
for (auto& x : augs_) {
x->Apply(img, gt);
}
}
std::vector<std::shared_ptr<Augmentation>> augs_; /**< @brief vector containing the Augmentation to be applied */
public:
DEFINE_AUGMENTATION_CLONE(SequentialAugmentationContainer)
template<typename ...Ts>
SequentialAugmentationContainer(Ts&&... t) : augs_({ std::make_shared<Ts>(std::forward<Ts>(t))... }) {}
SequentialAugmentationContainer(std::vector<std::shared_ptr<Augmentation>> augs) : augs_(augs) {}
SequentialAugmentationContainer(const SequentialAugmentationContainer& other) : Augmentation(other)
{
for (const auto& a : other.augs_) {
augs_.emplace_back(a->Clone());
}
}
SequentialAugmentationContainer(std::istream& is)
{
while (true) {
std::string name;
is >> name;
if (!is) {
ECVL_ERROR_AUGMENTATION_NAME
}
if (name == "end") {
break;
}
augs_.emplace_back(AugmentationFactory::create(name, is));
}
}
};
/** @brief OneOfAugmentationContainer.
This class represents a container for multiple augmentations from which one will be randomly chosen.
The chosen augmentation will be applied with a probability that must be specified by the user.
@anchor OneOfAugmentationContainer
*/
class OneOfAugmentationContainer : public Augmentation
{
/** @brief Call the specialized augmentation functions.
@param[in] img Image on which apply the augmentations.
@param[in] gt Ground truth image on which apply the augmentations.
*/
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
int index = std::uniform_int_distribution<>(0, vsize(augs_) - 1)(AugmentationParam::re_);
if (params_["p"].value_ <= p_) {
augs_[index]->Apply(img, gt);
}
}
std::vector<std::shared_ptr<Augmentation>> augs_; /**< @brief vector containing the Augmentation to be applied */
double p_;
public:
DEFINE_AUGMENTATION_CLONE(OneOfAugmentationContainer)
template<typename ...Ts>
OneOfAugmentationContainer(double p, Ts&&... t) : p_(p), augs_({ std::make_shared<Ts>(std::forward<Ts>(t))... })
{
params_["p"] = AugmentationParam(0, 1);
}
OneOfAugmentationContainer(double p, std::vector<std::shared_ptr<Augmentation>> augs) : p_(p), augs_(augs)
{
params_["p"] = AugmentationParam(0, 1);
}
OneOfAugmentationContainer(const OneOfAugmentationContainer& other) : Augmentation(other)
{
for (const auto& a : other.augs_) {
augs_.emplace_back(a->Clone());
}
}
OneOfAugmentationContainer(std::istream& is)
{
param p;
try {
auto m = param::read(is, "OneOfAugmentationContainer");
if (m.Get("p", param::type::number, true, p)) {
p_ = p.vals_[0];
}
} catch (std::runtime_error&) {
std::cout << ECVL_ERROR_MSG "The first parameter in OneOfAugmentationContainer must be the probability p" << std::endl;
ECVL_ERROR_AUGMENTATION_FORMAT
}
while (true) {
std::string name;
is >> name;
if (!is) {
ECVL_ERROR_AUGMENTATION_NAME
}
if (name == "end") {
break;
}
augs_.emplace_back(AugmentationFactory::create(name, is));
}
}
};
InterpolationType StrToInterpolationType(const std::string& interp, const std::string& aug_name);
///////////////////////////////////////////////////////////////////////////////////
// Augmentations
///////////////////////////////////////////////////////////////////////////////////
/** @brief Augmentation wrapper for ecvl::Rotate2D.
@anchor AugRotate
*/
class AugRotate : public Augmentation
{
std::vector<double> center_;
double scale_;
InterpolationType interp_, gt_interp_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto angle = params_["angle"].value_;
Rotate2D(img, img, angle, center_, scale_, interp_);
if (!gt.IsEmpty()) {
Rotate2D(gt, const_cast<Image&>(gt), angle, center_, scale_, gt_interp_);
}
}
public:
DEFINE_AUGMENTATION_CLONE(AugRotate)
/** @brief AugRotate constructor
@param[in] angle Parameter which determines the range of degrees [min,max] to randomly select from.
@param[in] center A std::vector<double> representing the coordinates of the rotation center.
If empty, the center of the image is used.
@param[in] scale Optional scaling factor.
@param[in] interp InterpolationType to be used. Default is InterpolationType::linear.
@param[in] gt_interp InterpolationType to be used for ground truth. Default is InterpolationType::nearest.
*/
AugRotate(const std::array<double, 2>& angle,
const std::vector<double>& center = {},
const double& scale = 1.,
const InterpolationType& interp = InterpolationType::linear,
const InterpolationType& gt_interp = InterpolationType::nearest)
: center_(center), scale_(scale), interp_(interp), gt_interp_(gt_interp)
{
params_["angle"] = AugmentationParam(angle[0], angle[1]);
}
AugRotate(std::istream& is)
{
auto m = param::read(is, "AugRotate");
param p;
m.Get("angle", param::type::range, true, p);
params_["angle"] = AugmentationParam(p.vals_[0], p.vals_[1]);
if (m.Get("center", param::type::vector, false, p)) {
center_ = p.vals_;
}
scale_ = 1.;
if (m.Get("scale", param::type::number, false, p)) {
scale_ = p.vals_[0];
}
interp_ = InterpolationType::linear;
gt_interp_ = InterpolationType::nearest;
if (m.Get("interp", param::type::string, false, p)) {
interp_ = StrToInterpolationType(p.str_, "AugRotate");
}
if (m.Get("gt_interp", param::type::string, false, p)) {
gt_interp_ = StrToInterpolationType(p.str_, "AugRotate");
}
}
};
/** @brief Augmentation wrapper for ecvl::ResizeDim.
@anchor AugResizeDim
*/
class AugResizeDim : public Augmentation
{
std::vector<int> dims_;
InterpolationType interp_, gt_interp_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
ResizeDim(img, img, dims_, interp_);
if (!gt.IsEmpty()) {
ResizeDim(gt, const_cast<Image&>(gt), dims_, gt_interp_);
}
}
public:
DEFINE_AUGMENTATION_CLONE(AugResizeDim)
/** @brief AugResizeDim constructor
@param[in] dims std::vector<int> that specifies the new size of each dimension.
@param[in] interp InterpolationType to be used. Default is InterpolationType::linear.
@param[in] gt_interp InterpolationType to be used for ground truth. Default is InterpolationType::nearest.
*/
AugResizeDim(const std::vector<int>& dims,
const InterpolationType& interp = InterpolationType::linear,
const InterpolationType& gt_interp = InterpolationType::nearest)
: dims_{ dims }, interp_(interp), gt_interp_(gt_interp) {}
AugResizeDim(std::istream& is)
{
auto m = param::read(is, "AugResizeDim");
param p;
m.Get("dims", param::type::vector, true, p);
for (const auto& x : p.vals_) {
dims_.emplace_back(static_cast<int>(x));
}
interp_ = InterpolationType::linear;
gt_interp_ = InterpolationType::nearest;
if (m.Get("interp", param::type::string, false, p)) {
interp_ = StrToInterpolationType(p.str_, "");
}
if (m.Get("gt_interp", param::type::string, false, p)) {
gt_interp_ = StrToInterpolationType(p.str_, "AugResizeDim");
}
}
};
/** @brief Augmentation wrapper for ecvl::ResizeScale.
@anchor AugResizeScale
*/
class AugResizeScale : public Augmentation
{
std::vector<double> scale_;
InterpolationType interp_, gt_interp_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
ResizeScale(img, img, scale_, interp_);
if (!gt.IsEmpty()) {
ResizeScale(gt, const_cast<Image&>(gt), scale_, gt_interp_);
}
}
public:
DEFINE_AUGMENTATION_CLONE(AugResizeScale)
/** @brief AugResizeScale constructor
@param[in] scale std::vector<double> that specifies the scale to apply to each dimension.
@param[in] interp InterpolationType to be used. Default is InterpolationType::linear.
@param[in] gt_interp InterpolationType to be used for ground truth. Default is InterpolationType::nearest.
*/
AugResizeScale(const std::vector<double>& scale,
const InterpolationType& interp = InterpolationType::linear,
const InterpolationType& gt_interp = InterpolationType::nearest
) : scale_{ scale }, interp_(interp), gt_interp_(gt_interp){}
AugResizeScale(std::istream& is)
{
auto m = param::read(is, "AugResizeScale");
param p;
m.Get("scale", param::type::vector, true, p);
scale_ = p.vals_;
interp_ = InterpolationType::linear;
gt_interp_ = InterpolationType::nearest;
if (m.Get("interp", param::type::string, false, p)) {
interp_ = StrToInterpolationType(p.str_, "AugResizeScale");
}
if (m.Get("gt_interp", param::type::string, false, p)) {
gt_interp_ = StrToInterpolationType(p.str_, "AugResizeScale");
}
}
};
/** @brief Augmentation wrapper for ecvl::Flip2D.
@anchor AugFlip
*/
class AugFlip : public Augmentation
{
double p_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto p = params_["p"].value_;
if (p <= p_) {
Flip2D(img, img);
if (!gt.IsEmpty()) {
Flip2D(gt, const_cast<Image&>(gt));
}
}
}
public:
DEFINE_AUGMENTATION_CLONE(AugFlip)
/** @brief AugFlip constructor
@param[in] p Probability of each image to get flipped.
*/
AugFlip(double p = 0.5) : p_{ p }
{
params_["p"] = AugmentationParam(0, 1);
}
AugFlip(std::istream& is) : AugFlip()
{
auto m = param::read(is, "AugFlip");
param p;
if (m.Get("p", param::type::number, false, p)) {
p_ = p.vals_[0];
}
}
};
/** @brief Augmentation wrapper for ecvl::Mirror2D.
@anchor AugMirror
*/
class AugMirror : public Augmentation
{
double p_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto p = params_["p"].value_;
if (p <= p_) {
Mirror2D(img, img);
if (!gt.IsEmpty()) {
Mirror2D(gt, const_cast<Image&>(gt));
}
}
}
public:
DEFINE_AUGMENTATION_CLONE(AugMirror)
/** @brief AugMirror constructor
@param[in] p Probability of each image to get mirrored.
*/
AugMirror(double p = 0.5) : p_{ p }
{
params_["p"] = AugmentationParam(0, 1);
}
AugMirror(std::istream& is) : AugMirror()
{
auto m = param::read(is, "AugMirror");
param p;
if (m.Get("p", param::type::number, false, p)) {
p_ = p.vals_[0];
}
}
};
/** @brief Augmentation wrapper for ecvl::GaussianBlur.
@anchor AugGaussianBlur
*/
class AugGaussianBlur : public Augmentation
{
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto sigma = params_["sigma"].value_;
GaussianBlur(img, img, sigma);
}
public:
DEFINE_AUGMENTATION_CLONE(AugGaussianBlur)
/** @brief AugGaussianBlur constructor
@param[in] sigma Parameter which determines the range of sigma [min,max] to randomly select from.
*/
AugGaussianBlur(const std::array<double, 2>& sigma)
{
params_["sigma"] = AugmentationParam(sigma[0], sigma[1]);
}
AugGaussianBlur(std::istream& is)
{
auto m = param::read(is, "AugGaussianBlur");
param p;
m.Get("sigma", param::type::range, true, p);
params_["sigma"] = AugmentationParam(p.vals_[0], p.vals_[1]);
}
};
/** @brief Augmentation wrapper for ecvl::AdditiveLaplaceNoise.
@anchor AugAdditiveLaplaceNoise
*/
class AugAdditiveLaplaceNoise : public Augmentation
{
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto std_dev = params_["std_dev"].value_;
AdditiveLaplaceNoise(img, img, std_dev);
}
public:
DEFINE_AUGMENTATION_CLONE(AugAdditiveLaplaceNoise)
/** @brief AugAdditiveLaplaceNoise constructor
@param[in] std_dev Parameter which determines the range of values [min,max] to randomly select the standard deviation of the noise generating distribution.
Suggested values are around 255 * 0.05 for uint8 Images.
*/
AugAdditiveLaplaceNoise(const std::array<double, 2>& std_dev)
{
params_["std_dev"] = AugmentationParam(std_dev[0], std_dev[1]);
}
AugAdditiveLaplaceNoise(std::istream& is)
{
auto m = param::read(is, "AugAdditiveLaplaceNoise");
param p;
m.Get("std_dev", param::type::range, true, p);
params_["std_dev"] = AugmentationParam(p.vals_[0], p.vals_[1]);
}
};
/** @brief Augmentation wrapper for ecvl::AdditivePoissonNoise.
@anchor AugAdditivePoissonNoise
*/
class AugAdditivePoissonNoise : public Augmentation
{
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto lambda = params_["lambda"].value_;
AdditivePoissonNoise(img, img, lambda);
}
public:
DEFINE_AUGMENTATION_CLONE(AugAdditivePoissonNoise)
/** @brief AugAdditivePoissonNoise constructor
@param[in] lambda Parameter which determines the range of values [min,max] to randomly select the lambda of the noise generating distribution.
Suggested values are around 0.0 to 10.0.
*/
AugAdditivePoissonNoise(const std::array<double, 2>& lambda)
{
params_["lambda"] = AugmentationParam(lambda[0], lambda[1]);
}
AugAdditivePoissonNoise(std::istream& is)
{
auto m = param::read(is, "AugAdditivePoissonNoise");
param p;
m.Get("lambda", param::type::range, true, p);
params_["lambda"] = AugmentationParam(p.vals_[0], p.vals_[1]);
}
};
/** @brief Augmentation wrapper for ecvl::GammaContrast.
@anchor AugGammaContrast
*/
class AugGammaContrast : public Augmentation
{
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto gamma = params_["gamma"].value_;
GammaContrast(img, img, gamma);
}
public:
DEFINE_AUGMENTATION_CLONE(AugGammaContrast)
/** @brief AugGammaContrast constructor
@param[in] gamma Parameter which determines the range of values [min,max] to randomly select the exponent for the contrast adjustment.
Suggested values are around 0.5 to 2.0.
*/
AugGammaContrast(const std::array<double, 2>& gamma)
{
params_["gamma"] = AugmentationParam(gamma[0], gamma[1]);
}
AugGammaContrast(std::istream& is)
{
auto m = param::read(is, "AugGammaContrast");
param p;
m.Get("gamma", param::type::range, true, p);
params_["gamma"] = AugmentationParam(p.vals_[0], p.vals_[1]);
}
};
/** @brief Augmentation wrapper for ecvl::CoarseDropout.
@anchor AugCoarseDropout
*/
class AugCoarseDropout : public Augmentation
{
double per_channel_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto p = params_["p"].value_;
const auto drop_size = params_["drop_size"].value_;
const bool per_channel = params_["per_channel"].value_ <= per_channel_ ? true : false;
CoarseDropout(img, img, p, drop_size, per_channel);
}
public:
DEFINE_AUGMENTATION_CLONE(AugCoarseDropout)
/** @brief AugCoarseDropout constructor
@param[in] p Parameter which determines the range of values [min,max] to randomly select the probability of any rectangle being set to zero.
@param[in] drop_size Parameter which determines the range of values [min,max] to randomly select the size of rectangles in percentage of the input Image.
@param[in] per_channel Probability of each image to use the same value for all channels of a pixel or not.
*/
AugCoarseDropout(const std::array<double, 2>& p, const std::array<double, 2>& drop_size, const double& per_channel) : per_channel_(per_channel)
{
assert(per_channel >= 0 && per_channel <= 1);
params_["p"] = AugmentationParam(p[0], p[1]);
params_["drop_size"] = AugmentationParam(drop_size[0], drop_size[1]);
params_["per_channel"] = AugmentationParam(0, 1);
}
AugCoarseDropout(std::istream& is)
{
auto m = param::read(is, "AugCoarseDropout");
param p;
m.Get("p", param::type::range, true, p);
params_["p"] = AugmentationParam(p.vals_[0], p.vals_[1]);
m.Get("drop_size", param::type::range, true, p);
params_["drop_size"] = AugmentationParam(p.vals_[0], p.vals_[1]);
m.Get("per_channel", param::type::number, true, p);
params_["per_channel"] = AugmentationParam(0, 1);
per_channel_ = p.vals_[0];
}
};
/** @brief Augmentation wrapper for ecvl::Transpose.
@anchor AugTranspose
*/
class AugTranspose : public Augmentation
{
double p_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto p = params_["p"].value_;
if (p <= p_) {
Transpose(img, img);
if (!gt.IsEmpty()) {
Transpose(gt, const_cast<Image&>(gt));
}
}
}
public:
DEFINE_AUGMENTATION_CLONE(AugTranspose)
/** @brief AugTranspose constructor
@param[in] p Probability of each image to get transposed.
*/
AugTranspose(double p = 0.5) : p_{ p }
{
params_["p"] = AugmentationParam(0, 1);
}
AugTranspose(std::istream& is) : AugTranspose()
{
auto m = param::read(is, "AugTranspose");
param p;
if (m.Get("p", param::type::number, false, p)) {
p_ = p.vals_[0];
}
}
};
/** @brief Augmentation wrapper for brightness adjustment.
@anchor AugBrightness
*/
class AugBrightness : public Augmentation
{
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto beta = params_["beta"].value_;
Add(img, beta, img);
}
public:
DEFINE_AUGMENTATION_CLONE(AugBrightness)
/** @brief AugBrightness constructor
@param[in] beta Parameter which determines the range of values [min,max] to randomly select the value for the brightness adjustment.
Suggested values are around 0 to 100.
*/
AugBrightness(const std::array<double, 2>& beta)
{
params_["beta"] = AugmentationParam(beta[0], beta[1]);
}
AugBrightness(std::istream& is)
{
auto m = param::read(is, "AugBrightness");
param p;
m.Get("beta", param::type::range, true, p);
params_["beta"] = AugmentationParam(p.vals_[0], p.vals_[1]);
}
};
/** @brief Augmentation wrapper for ecvl::GridDistortion.
@anchor AugGridDistortion
*/
class AugGridDistortion : public Augmentation
{
std::array<float, 2> distort_limit_;
InterpolationType interp_;
BorderType border_type_;
int border_value_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto num_steps = params_["num_steps"].value_;
const auto seed = params_["seed"].value_;
GridDistortion(img, img, static_cast<int>(num_steps), distort_limit_, interp_, border_type_,
border_value_, static_cast<unsigned>(seed));
if (!gt.IsEmpty()) {
GridDistortion(gt, const_cast<Image&>(gt), static_cast<int>(num_steps), distort_limit_,
interp_, border_type_, border_value_, static_cast<unsigned>(seed));
}
}
public:
DEFINE_AUGMENTATION_CLONE(AugGridDistortion)
/** @brief AugGridDistortion constructor
@param[in] num_steps Parameter which determines the range of values [min,max] to randomly select the number of grid cells on each side.
@param[in] distort_limit Parameter which determines the range of values [min,max] to randomly select the distortion steps.
@param[in] interp InterpolationType to be used. Default is InterpolationType::linear.
@param[in] border_type Flag used to specify the pixel extrapolation method. Default is BorderType::BORDER_REFLECT_101.
@param[in] border_value Integer padding value if border_type is BorderType::BORDER_CONSTANT.
*/
AugGridDistortion(const std::array<int, 2>& num_steps,
const std::array<float, 2>& distort_limit,
const InterpolationType& interp = InterpolationType::linear,
const BorderType& border_type = BorderType::BORDER_REFLECT_101,
const int& border_value = 0)
: distort_limit_(distort_limit), interp_(interp), border_type_(border_type), border_value_(border_value)
{
params_["num_steps"] = AugmentationParam(num_steps[0], num_steps[1]);
params_["seed"] = AugmentationParam(AugmentationParam::seed_min, AugmentationParam::seed_max);
}
AugGridDistortion(std::istream& is)
{
auto m = param::read(is, "AugGridDistortion");
param p;
m.Get("num_steps", param::type::range, true, p);
params_["num_steps"] = AugmentationParam(p.vals_[0], p.vals_[1]);
// seed is managed by AugmentationParam
params_["seed"] = AugmentationParam(AugmentationParam::seed_min, AugmentationParam::seed_max);
m.Get("distort_limit", param::type::range, true, p);
distort_limit_ = { static_cast<float>(p.vals_[0]), static_cast<float>(p.vals_[1]) };
interp_ = InterpolationType::linear;
if (m.Get("interp", param::type::string, false, p)) {
interp_ = StrToInterpolationType(p.str_, "AugGridDistortion");
}
border_type_ = BorderType::BORDER_REFLECT_101;
if (m.Get("border_type", param::type::string, false, p)) {
if (p.str_ == "constant") {
border_type_ = BorderType::BORDER_CONSTANT;
} else if (p.str_ == "replicate") {
border_type_ = BorderType::BORDER_REPLICATE;
} else if (p.str_ == "reflect") {
border_type_ = BorderType::BORDER_REFLECT;
} else if (p.str_ == "wrap") {
border_type_ = BorderType::BORDER_WRAP;
} else if (p.str_ == "reflect_101") {
border_type_ = BorderType::BORDER_REFLECT_101;
} else if (p.str_ == "transparent") {
border_type_ = BorderType::BORDER_TRANSPARENT;
} else {
throw std::runtime_error("AugGridDistortion: invalid border type"); // TODO: standardize
}
}
border_value_ = 0;
m.Get("border_value", param::type::number, false, p);
border_value_ = static_cast<int>(p.vals_[0]);
}
};
/** @brief Augmentation wrapper for ecvl::ElasticTransform.
@anchor AugElasticTransform
*/
class AugElasticTransform : public Augmentation
{
InterpolationType interp_;
BorderType border_type_;
int border_value_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto alpha = params_["alpha"].value_;
const auto sigma = params_["sigma"].value_;
const auto seed = params_["seed"].value_;
ElasticTransform(img, img, alpha, sigma, interp_, border_type_, border_value_, static_cast<unsigned>(seed));
if (!gt.IsEmpty()) {
ElasticTransform(gt, const_cast<Image&>(gt), alpha, sigma, interp_,
border_type_, border_value_, static_cast<unsigned>(seed));
}
}
public:
DEFINE_AUGMENTATION_CLONE(AugElasticTransform)
/** @brief AugElasticTransform constructor
@param[in] alpha Parameter which determines the range of values [min,max] to randomly select the scaling factor that controls the intensity of the deformation.
@param[in] sigma Parameter which determines the range of values [min,max] to randomly select the gaussian kernel standard deviation.
@param[in] interp InterpolationType to be used. Default is InterpolationType::linear.
@param[in] border_type Flag used to specify the pixel extrapolation method. Default is BorderType::BORDER_REFLECT_101.
@param[in] border_value Integer padding value if border_type is BorderType::BORDER_CONSTANT.
*/
AugElasticTransform(const std::array<double, 2>& alpha,
const std::array<double, 2>& sigma,
const InterpolationType& interp = InterpolationType::linear,
const BorderType& border_type = BorderType::BORDER_REFLECT_101,
const int& border_value = 0)
: interp_(interp), border_type_(border_type), border_value_(border_value)
{
params_["alpha"] = AugmentationParam(alpha[0], alpha[1]);
params_["sigma"] = AugmentationParam(sigma[0], sigma[1]);
params_["seed"] = AugmentationParam(AugmentationParam::seed_min, AugmentationParam::seed_max);
}
AugElasticTransform(std::istream& is)
{
auto m = param::read(is, "AugElasticTransform");
param p;
m.Get("alpha", param::type::range, true, p);
params_["alpha"] = AugmentationParam(p.vals_[0], p.vals_[1]);
m.Get("sigma", param::type::range, true, p);
params_["sigma"] = AugmentationParam(p.vals_[0], p.vals_[1]);
// seed is managed by AugmentationParam
params_["seed"] = AugmentationParam(AugmentationParam::seed_min, AugmentationParam::seed_max);
interp_ = InterpolationType::linear;
if (m.Get("interp", param::type::string, false, p)) {
interp_ = StrToInterpolationType(p.str_, "AugElasticTransform");
}
border_type_ = BorderType::BORDER_REFLECT_101;
if (m.Get("border_type", param::type::string, false, p)) {
if (p.str_ == "constant") {
border_type_ = BorderType::BORDER_CONSTANT;
} else if (p.str_ == "replicate") {
border_type_ = BorderType::BORDER_REPLICATE;
} else if (p.str_ == "reflect") {
border_type_ = BorderType::BORDER_REFLECT;
} else if (p.str_ == "wrap") {
border_type_ = BorderType::BORDER_WRAP;
} else if (p.str_ == "reflect_101") {
border_type_ = BorderType::BORDER_REFLECT_101;
} else if (p.str_ == "transparent") {
border_type_ = BorderType::BORDER_TRANSPARENT;
} else {
throw std::runtime_error("AugGridDistortion: invalid border type"); // TODO: standardize
}
}
border_value_ = 0;
m.Get("border_value", param::type::number, false, p);
border_value_ = static_cast<int>(p.vals_[0]);
}
};
/** @brief Augmentation wrapper for ecvl::OpticalDistortion.
@anchor AugOpticalDistortion
*/
class AugOpticalDistortion : public Augmentation
{
std::array<float, 2> distort_limit_;
std::array<float, 2> shift_limit_;
InterpolationType interp_;
BorderType border_type_;
int border_value_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto seed = params_["seed"].value_;
OpticalDistortion(img, img, distort_limit_, shift_limit_, interp_, border_type_,
border_value_, static_cast<unsigned>(seed));
if (!gt.IsEmpty()) {
OpticalDistortion(gt, const_cast<Image&>(gt), distort_limit_, shift_limit_, interp_, border_type_,
border_value_, static_cast<unsigned>(seed));
}
}
public:
DEFINE_AUGMENTATION_CLONE(AugOpticalDistortion)
/** @brief AugOpticalDistortion constructor
@param[in] distort_limit Parameter which determines the range of values [min,max] to randomly select the distortion steps.
@param[in] shift_limit Parameter which determines the range of values [min,max] to randomly select the image shifting.
@param[in] interp InterpolationType to be used. Default is InterpolationType::linear.
@param[in] border_type Flag used to specify the pixel extrapolation method. Default is BorderType::BORDER_REFLECT_101.
@param[in] border_value Integer padding value if border_type is BorderType::BORDER_CONSTANT.
*/
AugOpticalDistortion(const std::array<float, 2>& distort_limit,
const std::array<float, 2>& shift_limit,
const InterpolationType& interp = InterpolationType::linear,
const BorderType& border_type = BorderType::BORDER_REFLECT_101,
const int& border_value = 0)
: distort_limit_(distort_limit), shift_limit_(shift_limit), interp_(interp), border_type_(border_type), border_value_(border_value)
{
params_["seed"] = AugmentationParam(AugmentationParam::seed_min, AugmentationParam::seed_max);
}
AugOpticalDistortion(std::istream& is)
{
auto m = param::read(is, "AugOpticalDistortion");
param p;
// seed is managed by AugmentationParam
params_["seed"] = AugmentationParam(AugmentationParam::seed_min, AugmentationParam::seed_max);
m.Get("distort_limit", param::type::range, true, p);
distort_limit_ = { static_cast<float>(p.vals_[0]), static_cast<float>(p.vals_[1]) };
m.Get("shift_limit", param::type::range, true, p);
shift_limit_ = { static_cast<float>(p.vals_[0]), static_cast<float>(p.vals_[1]) };
interp_ = InterpolationType::linear;
if (m.Get("interp", param::type::string, false, p)) {
interp_ = StrToInterpolationType(p.str_, "AugOpticalDistortion");
}
border_type_ = BorderType::BORDER_REFLECT_101;
if (m.Get("border_type", param::type::string, false, p)) {
if (p.str_ == "constant") {
border_type_ = BorderType::BORDER_CONSTANT;
} else if (p.str_ == "replicate") {
border_type_ = BorderType::BORDER_REPLICATE;
} else if (p.str_ == "reflect") {
border_type_ = BorderType::BORDER_REFLECT;
} else if (p.str_ == "wrap") {
border_type_ = BorderType::BORDER_WRAP;
} else if (p.str_ == "reflect_101") {
border_type_ = BorderType::BORDER_REFLECT_101;
} else if (p.str_ == "transparent") {
border_type_ = BorderType::BORDER_TRANSPARENT;
} else {
throw std::runtime_error("AugGridDistortion: invalid border type"); // TODO: standardize
}
}
border_value_ = 0;
m.Get("border_value", param::type::number, false, p);
border_value_ = static_cast<int>(p.vals_[0]);
}
};
/** @brief Augmentation wrapper for ecvl::Salt.
@anchor AugSalt
*/
class AugSalt : public Augmentation
{
double per_channel_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto p = params_["p"].value_;
const auto seed = params_["seed"].value_;
const bool per_channel = params_["per_channel"].value_ <= per_channel_ ? true : false;
Salt(img, img, p, per_channel, static_cast<unsigned>(seed));
}
public:
DEFINE_AUGMENTATION_CLONE(AugSalt)
/** @brief AugSalt constructor
@param[in] p Parameter which determines the range of values [min,max] to randomly select the probability of any pixel being set to white.
@param[in] per_channel Probability of each image to use the same value for all channels of a pixel or not.
*/
AugSalt(const std::array<double, 2>& p, const double& per_channel) : per_channel_(per_channel)
{
assert(per_channel >= 0 && per_channel <= 1);
params_["p"] = AugmentationParam(p[0], p[1]);
params_["per_channel"] = AugmentationParam(0, 1);
params_["seed"] = AugmentationParam(AugmentationParam::seed_min, AugmentationParam::seed_max);
}
AugSalt(std::istream& is)
{
auto m = param::read(is, "AugSalt");
param p;
// seed is managed by AugmentationParam
params_["seed"] = AugmentationParam(AugmentationParam::seed_min, AugmentationParam::seed_max);
m.Get("p", param::type::range, true, p);
params_["p"] = AugmentationParam(p.vals_[0], p.vals_[1]);
m.Get("per_channel", param::type::number, true, p);
params_["per_channel"] = AugmentationParam(0, 1);
per_channel_ = p.vals_[0];
}
};
/** @brief Augmentation wrapper for ecvl::Pepper.
@anchor AugPepper
*/
class AugPepper : public Augmentation
{
double per_channel_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto p = params_["p"].value_;
const auto seed = params_["seed"].value_;
const bool per_channel = params_["per_channel"].value_ <= per_channel_ ? true : false;
Pepper(img, img, p, per_channel, static_cast<unsigned>(seed));
}
public:
DEFINE_AUGMENTATION_CLONE(AugPepper)
/** @brief AugPepper constructor
@param[in] p Parameter which determines the range of values [min,max] to randomly select the probability of any pixel being set to black.
@param[in] per_channel Probability of each image to use the same value for all channels of a pixel or not.
*/
AugPepper(const std::array<double, 2>& p, const double& per_channel) : per_channel_(per_channel)
{
assert(per_channel >= 0 && per_channel <= 1);
params_["p"] = AugmentationParam(p[0], p[1]);
params_["per_channel"] = AugmentationParam(0, 1);
params_["seed"] = AugmentationParam(AugmentationParam::seed_min, AugmentationParam::seed_max);
}
AugPepper(std::istream& is)
{
auto m = param::read(is, "AugPepper");
param p;
// seed is managed by AugmentationParam
params_["seed"] = AugmentationParam(AugmentationParam::seed_min, AugmentationParam::seed_max);
m.Get("p", param::type::range, true, p);
params_["p"] = AugmentationParam(p.vals_[0], p.vals_[1]);
m.Get("per_channel", param::type::number, true, p);
params_["per_channel"] = AugmentationParam(0, 1);
per_channel_ = p.vals_[0];
}
};
/** @brief Augmentation wrapper for ecvl::SaltAndPepper.
@anchor AugSaltAndPepper
*/
class AugSaltAndPepper : public Augmentation
{
double per_channel_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
const auto p = params_["p"].value_;
const auto seed = params_["seed"].value_;
const bool per_channel = params_["per_channel"].value_ <= per_channel_ ? true : false;
SaltAndPepper(img, img, p, per_channel, static_cast<unsigned>(seed));
}
public:
DEFINE_AUGMENTATION_CLONE(AugSaltAndPepper)
/** @brief AugSaltAndPepper constructor
@param[in] p Parameter which determines the range of values [min,max] to randomly select the probability of any pixel being set to white or black.
@param[in] per_channel Probability of each image to use the same value for all channels of a pixel or not.
*/
AugSaltAndPepper(const std::array<double, 2>& p, const double& per_channel) : per_channel_(per_channel)
{
assert(per_channel >= 0 && per_channel <= 1);
params_["p"] = AugmentationParam(p[0], p[1]);
params_["per_channel"] = AugmentationParam(0, 1);
params_["seed"] = AugmentationParam(AugmentationParam::seed_min, AugmentationParam::seed_max);
}
AugSaltAndPepper(std::istream& is)
{
auto m = param::read(is, "AugSaltAndPepper");
param p;
// seed is managed by AugmentationParam
params_["seed"] = AugmentationParam(AugmentationParam::seed_min, AugmentationParam::seed_max);
m.Get("p", param::type::range, true, p);
params_["p"] = AugmentationParam(p.vals_[0], p.vals_[1]);
m.Get("per_channel", param::type::number, true, p);
params_["per_channel"] = AugmentationParam(0, 1);
per_channel_ = p.vals_[0];
}
};
/** @brief Augmentation wrapper for ecvl::Normalize.
@anchor AugNormalize
*/
class AugNormalize : public Augmentation
{
double mean_ = 0., std_ = 1.;
std::vector<double> ch_mean_;
std::vector<double> ch_std_;
bool per_channel_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
if (per_channel_) {
Normalize(img, img, ch_mean_, ch_std_);
} else {
Normalize(img, img, mean_, std_);
}
}
public:
DEFINE_AUGMENTATION_CLONE(AugNormalize)
/** @brief AugNormalize constructor
@param[in] mean Mean to substract from all pixel.
@param[in] std Standard deviation to use for normalization.
*/
AugNormalize(const double& mean, const double& std) : mean_(mean), std_(std), per_channel_(false) {}
/** @brief AugNormalize constructor with separate statistics for each channel
@param[in] mean Per channel mean to substract from all pixel.
@param[in] std Per channel standard deviation to use for normalization.
*/
AugNormalize(const std::vector<double>& mean, const std::vector<double>& std) : ch_mean_(mean), ch_std_(std), per_channel_(true) {}
AugNormalize(std::istream& is)
{
auto m = param::read(is, "AugNormalize");
param p;
m.GenericGet("mean", true, p);
if (p.type_ == param::type::number) {
mean_ = p.vals_[0];
per_channel_ = false;
} else if (p.type_ == param::type::vector) {
ch_mean_ = p.vals_;
per_channel_ = true;
} else {
throw std::runtime_error("AugNormalize: invalid mean type");
}
if (per_channel_ == false) {
m.Get("std", param::type::number, true, p);
std_ = p.vals_[0];
} else {
m.Get("std", param::type::vector, true, p);
ch_std_ = p.vals_;
}
}
};
/** @brief Augmentation CenterCrop wrapper for ecvl::CenterCrop.
@anchor AugCenterCrop
*/
class AugCenterCrop : public Augmentation
{
std::vector<int> size_;
bool infer_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
std::vector<int> new_size = size_;
if (infer_) {
// TODO: 3D implementation
new_size = std::vector<int>(2, std::min(img.Width(), img.Height()));
}
CenterCrop(img, img, new_size);
if (!gt.IsEmpty()) {
CenterCrop(gt, const_cast<Image&>(gt), new_size);
}
}
public:
DEFINE_AUGMENTATION_CLONE(AugCenterCrop)
/** @brief AugCenterCrop constructor. Crop size is inferred from the minimum image dimension.
\f$
crop\_size = min(Image_{cols}, Image_{rows})
\f$
*/
AugCenterCrop() : infer_{ true } {}
/** @brief AugCenterCrop constructor
@param[in] size std::vector<int> that specifies the new size of each dimension [w,h].
*/
AugCenterCrop(const std::vector<int>& size) : size_{ size }, infer_{ false } {}
AugCenterCrop(std::istream& is)
{
auto m = param::read(is, "AugCenterCrop");
param p;
if (m.Get("size", param::type::vector, false, p)) {
for (const auto& x : p.vals_) {
size_.emplace_back(static_cast<int>(x));
}
infer_ = false;
} else {
infer_ = true;
}
}
};
/** @brief Augmentation ToFloat32
This augmentation converts an Image (and ground truth) to DataType::float32 dividing it by divisor (or divisor_gt) parameter.
@anchor AugToFloat32
*/
class AugToFloat32 : public Augmentation
{
double divisor_, divisor_gt_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
img.ConvertTo(DataType::float32);
img.Div(divisor_);
if (!gt.IsEmpty()) {
const_cast<Image&>(gt).ConvertTo(DataType::float32);
const_cast<Image&>(gt).Div(divisor_gt_);
}
}
public:
DEFINE_AUGMENTATION_CLONE(AugToFloat32)
/** @brief AugToFloat32 constructor
@param[in] divisor Value used to divide the img Image.
@param[in] divisor_gt Value used to divide the gt Image.
*/
AugToFloat32(const double& divisor = 1., const double& divisor_gt = 1.) : divisor_{ divisor }, divisor_gt_{ divisor_gt } {}
AugToFloat32(std::istream& is)
{
auto m = param::read(is, "AugToFloat32");
param p;
m.Get("divisor", param::type::number, false, p);
divisor_ = p.vals_[0];
m.Get("divisor_gt", param::type::number, false, p);
divisor_gt_ = p.vals_[0];
}
};
/** @brief Augmentation DivBy255
This augmentation divides an Image (and ground truth if provided) by 255.
@anchor AugDivBy255
*/
class AugDivBy255 : public Augmentation
{
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
img.Div(255);
if (!gt.IsEmpty()) {
const_cast<Image&>(gt).Div(255);
}
}
public:
DEFINE_AUGMENTATION_CLONE(AugDivBy255)
/** @brief AugDivBy255 constructor */
AugDivBy255() {}
AugDivBy255(std::istream& is) {}
};
/** @brief Augmentation wrapper for ecvl::AugScaleTo.
@anchor AugScaleTo
*/
class AugScaleTo : public Augmentation
{
double new_min_, new_max_;
virtual void RealApply(ecvl::Image& img, const ecvl::Image& gt = Image()) override
{
ScaleTo(img, img, new_min_, new_max_);
}
public:
DEFINE_AUGMENTATION_CLONE(AugScaleTo)
/** @brief AugScaleTo constructor
@param[in] new_min double which indicates the new minimum value.
@param[in] new_max double which indicates the new maximum value.
*/
AugScaleTo(const double& new_min, const double& new_max) : new_min_{ new_min }, new_max_{ new_max } {}
AugScaleTo(std::istream& is)
{
auto m = param::read(is, "AugScaleTo");
param p;
m.Get("new_min", param::type::number, true, p);
new_min_ = p.vals_[0];
m.Get("new_max", param::type::number, true, p);
new_max_ = p.vals_[0];
}
};
} // namespace ecvl
#endif // AUGMENTATIONS_H_ | 33.454606 | 163 | 0.627795 | [
"vector",
"3d"
] |
ad6a931de0ed40ed0ea9de194624e8c0108ea72c | 1,305 | h | C | src/prod/src/query/QueryArgument.h | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/query/QueryArgument.h | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/query/QueryArgument.h | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Query
{
class QueryArgument
{
public:
explicit QueryArgument(std::wstring const & queryArgument, bool isRequired = true, std::wstring const & argumentSets = L"")
: queryArgumentName_(queryArgument), isRequired_(isRequired), argumentSets_()
{
Common::StringUtility::Split<std::wstring>(argumentSets, argumentSets_, L",");
}
__declspec(property(get=get_Name)) std::wstring const & Name;
std::wstring const & get_Name() const { return queryArgumentName_; }
__declspec(property(get=get_IsRequired)) bool IsRequired;
bool get_IsRequired() const { return isRequired_; }
__declspec(property(get=get_ArgumentSets)) std::vector<std::wstring> const & ArgumentSets;
std::vector<std::wstring> const & get_ArgumentSets() const { return argumentSets_; }
private:
std::wstring queryArgumentName_;
bool isRequired_;
std::vector<std::wstring> argumentSets_;
};
}
| 38.382353 | 131 | 0.612261 | [
"vector"
] |
ad75441765ff247af4f16d270b8a1ff98ffdd918 | 1,156 | c | C | d/avatars/helm/scorpwhip.c | gesslar/shadowgate | 97ce5d33a2275bb75c0cf6556602564b7870bc77 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/avatars/helm/scorpwhip.c | gesslar/shadowgate | 97ce5d33a2275bb75c0cf6556602564b7870bc77 | [
"MIT"
] | null | null | null | d/avatars/helm/scorpwhip.c | gesslar/shadowgate | 97ce5d33a2275bb75c0cf6556602564b7870bc77 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include <std.h>
inherit WEAPON;
void create(){
::create();
set_name("whip");
set_id(({ "whip", "scorpion whip", "weapon" }));
set_short("%^RESET%^%^ORANGE%^Scorpion whip%^RESET%^");
set_obvious_short("A nasty bullwhip");
set_long(
@AVATAR
This weapon looks quite the same as an ordinary bullwhip except that the very end of the whip resembles a vicious scorpion stinger. It is made out of quality hide, plaited and treated with skill. It appears to be well made.
AVATAR
);
set_weight(5);
set_value(0);
set_type("slashing");
set_prof_type("whip");
set_size(2);
set_wc(1,8);
set_large_wc(1,8);
set_property("enchantment",2);
set_hit((:TO,"hit_func":));
}
int hit_func(object targ){
if(random(1000) < 200){
tell_room(environment(query_wielded()),"%^RESET%^%^ORANGE%^"+ETOQCN+"'s aim is true and the stinger sinks into the flesh of "+targ->QCN+".%^RESET%^",({ETO,targ}));
tell_object(ETO,"%^RESET%^%^ORANGE%^Your aim is true and the stinger sinks into the flesh of your opponent.%^RESET%^");
tell_object(targ,"%^RESET%^%^ORANGE%^"+ETOQCN+"'s aim is true and the stinger sinks into your flesh.%^RESET%^");
return roll_dice(1,6)+0; }
} | 34 | 223 | 0.694637 | [
"object"
] |
ad78d359236aa6309bd76d1ef80fcd47c2144754 | 1,268 | h | C | include/utilities.h | ialzugaray/EventBasedVisualOdometry | 776545e0970234390ef7fe4da8b55e3af7d90655 | [
"MIT"
] | 56 | 2017-07-08T14:13:54.000Z | 2022-01-08T23:55:20.000Z | include/utilities.h | kazuotani14/EVO | fdadb3752c990f950361923a304ea2ac18464a01 | [
"MIT"
] | 2 | 2017-08-08T03:09:42.000Z | 2020-12-08T07:17:47.000Z | include/utilities.h | kazuotani14/EventBasedVisualOdometry | fdadb3752c990f950361923a304ea2ac18464a01 | [
"MIT"
] | 32 | 2017-08-31T03:36:47.000Z | 2021-04-13T11:37:46.000Z | #ifndef _OPENCV_DEFS_H_
#define _OPENCV_DEFS_H_
#include <vector>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <Eigen/Core>
#include <cv.h>
#include <opencv2/opencv.hpp>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
// Commonly used OpenCV Mat types
#define EVENT_IMAGE_TYPE CV_8U
#define DOUBLE_TYPE CV_64F
typedef pcl::PointCloud<pcl::PointXYZ> PointCloud;
namespace emvs{
// Visualize opencv image, with normalized values so that low values are visible
void showNormalizedImage(std::string window, const cv::Mat& image, int milliseconds=1);
// Quaternion to rotation matrix
cv::Mat quat2rotm(double q_x, double q_y, double q_z, double q_w);
cv::Mat quat2rotm(const Eigen::Vector4d q);
// Make 4x4 homogeneous transformation matrix from relative position and rotation values
cv::Mat makeTransformMatrix(double x, double y, double z, double qx, double qy, double qz, double qw);
// C++ implementation of Matlab linspace
// From: https://gist.github.com/jmbr/2375233
template <typename T>
std::vector<T> linspace(T start, T end, int N)
{
std::vector<T> vec(N);
T h = (end - start) / static_cast<T>(N-1);
vec[0] = start;
for(int i=1; i<N; i++)
vec[i] = vec[i-1] + h;
return vec;
}
} // end namespace emvs
#endif
| 23.481481 | 102 | 0.731073 | [
"vector"
] |
ad7a17f21cafbac488d7d9ea0fe0e0471bdc562f | 19,709 | c | C | src/cos_object.c | kyllikki/libnspdf | d9bf14b9a1a5fa5770808c18d8039da0fb34021c | [
"MIT"
] | 2 | 2017-07-15T15:27:06.000Z | 2019-11-08T18:01:42.000Z | src/cos_object.c | kyllikki/libnspdf | d9bf14b9a1a5fa5770808c18d8039da0fb34021c | [
"MIT"
] | null | null | null | src/cos_object.c | kyllikki/libnspdf | d9bf14b9a1a5fa5770808c18d8039da0fb34021c | [
"MIT"
] | null | null | null | /*
* Copyright 2018 Vincent Sanders <vince@netsurf-browser.org>
*
* This file is part of libnspsl
*
* Licensed under the MIT License,
* http://www.opensource.org/licenses/mit-license.php
*/
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <nspdf/errors.h>
#include "xref.h"
#include "cos_content.h"
#include "cos_object.h"
#include "cos_parse.h"
#include "pdf_doc.h"
static nspdferror cos_dump_object(const char *fmt, struct cos_object *cos_obj)
{
printf("%s\n", fmt);
switch (cos_obj->type) {
case COS_TYPE_NAMETREE:
printf(" type = COS_TYPE_NAMETREE\n");
break;
case COS_TYPE_NUMBERTREE:
printf(" type = COS_TYPE_NUMBERTREE\n");
break;
case COS_TYPE_REFERENCE:
printf(" type = COS_TYPE_REFERENCE\n"
" u.reference->id = %lu\n"
" u.reference->generation = %lu\n",
cos_obj->u.reference->id,
cos_obj->u.reference->generation);
break;
case COS_TYPE_NULL:
printf(" type = COS_TYPE_NULL\n");
break;
case COS_TYPE_CONTENT:
printf(" type = COS_TYPE_CONTENT\n"
" u.content->length = %d\n"
" u.content->alloc = %d\n"
" u.content->operations = %p\n",
cos_obj->u.content->length,
cos_obj->u.content->alloc,
cos_obj->u.content->operations);
break;
case COS_TYPE_BOOL:
printf(" type = COS_TYPE_BOOL\n u.b = %s\n",
cos_obj->u.b ? "true" : "false");
break;
case COS_TYPE_INT:
printf(" type = COS_TYPE_INT\n u.i = %ld\n", cos_obj->u.i);
break;
case COS_TYPE_REAL:
printf(" type = COS_TYPE_REAL\n u.real = %f\n", cos_obj->u.real);
break;
case COS_TYPE_NAME:
printf(" type = COS_TYPE_NAME\n u.name = %s\n", cos_obj->u.name);
break;
case COS_TYPE_STRING:
printf(" type = COS_TYPE_STRING\n");
//free(cos_obj->u.s->data);
//free(cos_obj->u.s);
break;
case COS_TYPE_DICTIONARY:
printf(" type = COS_TYPE_DICTIONARY\n");
/*
dentry = cos_obj->u.dictionary;
while (dentry != NULL) {
struct cos_dictionary_entry *odentry;
cos_free_object(dentry->key);
cos_free_object(dentry->value);
odentry = dentry;
dentry = dentry->next;
free(odentry);
}
*/
break;
case COS_TYPE_ARRAY:
printf(" type = COS_TYPE_ARRAY\n");
/*
if (cos_obj->u.array->alloc > 0) {
for (aentry = 0; aentry < cos_obj->u.array->length; aentry++) {
cos_free_object(*(cos_obj->u.array->values + aentry));
}
free(cos_obj->u.array->values);
}
free(cos_obj->u.array);
*/
break;
case COS_TYPE_STREAM:
printf(" type = COS_TYPE_STREAM\n");
/*
free(cos_obj->u.stream);
*/
break;
}
return NSPDFERROR_OK;
}
nspdferror cos_free_object(struct cos_object *cos_obj)
{
struct cos_dictionary_entry *dentry;
unsigned int aentry;
switch (cos_obj->type) {
case COS_TYPE_NAME:
free(cos_obj->u.name);
break;
case COS_TYPE_STRING:
free(cos_obj->u.s->data);
free(cos_obj->u.s);
break;
case COS_TYPE_DICTIONARY:
dentry = cos_obj->u.dictionary;
while (dentry != NULL) {
struct cos_dictionary_entry *odentry;
cos_free_object(dentry->key);
cos_free_object(dentry->value);
odentry = dentry;
dentry = dentry->next;
free(odentry);
}
break;
case COS_TYPE_ARRAY:
if (cos_obj->u.array->alloc > 0) {
for (aentry = 0; aentry < cos_obj->u.array->length; aentry++) {
cos_free_object(*(cos_obj->u.array->values + aentry));
}
free(cos_obj->u.array->values);
}
free(cos_obj->u.array);
break;
case COS_TYPE_STREAM:
free(cos_obj->u.stream);
break;
}
free(cos_obj);
return NSPDFERROR_OK;
}
/*
* extracts a value for a key in a dictionary.
*
* this finds and returns a value for a given key removing it from a dictionary
*/
nspdferror
cos_extract_dictionary_value(struct nspdf_doc *doc,
struct cos_object *dict,
const char *key,
struct cos_object **value_out)
{
nspdferror res;
res = nspdf__xref_get_referenced(doc, &dict);
if (res == NSPDFERROR_OK) {
if (dict->type != COS_TYPE_DICTIONARY) {
res = NSPDFERROR_TYPE;
} else {
struct cos_dictionary_entry **prev;
struct cos_dictionary_entry *entry;
res = NSPDFERROR_NOTFOUND;
prev = &dict->u.dictionary;
entry = *prev;
while (entry != NULL) {
if (strcmp(entry->key->u.name, key) == 0) {
*value_out = entry->value;
*prev = entry->next;
cos_free_object(entry->key);
free(entry);
res = NSPDFERROR_OK;
break;
}
prev = &entry->next;
entry = *prev;
}
}
}
return res;
}
/*
* get a value for a key from a dictionary
*/
nspdferror
cos_get_dictionary_value(struct nspdf_doc *doc,
struct cos_object *dict,
const char *key,
struct cos_object **value_out)
{
nspdferror res;
struct cos_dictionary_entry *entry;
res = nspdf__xref_get_referenced(doc, &dict);
if (res == NSPDFERROR_OK) {
if (dict->type != COS_TYPE_DICTIONARY) {
res = NSPDFERROR_TYPE;
} else {
res = NSPDFERROR_NOTFOUND;
entry = dict->u.dictionary;
while (entry != NULL) {
if (strcmp(entry->key->u.name, key) == 0) {
*value_out = entry->value;
res = NSPDFERROR_OK;
break;
}
entry = entry->next;
}
}
}
return res;
}
nspdferror
cos_get_dictionary_int(struct nspdf_doc *doc,
struct cos_object *dict,
const char *key,
int64_t *value_out)
{
nspdferror res;
struct cos_object *dict_value;
res = cos_get_dictionary_value(doc, dict, key, &dict_value);
if (res != NSPDFERROR_OK) {
return res;
}
return cos_get_int(doc, dict_value, value_out);
}
nspdferror
cos_get_dictionary_name(struct nspdf_doc *doc,
struct cos_object *dict,
const char *key,
const char **value_out)
{
nspdferror res;
struct cos_object *dict_value;
res = cos_get_dictionary_value(doc, dict, key, &dict_value);
if (res != NSPDFERROR_OK) {
return res;
}
return cos_get_name(doc, dict_value, value_out);
}
nspdferror
cos_get_dictionary_string(struct nspdf_doc *doc,
struct cos_object *dict,
const char *key,
struct cos_string **string_out)
{
nspdferror res;
struct cos_object *dict_value;
res = cos_get_dictionary_value(doc, dict, key, &dict_value);
if (res != NSPDFERROR_OK) {
return res;
}
return cos_get_string(doc, dict_value, string_out);
}
nspdferror
cos_get_dictionary_dictionary(struct nspdf_doc *doc,
struct cos_object *dict,
const char *key,
struct cos_object **value_out)
{
nspdferror res;
struct cos_object *dict_value;
res = cos_get_dictionary_value(doc, dict, key, &dict_value);
if (res != NSPDFERROR_OK) {
return res;
}
return cos_get_dictionary(doc, dict_value, value_out);
}
nspdferror
cos_heritable_dictionary_dictionary(struct nspdf_doc *doc,
struct cos_object *dict,
const char *key,
struct cos_object **value_out)
{
nspdferror res;
struct cos_object *dict_value;
res = cos_get_dictionary_value(doc, dict, key, &dict_value);
if (res == NSPDFERROR_NOTFOUND) {
/* \todo get parent entry and extract key from that dictionary instead */
}
if (res != NSPDFERROR_OK) {
return res;
}
return cos_get_dictionary(doc, dict_value, value_out);
}
/* get an inheritable array object from a dictionary */
nspdferror
cos_get_dictionary_array(struct nspdf_doc *doc,
struct cos_object *dict,
const char *key,
struct cos_object **value_out)
{
nspdferror res;
struct cos_object *dict_value;
res = cos_get_dictionary_value(doc, dict, key, &dict_value);
if (res != NSPDFERROR_OK) {
return res;
}
return cos_get_array(doc, dict_value, value_out);
}
nspdferror
cos_heritable_dictionary_array(struct nspdf_doc *doc,
struct cos_object *dict,
const char *key,
struct cos_object **value_out)
{
nspdferror res;
struct cos_object *dict_value;
res = cos_get_dictionary_value(doc, dict, key, &dict_value);
if (res == NSPDFERROR_NOTFOUND) {
/* \todo get parent entry and extract key from that dictionary instead */
}
if (res != NSPDFERROR_OK) {
return res;
}
return cos_get_array(doc, dict_value, value_out);
}
nspdferror
cos_get_int(struct nspdf_doc *doc,
struct cos_object *cobj,
int64_t *value_out)
{
nspdferror res;
res = nspdf__xref_get_referenced(doc, &cobj);
if (res == NSPDFERROR_OK) {
if (cobj->type != COS_TYPE_INT) {
res = NSPDFERROR_TYPE;
} else {
*value_out = cobj->u.i;
}
}
return res;
}
nspdferror
cos_get_number(struct nspdf_doc *doc,
struct cos_object *cobj,
float *value_out)
{
nspdferror res;
res = nspdf__xref_get_referenced(doc, &cobj);
if (res == NSPDFERROR_OK) {
if (cobj->type == COS_TYPE_INT) {
*value_out = (float)cobj->u.i;
} else if (cobj->type == COS_TYPE_REAL) {
*value_out = cobj->u.real;
} else {
res = NSPDFERROR_TYPE;
}
}
return res;
}
nspdferror
cos_get_name(struct nspdf_doc *doc,
struct cos_object *cobj,
const char **value_out)
{
nspdferror res;
res = nspdf__xref_get_referenced(doc, &cobj);
if (res == NSPDFERROR_OK) {
if (cobj->type != COS_TYPE_NAME) {
res = NSPDFERROR_TYPE;
} else {
*value_out = cobj->u.name;
}
}
return res;
}
nspdferror
cos_get_dictionary(struct nspdf_doc *doc,
struct cos_object *cobj,
struct cos_object **value_out)
{
nspdferror res;
res = nspdf__xref_get_referenced(doc, &cobj);
if (res == NSPDFERROR_OK) {
if (cobj->type != COS_TYPE_DICTIONARY) {
res = NSPDFERROR_TYPE;
} else {
*value_out = cobj;
}
}
return res;
}
nspdferror
cos_get_array(struct nspdf_doc *doc,
struct cos_object *cobj,
struct cos_object **value_out)
{
nspdferror res;
res = nspdf__xref_get_referenced(doc, &cobj);
if (res == NSPDFERROR_OK) {
if (cobj->type != COS_TYPE_ARRAY) {
res = NSPDFERROR_TYPE;
} else {
*value_out = cobj;
}
}
return res;
}
nspdferror
cos_get_string(struct nspdf_doc *doc,
struct cos_object *cobj,
struct cos_string **string_out)
{
nspdferror res;
res = nspdf__xref_get_referenced(doc, &cobj);
if (res == NSPDFERROR_OK) {
if (cobj->type != COS_TYPE_STRING) {
res = NSPDFERROR_TYPE;
} else {
*string_out = cobj->u.s;
}
}
return res;
}
nspdferror
cos_get_stream(struct nspdf_doc *doc,
struct cos_object *cobj,
struct cos_stream **stream_out)
{
nspdferror res;
//printf("%p %d\n", cobj, cobj->type);
res = nspdf__xref_get_referenced(doc, &cobj);
//printf("%p %d res:%d\n", cobj, cobj->type, res);
if (res == NSPDFERROR_OK) {
if (cobj->type != COS_TYPE_STREAM) {
res = NSPDFERROR_TYPE;
} else {
*stream_out = cobj->u.stream;
}
}
return res;
}
/*
* get object from object reference
*/
nspdferror
cos_get_object(struct nspdf_doc *doc,
struct cos_object *cobj,
struct cos_object **value_out)
{
nspdferror res;
res = nspdf__xref_get_referenced(doc, &cobj);
if (res == NSPDFERROR_OK) {
*value_out = cobj;
}
return res;
}
nspdferror
cos_get_rectangle(struct nspdf_doc *doc,
struct cos_object *cobj,
struct cos_rectangle *rect_out)
{
nspdferror res;
struct cos_rectangle rect;
res = nspdf__xref_get_referenced(doc, &cobj);
if (res == NSPDFERROR_OK) {
if ((cobj->type != COS_TYPE_ARRAY) ||
(cobj->u.array->length != 4)) {
res = NSPDFERROR_TYPE;
} else {
res = cos_get_number(doc, cobj->u.array->values[0], &rect.llx);
if (res == NSPDFERROR_OK) {
res = cos_get_number(doc, cobj->u.array->values[1], &rect.lly);
if (res == NSPDFERROR_OK) {
res = cos_get_number(doc, cobj->u.array->values[2], &rect.urx);
if (res == NSPDFERROR_OK) {
res = cos_get_number(doc, cobj->u.array->values[3], &rect.ury);
if (res == NSPDFERROR_OK) {
*rect_out = rect;
}
}
}
}
}
}
return res;
}
/*
* exported interface documented in cos_object.h
*
* slightly different behaviour to other getters:
*
* - This getter can be passed an object pointer to a synthetic parsed content
* stream object in which case it returns that objects content operation
* list.
*
* - Alternatively it can be passed a single indirect object reference to a
* content stream which will be processed into a filtered stream and then
* converted into a parsed content stream which replaces the passed
* object. The underlying filtered streams will then be freed.
*
* - An array of indirect object references to content streams all of which
* will be converted as if a single stream of tokens and the result handled
* as per the single reference case.
*/
nspdferror
cos_get_content(struct nspdf_doc *doc,
struct cos_object *cobj,
struct cos_content **content_out)
{
nspdferror res;
struct cos_object **references;
unsigned int reference_count;
struct cos_stream **streams;
unsigned int index;
struct cos_object *content_obj; /* parsed content object */
struct cos_object tmpobj;
//cos_dump_object("get content of", cobj);
if (cobj->type == COS_TYPE_CONTENT) {
/* already parsed the content stream */
goto cos_get_content_done;
}
if (cobj->type == COS_TYPE_REFERENCE) {
/* single reference */
reference_count = 1;
references = calloc(reference_count, sizeof(struct cos_object *));
if (references == NULL) {
return NSPDFERROR_NOMEM;
}
*references = cobj;
} else if (cobj->type == COS_TYPE_ARRAY) {
/* array of references */
reference_count = cobj->u.array->length;
references = malloc(reference_count * sizeof(struct cos_object *));
if (references == NULL) {
return NSPDFERROR_NOMEM;
}
memcpy(references, cobj->u.array->values, reference_count * sizeof(struct cos_object *));
/* check all objects in array are references */
for (index = 0; index < reference_count ; index++) {
if ((*(references + index))->type != COS_TYPE_REFERENCE) {
free(references);
return NSPDFERROR_TYPE;
}
}
} else {
return NSPDFERROR_TYPE;
}
/* obtain array of streams */
streams = malloc(reference_count * sizeof(struct cos_stream *));
if (streams == NULL) {
free(references);
return NSPDFERROR_TYPE;
}
for (index = 0; index < reference_count ; index++) {
struct cos_object *stream_obj;
stream_obj = *(references + index);
res = nspdf__xref_get_referenced(doc, &stream_obj);
if (res != NSPDFERROR_OK) {
free(references);
free(streams);
return res;
}
if (stream_obj->type != COS_TYPE_STREAM) {
free(references);
free(streams);
return NSPDFERROR_TYPE;
}
*(streams + index) = stream_obj->u.stream;;
}
res = cos_parse_content_streams(doc, streams, reference_count, &content_obj);
if (res != NSPDFERROR_OK) {
free(references);
free(streams);
return res;
}
/* replace passed object with parsed content operations object */
tmpobj = *cobj;
*cobj = *content_obj;
*content_obj = tmpobj;
//cos_dump_object("content object", cobj);
//cos_dump_object("free object", content_obj);
cos_free_object(content_obj);
/** \todo call nspdf__xref_free_referenced(doc, *(references + index)); to free up storage associated with already parsed streams */
cos_get_content_done:
*content_out = cobj->u.content;
return NSPDFERROR_OK;
}
/*
* get a value for a key from a dictionary
*/
nspdferror
cos_get_array_value(struct nspdf_doc *doc,
struct cos_object *array,
unsigned int index,
struct cos_object **value_out)
{
nspdferror res;
res = nspdf__xref_get_referenced(doc, &array);
if (res == NSPDFERROR_OK) {
if (array->type != COS_TYPE_ARRAY) {
res = NSPDFERROR_TYPE;
} else {
if (index >= array->u.array->length) {
res = NSPDFERROR_RANGE;
} else {
*value_out = *(array->u.array->values + index);
}
}
}
return res;
}
nspdferror
cos_get_array_dictionary(struct nspdf_doc *doc,
struct cos_object *array,
unsigned int index,
struct cos_object **value_out)
{
nspdferror res;
struct cos_object *array_value;
res = cos_get_array_value(doc, array, index, &array_value);
if (res != NSPDFERROR_OK) {
return res;
}
return cos_get_dictionary(doc, array_value, value_out);
}
nspdferror
cos_get_array_size(struct nspdf_doc *doc,
struct cos_object *cobj,
unsigned int *size_out)
{
nspdferror res;
res = nspdf__xref_get_referenced(doc, &cobj);
if (res == NSPDFERROR_OK) {
if (cobj->type != COS_TYPE_ARRAY) {
res = NSPDFERROR_TYPE;
} else {
*size_out = cobj->u.array->length;
}
}
return res;
}
| 26.924863 | 136 | 0.559643 | [
"object"
] |
ad7e6fb85b3fc530f91fbb7b01c6d6a856a57381 | 1,772 | h | C | Sources/Elastos/LibCore/inc/org/apache/http/impl/NoConnectionReuseStrategy.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/LibCore/inc/org/apache/http/impl/NoConnectionReuseStrategy.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/LibCore/inc/org/apache/http/impl/NoConnectionReuseStrategy.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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 __ORG_APACHE_HTTP_IMPL_NOCONNECTIONREUSESTRATETY_H__
#define __ORG_APACHE_HTTP_IMPL_NOCONNECTIONREUSESTRATETY_H__
#include "Elastos.CoreLibrary.Apache.h"
#include "elastos/core/Object.h"
using Org::Apache::Http::IConnectionReuseStrategy;
using Org::Apache::Http::IHttpResponse;
using Org::Apache::Http::Protocol::IHttpContext;
namespace Org {
namespace Apache {
namespace Http {
namespace Impl {
/**
* A strategy that never re-uses a connection.
*
* @author <a href="mailto:rolandw at apache.org">Roland Weber</a>
*
* @version $Revision: 502684 $
*
* @since 4.0
*/
class NoConnectionReuseStrategy
: public Object
, public IConnectionReuseStrategy
{
public:
CAR_INTERFACE_DECL()
CARAPI KeepAlive(
/* [in] */ IHttpResponse* response,
/* [in] */ IHttpContext* context,
/* [out] */ Boolean* result);
};
} // namespace Impl
} // namespace Http
} // namespace Apache
} // namespace Org
#endif // __ORG_APACHE_HTTP_IMPL_NOCONNECTIONREUSESTRATETY_H__
| 29.533333 | 75 | 0.668736 | [
"object"
] |
ad805fc7bc5ff9c6034e7afe3285a38c3422a58d | 3,136 | h | C | chromeos/cryptohome/cryptohome_util.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromeos/cryptohome/cryptohome_util.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromeos/cryptohome/cryptohome_util.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROMEOS_CRYPTOHOME_CRYPTOHOME_UTIL_H_
#define CHROMEOS_CRYPTOHOME_CRYPTOHOME_UTIL_H_
#include <string>
#include "base/component_export.h"
#include "base/optional.h"
#include "chromeos/cryptohome/cryptohome_parameters.h"
#include "chromeos/dbus/cryptohome/key.pb.h"
#include "chromeos/dbus/cryptohome/rpc.pb.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace cryptohome {
// Returns a MountError code from the MountEx |reply| returning
// MOUNT_ERROR_NONE if the reply is well-formed and there is no error.
COMPONENT_EXPORT(CHROMEOS_CRYPTOHOME)
MountError MountExReplyToMountError(const base::Optional<BaseReply>& reply);
// Returns a MountError code from |reply|, returning MOUNT_ERROR_NONE
// if the reply is well-formed and there is no error.
COMPONENT_EXPORT(CHROMEOS_CRYPTOHOME)
MountError BaseReplyToMountError(const base::Optional<BaseReply>& reply);
// Returns a MountError code from the GetKeyDataEx |reply| returning
// MOUNT_ERROR_NONE if the reply is well-formed and there is no error.
COMPONENT_EXPORT(CHROMEOS_CRYPTOHOME)
MountError GetKeyDataReplyToMountError(const base::Optional<BaseReply>& reply);
COMPONENT_EXPORT(CHROMEOS_CRYPTOHOME)
std::vector<KeyDefinition> GetKeyDataReplyToKeyDefinitions(
const base::Optional<BaseReply>& reply);
// Extracts the account's disk usage size from |reply|.
// If |reply| is malformed, returns -1.
COMPONENT_EXPORT(CHROMEOS_CRYPTOHOME)
int64_t AccountDiskUsageReplyToUsageSize(
const base::Optional<BaseReply>& reply);
// Extracts the mount hash from |reply|.
// This method assumes |reply| is well-formed. To check if a reply
// is well-formed, callers can check if BaseReplyToMountError returns
// MOUNT_ERROR_NONE.
COMPONENT_EXPORT(CHROMEOS_CRYPTOHOME)
const std::string& MountExReplyToMountHash(const BaseReply& reply);
// Creates an AuthorizationRequest from the given secret and label.
COMPONENT_EXPORT(CHROMEOS_CRYPTOHOME)
AuthorizationRequest CreateAuthorizationRequest(const std::string& label,
const std::string& secret);
// Creates an AuthorizationRequest from the given key definition.
COMPONENT_EXPORT(CHROMEOS_CRYPTOHOME)
AuthorizationRequest CreateAuthorizationRequestFromKeyDef(
const KeyDefinition& key_def);
// Converts the given KeyDefinition to a Key.
COMPONENT_EXPORT(CHROMEOS_CRYPTOHOME)
void KeyDefinitionToKey(const KeyDefinition& key_def, Key* key);
// Converts CryptohomeErrorCode to MountError.
COMPONENT_EXPORT(CHROMEOS_CRYPTOHOME)
MountError CryptohomeErrorToMountError(CryptohomeErrorCode code);
// Converts the given KeyAuthorizationData to AuthorizationData pointed to by
// |authorization_data|.
COMPONENT_EXPORT(CHROMEOS_CRYPTOHOME)
void KeyAuthorizationDataToAuthorizationData(
const KeyAuthorizationData& authorization_data_proto,
KeyDefinition::AuthorizationData* authorization_data);
} // namespace cryptohome
#endif // CHROMEOS_CRYPTOHOME_CRYPTOHOME_UTIL_H_
| 39.696203 | 79 | 0.807079 | [
"vector"
] |
ad84212124a05a59883a8d5f5ea2873fb2f88874 | 4,179 | h | C | model/ownergroup.h | rdffg/bcaa_importer | f92e0b39673b5c557540154d4567c53a15adadcd | [
"Apache-2.0"
] | null | null | null | model/ownergroup.h | rdffg/bcaa_importer | f92e0b39673b5c557540154d4567c53a15adadcd | [
"Apache-2.0"
] | 2 | 2019-05-07T22:49:31.000Z | 2021-08-20T20:03:53.000Z | model/ownergroup.h | rdffg/bcaa_importer | f92e0b39673b5c557540154d4567c53a15adadcd | [
"Apache-2.0"
] | null | null | null | #ifndef OWNERGROUP_H
#define OWNERGROUP_H
#include <QDate>
#include "QDjangoModel.h"
#include "model/folio.h"
#include "model/owner.h"
#include "model/formattedmailingaddress.h"
#define FOLIO_PROPERTY "folio"
#define MAILING_ADDRESS_PROPERTY "mailingAddress"
#define FORMATTED_MAILING_ADDRESS_PROPERTY "formattedMailingAddress"
#define OWNERSHIP_GROUP_ID_PROPERTY "ownershipGroupId"
namespace model {
class Owner;
class FormattedMailingAddress;
class MailingAddress;
class OwnershipGroup : public QDjangoModel
{
Q_OBJECT
Q_PROPERTY(bool assessmentNoticeReturned READ assessmentNoticeReturned WRITE setAssessmentNoticeReturned)
Q_PROPERTY(bool assessmentNoticeSuppressed READ assessmentNoticeSuppressed WRITE setAssessmentNoticeSuppressed)
Q_PROPERTY(QString changeType READ changeType WRITE setChangeType)
Q_PROPERTY(QString changeTypeDescription READ changeTypeDescription WRITE setChangeTypeDescription)
Q_PROPERTY(QDate changeDate READ changeDate WRITE setChangeDate)
Q_PROPERTY(QString changeSource READ changeSource WRITE setChangeSource)
Q_PROPERTY(QString changeSourceDescription READ changeSourceDescription WRITE setChangeSourceDescription)
Q_PROPERTY(model::Folio * folio READ folio WRITE setFolio)
Q_PROPERTY(model::MailingAddress* mailingAddress READ mailingAddress WRITE setMailingAddress)
Q_PROPERTY(model::FormattedMailingAddress* formattedMailingAddress READ formattedMailingAddress WRITE setFormattedMailingAddress)
Q_PROPERTY(QString ownershipGroupId READ ownershipGroupId WRITE setOwnershipGroupId)
Q_CLASSINFO("__meta__", "db_table=ownership_group")
Q_CLASSINFO("assessmentNoticeReturned", "null=true")
Q_CLASSINFO("assessmentNoticeSuppressed", "null=true")
Q_CLASSINFO("changeType", "null=true")
Q_CLASSINFO("changeTypeDescription", "null=true")
Q_CLASSINFO("changeDate", "null=true")
Q_CLASSINFO("changeSource", "null=true")
Q_CLASSINFO("changeSourceDescription", "null=true")
Q_CLASSINFO(OWNERSHIP_GROUP_ID_PROPERTY, "db_column=ownership_group_id null=true")
Q_CLASSINFO(MAILING_ADDRESS_PROPERTY, "db_column=mailing_address_id null=true")
Q_CLASSINFO(FORMATTED_MAILING_ADDRESS_PROPERTY, "db_column=formatted_mailing_address_id null=true")
Q_CLASSINFO(FOLIO_PROPERTY, "on_delete=cascade")
public:
explicit OwnershipGroup(QObject *parent = nullptr);
bool assessmentNoticeReturned() const;
void setAssessmentNoticeReturned(bool returned);
bool assessmentNoticeSuppressed() const;
void setAssessmentNoticeSuppressed(bool suppressed);
QString changeType() const;
void setChangeType(QString changeType);
QString changeTypeDescription() const;
void setChangeTypeDescription(QString descr);
QDate changeDate() const;
void setChangeDate(QDate date);
QString changeSource() const;
void setChangeSource(QString source);
QString changeSourceDescription() const;
void setChangeSourceDescription(QString descr);
Folio *folio() const;
void setFolio(Folio *folio);
std::vector<std::unique_ptr<model::Owner>>& owners();
void setOwners(std::vector<std::unique_ptr<model::Owner>> &owners);
model::FormattedMailingAddress* formattedMailingAddress();
void setFormattedMailingAddress(model::FormattedMailingAddress* addresses);
void setFormattedMailingAddress(std::unique_ptr<model::FormattedMailingAddress> addresses);
model::MailingAddress* mailingAddress();
void setMailingAddress(model::MailingAddress*);
void setMailingAddress(std::unique_ptr<model::MailingAddress> mailingAddress);
void setOwnershipGroupId(QString id);
QString ownershipGroupId() const;
signals:
public slots:
private:
bool m_assessmentNoticeReturned;
bool m_assessmentNoticeSuppressed;
QString m_changeType;
QString m_changeTypeDescription;
QDate m_changeDate;
QString m_changeSource;
QString m_changeSourceDescription;
std::vector<std::unique_ptr<model::Owner> > m_owners;
std::unique_ptr<model::FormattedMailingAddress> m_address;
std::unique_ptr<model::MailingAddress> m_mailingAddress;
QString m_ownershipGroupId;
};
}
#endif // OWNERGROUP_H
| 43.082474 | 133 | 0.798038 | [
"vector",
"model"
] |
ad9045fac351128c25562bd5d3e5086c5cb09f07 | 975 | h | C | atvHelloWorld/include/BackRow/BRMenuItemLayerFactory.h | mgile/atvHelloWorld | 3570f4ec49a8208eb759edae5501be22be43c25e | [
"MIT"
] | 3 | 2015-01-04T14:00:54.000Z | 2017-06-18T04:39:58.000Z | atvHelloWorld/include/BackRow/BRMenuItemLayerFactory.h | iBaa/atvHelloWorld | 3570f4ec49a8208eb759edae5501be22be43c25e | [
"MIT"
] | 3 | 2016-05-17T20:03:23.000Z | 2017-07-20T00:48:48.000Z | eyetv4atv/include/BackRow/BRMenuItemLayerFactory.h | tandrup/eyetv4atv | 58bf879362a0ae36e62c11d18468b84bebdc2e09 | [
"MIT"
] | 2 | 2015-04-07T05:55:33.000Z | 2015-08-05T04:42:38.000Z | /**
* This header is generated by class-dump-z 0.2a.
* class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3.
*
* Source: /System/Library/PrivateFrameworks/BackRow.framework/BackRow
*/
#import "BRSingleton.h"
@class NSArray;
@interface BRMenuItemLayerFactory : BRSingleton {
@private
NSArray *_populators; // 4 = 0x4
}
+ (void)setSingleton:(id)singleton; // 0x31593029
+ (id)singleton; // 0x3159301d
- (id)init; // 0x3160a819
- (id)_populatorForObject:(id)object; // 0x3160a8e1
- (void)dealloc; // 0x3160a7d1
- (id)menuItemForObject:(id)object; // 0x3160a7b9
- (id)menuItemForObject:(id)object delegate:(id)delegate; // 0x3160a75d
- (float)menuItemHeightForObject:(id)object; // 0x3160a7a1
- (float)menuItemHeightForObject:(id)object delegate:(id)delegate; // 0x3160a72d
- (void)registerPopulator:(Class)populator; // 0x31593035
- (id)titleForObject:(id)object; // 0x3160a789
- (id)titleForObject:(id)object delegate:(id)delegate; // 0x3160a701
@end
| 32.5 | 80 | 0.737436 | [
"object"
] |
ad90c8c71d7ab0d361635c3551e4aa3fb2a8f3b0 | 9,596 | h | C | hackathon/hanchuan/sscope/FlyCapture2/gtk64/include/glibmm-2.4/glibmm/optioncontext.h | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | hackathon/hanchuan/sscope/FlyCapture2/gtk64/include/glibmm-2.4/glibmm/optioncontext.h | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2016-12-03T05:33:13.000Z | 2016-12-03T05:33:13.000Z | hackathon/hanchuan/sscope/FlyCapture2/gtk64/include/glibmm-2.4/glibmm/optioncontext.h | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | // -*- c++ -*-
// Generated by gtkmmproc -- DO NOT MODIFY!
#ifndef _GLIBMM_OPTIONCONTEXT_H
#define _GLIBMM_OPTIONCONTEXT_H
/* $Id: optioncontext.hg,v 1.6 2005/01/10 17:42:17 murrayc Exp $ */
/* Copyright (C) 2004 The glibmm Development Team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <glibmm/optionentry.h>
#include <glibmm/optiongroup.h>
#include <glibmm/error.h>
#include <sigc++/signal.h>
#ifndef DOXYGEN_SHOULD_SKIP_THIS
extern "C" { typedef struct _GOptionContext GOptionContext; }
#endif
namespace Glib
{
/** Exception class for options.
*/
class OptionError : public Glib::Error
{
public:
enum Code
{
UNKNOWN_OPTION,
BAD_VALUE,
FAILED
};
OptionError(Code error_code, const Glib::ustring& error_message);
explicit OptionError(GError* gobject);
Code code() const;
#ifndef DOXYGEN_SHOULD_SKIP_THIS
private:
#ifdef GLIBMM_EXCEPTIONS_ENABLED
static void throw_func(GError* gobject);
#else
//When not using exceptions, we just pass the Exception object around without throwing it:
static std::auto_ptr<Glib::Error> throw_func(GError* gobject);
#endif //GLIBMM_EXCEPTIONS_ENABLED
friend void wrap_init(); // uses throw_func()
#endif
};
/** An OptionContext defines which options are accepted by the commandline option parser.
*/
class OptionContext
{
public:
#ifndef DOXYGEN_SHOULD_SKIP_THIS
typedef OptionContext CppObjectType;
typedef GOptionContext BaseObjectType;
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
private:
public:
/** Creates a new option context.
* @param parameter_string A string which is displayed in the first line of --help output, after programname [OPTION...]
*/
explicit OptionContext(const Glib::ustring& parameter_string = Glib::ustring());
//Note that, unlike Glib::Wrap(), this would create a second C++ instance for the same C instance,
//so it should be used carefully. For instance you could not access data in a derived class via this second instance.
explicit OptionContext(GOptionContext* castitem, bool take_ownership = false);
virtual ~OptionContext();
/** Enables or disables automatic generation of <option>--help</option>
* output. By default, g_option_context_parse() recognizes
* <option>--help</option>, <option>-?</option>, <option>--help-all</option>
* and <option>--help-</option><replaceable>groupname</replaceable> and creates
* suitable output to stdout.
*
* @newin2p6
* @param help_enabled <tt>true</tt> to enable <option>--help</option>, <tt>false</tt> to disable it.
*/
void set_help_enabled(bool help_enabled = true);
/** Returns: <tt>true</tt> if automatic help generation is turned on.
* @return <tt>true</tt> if automatic help generation is turned on.
*
* @newin2p6.
*/
bool get_help_enabled() const;
/** Sets whether to ignore unknown options or not. If an argument is
* ignored, it is left in the @a argv array after parsing. By default,
* g_option_context_parse() treats unknown options as error.
*
* This setting does not affect non-option arguments (i.e. arguments
* which don't start with a dash). But note that GOption cannot reliably
* determine whether a non-option belongs to a preceding unknown option.
*
* @newin2p6
* @param ignore_unknown <tt>true</tt> to ignore unknown options, <tt>false</tt> to produce
* an error when unknown options are met.
*/
void set_ignore_unknown_options(bool ignore_unknown = true);
/** Returns: <tt>true</tt> if unknown options are ignored.
* @return <tt>true</tt> if unknown options are ignored.
*
* @newin2p6.
*/
bool get_ignore_unknown_options() const;
/** Parses the command line arguments, recognizing options
* which have been added to @a context. A side-effect of
* calling this function is that g_set_prgname() will be
* called.
*
* If the parsing is successful, any parsed arguments are
* removed from the array and @a argc and @a argv are updated
* accordingly. A '--' option is stripped from @a argv
* unless there are unparsed options before and after it,
* or some of the options after it start with '-'. In case
* of an error, @a argc and @a argv are left unmodified.
*
* If automatic <option>--help</option> support is enabled
* (see g_option_context_set_help_enabled()), and the
* @a argv array contains one of the recognized help options,
* this function will produce help output to stdout and
* call <tt>exit (0)</tt>.
*
* Note that function depends on the
* current locale for
* automatic character set conversion of string and filename
* arguments.
* @param argc A pointer to the number of command line arguments.
* @param argv A pointer to the array of command line arguments.
* @return <tt>true</tt> if the parsing was successful,
* <tt>false</tt> if an error occurred
*
* @newin2p6.
*/
#ifdef GLIBMM_EXCEPTIONS_ENABLED
bool parse(int& argc, char**& argv);
#else
bool parse(int& argc, char**& argv, std::auto_ptr<Glib::Error>& error);
#endif //GLIBMM_EXCEPTIONS_ENABLED
//g_option_context_add_main_entries(), just creates a group internally, adds them to it, and does a set_main_group()
//- a group without callbacks seems to do some simple default parsing.
/** Adds an OptionGroup to the context, so that parsing with context will recognize the options in the group.
* Note that the group will not be copied, so it should exist for as long as the context exists.
*
* @param group The group to add.
*/
void add_group(OptionGroup& group);
/** Sets an OptionGroup as the main group of the context. This has the same effect as calling add_group(), the only
* difference is that the options in the main group are treated differently when generating --help output.
* Note that the group will not be copied, so it should exist for as long as the context exists.
*
* @param group The group to add.
*/
void set_main_group(OptionGroup& group);
//We don't need this (hopefully), and the memory management would be really awkward.
//OptionGroup& get_main_group();
//const OptionGroup& get_main_group() const;
/** Returns: A newly allocated string containing the help text
* @param main_help If <tt>true</tt>, only include the main group.
* @param group The OptionGroup to create help for, or <tt>0</tt>.
* @return A newly allocated string containing the help text
*
* @newin2p14.
*/
Glib::ustring get_help(bool main_help, const OptionGroup& group) const;
//TODO: Documentation.
Glib::ustring get_help(bool main_help = true) const;
GOptionContext* gobj() { return gobject_; }
const GOptionContext* gobj() const { return gobject_; }
/** Adds a string to be displayed in --help output before the list of options. This
* is typically a summary of the program functionality.
*
* Note that the summary is translated (see set_translate_func(),
* set_translation_domain()).
*
* @newin2p14
*/
void set_summary(const Glib::ustring& summary);
/** Returns: the summary
* See set_summary() for more information
* @return The summary
*
* @newin2p14.
*/
Glib::ustring get_summary() const;
/** Adds a string to be displayed in --help output after the list of
* options. This text often includes a bug reporting address.
*
* Note that the summary is translated (see set_translate_func()).
*
* @newin2p14
*/
void set_description(const Glib::ustring& description);
/** Returns: the description
* See set_description() for more information
* @return The description
*
* @newin2p14.
*/
Glib::ustring get_description() const;
/** A convenience function to use gettext() for translating
* user-visible strings.
*
* @newin2p14
*/
void set_translation_domain(const Glib::ustring& domain);
/**
* This function is used to translate user-visible strings, for --help output.
* The function takes an untranslated string and returns a translated string
*/
typedef sigc::slot<Glib::ustring, const Glib::ustring&> SlotTranslate;
/**
* Sets the function which is used to translate user-visible
* strings, for --help output. Different groups can use different functions.
*
* If you are using gettext(), you only need to set the translation domain,
* see set_translation_domain().
*
* @newin2p14
*/
void set_translate_func (const SlotTranslate& slot);
protected:
GOptionContext* gobject_;
bool has_ownership_;
};
} // namespace Glib
#endif /* _GLIBMM_OPTIONCONTEXT_H */
| 33.089655 | 122 | 0.692789 | [
"object"
] |
ad9b738d3906e31da7ae1c224b18141ca9c11657 | 4,537 | h | C | openembedding/client/Connection.h | acmore/OpenEmbedding | 607a47c0543f8108d6390bda83db1fb4f4280a90 | [
"Apache-2.0"
] | 20 | 2021-08-20T10:55:42.000Z | 2022-02-22T12:15:34.000Z | openembedding/client/Connection.h | acmore/OpenEmbedding | 607a47c0543f8108d6390bda83db1fb4f4280a90 | [
"Apache-2.0"
] | null | null | null | openembedding/client/Connection.h | acmore/OpenEmbedding | 607a47c0543f8108d6390bda83db1fb4f4280a90 | [
"Apache-2.0"
] | 5 | 2021-09-12T09:01:03.000Z | 2021-11-01T02:43:00.000Z | #ifndef PARADIGM4_HYPEREMBEDDING_CONNECTION_H
#define PARADIGM4_HYPEREMBEDDING_CONNECTION_H
#include <pico-core/PicoJsonNode.h>
#include <pico-core/RpcServer.h>
#include <pico-core/MasterClient.h>
#include <pico-ps/service/Server.h>
#include <pico-ps/service/Client.h>
#include <pico-ps/common/defs.h>
#include <pico-ps/controller/Controller.h>
#include "Meta.h"
#include "EmbeddingVariableHandle.h"
#include "EnvConfig.h"
namespace paradigm4 {
namespace pico {
namespace embedding {
class Connection {
public:
virtual ~Connection() {};
virtual comm_rank_t global_rank() = 0;
virtual ps::Context* server_context() = 0;
virtual std::vector<int32_t> running_servers() = 0;
virtual ps::Status close_server(int32_t server_id) = 0;
virtual void close_servers() = 0;
virtual ps::Status create_storage(const std::map<int32_t, std::vector<int32_t>>& node_shards, int32_t& storage_id) = 0;
virtual ps::Status delete_storage(int32_t storage_id) = 0;
virtual ps::Status set_storage_restore_uri(int32_t storage_id, const core::URIConfig& uri) = 0;
virtual ps::Status create_storage_handler(int32_t storage_id, std::unique_ptr<EmbeddingStorageHandler>&) = 0;
virtual uint32_t generate_id(const std::string&) = 0;
virtual ps::Status pull_model_meta(const std::string& model_sign, ModelMeta& model_meta) = 0;
virtual const EnvConfig& env_config()const = 0;
void set_default_hadoop_bin(core::URIConfig& uri);
protected:
ps::Status create_operator(int32_t storage_id, const std::string& key,
int32_t& handler_id, std::shared_ptr<ps::Operator>& op);
};
class RpcConnection: public Connection {
public:
RpcConnection(const EnvConfig& env);
~RpcConnection() override;
comm_rank_t global_rank() override {
return _rpc->global_rank();
}
std::unique_ptr<ps::Server> create_server();
std::unique_ptr<ps::Controller> create_controller();
ps::Context* server_context() override {
return _client->context().get();
}
std::vector<int32_t> running_servers()override;
ps::Status close_server(int32_t server_id)override;
void close_servers() override;
ps::Status create_storage(const std::map<int32_t, std::vector<int32_t>>& node_shards, int32_t& storage_id)override;
ps::Status delete_storage(int32_t storage_id)override;
ps::Status create_storage_handler(int32_t storage_id, std::unique_ptr<EmbeddingStorageHandler>& storage)override;
ps::Status set_storage_restore_uri(int32_t storage_id, const core::URIConfig& uri);
uint32_t generate_id(const std::string& name);
ps::Status pull_model_meta(const std::string& model_sign, ModelMeta& model_meta)override;
ps::Status push_model_meta(const ModelMeta& model_meta);
ps::Status update_model_meta(const ModelMeta& model_meta);
ps::Status delete_model_meta(const std::string& model_sign);
std::vector<std::string> list_model();
bool try_lock_model(const std::string& model_sign);
void unlock_model(const std::string& model_sign);
const EnvConfig& env_config()const override {
return _env;
}
core::RpcService* rpc()const {
return _rpc.get();
}
core::MasterClient* master_client()const {
return _master_client.get();
}
private:
template<class T>
ps::Status create_handler(int32_t storage_id, const std::string& key, std::unique_ptr<T>& handler) {
int32_t handler_id = -1;
std::shared_ptr<ps::Operator> op;
CHECK_STATUS_RETURN(create_operator(storage_id, key, handler_id, op));
handler = std::make_unique<T>(storage_id, handler_id, op, _client.get());
return ps::Status();
}
template<class T>
void create_handler_pool(int32_t storage_id, const std::string& key,
ObjectPool<std::unique_ptr<T>>& handler_pool) {
handler_pool = [this, storage_id, key]() {
std::unique_ptr<T> handler;
ps::Status status = create_handler(storage_id, key, handler);
if (!status.ok()) {
SLOG(WARNING) << key << " " << status.ToString();
}
return handler;
};
}
std::string _model_path = "_hyper-embedding-model_";
std::string _model_lock_path = "_hyper-embedding-model-lock_";
std::unique_ptr<core::RpcService> _rpc;
std::unique_ptr<core::MasterClient> _master_client;
std::unique_ptr<core::RpcClient> _rpc_client;
std::unique_ptr<ps::Client> _client;
EnvConfig _env;
};
}
}
}
#endif
| 31.506944 | 123 | 0.698038 | [
"vector",
"model"
] |
adae6f0d893e00b4dd360b0c323a676674334a88 | 1,975 | h | C | CryptocurrencyProject/include/Wallet.h | iljubic/Cryptocurrency | 929e0eeae87231b2e04e72439fa5ab892b7125c3 | [
"MIT"
] | 2 | 2021-12-14T08:14:58.000Z | 2021-12-15T13:55:41.000Z | CryptocurrencyProject/include/Wallet.h | iljubic/Cryptocurrency | 929e0eeae87231b2e04e72439fa5ab892b7125c3 | [
"MIT"
] | null | null | null | CryptocurrencyProject/include/Wallet.h | iljubic/Cryptocurrency | 929e0eeae87231b2e04e72439fa5ab892b7125c3 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <string>
#include <ctime>
#include <sstream>
#include "SHA512.h"
#include "TraceableRingSignature.h"
#include "Node.h"
class Wallet {
private:
// Constants - this is the public data used to generate the public keys (changing these influences difficulty to crack)
const int primeModulus = 2147483647; // Large prime number (max for int type) - used in the Diffie Hellman Exchange
const int generator = 3; // Used with the primeModulus to implement the Diffie Hellman Exchange
// Counters
int transactionCounter = 0; // The number of transactions the wallet has completed
int validationCounter = 0; // The number of blocks/transaction that the node linked to this wallet has validated
// Inputted Data
std::string username; // The wallet username - used in the creation of the Private Key
std::string password; // The wallet password - used in the creation of the Private Key
std::time_t timestamp; // The time the wallet was created - used in the creation of the Private Key
Node node; // Every wallet acts as a node
double balance; // The balance of the wallet - starts at 0 when the wallet is generated
std::string privateKey; // The private key - generated by hashing the username, password and timestamp
std::string publicKey; // The public key - generated by hashing the privateKey with readily available public data
void generatePrivateKey(); // Private Key is generated from password, timestamp and username
void generatePublicKey(); // Public Key is generated from the private key combined with readily available public data on the Blockchain
public:
Wallet(time_t t, std::string user, std::string pass);
void sendTransaction(double amount, std::size_t receiverAddress); // Transfers balance from wallet to wallet on the blockchain through the use of Traceable Ring Signatures
// Getters
int getTransactionCounter();
int getValidationCounter();
std::string getPublicKey();
};
| 43.888889 | 172 | 0.757975 | [
"vector"
] |
adb923457f8c02098c33bcad07aa3a30140241f8 | 11,902 | h | C | memory.h | sdrea/bdi | 0cc2753d923859af92800548976ea6293c9f169e | [
"CECILL-B"
] | 1 | 2019-04-04T03:33:36.000Z | 2019-04-04T03:33:36.000Z | simplesim-3.0/memory.h | syang2forever/ComputerArchitecture | 2d840b7665b23028e7f69003364bc0b59cd5dc36 | [
"MIT"
] | null | null | null | simplesim-3.0/memory.h | syang2forever/ComputerArchitecture | 2d840b7665b23028e7f69003364bc0b59cd5dc36 | [
"MIT"
] | null | null | null | /* memory.h - flat memory space interfaces */
/* SimpleScalar(TM) Tool Suite
* Copyright (C) 1994-2003 by Todd M. Austin, Ph.D. and SimpleScalar, LLC.
* All Rights Reserved.
*
* THIS IS A LEGAL DOCUMENT, BY USING SIMPLESCALAR,
* YOU ARE AGREEING TO THESE TERMS AND CONDITIONS.
*
* No portion of this work may be used by any commercial entity, or for any
* commercial purpose, without the prior, written permission of SimpleScalar,
* LLC (info@simplescalar.com). Nonprofit and noncommercial use is permitted
* as described below.
*
* 1. SimpleScalar is provided AS IS, with no warranty of any kind, express
* or implied. The user of the program accepts full responsibility for the
* application of the program and the use of any results.
*
* 2. Nonprofit and noncommercial use is encouraged. SimpleScalar may be
* downloaded, compiled, executed, copied, and modified solely for nonprofit,
* educational, noncommercial research, and noncommercial scholarship
* purposes provided that this notice in its entirety accompanies all copies.
* Copies of the modified software can be delivered to persons who use it
* solely for nonprofit, educational, noncommercial research, and
* noncommercial scholarship purposes provided that this notice in its
* entirety accompanies all copies.
*
* 3. ALL COMMERCIAL USE, AND ALL USE BY FOR PROFIT ENTITIES, IS EXPRESSLY
* PROHIBITED WITHOUT A LICENSE FROM SIMPLESCALAR, LLC (info@simplescalar.com).
*
* 4. No nonprofit user may place any restrictions on the use of this software,
* including as modified by the user, by any other authorized user.
*
* 5. Noncommercial and nonprofit users may distribute copies of SimpleScalar
* in compiled or executable form as set forth in Section 2, provided that
* either: (A) it is accompanied by the corresponding machine-readable source
* code, or (B) it is accompanied by a written offer, with no time limit, to
* give anyone a machine-readable copy of the corresponding source code in
* return for reimbursement of the cost of distribution. This written offer
* must permit verbatim duplication by anyone, or (C) it is distributed by
* someone who received only the executable form, and is accompanied by a
* copy of the written offer of source code.
*
* 6. SimpleScalar was developed by Todd M. Austin, Ph.D. The tool suite is
* currently maintained by SimpleScalar LLC (info@simplescalar.com). US Mail:
* 2395 Timbercrest Court, Ann Arbor, MI 48105.
*
* Copyright (C) 1994-2003 by Todd M. Austin, Ph.D. and SimpleScalar, LLC.
*/
#ifndef MEMORY_H
#define MEMORY_H
#include <stdio.h>
#include "host.h"
#include "misc.h"
#include "machine.h"
#include "options.h"
#include "stats.h"
/* number of entries in page translation hash table (must be power-of-two) */
#define MEM_PTAB_SIZE (32*1024)
#define MEM_LOG_PTAB_SIZE 15
/* page table entry */
struct mem_pte_t {
struct mem_pte_t *next; /* next translation in this bucket */
md_addr_t tag; /* virtual page number tag */
byte_t *page; /* page pointer */
};
/* memory object */
struct mem_t {
/* memory object state */
char *name; /* name of this memory space */
struct mem_pte_t *ptab[MEM_PTAB_SIZE];/* inverted page table */
/* memory object stats */
counter_t page_count; /* total number of pages allocated */
counter_t ptab_misses; /* total first level page tbl misses */
counter_t ptab_accesses; /* total page table accesses */
};
/* memory access command */
enum mem_cmd {
Read, /* read memory from target (simulated prog) to host */
Write /* write memory from host (simulator) to target */
};
/* memory access function type, this is a generic function exported for the
purpose of access the simulated vitual memory space */
typedef enum md_fault_type
(*mem_access_fn)(struct mem_t *mem, /* memory space to access */
enum mem_cmd cmd, /* Read or Write */
md_addr_t addr, /* target memory address to access */
void *p, /* where to copy to/from */
int nbytes); /* transfer length in bytes */
/*
* virtual to host page translation macros
*/
/* compute page table set */
#define MEM_PTAB_SET(ADDR) \
(((ADDR) >> MD_LOG_PAGE_SIZE) & (MEM_PTAB_SIZE - 1))
/* compute page table tag */
#define MEM_PTAB_TAG(ADDR) \
((ADDR) >> (MD_LOG_PAGE_SIZE + MEM_LOG_PTAB_SIZE))
/* convert a pte entry at idx to a block address */
#define MEM_PTE_ADDR(PTE, IDX) \
(((PTE)->tag << (MD_LOG_PAGE_SIZE + MEM_LOG_PTAB_SIZE)) \
| ((IDX) << MD_LOG_PAGE_SIZE))
/* locate host page for virtual address ADDR, returns NULL if unallocated */
#define MEM_PAGE(MEM, ADDR) \
(/* first attempt to hit in first entry, otherwise call xlation fn */ \
((MEM)->ptab[MEM_PTAB_SET(ADDR)] \
&& (MEM)->ptab[MEM_PTAB_SET(ADDR)]->tag == MEM_PTAB_TAG(ADDR)) \
? (/* hit - return the page address on host */ \
(MEM)->ptab_accesses++, \
(MEM)->ptab[MEM_PTAB_SET(ADDR)]->page) \
: (/* first level miss - call the translation helper function */ \
mem_translate((MEM), (ADDR))))
/* compute address of access within a host page */
#define MEM_OFFSET(ADDR) ((ADDR) & (MD_PAGE_SIZE - 1))
/* memory tickle function, allocates pages when they are first written */
#define MEM_TICKLE(MEM, ADDR) \
(!MEM_PAGE(MEM, ADDR) \
? (/* allocate page at address ADDR */ \
mem_newpage(MEM, ADDR)) \
: (/* nada... */ (void)0))
/* memory page iterator */
#define MEM_FORALL(MEM, ITER, PTE) \
for ((ITER)=0; (ITER) < MEM_PTAB_SIZE; (ITER)++) \
for ((PTE)=(MEM)->ptab[i]; (PTE) != NULL; (PTE)=(PTE)->next)
/*
* memory accessors macros, fast but difficult to debug...
*/
/* safe version, works only with scalar types */
/* FIXME: write a more efficient GNU C expression for this... */
#define MEM_READ(MEM, ADDR, TYPE) \
(MEM_PAGE(MEM, (md_addr_t)(ADDR)) \
? *((TYPE *)(MEM_PAGE(MEM, (md_addr_t)(ADDR)) + MEM_OFFSET(ADDR))) \
: /* page not yet allocated, return zero value */ 0)
/* unsafe version, works with any type */
#define __UNCHK_MEM_READ(MEM, ADDR, TYPE) \
(*((TYPE *)(MEM_PAGE(MEM, (md_addr_t)(ADDR)) + MEM_OFFSET(ADDR))))
/* safe version, works only with scalar types */
/* FIXME: write a more efficient GNU C expression for this... */
#define MEM_WRITE(MEM, ADDR, TYPE, VAL) \
(MEM_TICKLE(MEM, (md_addr_t)(ADDR)), \
*((TYPE *)(MEM_PAGE(MEM, (md_addr_t)(ADDR)) + MEM_OFFSET(ADDR))) = (VAL))
/* unsafe version, works with any type */
#define __UNCHK_MEM_WRITE(MEM, ADDR, TYPE, VAL) \
(*((TYPE *)(MEM_PAGE(MEM, (md_addr_t)(ADDR)) + MEM_OFFSET(ADDR))) = (VAL))
/* fast memory accessor macros, typed versions */
#define MEM_READ_BYTE(MEM, ADDR) MEM_READ(MEM, ADDR, byte_t)
#define MEM_READ_SBYTE(MEM, ADDR) MEM_READ(MEM, ADDR, sbyte_t)
#define MEM_READ_HALF(MEM, ADDR) MD_SWAPH(MEM_READ(MEM, ADDR, half_t))
#define MEM_READ_SHALF(MEM, ADDR) MD_SWAPH(MEM_READ(MEM, ADDR, shalf_t))
#define MEM_READ_WORD(MEM, ADDR) MD_SWAPW(MEM_READ(MEM, ADDR, word_t))
#define MEM_READ_SWORD(MEM, ADDR) MD_SWAPW(MEM_READ(MEM, ADDR, sword_t))
#ifdef HOST_HAS_QWORD
#define MEM_READ_QWORD(MEM, ADDR) MD_SWAPQ(MEM_READ(MEM, ADDR, qword_t))
#define MEM_READ_SQWORD(MEM, ADDR) MD_SWAPQ(MEM_READ(MEM, ADDR, sqword_t))
#endif /* HOST_HAS_QWORD */
#define MEM_WRITE_BYTE(MEM, ADDR, VAL) MEM_WRITE(MEM, ADDR, byte_t, VAL)
#define MEM_WRITE_SBYTE(MEM, ADDR, VAL) MEM_WRITE(MEM, ADDR, sbyte_t, VAL)
#define MEM_WRITE_HALF(MEM, ADDR, VAL) \
MEM_WRITE(MEM, ADDR, half_t, MD_SWAPH(VAL))
#define MEM_WRITE_SHALF(MEM, ADDR, VAL) \
MEM_WRITE(MEM, ADDR, shalf_t, MD_SWAPH(VAL))
#define MEM_WRITE_WORD(MEM, ADDR, VAL) \
MEM_WRITE(MEM, ADDR, word_t, MD_SWAPW(VAL))
#define MEM_WRITE_SWORD(MEM, ADDR, VAL) \
MEM_WRITE(MEM, ADDR, sword_t, MD_SWAPW(VAL))
#define MEM_WRITE_SFLOAT(MEM, ADDR, VAL) \
MEM_WRITE(MEM, ADDR, sfloat_t, MD_SWAPW(VAL))
#define MEM_WRITE_DFLOAT(MEM, ADDR, VAL) \
MEM_WRITE(MEM, ADDR, dfloat_t, MD_SWAPQ(VAL))
#ifdef HOST_HAS_QWORD
#define MEM_WRITE_QWORD(MEM, ADDR, VAL) \
MEM_WRITE(MEM, ADDR, qword_t, MD_SWAPQ(VAL))
#define MEM_WRITE_SQWORD(MEM, ADDR, VAL) \
MEM_WRITE(MEM, ADDR, sqword_t, MD_SWAPQ(VAL))
#endif /* HOST_HAS_QWORD */
/* create a flat memory space */
struct mem_t *
mem_create(char *name); /* name of the memory space */
/* translate address ADDR in memory space MEM, returns pointer to host page */
byte_t *
mem_translate(struct mem_t *mem, /* memory space to access */
md_addr_t addr); /* virtual address to translate */
/* allocate a memory page */
void
mem_newpage(struct mem_t *mem, /* memory space to allocate in */
md_addr_t addr); /* virtual address to allocate */
/* generic memory access function, it's safe because alignments and permissions
are checked, handles any natural transfer sizes; note, faults out if nbytes
is not a power-of-two or larger then MD_PAGE_SIZE */
enum md_fault_type
mem_access(struct mem_t *mem, /* memory space to access */
enum mem_cmd cmd, /* Read (from sim mem) or Write */
md_addr_t addr, /* target address to access */
void *vp, /* host memory address to access */
int nbytes); /* number of bytes to access */
/* register memory system-specific statistics */
void
mem_reg_stats(struct mem_t *mem, /* memory space to declare */
struct stat_sdb_t *sdb); /* stats data base */
/* initialize memory system, call before loader.c */
void
mem_init(struct mem_t *mem); /* memory space to initialize */
/* dump a block of memory, returns any faults encountered */
enum md_fault_type
mem_dump(struct mem_t *mem, /* memory space to display */
md_addr_t addr, /* target address to dump */
int len, /* number bytes to dump */
FILE *stream); /* output stream */
/*
* memory accessor routines, these routines require a memory access function
* definition to access memory, the memory access function provides a "hook"
* for programs to instrument memory accesses, this is used by various
* simulators for various reasons; for the default operation - direct access
* to the memory system, pass mem_access() as the memory access function
*/
/* copy a '\0' terminated string to/from simulated memory space, returns
the number of bytes copied, returns any fault encountered */
enum md_fault_type
mem_strcpy(mem_access_fn mem_fn, /* user-specified memory accessor */
struct mem_t *mem, /* memory space to access */
enum mem_cmd cmd, /* Read (from sim mem) or Write */
md_addr_t addr, /* target address to access */
char *s); /* host memory string buffer */
/* copy NBYTES to/from simulated memory space, returns any faults */
enum md_fault_type
mem_bcopy(mem_access_fn mem_fn, /* user-specified memory accessor */
struct mem_t *mem, /* memory space to access */
enum mem_cmd cmd, /* Read (from sim mem) or Write */
md_addr_t addr, /* target address to access */
void *vp, /* host memory address to access */
int nbytes); /* number of bytes to access */
/* copy NBYTES to/from simulated memory space, NBYTES must be a multiple
of 4 bytes, this function is faster than mem_bcopy(), returns any
faults encountered */
enum md_fault_type
mem_bcopy4(mem_access_fn mem_fn, /* user-specified memory accessor */
struct mem_t *mem, /* memory space to access */
enum mem_cmd cmd, /* Read (from sim mem) or Write */
md_addr_t addr, /* target address to access */
void *vp, /* host memory address to access */
int nbytes); /* number of bytes to access */
/* zero out NBYTES of simulated memory, returns any faults encountered */
enum md_fault_type
mem_bzero(mem_access_fn mem_fn, /* user-specified memory accessor */
struct mem_t *mem, /* memory space to access */
md_addr_t addr, /* target address to access */
int nbytes); /* number of bytes to clear */
#endif /* MEMORY_H */
| 40.62116 | 79 | 0.698538 | [
"object"
] |
14aec3eaf0605531b4420ecd885366084a7d051b | 14,690 | h | C | ProcessLib/HydroMechanics/HydroMechanicsProcess-impl.h | zj39kevin/OGS | b616bbfe4a161759990c1453fcbbb465c9910b93 | [
"BSD-4-Clause"
] | null | null | null | ProcessLib/HydroMechanics/HydroMechanicsProcess-impl.h | zj39kevin/OGS | b616bbfe4a161759990c1453fcbbb465c9910b93 | [
"BSD-4-Clause"
] | null | null | null | ProcessLib/HydroMechanics/HydroMechanicsProcess-impl.h | zj39kevin/OGS | b616bbfe4a161759990c1453fcbbb465c9910b93 | [
"BSD-4-Clause"
] | null | null | null | /**
* \copyright
* Copyright (c) 2012-2018, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#pragma once
#include <cassert>
#include "MeshLib/Elements/Utils.h"
#include "NumLib/DOF/ComputeSparsityPattern.h"
#include "ProcessLib/HydroMechanics/CreateLocalAssemblers.h"
#include "ProcessLib/Process.h"
#include "HydroMechanicsFEM.h"
#include "HydroMechanicsProcessData.h"
#include "HydroMechanicsProcess.h"
namespace ProcessLib
{
namespace HydroMechanics
{
template <int DisplacementDim>
HydroMechanicsProcess<DisplacementDim>::HydroMechanicsProcess(
MeshLib::Mesh& mesh,
std::unique_ptr<ProcessLib::AbstractJacobianAssembler>&& jacobian_assembler,
std::vector<std::unique_ptr<ParameterBase>> const& parameters,
unsigned const integration_order,
std::vector<std::vector<std::reference_wrapper<ProcessVariable>>>&&
process_variables,
HydroMechanicsProcessData<DisplacementDim>&& process_data,
SecondaryVariableCollection&& secondary_variables,
NumLib::NamedFunctionCaller&& named_function_caller,
bool const use_monolithic_scheme)
: Process(mesh, std::move(jacobian_assembler), parameters,
integration_order, std::move(process_variables),
std::move(secondary_variables), std::move(named_function_caller),
use_monolithic_scheme),
_process_data(std::move(process_data))
{
}
template <int DisplacementDim>
bool HydroMechanicsProcess<DisplacementDim>::isLinear() const
{
return false;
}
template <int DisplacementDim>
MathLib::MatrixSpecifications
HydroMechanicsProcess<DisplacementDim>::getMatrixSpecifications(
const int process_id) const
{
// For the monolithic scheme or the M process (deformation) in the staggered
// scheme.
if (_use_monolithic_scheme || process_id == 1)
{
auto const& l = *_local_to_global_index_map;
return {l.dofSizeWithoutGhosts(), l.dofSizeWithoutGhosts(),
&l.getGhostIndices(), &this->_sparsity_pattern};
}
// For staggered scheme and H process (pressure).
auto const& l = *_local_to_global_index_map_with_base_nodes;
return {l.dofSizeWithoutGhosts(), l.dofSizeWithoutGhosts(),
&l.getGhostIndices(), &_sparsity_pattern_with_linear_element};
}
template <int DisplacementDim>
void HydroMechanicsProcess<DisplacementDim>::constructDofTable()
{
// Create single component dof in every of the mesh's nodes.
_mesh_subset_all_nodes =
std::make_unique<MeshLib::MeshSubset>(_mesh, &_mesh.getNodes());
// Create single component dof in the mesh's base nodes.
_base_nodes = MeshLib::getBaseNodes(_mesh.getElements());
_mesh_subset_base_nodes =
std::make_unique<MeshLib::MeshSubset>(_mesh, &_base_nodes);
// TODO move the two data members somewhere else.
// for extrapolation of secondary variables of stress or strain
std::vector<MeshLib::MeshSubsets> all_mesh_subsets_single_component;
all_mesh_subsets_single_component.emplace_back(
_mesh_subset_all_nodes.get());
_local_to_global_index_map_single_component =
std::make_unique<NumLib::LocalToGlobalIndexMap>(
std::move(all_mesh_subsets_single_component),
// by location order is needed for output
NumLib::ComponentOrder::BY_LOCATION);
if (_use_monolithic_scheme)
{
// For pressure, which is the first
std::vector<MeshLib::MeshSubsets> all_mesh_subsets;
all_mesh_subsets.emplace_back(_mesh_subset_base_nodes.get());
// For displacement.
const int monolithic_process_id = 0;
std::generate_n(
std::back_inserter(all_mesh_subsets),
getProcessVariables(monolithic_process_id)[1]
.get()
.getNumberOfComponents(),
[&]() {
return MeshLib::MeshSubsets{_mesh_subset_all_nodes.get()};
});
std::vector<int> const vec_n_components{1, DisplacementDim};
_local_to_global_index_map =
std::make_unique<NumLib::LocalToGlobalIndexMap>(
std::move(all_mesh_subsets), vec_n_components,
NumLib::ComponentOrder::BY_LOCATION);
assert(_local_to_global_index_map);
}
else
{
// For displacement equation.
const int process_id = 1;
std::vector<MeshLib::MeshSubsets> all_mesh_subsets;
std::generate_n(
std::back_inserter(all_mesh_subsets),
getProcessVariables(process_id)[0].get().getNumberOfComponents(),
[&]() {
return MeshLib::MeshSubsets{_mesh_subset_all_nodes.get()};
});
std::vector<int> const vec_n_components{DisplacementDim};
_local_to_global_index_map =
std::make_unique<NumLib::LocalToGlobalIndexMap>(
std::move(all_mesh_subsets), vec_n_components,
NumLib::ComponentOrder::BY_LOCATION);
// For pressure equation.
// Collect the mesh subsets with base nodes in a vector.
std::vector<MeshLib::MeshSubsets> all_mesh_subsets_base_nodes;
all_mesh_subsets_base_nodes.emplace_back(_mesh_subset_base_nodes.get());
_local_to_global_index_map_with_base_nodes =
std::make_unique<NumLib::LocalToGlobalIndexMap>(
std::move(all_mesh_subsets_base_nodes),
// by location order is needed for output
NumLib::ComponentOrder::BY_LOCATION);
_sparsity_pattern_with_linear_element = NumLib::computeSparsityPattern(
*_local_to_global_index_map_with_base_nodes, _mesh);
assert(_local_to_global_index_map);
assert(_local_to_global_index_map_with_base_nodes);
}
}
template <int DisplacementDim>
void HydroMechanicsProcess<DisplacementDim>::initializeConcreteProcess(
NumLib::LocalToGlobalIndexMap const& dof_table,
MeshLib::Mesh const& mesh,
unsigned const integration_order)
{
const int mechanical_process_id = _use_monolithic_scheme ? 0 : 1;
const int deformation_variable_id = _use_monolithic_scheme ? 1 : 0;
ProcessLib::HydroMechanics::createLocalAssemblers<
DisplacementDim, HydroMechanicsLocalAssembler>(
mesh.getDimension(), mesh.getElements(), dof_table,
// use displacement process variable to set shape function order
getProcessVariables(mechanical_process_id)[deformation_variable_id]
.get()
.getShapeFunctionOrder(),
_local_assemblers, mesh.isAxiallySymmetric(), integration_order,
_process_data);
Base::_secondary_variables.addSecondaryVariable(
"sigma_xx",
makeExtrapolator(1, getExtrapolator(), _local_assemblers,
&LocalAssemblerInterface::getIntPtSigmaXX));
Base::_secondary_variables.addSecondaryVariable(
"sigma_yy",
makeExtrapolator(1, getExtrapolator(), _local_assemblers,
&LocalAssemblerInterface::getIntPtSigmaYY));
Base::_secondary_variables.addSecondaryVariable(
"sigma_zz",
makeExtrapolator(1, getExtrapolator(), _local_assemblers,
&LocalAssemblerInterface::getIntPtSigmaZZ));
Base::_secondary_variables.addSecondaryVariable(
"sigma_xy",
makeExtrapolator(1, getExtrapolator(), _local_assemblers,
&LocalAssemblerInterface::getIntPtSigmaXY));
if (DisplacementDim == 3)
{
Base::_secondary_variables.addSecondaryVariable(
"sigma_xz",
makeExtrapolator(1, getExtrapolator(), _local_assemblers,
&LocalAssemblerInterface::getIntPtSigmaXZ));
Base::_secondary_variables.addSecondaryVariable(
"sigma_yz",
makeExtrapolator(1, getExtrapolator(), _local_assemblers,
&LocalAssemblerInterface::getIntPtSigmaYZ));
}
Base::_secondary_variables.addSecondaryVariable(
"epsilon_xx",
makeExtrapolator(1, getExtrapolator(), _local_assemblers,
&LocalAssemblerInterface::getIntPtEpsilonXX));
Base::_secondary_variables.addSecondaryVariable(
"epsilon_yy",
makeExtrapolator(1, getExtrapolator(), _local_assemblers,
&LocalAssemblerInterface::getIntPtEpsilonYY));
Base::_secondary_variables.addSecondaryVariable(
"epsilon_zz",
makeExtrapolator(1, getExtrapolator(), _local_assemblers,
&LocalAssemblerInterface::getIntPtEpsilonZZ));
Base::_secondary_variables.addSecondaryVariable(
"epsilon_xy",
makeExtrapolator(1, getExtrapolator(), _local_assemblers,
&LocalAssemblerInterface::getIntPtEpsilonXY));
Base::_secondary_variables.addSecondaryVariable(
"velocity",
makeExtrapolator(mesh.getDimension(), getExtrapolator(),
_local_assemblers,
&LocalAssemblerInterface::getIntPtDarcyVelocity));
}
template <int DisplacementDim>
void HydroMechanicsProcess<DisplacementDim>::initializeBoundaryConditions()
{
if (_use_monolithic_scheme)
{
const int process_id_of_hydromechancs = 0;
initializeProcessBoundaryConditionsAndSourceTerms(
*_local_to_global_index_map, process_id_of_hydromechancs);
return;
}
// Staggered scheme:
// for the equations of pressure
const int hydraulic_process_id = 0;
initializeProcessBoundaryConditionsAndSourceTerms(
*_local_to_global_index_map_with_base_nodes, hydraulic_process_id);
// for the equations of deformation.
const int mechanical_process_id = 1;
initializeProcessBoundaryConditionsAndSourceTerms(
*_local_to_global_index_map, mechanical_process_id);
}
template <int DisplacementDim>
void HydroMechanicsProcess<DisplacementDim>::assembleConcreteProcess(
const double t, GlobalVector const& x, GlobalMatrix& M, GlobalMatrix& K,
GlobalVector& b)
{
DBUG("Assemble the equations for HydroMechanics");
// Note: This assembly function is for the Picard nonlinear solver. Since
// only the Newton-Raphson method is employed to simulate coupled HM
// processes in this class, this function is actually not used so far.
std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>>
dof_table = {std::ref(*_local_to_global_index_map)};
// Call global assembler for each local assembly item.
GlobalExecutor::executeMemberDereferenced(
_global_assembler, &VectorMatrixAssembler::assemble, _local_assemblers,
dof_table, t, x, M, K, b, _coupled_solutions);
}
template <int DisplacementDim>
void HydroMechanicsProcess<DisplacementDim>::
assembleWithJacobianConcreteProcess(const double t, GlobalVector const& x,
GlobalVector const& xdot,
const double dxdot_dx,
const double dx_dx, GlobalMatrix& M,
GlobalMatrix& K, GlobalVector& b,
GlobalMatrix& Jac)
{
std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>>
dof_tables;
// For the monolithic scheme
if (_use_monolithic_scheme)
{
DBUG(
"Assemble the Jacobian of HydroMechanics for the monolithic"
" scheme.");
dof_tables.emplace_back(*_local_to_global_index_map);
}
else
{
// For the staggered scheme
if (_coupled_solutions->process_id == 0)
{
DBUG(
"Assemble the Jacobian equations of liquid fluid process in "
"HydroMechanics for the staggered scheme.");
}
else
{
DBUG(
"Assemble the Jacobian equations of mechanical process in "
"HydroMechanics for the staggered scheme.");
}
dof_tables.emplace_back(*_local_to_global_index_map_with_base_nodes);
dof_tables.emplace_back(*_local_to_global_index_map);
}
GlobalExecutor::executeMemberDereferenced(
_global_assembler, &VectorMatrixAssembler::assembleWithJacobian,
_local_assemblers, dof_tables, t, x, xdot, dxdot_dx, dx_dx, M, K, b,
Jac, _coupled_solutions);
}
template <int DisplacementDim>
void HydroMechanicsProcess<DisplacementDim>::preTimestepConcreteProcess(
GlobalVector const& x, double const t, double const dt,
const int process_id)
{
DBUG("PreTimestep HydroMechanicsProcess.");
_process_data.dt = dt;
_process_data.t = t;
if (hasMechanicalProcess(process_id))
GlobalExecutor::executeMemberOnDereferenced(
&LocalAssemblerInterface::preTimestep, _local_assemblers,
*_local_to_global_index_map, x, t, dt);
}
template <int DisplacementDim>
void HydroMechanicsProcess<DisplacementDim>::postTimestepConcreteProcess(
GlobalVector const& x, const int process_id)
{
DBUG("PostTimestep HydroMechanicsProcess.");
GlobalExecutor::executeMemberOnDereferenced(
&LocalAssemblerInterface::postTimestep, _local_assemblers,
getDOFTable(process_id), x);
}
template <int DisplacementDim>
void HydroMechanicsProcess<DisplacementDim>::postNonLinearSolverConcreteProcess(
GlobalVector const& x, const double t, const int process_id)
{
if (!hasMechanicalProcess(process_id))
{
return;
}
DBUG("PostNonLinearSolver HydroMechanicsProcess.");
// Calculate strain, stress or other internal variables of mechanics.
GlobalExecutor::executeMemberOnDereferenced(
&LocalAssemblerInterface::postNonLinearSolver, _local_assemblers,
getDOFTable(process_id), x, t, _use_monolithic_scheme);
}
template <int DisplacementDim>
std::tuple<NumLib::LocalToGlobalIndexMap*, bool>
HydroMechanicsProcess<DisplacementDim>::getDOFTableForExtrapolatorData() const
{
const bool manage_storage = false;
return std::make_tuple(_local_to_global_index_map_single_component.get(),
manage_storage);
}
template <int DisplacementDim>
NumLib::LocalToGlobalIndexMap const&
HydroMechanicsProcess<DisplacementDim>::getDOFTable(const int process_id) const
{
if (hasMechanicalProcess(process_id))
{
return *_local_to_global_index_map;
}
// For the equation of pressure
return *_local_to_global_index_map_with_base_nodes;
}
} // namespace HydroMechanics
} // namespace ProcessLib
| 38.155844 | 80 | 0.691219 | [
"mesh",
"shape",
"vector"
] |
14c9d29cef00dc9ace8c328ffff576d76178f588 | 26,525 | h | C | src/fabric_van.h | dmitrygx/ps-lite | c62cca03b6697f12933a1c19fd503b08436d80c7 | [
"Apache-2.0"
] | null | null | null | src/fabric_van.h | dmitrygx/ps-lite | c62cca03b6697f12933a1c19fd503b08436d80c7 | [
"Apache-2.0"
] | null | null | null | src/fabric_van.h | dmitrygx/ps-lite | c62cca03b6697f12933a1c19fd503b08436d80c7 | [
"Apache-2.0"
] | null | null | null |
// Copyright 2020 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.
// 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 PS_FABRIC_VAN_H_
#define PS_FABRIC_VAN_H_
#ifdef DMLC_USE_FABRIC
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <poll.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <zmq.h>
#include <sys/uio.h>
#include <algorithm>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <thread>
#include <tuple>
#include <unordered_map>
#include <vector>
#include "ps/internal/threadsafe_queue.h"
#include "ps/internal/van.h"
#include "van_common.h"
#include "fabric_transport.h"
#include "fabric_utils.h"
#include <rdma/fi_errno.h>
#include <rdma/fabric.h>
#include <rdma/fi_endpoint.h>
#include <rdma/fi_cm.h>
#include <rdma/fi_tagged.h>
namespace ps {
class FabricTransport;
struct FabricMemoryAllocator;
struct FabricEndpoint;
std::string hostport_str(const std::string& host, const int port) {
return host + ":" + std::to_string(port);
}
static_assert(std::is_pod<RendezvousMsg>::value,
"RendezvousMsg must be a POD type.");
class FabricVan : public Van {
public:
FabricVan() {
struct fi_info *hints = nullptr;
int fi_version, ret;
// set hints for capacity and modes, create fabric, domain and cq
hints = fi_allocinfo();
CHECK(hints != nullptr) << "Failed to allocate hints";
// hints to filter providers
hints->ep_attr->type = FI_EP_RDM;
hints->caps = FI_TAGGED | FI_MSG | FI_DIRECTED_RECV;
hints->mode = FI_CONTEXT;
hints->domain_attr->av_type = FI_AV_TABLE;
hints->domain_attr->control_progress = FI_PROGRESS_MANUAL;
hints->domain_attr->data_progress = FI_PROGRESS_MANUAL;
hints->tx_attr->msg_order = FI_ORDER_SAS;
hints->rx_attr->msg_order = FI_ORDER_SAS;
// request for EFA as the provider
hints->fabric_attr->prov_name = strdup("efa");
fi_version = FI_VERSION(1, 8);
// fi_getinfo
ret = fi_getinfo(fi_version, nullptr, 0, 0, hints, &info_);
CHECK_NE(ret, -FI_ENODATA) << "Could not find any optimal provider";
check_err(ret, "fi_getinfo failed");
struct fi_info* providers = info_;
while (providers) {
LOG(INFO) << "Found a fabric provider " << providers->fabric_attr->prov_name;
providers = providers->next;
}
}
~FabricVan() {
PS_VLOG(3) << "~FabricVan";
}
virtual std::string GetType() const {
return std::string("fabric");
}
protected:
void Start(int customer_id, bool standalone) override {
start_mu_.lock();
should_stop_ = false;
should_stop_polling_ = false;
auto val = Environment::Get()->find("DMLC_ROLE");
std::string role(val);
LOG(INFO) << "This is a " << role;
start_mu_.unlock();
zmq_ = Van::Create("zmq");
zmq_->Start(customer_id, true);
Van::Start(customer_id, false);
}
void Stop() override {
PS_VLOG(1) << "Stopping " << my_node_.ShortDebugString();
// stop zmq van
{
std::lock_guard<std::mutex> lk(endpoints_mu_);
std::string hostport = hostport_str(my_node_.hostname, my_node_.port);
if (zmq_connections_.find(hostport) != zmq_connections_.end()) {
int id = zmq_connections_[hostport];
Message exit;
exit.meta.control.cmd = Control::TERMINATE;
exit.meta.recver = id;
// only customer 0 would call this method
exit.meta.customer_id = 0;
int ret = zmq_->SendMsg(exit);
CHECK_NE(ret, -1);
}
}
should_stop_ = true;
Van::Stop();
PS_VLOG(1) << "Stopping event_polling_thread_";
event_polling_thread_->join();
event_polling_thread_.reset();
PS_VLOG(1) << "Clearing endpoints.";
{
std::lock_guard<std::mutex> lk(endpoints_mu_);
for (auto& t : workers_) {
t.second->join();
}
// endpoint must be cleared after thread->join
worker_endpoints_.clear();
}
// free fabric info
fi_freeinfo(info_);
}
int Bind(const Node &node, int max_retry) override {
std::lock_guard<std::mutex> lk(endpoints_mu_);
int my_port = zmq_->Bind(node, max_retry);
PS_VLOG(3) << "Done zmq->Bind. My port is " << my_port;
event_polling_thread_.reset(new std::thread(&FabricVan::EventPollingThread, this));
return my_port;
}
void Connect(const Node &node) override {
CHECK_NE(node.id, node.kEmpty);
CHECK_NE(node.port, node.kEmpty);
CHECK(node.hostname.size());
PS_VLOG(3) << "Connect: " << node.DebugString() << " from " << my_node_.DebugString();
// worker doesn't need to connect to the other workers. same for server
if ((node.role == my_node_.role) && (node.id != my_node_.id)) {
PS_VLOG(3) << "Fabric skipped connection to " << node.DebugString()
<< ". My node is " << my_node_.DebugString();
return;
}
if (node.id != Node::kEmpty) {
FabricEndpoint *endpoint = GetOrCreateEndpoint(node.hostname, node.port, node.role);
// set node id
endpoint->SetNodeID(node.id);
int connection_id = endpoint->connection_id;
while (endpoint->status != FabricEndpoint::CONNECTED) {
std::unique_lock<std::mutex> lk(endpoint->status_mu);
endpoint->status = FabricEndpoint::CONNECTING;
// addr_request message
Message req;
req.meta.recver = connection_id;
req.meta.control.cmd = Control::ADDR_REQUEST;
Node req_info;
req_info.role = my_node_.role;
req_info.hostname = my_node_.hostname;
req_info.port = my_node_.port;
req_info.id = my_node_.id;
// auxilary id for tracking connection requests
req_info.aux_id = node.id;
endpoint->fabric_ctx->addr.CopyTo(req_info.endpoint_name,
&req_info.endpoint_name_len);
req.meta.control.node.push_back(req_info);
zmq_->Send(req);
endpoint->status_cv.wait(lk, [endpoint] {
return endpoint->status != FabricEndpoint::CONNECTING;
});
if (endpoint->status == FabricEndpoint::CONNECTED) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
}
int SendMsg(Message &msg) override {
int remote_id = msg.meta.recver;
PS_VLOG(3) << "SendMsg: " << msg.DebugString() << " to node " << remote_id;
CHECK_NE(remote_id, Node::kEmpty);
endpoints_mu_.lock();
CHECK_NE(endpoints_.find(remote_id), endpoints_.end()) << remote_id << " v.s. " << EndpointsDebugStr();
FabricEndpoint *endpoint = endpoints_[remote_id];
endpoints_mu_.unlock();
int meta_len = GetPackMetaLen(msg.meta);
size_t data_len = msg.meta.data_size;
size_t total_len = meta_len + data_len;
CHECK(meta_len);
// pack meta info
if (IsValidPushpull(msg)) {
AddMeta(msg);
}
// push the request to corresponding send queue
endpoint->send_queue.Push(msg);
return total_len;
}
int RecvMsg(Message *msg) override {
msg->data.clear();
// recv the meta first
FabricBufferContext* buffer_ctx;
recv_buffers_.WaitAndPop(&buffer_ctx);
FabricEndpoint *endpoint = buffer_ctx->endpoint;
msg->meta.recver = my_node_.id;
msg->meta.sender = endpoint->node_id;
// the second argument is actually deprecated,
// we keep it as is in order to be compatible
UnpackMeta(buffer_ctx->meta_buffer, buffer_ctx->meta_len, &msg->meta);
int meta_len = GetPackMetaLen(msg->meta);
int total_len = 0;
total_len += meta_len;
auto trans = CHECK_NOTNULL(endpoint->GetTransport());
// PrintRecvLog(msg, buffer_ctx, meta_len);
if (!IsValidPushpull(*msg)) {
if (should_stop_.load()) {
PS_VLOG(3) << "set should_stop_polling_ = true";
should_stop_polling_ = true;
}
return total_len;
}
// valid data message
if (msg->meta.push && msg->meta.request) {
// push request
CHECK_NE(msg->meta.sender, Node::kEmpty);
total_len += trans->RecvPushRequest(msg, buffer_ctx, meta_len);
// StoreWorkerTensorAddress(msg);
} else if (!msg->meta.push && msg->meta.request) {
// pull request
total_len += trans->RecvPullRequest(msg, buffer_ctx, meta_len);
} else if (msg->meta.push && !msg->meta.request) {
// push response
CHECK_NE(msg->meta.sender, Node::kEmpty);
total_len += trans->RecvPushResponse(msg, buffer_ctx, meta_len);
} else if (!msg->meta.push && !msg->meta.request) {
// pull response
total_len += trans->RecvPullResponse(msg, buffer_ctx, meta_len);
} else {
CHECK(0) << "unknown msg type";
}
if (should_stop_.load()) {
VLOG(3) << "set should_stop_polling_ = true";
should_stop_polling_ = true;
}
return total_len;
}
inline void SetNode(const Node& node) {
my_node_ = node;
zmq_->SetNode(node);
}
private:
std::string EndpointsDebugStr() const {
std::stringstream ss;
ss << "{";
for (auto it = endpoints_.begin(); it != endpoints_.end(); it++) {
ss << std::to_string(it->first) << ",";
}
ss << "}";
return ss.str();
}
void PrintRecvLog(Message *msg, FabricBufferContext *buffer_ctx, int meta_len) {
std::lock_guard<std::mutex> lock(log_mu_);
if (!IsValidPushpull(*msg)) {
PS_VLOG(4) << "Recv Control Message" << std::flush;
} else if (msg->meta.push && msg->meta.request) {
// push request
PS_VLOG(4) << "Recv Push Request: key=" << msg->meta.key
<< "\t timestamp=" << msg->meta.timestamp
<< "\t sender=" << msg->meta.sender
<< "\t tensor_len=" << buffer_ctx->data_len[1]
<< std::flush;
} else if (!msg->meta.push && msg->meta.request) {
// pull request
PS_VLOG(4) << "Recv Pull Request: key=" << msg->meta.key
<< "\t timestamp=" << msg->meta.timestamp
<< "\t sender=" << msg->meta.sender
<< std::flush;
} else if (msg->meta.push && !msg->meta.request) {
// push response
PS_VLOG(4) << "Recv Push Response: key=" << msg->meta.key
<< "\t timestamp=" << msg->meta.timestamp
<< "\t sender=" << msg->meta.sender
<< std::flush;
} else if (!msg->meta.push && !msg->meta.request) {
// pull response
PS_VLOG(4) << "Recv Pull Response: key=" << msg->meta.key
<< "\t timestamp=" << msg->meta.timestamp
<< "\t sender=" << msg->meta.sender
<< "\t tensor_len=" << msg->meta.val_len;
}
}
FabricMessageBuffer* PrepareNewMsgBuf(Message& msg, FabricEndpoint *endpoint) {
FabricMessageBuffer *msg_buf = new FabricMessageBuffer();
auto meta_len = GetPackMetaLen(msg.meta);
msg_buf->inline_len = meta_len;
size_t meta_size = 0;
msg_buf->inline_buf = endpoint->mem_allocator->Alloc(meta_len, &meta_size);
msg_buf->data = msg.data;
PackMeta(msg.meta, &(msg_buf->inline_buf), &meta_len);
// prepare send context
FabricWRContext* ctx = new FabricWRContext();
ctx->type = kSendWithData;
msg_buf->reserved_context = ctx;
ctx->private_data = msg_buf;
void *data_buff = nullptr;
size_t data_size = 0;
if (msg.data.size() != 0) {
// pull response / push request : size = 3
// push response / pull request : size = 2
CHECK_GE(msg.data.size(), 2) << "Unexpected number of data: " << msg.data.size();
data_buff = static_cast<char*>(msg.data[1].data());
data_size = msg.data[1].size();
}
PrepareWRContext(ctx, msg_buf->inline_buf, meta_size, data_buff, data_size);
return msg_buf;
}
void AddMeta(Message &msg) {
if (msg.meta.request) {
msg.meta.key = DecodeKey(msg.data[0]);
// push request
if (msg.meta.push) {
CHECK_EQ(msg.data.size(), 3) << msg.data.size();
msg.meta.val_len = msg.data[1].size();
}
}
}
void ReleaseWRContext(FabricWRContext *context, FabricEndpoint *endpoint) {
switch (context->type) {
case kSendRendStart:
endpoint->free_start_ctx.Push(context);
break;
case kSendRendReply:
endpoint->free_reply_ctx.Push(context);
break;
case kSendWithData:
endpoint->StoreRemoteContext(reinterpret_cast<FabricMessageBuffer *>(context->private_data), context);
break;
case kReceiveWithData:
endpoint->PostRecv(context);
break;
case kReceiveRend:
endpoint->PostRecv(context);
break;
default:
CHECK(0);
}
}
void HandleCQError(struct fid_cq *cq) {
struct fi_cq_err_entry err_entry;
int ret = fi_cq_readerr(cq, &err_entry, 1);
if (ret == FI_EADDRNOTAVAIL) {
LOG(WARNING) << "fi_cq_readerr: FI_EADDRNOTAVAIL";
} else if (ret < 0) {
LOG(FATAL) << "fi_cq_readerr failed. Return Code: " << ret
<< ". ERROR: "
<< fi_cq_strerror(cq, err_entry.prov_errno,
err_entry.err_data, nullptr,
err_entry.err_data_size);
} else {
check_err(-err_entry.err, "fi_cq_read failed. retrieved error: ");
}
}
std::string EntryDebugStr(const struct fi_cq_tagged_entry& cq_entry) const {
uint64_t flags = cq_entry.flags;
bool is_send = flags & FI_SEND;
bool is_recv = flags & FI_RECV;
uint64_t tag = cq_entry.tag;
std::stringstream ss;
ss << "op_context = " << cq_entry.op_context
<< ", flags = " << flags;
if (is_send) ss << " sent ";
if (is_recv) ss << " received ";
bool start_msg = tag == kRendezvousStartMask;
bool reply_msg = tag == kRendezvousReplyMask;
bool data_msg = not start_msg and not reply_msg;
if (data_msg) ss << "a control message. tag = " << tag;
if (start_msg) ss << "a rendevous start message";
if (reply_msg) ss << "a rendevous reply message";
return ss.str();
}
void HandleCompletionEvent(const struct fi_cq_tagged_entry& cq_entry, FabricEndpoint *endpoint) {
uint64_t flags = cq_entry.flags;
bool is_tagged = flags & FI_TAGGED;
bool is_send = flags & FI_SEND;
bool is_recv = flags & FI_RECV;
CHECK(is_tagged) << "Completion events must be tagged";
uint64_t tag = cq_entry.tag;
// op_context is the local context
PS_VLOG(5) << EntryDebugStr(cq_entry);
FabricWRContext *context = static_cast<FabricWRContext *>(cq_entry.op_context);
CHECK_NE(context, nullptr) << "FabricWRContext should not be null: " << context;
CHECK_EQ(context->buffers[0].iov_base, cq_entry.buf) << "buffer address does not match";
bool start_msg = (tag == kRendezvousStartMask);
bool reply_msg = (tag == kRendezvousReplyMask);
bool data_msg = !start_msg && !reply_msg;
if (is_send) {
ReleaseWRContext(context, endpoint);
} else if (is_recv) {
// receive
if (start_msg) {
// kRendezvousStart
RendezvousMsg *req = static_cast<RendezvousMsg*>(context->buffers[0].iov_base);
auto trans = CHECK_NOTNULL(endpoint->GetTransport());
trans->SendRendezvousReply(req, endpoint->addr_pool);
ReleaseWRContext(context, endpoint);
} else if (data_msg) {
// the tag is the address of the buffer context posted for recving
FabricBufferContext *buf_ctx = endpoint->addr_pool.GetAddress(tag);
recv_buffers_.Push(buf_ctx);
ReleaseWRContext(context, buf_ctx->endpoint);
} else {
RendezvousMsg *req = static_cast<RendezvousMsg*>(context->buffers[0].iov_base);
// kRendezvousReply
uint64_t origin_addr = req->origin_addr;
FabricMessageBuffer *msg_buf =
reinterpret_cast<FabricMessageBuffer *>(origin_addr);
CHECK(msg_buf != nullptr);
FabricWRContext* send_context = msg_buf->reserved_context;
// now we know which tag to use to reach the peer
send_context->tag = req->tag;
endpoint->StoreRemoteContext(msg_buf, send_context);
// PrintSendLog(*msg, msg_buf, addr_tuple);
auto trans = CHECK_NOTNULL(endpoint->GetTransport());
trans->Send(send_context);
ReleaseWRContext(context, endpoint);
}
} else {
LOG(FATAL) << "unknown completion entry" << flags;
}
}
FabricEndpoint* WorkerCreateEndpoint(const std::string hostname, const int port,
const Node::Role role, fi_info* info) {
FabricEndpoint* endpoint = nullptr;
{
const std::string hostport = hostport_str(hostname, port);
// initialize context
std::lock_guard<std::mutex> lk(endpoints_mu_);
endpoint = worker_endpoints_[hostport].get();
CHECK(endpoint != nullptr);
// init fabric_ctx
PS_VLOG(3) << "Initializing a fabric endpoint";
endpoint->Create(hostport, info);
// init zmq connection
int connection_id = 10000 + zmq_connections_.size();
Node conn_node;
conn_node.role = role;
conn_node.id = connection_id;
conn_node.hostname = hostname;
conn_node.port = port;
zmq_->Connect(conn_node);
zmq_connections_.emplace(hostport, connection_id);
endpoint->connection_id = connection_id;
}
// unblock other threads waiting for this endpoint
{
std::lock_guard<std::mutex> lk(endpoint->status_mu);
endpoint->status = FabricEndpoint::IDLE;
}
endpoint->status_cv.notify_all();
return endpoint;
}
void WorkerInitPeerAddr(FabricEndpoint* endpoint) {
// wait for peer addr
PS_VLOG(4) << "wait peer addr info to initialize the endpoint";
{
std::unique_lock<std::mutex> lk(endpoint->addr_mu);
endpoint->addr_cv.wait(lk, [endpoint] {
return endpoint->peer_addr_ready;
});
}
endpoint->Init();
}
void WorkerSendMsg(FabricEndpoint* endpoint) {
Message msg;
endpoint->send_queue.WaitAndPop(&msg);
int meta_len = GetPackMetaLen(msg.meta);
auto trans = CHECK_NOTNULL(endpoint->GetTransport());
// start rendezvous if no remote info
if (!IsValidPushpull(msg)) {
FabricMessageBuffer *msg_buf = PrepareNewMsgBuf(msg, endpoint);
endpoint->StoreMsgBuf(msg_buf, msg);
trans->SendRendezvousBegin(msg, msg_buf);
return;
} else {
auto is_push = msg.meta.push;
auto key = msg.meta.key;
// store address if this is a pull request for zero-copy pull
if (!is_push && msg.meta.request) endpoint->StorePullAddr(msg);
if (!endpoint->HasRemoteInfo(key, is_push)) {
FabricMessageBuffer *msg_buf = PrepareNewMsgBuf(msg, endpoint);
endpoint->StoreMsgBuf(msg_buf, msg);
trans->SendRendezvousBegin(msg, msg_buf);
PS_VLOG(6) << "SendRendezvousBegin " << msg.DebugString();
return;
}
}
auto context_tuple = endpoint->GetRemoteContext(msg.meta.key, msg.meta.push);
FabricWRContext *ctx = std::get<0>(context_tuple); // WR context
FabricMessageBuffer *msg_buf = std::get<1>(context_tuple); // local message buffer
// prepare new meta and data
CHECK_EQ(msg_buf->inline_len, (size_t) meta_len);
CHECK(msg_buf->inline_buf);
msg_buf->data = msg.data; // may not need this
// the meta data might change. e.g. timestamp
PackMeta(msg.meta, &(msg_buf->inline_buf), &meta_len);
// PrintSendLog(msg, msg_buf, addr_tuple);
// knew remote address, directly send
trans->Send(ctx);
}
void WorkerPollCQ(FabricEndpoint* endpoint, struct fi_cq_tagged_entry *cq_entries) {
int ret = fi_cq_read(endpoint->fabric_ctx->cq, cq_entries, kMaxConcurrentWorkRequest);
if (ret == -FI_EAGAIN) {
return;
} else if (ret == -FI_EAVAIL) {
HandleCQError(endpoint->fabric_ctx->cq);
} else if (ret < 0) {
check_err(ret, "fi_cq_read failed");
} else {
CHECK_NE(ret, 0) << "at least one completion event is expected";
PS_VLOG(3) << ret << " completion events ... ";
for (int i = 0; i < ret; ++i) {
const auto& cq_entry = cq_entries[i];
HandleCompletionEvent(cq_entry, endpoint);
}
}
}
void WorkerThread(const std::string hostname, const int port, const Node::Role role) {
FabricEndpoint* endpoint = WorkerCreateEndpoint(hostname, port, role, info_);
WorkerInitPeerAddr(endpoint);
// Pre-allocated work completions array used for polling
struct fi_cq_tagged_entry cq_entries[kMaxConcurrentWorkRequest];
// non-blocking loop
while (!should_stop_polling_.load()) {
if (endpoint->send_queue.Size()) {
WorkerSendMsg(endpoint);
}
// read from completion queue
WorkerPollCQ(endpoint, cq_entries);
}
PS_VLOG(1) << "WorkerThread exited " << hostname << ":" << port;
}
void EventPollingThread() {
while (true) {
Message msg;
int recv_bytes = zmq_->RecvMsg(&msg);
CHECK_NE(recv_bytes, -1) << "unexpected message size " << recv_bytes;
PS_VLOG(3) << "zmq recv: " << msg.DebugString();
CHECK(!msg.meta.control.empty()) << "msg.meta.control is empty";
auto &ctrl = msg.meta.control;
if (ctrl.cmd == Control::ADDR_REQUEST) {
OnConnectRequest(msg);
} else if (ctrl.cmd == Control::ADDR_RESOLVED) {
OnConnected(msg);
} else if (ctrl.cmd == Control::TERMINATE) {
break;
} else {
LOG(FATAL) << "Drop unknown typed message " << msg.DebugString();
}
}
PS_VLOG(1) << "EventPollingThread exited";
}
FabricEndpoint* GetOrCreateEndpoint(const std::string& host, const int port, Node::Role role) {
const std::string hostport = hostport_str(host, port);
FabricEndpoint* endpoint;
// create worker thread
{
std::lock_guard<std::mutex> lk(endpoints_mu_);
if (workers_.find(hostport) == workers_.end()) {
CHECK(worker_endpoints_.find(hostport) == worker_endpoints_.end());
worker_endpoints_[hostport].reset(new FabricEndpoint());
auto thread = new std::thread(&FabricVan::WorkerThread, this,
host, port, role);
workers_[hostport].reset(thread);
}
endpoint = worker_endpoints_[hostport].get();
}
CHECK(endpoint != nullptr);
// wait for endpoint context to be initialized
{
std::unique_lock<std::mutex> lk(endpoint->status_mu);
endpoint->status_cv.wait(lk, [endpoint] {
return endpoint->status != FabricEndpoint::EMPTY;
});
}
return endpoint;
};
void OnConnectRequest(const Message &msg) {
// start worker thread if necessary
const auto& req_info = msg.meta.control.node[0];
PS_VLOG(3) << "EQ: connection request " << req_info.DebugString();
FabricEndpoint *endpoint = GetOrCreateEndpoint(req_info.hostname, req_info.port,
req_info.role);
// retrieve connection id - the connection_id is NOT the node id
int connection_id = endpoint->connection_id;
// set peer address
endpoint->SetPeerAddr(req_info.endpoint_name, req_info.endpoint_name_len);
// set endpoint node id
if (req_info.id != Node::kEmpty) {
endpoint->SetNodeID(req_info.id);
PS_VLOG(3) << "Set endpoint ID = " << req_info.id;
}
// send back my connection info
Node resp_info;
endpoint->fabric_ctx->addr.CopyTo(resp_info.endpoint_name,
&resp_info.endpoint_name_len);
resp_info.hostname = my_node_.hostname;
resp_info.port = my_node_.port;
resp_info.aux_id = req_info.aux_id;
// reply ADDR_RESOLVED message
Message reply;
reply.meta.recver = connection_id;
reply.meta.control.cmd = Control::ADDR_RESOLVED;
reply.meta.control.node.push_back(resp_info);
zmq_->Send(reply);
}
void OnConnected(const Message &msg) {
const auto& addr_info = msg.meta.control.node[0];
const int node_id = addr_info.aux_id;
const std::string hostport = hostport_str(addr_info.hostname, addr_info.port);
PS_VLOG(3) << "EQ: connected reply" << addr_info.DebugString();
// init node id -> endpoint lookup
FabricEndpoint *endpoint = nullptr;
{
std::lock_guard<std::mutex> lk(endpoints_mu_);
endpoint = worker_endpoints_[hostport].get();
endpoints_[node_id] = endpoint;
}
CHECK(endpoint != nullptr);
endpoint->SetPeerAddr(addr_info.endpoint_name, addr_info.endpoint_name_len);
{
std::lock_guard<std::mutex> lk(endpoint->status_mu);
endpoint->status = FabricEndpoint::CONNECTED;
}
endpoint->status_cv.notify_all();
}
// stop signals
std::atomic<bool> should_stop_;
// stop signal for the non-blocking polling thread
std::atomic<bool> should_stop_polling_;
std::mutex endpoints_mu_;
// node id -> endpoint for fast lookup
std::unordered_map<int, FabricEndpoint*> endpoints_;
// host:port -> endpoint for connections
std::unordered_map<std::string, std::unique_ptr<FabricEndpoint>> worker_endpoints_;
// worker threads
std::unordered_map<std::string, std::unique_ptr<std::thread>> workers_;
// event thread
std::unique_ptr<std::thread> event_polling_thread_;
// Recv buffer queue
ThreadsafeQueue<FabricBufferContext *> recv_buffers_;
// whether my role is server or not
bool is_server;
// note that ZMQ use the node id to identify the senders.
// to setup the connection for libfabric, we don't know the node id ahead of time
// therefore, we need to use the add sender / receiver hostport to the message meta
// such that when we unpack the message, we can still know where the message was sent
std::unordered_map<std::string, int> zmq_connections_;
Van* zmq_;
bool is_worker_;
// fabric provider info
struct fi_info *info_;
std::mutex log_mu_;
// TODO(haibin): make it configurable
int kMaxConcurrentWorkRequest = 4224; // 128 + 2048 * 2
}; // FabricVan
}; // namespace ps
#endif // DMLC_USE_FABRIC
#endif // PS_FABRIC_VAN_H_
| 34.358808 | 110 | 0.642262 | [
"vector"
] |
14cfd3785e5fd50a09b9a5c7c47e15ecc3411a9a | 1,430 | h | C | modules/mod_python-3.3.1/src/include/tableobject.h | yinsen/apache-text | 77a69659b476f4b18399187fe0b1e77d0b069107 | [
"Apache-2.0"
] | null | null | null | modules/mod_python-3.3.1/src/include/tableobject.h | yinsen/apache-text | 77a69659b476f4b18399187fe0b1e77d0b069107 | [
"Apache-2.0"
] | null | null | null | modules/mod_python-3.3.1/src/include/tableobject.h | yinsen/apache-text | 77a69659b476f4b18399187fe0b1e77d0b069107 | [
"Apache-2.0"
] | 2 | 2020-11-04T06:31:32.000Z | 2020-11-06T11:02:20.000Z | #ifndef Mp_TABLEOBJECT_H
#define Mp_TABLEOBJECT_H
#ifdef __cplusplus
extern "C" {
#endif
/*
* Copyright 2004 Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* Originally developed by Gregory Trubetskoy.
*
*
* tableobject.h
*
* $Id: tableobject.h 106619 2004-11-25 22:10:52Z nd $
*
*/
/*
* This is a mapping of a Python object to an Apache table.
*
*/
typedef struct tableobject {
PyObject_VAR_HEAD
apr_table_t *table;
apr_pool_t *pool;
} tableobject;
extern DL_IMPORT(PyTypeObject) MpTable_Type;
extern DL_IMPORT(PyTypeObject) MpTableIter_Type;
#define MpTable_Check(op) ((op)->ob_type == &MpTable_Type)
extern DL_IMPORT(PyObject *) MpTable_FromTable Py_PROTO((apr_table_t *t));
extern DL_IMPORT(PyObject *) MpTable_New Py_PROTO((void));
#ifdef __cplusplus
}
#endif
#endif /* !Mp_TABLEOBJECT_H */
| 26.481481 | 78 | 0.706294 | [
"object"
] |
14d6258821c3c7c0006ec55e81962609667bcd67 | 5,853 | h | C | krc-2016-03-31/listhdr.h | dbremner/krc | 735cee5803994826fce833b1d30b5047cfe93010 | [
"BSD-2-Clause"
] | 1 | 2019-12-27T13:34:36.000Z | 2019-12-27T13:34:36.000Z | krc-2016-03-31/listhdr.h | dbremner/krc | 735cee5803994826fce833b1d30b5047cfe93010 | [
"BSD-2-Clause"
] | null | null | null | krc-2016-03-31/listhdr.h | dbremner/krc | 735cee5803994826fce833b1d30b5047cfe93010 | [
"BSD-2-Clause"
] | 2 | 2019-12-05T02:11:05.000Z | 2019-12-27T13:25:19.000Z | // HEADER FOR LIST PROCESSING PACKAGE DAT 23/11/79
//----------------------------------------------------------------------
//The KRC system is Copyright (c) D. A. Turner 1981
//All rights reserved. It is distributed as free software under the
//terms in the file "COPYING", which is included in the distribution.
//----------------------------------------------------------------------
#include "bcpl.h"
// Include code to check validity of pointers handed to HD() and TL
// #define INSTRUMENT_KRC_GC
/* An element in LIST space */
typedef struct LIST {
struct LIST *hd;
struct LIST *tl;
} *LIST;
// HD can contain:
// - the memory address of another cell in the CONS space
// - the memory address of a cell in the ATOM space
// - improbable pointer values of HD() for special values:
// FULLWORD (see above) or GONETO (see listpack.c)
//#define NIL ((LIST)0) //causes problems
#define NIL ((LIST)0x40000000) //from oldbcpl/listhdr, may need changing
#ifdef INSTRUMENT_KRC_GC
extern LIST ISOKCONS(LIST);
#define HD(p) (ISOKCONS(p)->hd)
#define TL(p) (ISOKCONS(p)->tl)
#else
#define HD(p) ((p)->hd)
#define TL(p) ((p)->tl)
#endif
/* An element in ATOM space */
typedef struct ATOM {
struct ATOM *link;
struct LIST *val;
char name[];
} *ATOM;
// link points to the next item in the linked list of values,
// or has value 0 if it is the end of this list.
// val points to the item's value in the CONS space.
// NOTE: VAL is used on items in both ATOM and CONS spaces.
// name is a combined BCPL- and C-like string, i.e. the length in the
// first byte, then the string itself followed by a nul character.
#define LINK(p) ((p)->link)
#define VAL(p) ((p)->val)
#define NAME(p) ((p)->name)
#define LEN(p) ((p)->name[0]&0xff)
#define OFFSET 2 // Offset of "name" field in pointer words
#define atomsize (sizeof(struct ATOM)) //unit of allocation for ATOMSPACE
// The C string version of the name
#define PRINTNAME(X) (NAME(X)+1)
WORD HAVEPARAM(WORD CH);
extern int ARGC;
extern char **ARGV;
//FOR PICKING UP SYSTEM PARAMETERS PASSED TO PROGRAM
extern BOOL ATGC;
// PACKAGE SPECIFICATIONS:
// "GO" "BASES" "SPACE.ERROR" MUST BE DEFINED BY THE USER
// ALL THE OTHER FUNCTIONS ETC ARE DEFINED BY THE PACKAGE
// "GO()" IS THE MAIN ROUTINE OF THE USERS PROGRAM (NECESSARY BECAUSE
// THE PACKAGE HAS ITS OWN "START" ROUTINE)
// "BASES" IS USED TO INFORM THE PACKAGE WHICH OF THE USERS OFF-STACK
// VARIABLES ARE BASES FOR GARBAGE COLLECTION - IT SHOULD BE DEFINED
// THUS - "LET BASES(F) BE $( F(@A); F(@B); ... $)" WHERE A, B ETC.
// ARE THE RELEVANT VARIABLES. SEE NOTE 1 BELOW.
// "SPACE.ERROR()" DEFINES THE ACTION THE USER WISHES TO TAKE WHEN LIST
// SPACE IS EXHAUSTED (E.G. PRINT A MESSAGE AND CALL FINISH)
extern void GO(void);
extern void BASES(void (*f)(LIST *));
extern void SPACE_ERROR(char *MESSAGE);
// "CONS(X,Y)" CREATES A LIST CELL, Z SAY, WITH X AND Y FOR ITS FIELDS
// AND "HD!Z", "TL!Z" GIVE ACCESS TO THE FIELDS
LIST CONS(LIST X, LIST Y);
// "STONUM(N)" STORES AWAY THE NUMBER N AS A LIST OBJECT AND "GETNUM(X)"
// GETS IT OUT AGAIN. SEE NOTE 2 BELOW.
LIST STONUM(WORD N);
WORD GETNUM(LIST X);
// "MKATOM(S)" CREATES AN ATOM FROM BCPL STRING S - ATOMS ARE STORED
// UNIQUELY, MKATOM USES A HASHING ALGORITHM TO ACCOMPLISH THIS
// EFFICIENTLY. "PRINTNAME(X)" RECOVERS THE BCPL STRING. THERE IS A LIST
// VALUED FIELD "VAL!A" ASSOCIATED WITH EACH ATOM A, INITIALLY
// CONTAINING "NIL".
ATOM MKATOM(char *s);
ATOM MKATOMN(char *s, int len);
// "BUFCH(CH)" PUTS THE CHARACTER CH INTO A BUFFER, "PACKBUFFER()"
// EMPTIES THE BUFFER AND RETURNS AN ATOM FORMED FROM THE CHARACTERS
// WHICH HAD BEEN PLACED IN IT(BY CALLING "MKATOM")
void BUFCH(WORD CH);
ATOM PACKBUFFER(void);
// THE FUNCTIONS "ISCONS(X)", "ISATOM(X)", "ISNUM(X)" DISTINGUISH
// THE THREE DIFFERENT KINDS OF CONSTRUCTED LIST OBJECT.
// NOTE THAT THE SPECIAL OBJECT "NIL" IS NEITHER AN ATOM NOR A LIST.
// (SO REMEMBER THAT "NIL" HAS NO PRINTNAME AND NO "VAL" FIELD.)
// THERE IS A FIFTH KIND OF VALUE WHICH CAN BE STORED IN A LIST FIELD
// NAMELY A SMALL INTEGER (WHERE "SMALL" IS AN IMPLEMENTATION DEPENDENT
// ADJECTIVE MEANING SMALL ENOUGH NOT TO BE CONFUSED WITH ONE OF THE
// THREE ABOVE MENTIONED TYPES OF LIST OBJECT - SEE NOTE 3, BELOW).
WORD ISCONS(LIST X);
WORD ISATOM(LIST X);
WORD ISNUM(LIST X);
// "ALFA.LS(A,B)" TESTS ATOMS FOR ALPHABETICAL ORDER
// "LENGTH(X)" GIVES THE LENGTH OF LIST X
// "MEMBER(X,A)" SAYS IF "A" IS = AN ELEMENT OF X
// "APPEND(X,Y)" APPENDS (A COPY OF) LIST X TO THE FRONT OF LIST Y
// "EQUAL(X,Y)" DETERMINES IF LIST OBJECTS X AND Y ARE ISOMORPHIC
// "ELEM(X,N)" RETURNS THE N'TH ELEMENT OF LIST X
// "PRINTOB(X)" PRINTS AN ARBITRARY LIST OBJECT X
// "FORCE.GC()" FORCES A GARBAGE COLLECTION
// "REVERSE(X)" REVERSES THE LIST X
// "SHUNT(X,Y)" APPENDS REVERSE(X) TO THE LIST Y
// "SUB1(X,A)" REMOVES A FROM THE LIST X (DESTRUCTIVELY) IF PRESENT
BOOL ALFA_LS(ATOM A, ATOM B);
WORD LENGTH(LIST X);
WORD MEMBER(LIST X, LIST A);
LIST APPEND(LIST X, LIST Y);
WORD EQUAL(LIST X, LIST Y);
LIST ELEM(LIST X, WORD N);
void PRINTOB(LIST X);
void RESETGCSTATS(void);
void FORCE_GC(void);
void REPORTDIC(void);
void LISTPM(void);
LIST REVERSE(LIST X);
LIST SHUNT(LIST X, LIST Y);
LIST SUB1(LIST X, ATOM A);
// NOTES FOR 2960/EMAS IMPLEMENTATION AT UKC:
// NOTE 1
// AT GARBAGE COLLECTION TIME THE BCPL STACK IS SEARCHED AND ANY VALUE
// WITHIN THE ADDRESS RANGE OF LIST OBJECTS IS TREATED AS A BASE AND
// POSSIBLY RELOCATED. IT IS THEREFORE ESSENTIAL THAT THERE SHOULD BE
// NO INTEGERS ON THE STACK LARGE ENOUGH TO BE CONFUSED WITH A BCPL
// ADDRESS - INTEGERS LESS THAN 8 MEG ARE SAFE.
// NOTE 2
// THE NUMBERS STORED AND RECOVERED BY MKNUM AND GETNUM ARE 32 BIT
// INTEGERS - TAKE CARE NOT TO LEAVE THEM ON THE STACK.
// NOTE 3
// "SMALL" HERE MEANS LESS THAN 8 MEG
| 36.354037 | 73 | 0.684606 | [
"object"
] |
14daae004474c599e67eb6bcaa5a777aa6e20248 | 3,335 | h | C | C++/pacman-legacy-cpp/include/pacman.h | sirarsalih/Games | c83cd8d9ebf9f9775994dd55f93f6e975c8520c1 | [
"MIT"
] | null | null | null | C++/pacman-legacy-cpp/include/pacman.h | sirarsalih/Games | c83cd8d9ebf9f9775994dd55f93f6e975c8520c1 | [
"MIT"
] | null | null | null | C++/pacman-legacy-cpp/include/pacman.h | sirarsalih/Games | c83cd8d9ebf9f9775994dd55f93f6e975c8520c1 | [
"MIT"
] | null | null | null | /***************************************************************************************************************************************
****************************************************************************************************************************************
This is the pacman class. We initially create 2 pacman objects (in the game class), each with unique player identifier integers. This
class is naturally a very important class in the game.
****************************************************************************************************************************************
***************************************************************************************************************************************/
#ifndef PACMAN_H
#define PACMAN_H
#include <SDL.h>
class Pacman
{
public:
//Default constructor
Pacman();
//Custom constructor
Pacman(int player);
//Get player (used to identifiy player)
int getPlayer();
//Get starting position on the x-axis ( in pixels )
int getX();
//Set starting position on the x-axis ( in pixels )
void setX(int x);
//Get starting position on the y-axis ( in pixels )
int getY();
//Set starting position on the y-axis ( in pixels )
void setY(int y);
//Get current position on the x-axis ( in pixels )
int getDx();
//Set current position on the x-axis ( in pixels )
void setDx(int dx);
//Get current position on the y-axis ( in pixels )
int getDy();
//Set current position on the y-axis ( in pixels )
void setDy(int dy);
//Get current position on the x-axis ( on the array )
int getArrayPosX();
//Get current position on the y-axis ( on the array )
int getArrayPosY();
//Get number of lives left function
int getLife();
//Set amount of lives function
void setLife(int life);
//Get current position vector function
char getPosVector();
//Set current position vector function
void setPosVector(char pos);
//Get next position vector function
char getNextVector();
//Set next position vector function
void setNextVector(char nPos);
//Check power pellet function
bool getPowerPellet();
//Set power pellet function
void setPowerPellet(bool powerPellet);
//Get bonus item function ( for sound )
bool getBonusItem();
//Set bonus item function ( for sound )
void setBonusItem(bool bonusItem);
//Get score function
int getScore();
//Set score function
void setScore(int score);
//Check Pacman dead function
bool getPacmanDead();
//Set Pacman dead function
void setPacmanDead(bool pacmanDead);
//Check Pacman dead final ( all lives lost )
bool getPacmanDeadFinal();
//Set Pacman dead final ( all lives lost )
void setPacmanDeadFinal(bool pacmanDeadFinal);
private:
//Position vector
char posVector;
//Next Position vector
char nextVector;
//Player ID
int player;
//Pacman life
int life;
//Start position x ( in pixels )
int x;
//Start position y ( in pixels )
int y;
//Current position x ( in pixels )
int dx;
//Current position y ( in pixels )
int dy;
//Current position x ( in array )
int arrayPosX;
//Current position y ( in array )
int arrayPosY;
//Score
int score;
//Power pellet flag
bool powerPellet;
//Bonus item flag
bool bonusItem;
//Pacman dead flag
bool pacmanDead;
//Pacman dead final flag
bool pacmanDeadFinal;
};
#endif | 21.107595 | 136 | 0.589505 | [
"vector"
] |
14dd3a1ca567f1346df09474db1899185d6db2d2 | 1,318 | h | C | src/lycon/util/tls.h | peter0749/lycon | 0e7b3e51f56140d68e0466d00be45d79b4de682b | [
"BSD-3-Clause"
] | 278 | 2017-01-17T22:54:24.000Z | 2022-03-16T07:33:31.000Z | src/lycon/util/tls.h | peter0749/lycon | 0e7b3e51f56140d68e0466d00be45d79b4de682b | [
"BSD-3-Clause"
] | 22 | 2017-01-31T02:18:55.000Z | 2021-12-07T17:52:49.000Z | src/lycon/util/tls.h | peter0749/lycon | 0e7b3e51f56140d68e0466d00be45d79b4de682b | [
"BSD-3-Clause"
] | 25 | 2017-08-29T17:19:52.000Z | 2022-01-12T12:14:34.000Z | #pragma once
#include <vector>
#include "lycon/defs.h"
namespace lycon
{
class LYCON_EXPORTS TLSDataContainer
{
protected:
TLSDataContainer();
virtual ~TLSDataContainer();
void gatherData(std::vector<void*>& data) const;
void* getData() const;
void release();
private:
virtual void* createDataInstance() const = 0;
virtual void deleteDataInstance(void* pData) const = 0;
int key_;
};
// Main TLS data class
template <typename T>
class TLSData : protected TLSDataContainer
{
public:
inline TLSData() {}
inline ~TLSData() { release(); } // Release key and delete associated data
inline T* get() const { return (T*)getData(); } // Get data assosiated with key
// Get data from all threads
inline void gather(std::vector<T*>& data) const
{
std::vector<void*>& dataVoid = reinterpret_cast<std::vector<void*>&>(data);
gatherData(dataVoid);
}
private:
virtual void* createDataInstance() const { return new T; } // Wrapper to allocate data by template
virtual void deleteDataInstance(void* pData) const { delete (T*)pData; } // Wrapper to release data by template
// Disable TLS copy operations
TLSData(TLSData&) {}
TLSData& operator=(const TLSData&) { return *this; }
};
}
| 25.346154 | 117 | 0.650228 | [
"vector"
] |
14e506899e6980927f0a643804d010e19506c248 | 8,382 | c | C | mex/include/sisl-4.5.0/src/s1530.c | sangyoonHan/extern | a3c874538a7262b895b60d3c4d493e5b34cf81f8 | [
"BSD-2-Clause"
] | null | null | null | mex/include/sisl-4.5.0/src/s1530.c | sangyoonHan/extern | a3c874538a7262b895b60d3c4d493e5b34cf81f8 | [
"BSD-2-Clause"
] | null | null | null | mex/include/sisl-4.5.0/src/s1530.c | sangyoonHan/extern | a3c874538a7262b895b60d3c4d493e5b34cf81f8 | [
"BSD-2-Clause"
] | null | null | null | //===========================================================================
// SISL - SINTEF Spline Library, version 4.5.0.
// Definition and interrogation of NURBS curves and surfaces.
//
// Copyright (C) 2000-2005, 2010 SINTEF ICT, Applied Mathematics, Norway.
//
// 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 version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc.,
// 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
// Contact information: E-mail: tor.dokken@sintef.no
// SINTEF ICT, Department of Applied Mathematics,
// P.O. Box 124 Blindern,
// 0314 Oslo, Norway.
//
// Other licenses are also available for this software, notably licenses
// for:
// - Building commercial software.
// - Building software whose source code you wish to keep private.
//===========================================================================
#include "sisl-copyright.h"
/*
*
* $Id: s1530.c,v 1.2 2001-03-19 15:58:50 afr Exp $
*
*/
#define S1530
#include "sislP.h"
#if defined(SISLNEEDPROTOTYPES)
void s1530(double ep[],double eder10[],double eder01[],double eder11[],
double epar1[],double epar2[],
int im1,int im2,int idim,
SISLSurf **rsurf,int *jstat)
#else
void s1530(ep,eder10,eder01,eder11,epar1,epar2,
im1,im2,idim,rsurf,jstat)
double ep[];
double eder10[];
double eder01[];
double eder11[];
double epar1[];
double epar2[];
int im1;
int im2;
int idim;
SISLSurf **rsurf;
int *jstat;
#endif
/*
************************************************************************
*
* PURPOSE: To compute the cubic Hermite interpolant to the data given.
* More specifically, given positions, 10, 01, and 11
* derivatives at points of a rectangular grid, the routine
* computes a cubic tensor-product B-spline interpolant to
* the given data with double knots at each data (the first
* knot vector will have double knots at all interior points
* in epar1, quadruple knots at the first and last points,
* and similarly for the second knot vector).
*
* INPUT:
* ep - Array of dimension idim*im1*im2 containing
* the positions of the nodes (using the same ordering
* as ecoef in the SISLSurf structure).
*
* eder10 - Array of dimension idim*im1*im2 containing the
* first derivative in the first parameter direction.
*
* eder01 - Array of dimension idim*im1*im2 containing the
* first derivative in the second parameter direction.
*
* eder11 - Array of dimension idim*im1*im2 containing
* the cross derivative (twist vector).
*
* epar1 - Array of dimension im1 containing the
* parametrization in the first direction.
*
* epar2 - Array of dimension im2 containing the
* parametrization in the first direction.
*
* im1 - The number of interpolation points in the
* first parameter direction.
*
* im2 - The number of interpolation points in the
* second parameter direction.
*
* idim - Dimension of the space we are working in.
*
* Output:
* rsurf - Pointer to the surf produced
* jstat - Status variable
* < 0 - Error.
*
* Method:
* The interpolation is accomplished by using a one dimensional
* routine for cubic Hermite spline interpolation. First, the data
* is considered to be im2 positional and derivative vectors on
* two curves in idim * im1 dimensional space sampled at the
* points of epar2.
* The first of these has position vectors given by ep and
* derivative vectors given by eder01, the second position vectors
* given by eder10 and derivative vectors given by eder11.
* Running these curves through the one dimensional cubic Hermite
* spline interpolation routine then produces two cubic splines rpos
* and rder with coefficients of dimension (idim * im1) * (2 * im2)
* on the knot vector et2 which is just the points of epar2 with
* multiplicity 2 for the interior points and 4 for the
* end points.
* These coefficients are then considered to be im1 position vectors
* and derivative vectors on a curve in 2*idim*im2 dimensional
* space (after an appropriate tranposition) sampled at the
* points of epar1. Running this data through the one dimensional
* cubic Hermite spline routine results in a cubic spline
* with coefficients of dimension (2 * idim * im2) * (2 * im1)
* with knot vector et1 similar to et2.
* A transposition of these coefficients yields the B-spline
* coefficients of the bicubic Hermite tensor-product spline
* interpolant.
* REFERENCES :
*
* CALLS :
*
* WRITTEN BY : Michael Floater, SI, June 1992.
*
*********************************************************************
*/
{
SISLCurve *rpos; /* Curve of positions of dimension idim*im1 */
SISLCurve *rder; /* Curve of derivatives of dimension idim*im1 */
SISLCurve *rcurve; /* Curve of dimension idim*im2 */
int kstat=0; /* Status variable */
int kpos=0; /* Position of error */
double *ph=SISL_NULL; /* Transposed positions (in rpos) */
double *dh=SISL_NULL; /* Transposed derivatives (in rder) */
double *scoef=SISL_NULL; /* Transposed positions in rcurve */
/* Check input */
if (im1 < 2 || im2 < 2 || idim < 1) goto err102;
/* Interpolate position and derivative
in the second parameter direction. */
s1379(ep,eder01,epar2,im2,idim * im1,&rpos,&kstat);
if(kstat < 0) goto error;
s1379(eder10,eder11,epar2,im2,idim * im1,&rder,&kstat);
if(kstat < 0) goto error;
/* Transpose the matrices (ecoef arrays) of the curves. */
s1531(rpos->ecoef, idim, im1, rpos->in, &ph, &kstat);
if(kstat < 0) goto error;
s1531(rder->ecoef, idim, im1, rder->in, &dh, &kstat);
if(kstat < 0) goto error;
/* Interpolate in the first parameter direction. */
s1379(ph,dh,epar1,im1,idim * rpos->in,&rcurve,&kstat);
if(kstat < 0) goto error;
/* Transpose coefficient matrix of rcurve. */
s1531(rcurve->ecoef, idim, rpos->in, rcurve->in, &scoef, &kstat);
if(kstat < 0) goto error;
/* Create instance of surface. */
(*rsurf) = newSurf(rcurve->in,rpos->in,rcurve->ik,rpos->ik,
rcurve->et,rpos->et,scoef,1,idim,1);
if((*rsurf) == SISL_NULL) goto err101;
/* Set periodicity flag. */
(*rsurf)->cuopen_1 = rcurve->cuopen;
(*rsurf)->cuopen_2 = rpos->cuopen;
/* Bicubic surface made. */
*jstat = 0;
goto out;
/* Error in space allocation. */
err101: *jstat = -101;
s6err("s1530",*jstat,kpos);
goto out;
/* Error in input data. */
err102: *jstat = -102;
s6err("s1530",*jstat,kpos);
goto out;
/* Error in lower level routine. */
error: *jstat =kstat;
s6err("s1530",*jstat,kpos);
goto out;
out:
if (rpos != SISL_NULL) freeCurve(rpos);
if (rder != SISL_NULL) freeCurve(rder);
if (rcurve != SISL_NULL) freeCurve(rcurve);
if (scoef != SISL_NULL) freearray(scoef);
if (ph != SISL_NULL) freearray(ph);
if (dh != SISL_NULL) freearray(dh);
return;
}
| 35.07113 | 77 | 0.583035 | [
"vector"
] |
14f3929c1ac74553879de1ccecb4a962f34f936e | 5,316 | h | C | Gem/Code/Source/RHI/SphericalHarmonicsExampleComponent.h | Bindless-Chicken/o3de-atom-sampleviewer | 13b11996079675445ce4e321f53c3ac79e01702d | [
"Apache-2.0",
"MIT"
] | 15 | 2021-07-07T02:16:06.000Z | 2022-03-22T07:39:06.000Z | Gem/Code/Source/RHI/SphericalHarmonicsExampleComponent.h | Bindless-Chicken/o3de-atom-sampleviewer | 13b11996079675445ce4e321f53c3ac79e01702d | [
"Apache-2.0",
"MIT"
] | 66 | 2021-07-07T00:01:05.000Z | 2022-03-28T06:37:41.000Z | Gem/Code/Source/RHI/SphericalHarmonicsExampleComponent.h | Bindless-Chicken/o3de-atom-sampleviewer | 13b11996079675445ce4e321f53c3ac79e01702d | [
"Apache-2.0",
"MIT"
] | 13 | 2021-07-06T18:21:33.000Z | 2022-01-04T18:29:18.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <RHI/BasicRHIComponent.h>
#include <Atom/RPI.Public/Shader/ShaderResourceGroup.h>
#include <Atom/RHI/BufferPool.h>
#include <Atom/RHI/DrawItem.h>
#include <Atom/RHI.Reflect/SamplerState.h>
#include <AzCore/Component/TickBus.h>
#include <Utils/ImGuiSidebar.h>
namespace AtomSampleViewer
{
/*
* sample for demonstrating application of spherical harominics with two modes
* Demo mode: provides visualisation of shapes of each SH basis, and differences
* between three solvers on performance and flexibility
* Render mode: demonstrates how to calculate exiting diffuse radiance based on SH coefficients and how to
* rotate an exsiting SH sets with provided functions
*/
class SphericalHarmonicsExampleComponent final
: public BasicRHIComponent
, public AZ::TickBus::Handler
{
public:
AZ_COMPONENT(SphericalHarmonicsExampleComponent, "{7E99662E-2C3D-4E3F-87B1-B9A6BB4B4AF5}", AZ::Component);
static void Reflect(AZ::ReflectContext* context);
SphericalHarmonicsExampleComponent();
~SphericalHarmonicsExampleComponent() = default;
protected:
AZ_DISABLE_COPY(SphericalHarmonicsExampleComponent);
// AZ::Component overrides ...
virtual void Activate() override;
virtual void Deactivate() override;
// AZ::TickBus::Handler overrides ...
void OnTick(float deltaTime, AZ::ScriptTimePoint time) override;
// AZ::Component overrides ...
bool ReadInConfig(const AZ::ComponentConfig* baseConfig) override;
void DrawIMGui();
float CalFakeLightSH(bool& flag);
// ------------------- demo mode variables -------------------
AZ::RHI::ConstPtr<AZ::RHI::PipelineState> m_demoPipelineState;
AZ::Data::Instance<AZ::RPI::ShaderResourceGroup> m_demoShaderResourceGroup;
AZ::RHI::ShaderInputConstantIndex m_demoObjectMatrixInputIndex;
AZ::RHI::ShaderInputConstantIndex m_SHBandInputIndex;
AZ::RHI::ShaderInputConstantIndex m_SHOrderInputIndex;
AZ::RHI::ShaderInputConstantIndex m_SHSolverInputIndex;
AZ::RHI::ShaderInputConstantIndex m_EnableDistortionInputIndex;
// set band(l) of displayed SHbasis
int m_shaderInputSHBand = 0;
// set order(m) of displayed SHbasis
int m_shaderInputSHOrder = 0;
// change solver used for evaluation
int m_shaderInputSHSolver = 0;
// enable distortion based on magnitude of SH basis
bool m_shaderInputEnableDistortion = true;
bool m_updateDemoSRG = true;
// -----------------------------------------------------------
// ------------------- render mode variables -------------------
AZ::RHI::ConstPtr<AZ::RHI::PipelineState> m_renderPipelineState;
AZ::Data::Instance<AZ::RPI::ShaderResourceGroup> m_renderShaderResourceGroup;
AZ::Data::Instance<AZ::RPI::ShaderResourceGroup> m_viewShaderResourceGroup;
AZ::RHI::ShaderInputConstantIndex m_renderObjectMatrixInputIndex;
AZ::RHI::ShaderInputConstantIndex m_presetIndexInputIndex;
AZ::RHI::ShaderInputConstantIndex m_exposureInputIndex;
AZ::RHI::ShaderInputConstantIndex m_enableGammaCorrectionInputIndex;
AZ::RHI::ShaderInputConstantIndex m_SHFakeLightCoefficientsInputIndex;
AZ::RHI::ShaderInputConstantIndex m_rotationAngleInputIndex;
// change SH coeffiicent set used for shading
int m_shaderInputPresetIndex = 0;
// change tone mapping exposure
float m_shaderInputExposure = 1.0;
// enable gamme correction
bool m_shaderInputEnableGammaCorrection = false;
// 16 floats represent first 4 bands SH coefficients (0 to 3) for fake ligt function
AZ::Matrix4x4 m_shaderInputSHFakeLightCoefficients;
// Euler angle for rotation demo case
AZ::Vector3 m_shaderInputRotationAngle;
bool m_updateRenderSRG = true;
// -------------------------------------------------------------
// ----------------------- gui variables -----------------------
ImGuiSidebar m_imguiSidebar;
bool m_mode = true;
bool m_recomputeFakeLight = false;
// -------------------------------------------------------------
// ---------------- streaming buffer variables ----------------
AZ::RHI::Ptr<AZ::RHI::BufferPool> m_bufferPool;
AZ::RHI::Ptr<AZ::RHI::Buffer> m_indexBuffer;
AZ::RHI::Ptr<AZ::RHI::Buffer> m_positionBuffer;
AZ::RHI::Ptr<AZ::RHI::Buffer> m_uvBuffer;
struct BufferData
{
AZStd::array<VertexPosition, 4> m_positions;
AZStd::array<VertexUV, 4> m_uvs;
AZStd::array<uint16_t, 6> m_indices;
};
AZ::RHI::DrawItem m_drawItem;
AZStd::array<AZ::RHI::StreamBufferView, 2> m_streamBufferViews;
// ------------------------------------------------------------
AZ::EntityId m_cameraEntityId;
};
}
| 36.662069 | 114 | 0.629044 | [
"render",
"3d"
] |
14f7da66af8d412d229d2f86718cfd18003b2e61 | 2,416 | c | C | src/core/output_ids.c | oopsmonk/goshimmer-client-c | 858fc10b2b44ae85e95a25e2cdaf69e85f8faf37 | [
"Apache-2.0"
] | 9 | 2020-11-11T07:38:24.000Z | 2021-06-03T02:41:08.000Z | src/core/output_ids.c | oopsmonk/pollen_qianbao | 858fc10b2b44ae85e95a25e2cdaf69e85f8faf37 | [
"Apache-2.0"
] | null | null | null | src/core/output_ids.c | oopsmonk/pollen_qianbao | 858fc10b2b44ae85e95a25e2cdaf69e85f8faf37 | [
"Apache-2.0"
] | 1 | 2020-11-02T08:27:35.000Z | 2020-11-02T08:27:35.000Z | #include "core/output_ids.h"
int output_ids_add(output_ids_t **t, byte_t const id[], balance_ht_t *balances, inclusion_state_t *st) {
output_ids_t *elm = output_ids_find(t, id);
if (elm) {
// printf("[%s:%d] output id exists in table\n", __func__, __LINE__);
return 0;
}
// adding to table
elm = malloc(sizeof(output_ids_t));
if (elm == NULL) {
printf("[Err %s:%d] OOM\n", __func__, __LINE__);
return -1;
}
elm->balances = balance_ht_clone(&balances);
memcpy(elm->id, id, TX_ID_BYTES);
memcpy(&elm->st, st, sizeof(inclusion_state_t));
HASH_ADD(hh, *t, id, TX_ID_BYTES, elm);
return 0;
}
int output_ids_update(output_ids_t **t, byte_t const id[], balance_ht_t *balances, inclusion_state_t *st) {
output_ids_remove(t, id);
return output_ids_add(t, id, balances, st);
}
output_ids_t *output_ids_clone(output_ids_t **t) {
output_ids_t *dst = output_ids_init();
output_ids_t *src, *tmp;
HASH_ITER(hh, *t, src, tmp) { output_ids_add(&dst, src->id, src->balances, &src->st); }
return dst;
}
uint64_t output_ids_balance(output_ids_t **t) {
uint64_t sum = 0;
output_ids_t *elm, *tmp;
HASH_ITER(hh, *t, elm, tmp) {
if (elm->st.confirmed) {
sum += balance_ht_sum(&elm->balances);
}
}
return sum;
}
uint64_t output_ids_balance_with_color(output_ids_t **t, byte_t color[]) {
uint64_t sum = 0;
output_ids_t *elm, *tmp;
HASH_ITER(hh, *t, elm, tmp) {
if (elm->st.confirmed) {
sum += balance_ht_sum_with_color(&elm->balances, color);
}
}
return sum;
}
void output_ids_print(output_ids_t **t) {
output_ids_t *elm, *tmp;
char id_str[TX_ID_BASE58_BUF] = {};
printf("output_ids: [\n===\n");
HASH_ITER(hh, *t, elm, tmp) {
tx_id_2_base58(elm->id, id_str);
printf("id: %s\n", id_str);
inclustion_state_print(&elm->st);
balance_ht_print(&elm->balances);
printf("===\n");
}
printf("]\n");
}
void inclustion_state_print(inclusion_state_t *st) {
printf("inclusion_state: [ ");
if (st->confirmed) {
printf("confirmed: true, ");
}
if (st->conflicting) {
printf("conflicting: true, ");
}
if (st->finalized) {
printf("finalized: true, ");
}
if (st->liked) {
printf("liked: true, ");
}
if (st->preferred) {
printf("preferred: true, ");
}
if (st->rejected) {
printf("rejected: true, ");
}
if (st->solid) {
printf("solid: true ");
}
printf(" ]\n");
}
| 25.166667 | 107 | 0.631623 | [
"solid"
] |
090443dc3f41b73fcaae5d20fd0e2130c5f26ace | 21,480 | c | C | lib-src/redland/rasqal/src/rasqal_raptor.c | gspeedtech/Audacity | 570c5651c5934469c18dad25db03f05076f91225 | [
"CC-BY-3.0"
] | 16 | 2015-01-26T18:58:26.000Z | 2017-11-12T05:42:58.000Z | lib-src/redland/rasqal/src/rasqal_raptor.c | gspeedtech/Audacity | 570c5651c5934469c18dad25db03f05076f91225 | [
"CC-BY-3.0"
] | null | null | null | lib-src/redland/rasqal/src/rasqal_raptor.c | gspeedtech/Audacity | 570c5651c5934469c18dad25db03f05076f91225 | [
"CC-BY-3.0"
] | 7 | 2015-04-13T20:01:00.000Z | 2021-07-05T09:28:22.000Z | /* -*- Mode: c; c-basic-offset: 2 -*-
*
* rasqal_raptor.c - Rasqal triple store implementation with raptor
*
* Copyright (C) 2004-2008, David Beckett http://www.dajobe.org/
* Copyright (C) 2004-2005, University of Bristol, UK http://www.bristol.ac.uk/
*
* This package is Free Software and part of Redland http://librdf.org/
*
* It is licensed under the following three licenses as alternatives:
* 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version
* 2. GNU General Public License (GPL) V2 or any newer version
* 3. Apache License, V2.0 or any newer version
*
* You may not use this file except in compliance with at least one of
* the above three licenses.
*
* See LICENSE.html or LICENSE.txt at the top of this package for the
* complete terms and further detail along with the license texts for
* the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively.
*
*
*/
#ifdef HAVE_CONFIG_H
#include <rasqal_config.h>
#endif
#ifdef WIN32
#include <win32_rasqal_config.h>
#endif
#include <stdio.h>
#include <string.h>
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#include <stdarg.h>
#include "rasqal.h"
#include "rasqal_internal.h"
struct rasqal_raptor_triple_s {
struct rasqal_raptor_triple_s *next;
rasqal_triple *triple;
};
typedef struct rasqal_raptor_triple_s rasqal_raptor_triple;
typedef struct {
rasqal_query* query;
rasqal_raptor_triple *head;
rasqal_raptor_triple *tail;
/* index used while reading triples into the two arrays below.
* This is used to connect a triple to the URI literal of the source
*/
int source_index;
/* size of the two arrays below */
int sources_count;
/* shared pointers into query->data_graph uris */
raptor_uri* source_uri;
/* array of URI literals (allocated here) */
rasqal_literal **source_literals;
/* genid base for mapping user bnodes */
unsigned char* mapped_id_base;
/* length of above string */
int mapped_id_base_len;
} rasqal_raptor_triples_source_user_data;
/* prototypes */
static int rasqal_raptor_init_triples_match(rasqal_triples_match* rtm, rasqal_triples_source *rts, void *user_data, rasqal_triple_meta *m, rasqal_triple *t);
static int rasqal_raptor_triple_present(rasqal_triples_source *rts, void *user_data, rasqal_triple *t);
static void rasqal_raptor_free_triples_source(void *user_data);
static raptor_uri*
ordinal_as_uri(int ordinal)
{
int t=ordinal;
size_t len;
unsigned char *buffer;
raptor_uri* uri;
len=raptor_rdf_namespace_uri_len + 1 + 1; /* 1 for min-length, 1 for '_' */
while(t/=10)
len++;
buffer=(unsigned char*)RASQAL_MALLOC(cstring, len+1);
if(!buffer)
return NULL;
sprintf((char*)buffer, "%s_%d", raptor_rdf_namespace_uri, ordinal);
uri=raptor_new_uri(buffer);
RASQAL_FREE(cstring, buffer);
return uri;
}
static rasqal_triple*
raptor_statement_as_rasqal_triple(rasqal_world* world, const raptor_statement *statement) {
rasqal_literal *s, *p, *o;
if(statement->subject_type == RAPTOR_IDENTIFIER_TYPE_ANONYMOUS) {
unsigned char *new_blank=(unsigned char*)RASQAL_MALLOC(cstring, strlen((char*)statement->subject)+1);
strcpy((char*)new_blank, (const char*)statement->subject);
s=rasqal_new_simple_literal(world, RASQAL_LITERAL_BLANK, new_blank);
} else if(statement->subject_type == RAPTOR_IDENTIFIER_TYPE_ORDINAL) {
raptor_uri* uri=ordinal_as_uri(*((int*)statement->subject));
if(!uri)
return NULL;
s=rasqal_new_uri_literal(world, uri);
} else
s=rasqal_new_uri_literal(world, raptor_uri_copy((raptor_uri*)statement->subject));
if(statement->predicate_type == RAPTOR_IDENTIFIER_TYPE_ORDINAL) {
raptor_uri* uri=ordinal_as_uri(*((int*)statement->predicate));
if(!uri)
return NULL;
p=rasqal_new_uri_literal(world, uri);
} else
p=rasqal_new_uri_literal(world, raptor_uri_copy((raptor_uri*)statement->predicate));
if(statement->object_type == RAPTOR_IDENTIFIER_TYPE_LITERAL ||
statement->object_type == RAPTOR_IDENTIFIER_TYPE_XML_LITERAL) {
unsigned char *string;
char *language=NULL;
raptor_uri *uri=NULL;
string=(unsigned char*)RASQAL_MALLOC(cstring, strlen((char*)statement->object)+1);
strcpy((char*)string, (const char*)statement->object);
if(statement->object_literal_language) {
language=(char*)RASQAL_MALLOC(cstring, strlen((const char*)statement->object_literal_language)+1);
strcpy(language, (const char*)statement->object_literal_language);
}
if(statement->object_type == RAPTOR_IDENTIFIER_TYPE_XML_LITERAL) {
uri=raptor_new_uri((const unsigned char*)raptor_xml_literal_datatype_uri_string);
} else if(statement->object_literal_datatype) {
uri=raptor_uri_copy((raptor_uri*)statement->object_literal_datatype);
}
o=rasqal_new_string_literal(world, string, language, uri, NULL);
} else if(statement->object_type == RAPTOR_IDENTIFIER_TYPE_ANONYMOUS) {
char *blank=(char*)statement->object;
unsigned char *new_blank=(unsigned char*)RASQAL_MALLOC(cstring, strlen(blank)+1);
strcpy((char*)new_blank, (const char*)blank);
o=rasqal_new_simple_literal(world, RASQAL_LITERAL_BLANK, new_blank);
} else if(statement->object_type == RAPTOR_IDENTIFIER_TYPE_ORDINAL) {
raptor_uri* uri=ordinal_as_uri(*((int*)statement->object));
if(!uri)
return NULL;
o=rasqal_new_uri_literal(world, uri);
} else {
raptor_uri *uri=raptor_uri_copy((raptor_uri*)statement->object);
o=rasqal_new_uri_literal(world, uri);
}
return rasqal_new_triple(s, p, o);
}
static void
rasqal_raptor_statement_handler(void *user_data,
const raptor_statement *statement)
{
rasqal_raptor_triples_source_user_data* rtsc=(rasqal_raptor_triples_source_user_data*)user_data;
rasqal_raptor_triple *triple;
triple=(rasqal_raptor_triple*)RASQAL_MALLOC(rasqal_raptor_triple, sizeof(rasqal_raptor_triple));
triple->next=NULL;
triple->triple=raptor_statement_as_rasqal_triple(rtsc->query->world, statement);
/* this origin URI literal is shared amongst the triples and
* freed only in rasqal_raptor_free_triples_source
*/
rasqal_triple_set_origin(triple->triple,
rtsc->source_literals[rtsc->source_index]);
if(rtsc->tail)
rtsc->tail->next=triple;
else
rtsc->head=triple;
rtsc->tail=triple;
}
static void
rasqal_raptor_error_handler(void *user_data,
raptor_locator* locator, const char *message) {
rasqal_query* query=(rasqal_query*)user_data;
query->failed=1;
if(locator) {
int locator_len=raptor_format_locator(NULL, 0, locator);
char *buffer=(char*)RASQAL_MALLOC(cstring, locator_len+1);
raptor_format_locator(buffer, locator_len, locator);
rasqal_log_error_simple(query->world, RAPTOR_LOG_LEVEL_ERROR,
&query->locator,
"Failed to parse %s - %s", buffer, message);
RASQAL_FREE(cstring, buffer);
} else
rasqal_log_error_simple(query->world, RAPTOR_LOG_LEVEL_ERROR,
&query->locator,
"Failed to parse - %s", message);
}
static unsigned char*
rasqal_raptor_generate_id_handler(void *user_data,
raptor_genid_type type,
unsigned char *user_bnodeid)
{
rasqal_raptor_triples_source_user_data* rtsc=(rasqal_raptor_triples_source_user_data*)user_data;
if(user_bnodeid) {
unsigned char *mapped_id;
mapped_id=(unsigned char*)RASQAL_MALLOC(cstring,
rtsc->mapped_id_base_len + 1 +
strlen((const char*)user_bnodeid) + 1);
strncpy((char*)mapped_id, (const char*)rtsc->mapped_id_base,
rtsc->mapped_id_base_len);
mapped_id[rtsc->mapped_id_base_len]='_';
strcpy((char*)(mapped_id+rtsc->mapped_id_base_len+1),
(const char*)user_bnodeid);
raptor_free_memory(user_bnodeid);
return mapped_id;
}
return rasqal_query_get_genid(rtsc->query, (const unsigned char*)"genid", -1);
}
static int
rasqal_raptor_new_triples_source(rasqal_query* rdf_query,
void *factory_user_data,
void *user_data,
rasqal_triples_source *rts) {
rasqal_raptor_triples_source_user_data* rtsc=(rasqal_raptor_triples_source_user_data*)user_data;
raptor_parser *parser;
int i;
if(!rdf_query->data_graphs)
return -1; /* no data */
rts->init_triples_match=rasqal_raptor_init_triples_match;
rts->triple_present=rasqal_raptor_triple_present;
rts->free_triples_source=rasqal_raptor_free_triples_source;
rtsc->sources_count=raptor_sequence_size(rdf_query->data_graphs);
/* no default triple source possible */
if(!rtsc->sources_count)
return -1; /* no data */
rtsc->source_literals=(rasqal_literal**)RASQAL_CALLOC(rasqal_literal_ptr, rtsc->sources_count, sizeof(rasqal_literal*));
rtsc->query=rdf_query;
for(i=0; i< rtsc->sources_count; i++) {
rasqal_data_graph *dg=(rasqal_data_graph*)raptor_sequence_get_at(rdf_query->data_graphs, i);
raptor_uri* uri=dg->uri;
raptor_uri* name_uri=dg->name_uri;
rtsc->source_index=i;
rtsc->source_uri=raptor_uri_copy(uri);
if(name_uri)
rtsc->source_literals[i]=rasqal_new_uri_literal(rdf_query->world, raptor_uri_copy(name_uri));
rtsc->mapped_id_base=rasqal_query_get_genid(rdf_query,
(const unsigned char*)"graphid",
i);
rtsc->mapped_id_base_len=strlen((const char*)rtsc->mapped_id_base);
parser=raptor_new_parser("guess");
raptor_set_statement_handler(parser, rtsc, rasqal_raptor_statement_handler);
raptor_set_error_handler(parser, rdf_query, rasqal_raptor_error_handler);
raptor_set_generate_id_handler(parser, rtsc,
rasqal_raptor_generate_id_handler);
#ifdef RAPTOR_FEATURE_NO_NET
if(rdf_query->features[RASQAL_FEATURE_NO_NET])
raptor_set_feature(parser, RAPTOR_FEATURE_NO_NET,
rdf_query->features[RASQAL_FEATURE_NO_NET]);
#endif
raptor_parse_uri(parser, uri, dg->name_uri);
raptor_free_parser(parser);
raptor_free_uri(rtsc->source_uri);
/* This is freed in rasqal_raptor_free_triples_source() */
/* rasqal_free_literal(rtsc->source_literal); */
RASQAL_FREE(cstring, rtsc->mapped_id_base);
if(rdf_query->failed) {
rasqal_raptor_free_triples_source(user_data);
break;
}
}
return rdf_query->failed;
}
/**
* rasqal_raptor_triple_match:
* @triple: #rasqal_triple to match against
* @match: #rasqal_triple with wildcards
* @parts; parts of the triple to match
* .
*
* Match a rasqal_triple against a rasqal_triple with NULL
* signifying wildcard fields in the rasqal_triple.
*
* Return value: non-0 on match
**/
static int
rasqal_raptor_triple_match(rasqal_triple *triple, rasqal_triple *match,
rasqal_triple_parts parts)
{
int rc=0;
#if RASQAL_DEBUG > 1
RASQAL_DEBUG1("\ntriple ");
rasqal_triple_print(triple, stderr);
fputs("\nmatch ", stderr);
rasqal_triple_print(match, stderr);
fputs("\n", stderr);
#endif
if(match->subject && (parts & RASQAL_TRIPLE_SUBJECT)) {
if(!rasqal_literal_equals_flags(triple->subject, match->subject,
RASQAL_COMPARE_RDF, NULL))
goto done;
}
if(match->predicate && (parts & RASQAL_TRIPLE_PREDICATE)) {
if(!rasqal_literal_equals_flags(triple->predicate, match->predicate,
RASQAL_COMPARE_RDF, NULL))
goto done;
}
if(match->object && (parts & RASQAL_TRIPLE_OBJECT)) {
if(!rasqal_literal_equals_flags(triple->object, match->object,
RASQAL_COMPARE_RDF, NULL))
goto done;
}
if(parts & RASQAL_TRIPLE_ORIGIN) {
/* Binding a graph */
/* If expecting a graph and triple has none then no match */
if(!triple->origin)
goto done;
if(match->origin) {
if(match->origin->type == RASQAL_LITERAL_URI ) {
raptor_uri* triple_uri=triple->origin->value.uri;
raptor_uri* match_uri=match->origin->value.uri;
if(!raptor_uri_equals(triple_uri, match_uri))
goto done;
}
}
} else {
/* Not binding a graph */
/* If triple has a GRAPH and there is none in the triple pattern, no match */
if(triple->origin)
goto done;
}
rc=1;
done:
#if RASQAL_DEBUG > 1
RASQAL_DEBUG2("result: %s\n", (rc ? "match" : "no match"));
#endif
return rc;
}
/* non-0 if present */
static int
rasqal_raptor_triple_present(rasqal_triples_source *rts, void *user_data,
rasqal_triple *t)
{
rasqal_raptor_triples_source_user_data* rtsc=(rasqal_raptor_triples_source_user_data*)user_data;
rasqal_raptor_triple *triple;
rasqal_triple_parts parts=RASQAL_TRIPLE_SPO;
if(t->origin)
parts = (rasqal_triple_parts)(parts | RASQAL_TRIPLE_GRAPH);
for(triple=rtsc->head; triple; triple=triple->next) {
if(rasqal_raptor_triple_match(triple->triple, t, parts))
return 1;
}
return 0;
}
static void
rasqal_raptor_free_triples_source(void *user_data) {
rasqal_raptor_triples_source_user_data* rtsc=(rasqal_raptor_triples_source_user_data*)user_data;
rasqal_raptor_triple *cur=rtsc->head;
int i;
while(cur) {
rasqal_raptor_triple *next=cur->next;
rasqal_triple_set_origin(cur->triple, NULL); /* shared URI literal */
rasqal_free_triple(cur->triple);
RASQAL_FREE(rasqal_raptor_triple, cur);
cur=next;
}
for(i=0; i< rtsc->sources_count; i++) {
if(rtsc->source_literals[i])
rasqal_free_literal(rtsc->source_literals[i]);
}
RASQAL_FREE(raptor_literal_ptr, rtsc->source_literals);
}
static void
rasqal_raptor_register_triples_source_factory(rasqal_triples_source_factory *factory)
{
factory->user_data_size=sizeof(rasqal_raptor_triples_source_user_data);
factory->new_triples_source=rasqal_raptor_new_triples_source;
}
typedef struct {
rasqal_raptor_triple *cur;
rasqal_raptor_triples_source_user_data* source_context;
rasqal_triple match;
/* parts of the triple above to match: always (S,P,O) sometimes C */
rasqal_triple_parts parts;
} rasqal_raptor_triples_match_context;
static rasqal_triple_parts
rasqal_raptor_bind_match(struct rasqal_triples_match_s* rtm,
void *user_data,
rasqal_variable* bindings[4],
rasqal_triple_parts parts) {
rasqal_raptor_triples_match_context* rtmc=(rasqal_raptor_triples_match_context*)rtm->user_data;
int error=0;
rasqal_triple_parts result=(rasqal_triple_parts)0;
#ifdef RASQAL_DEBUG
if(rtmc->cur) {
RASQAL_DEBUG1(" matched statement ");
rasqal_triple_print(rtmc->cur->triple, stderr);
fputc('\n', stderr);
} else
RASQAL_FATAL1(" matched NO statement - BUG\n");
#endif
/* set variable values from the fields of statement */
if(bindings[0] && (parts & RASQAL_TRIPLE_SUBJECT)) {
RASQAL_DEBUG1("binding subject to variable\n");
rasqal_variable_set_value(bindings[0],
rasqal_new_literal_from_literal(rtmc->cur->triple->subject));
result= RASQAL_TRIPLE_SUBJECT;
}
if(bindings[1] && (parts & RASQAL_TRIPLE_PREDICATE)) {
if(bindings[0] == bindings[1]) {
if(!rasqal_literal_equals_flags(rtmc->cur->triple->subject,
rtmc->cur->triple->predicate,
RASQAL_COMPARE_RDF, &error))
return (rasqal_triple_parts)0;
if(error)
return (rasqal_triple_parts)0;
RASQAL_DEBUG1("subject and predicate values match\n");
} else {
RASQAL_DEBUG1("binding predicate to variable\n");
rasqal_variable_set_value(bindings[1],
rasqal_new_literal_from_literal(rtmc->cur->triple->predicate));
result= (rasqal_triple_parts)(result | RASQAL_TRIPLE_PREDICATE);
}
}
if(bindings[2] && (parts & RASQAL_TRIPLE_OBJECT)) {
int bind=1;
if(bindings[0] == bindings[2]) {
if(!rasqal_literal_equals_flags(rtmc->cur->triple->subject,
rtmc->cur->triple->object,
RASQAL_COMPARE_RDF, &error))
return (rasqal_triple_parts)0;
if(error)
return (rasqal_triple_parts)0;
bind=0;
RASQAL_DEBUG1("subject and object values match\n");
}
if(bindings[1] == bindings[2] &&
!(bindings[0] == bindings[1]) /* don't do this check if ?x ?x ?x */
) {
if(!rasqal_literal_equals_flags(rtmc->cur->triple->predicate,
rtmc->cur->triple->object,
RASQAL_COMPARE_RDF, &error))
return (rasqal_triple_parts)0;
if(error)
return (rasqal_triple_parts)0;
bind=0;
RASQAL_DEBUG1("predicate and object values match\n");
}
if(bind) {
RASQAL_DEBUG1("binding object to variable\n");
rasqal_variable_set_value(bindings[2],
rasqal_new_literal_from_literal(rtmc->cur->triple->object));
result= (rasqal_triple_parts)(result | RASQAL_TRIPLE_OBJECT);
}
}
if(bindings[3] && (parts & RASQAL_TRIPLE_ORIGIN)) {
rasqal_literal *l=rasqal_new_literal_from_literal(rtmc->cur->triple->origin);
RASQAL_DEBUG1("binding origin to variable\n");
rasqal_variable_set_value(bindings[3], l);
result= (rasqal_triple_parts)(result | RASQAL_TRIPLE_ORIGIN);
}
return result;
}
static void
rasqal_raptor_next_match(struct rasqal_triples_match_s* rtm, void *user_data)
{
rasqal_raptor_triples_match_context* rtmc=(rasqal_raptor_triples_match_context*)rtm->user_data;
while(rtmc->cur) {
rtmc->cur=rtmc->cur->next;
if(rtmc->cur &&
rasqal_raptor_triple_match(rtmc->cur->triple, &rtmc->match, rtmc->parts))
break;
}
}
static int
rasqal_raptor_is_end(struct rasqal_triples_match_s* rtm, void *user_data)
{
rasqal_raptor_triples_match_context* rtmc=(rasqal_raptor_triples_match_context*)rtm->user_data;
return !rtmc || rtmc->cur == NULL;
}
static void
rasqal_raptor_finish_triples_match(struct rasqal_triples_match_s* rtm,
void *user_data) {
rasqal_raptor_triples_match_context* rtmc=(rasqal_raptor_triples_match_context*)rtm->user_data;
if(rtmc->match.subject)
rasqal_free_literal(rtmc->match.subject);
if(rtmc->match.predicate)
rasqal_free_literal(rtmc->match.predicate);
if(rtmc->match.object)
rasqal_free_literal(rtmc->match.object);
if(rtmc->match.origin)
rasqal_free_literal(rtmc->match.origin);
RASQAL_FREE(rasqal_raptor_triples_match_context, rtmc);
}
static int
rasqal_raptor_init_triples_match(rasqal_triples_match* rtm,
rasqal_triples_source *rts, void *user_data,
rasqal_triple_meta *m, rasqal_triple *t) {
rasqal_raptor_triples_source_user_data* rtsc=(rasqal_raptor_triples_source_user_data*)user_data;
rasqal_raptor_triples_match_context* rtmc;
rasqal_variable* var;
rtm->bind_match=rasqal_raptor_bind_match;
rtm->next_match=rasqal_raptor_next_match;
rtm->is_end=rasqal_raptor_is_end;
rtm->finish=rasqal_raptor_finish_triples_match;
rtmc=(rasqal_raptor_triples_match_context*)RASQAL_CALLOC(rasqal_raptor_triples_match_context, 1, sizeof(rasqal_raptor_triples_match_context));
rtm->user_data=rtmc;
rtmc->source_context=rtsc;
rtmc->cur=rtsc->head;
/* at least one of the triple terms is a variable and we need to
* do a triplesMatching() over the list of stored raptor_statements
*/
if((var=rasqal_literal_as_variable(t->subject))) {
if(var->value)
rtmc->match.subject=rasqal_new_literal_from_literal(var->value);
} else
rtmc->match.subject=rasqal_new_literal_from_literal(t->subject);
m->bindings[0]=var;
if((var=rasqal_literal_as_variable(t->predicate))) {
if(var->value)
rtmc->match.predicate=rasqal_new_literal_from_literal(var->value);
} else
rtmc->match.predicate=rasqal_new_literal_from_literal(t->predicate);
m->bindings[1]=var;
if((var=rasqal_literal_as_variable(t->object))) {
if(var->value)
rtmc->match.object=rasqal_new_literal_from_literal(var->value);
} else
rtmc->match.object=rasqal_new_literal_from_literal(t->object);
m->bindings[2]=var;
rtmc->parts = RASQAL_TRIPLE_SPO;
if(t->origin) {
if((var=rasqal_literal_as_variable(t->origin))) {
if(var->value)
rtmc->match.origin=rasqal_new_literal_from_literal(var->value);
} else
rtmc->match.origin=rasqal_new_literal_from_literal(t->origin);
m->bindings[3]=var;
rtmc->parts = (rasqal_triple_parts)(rtmc->parts | RASQAL_TRIPLE_GRAPH);
}
while(rtmc->cur) {
if(rasqal_raptor_triple_match(rtmc->cur->triple, &rtmc->match, rtmc->parts))
break;
rtmc->cur=rtmc->cur->next;
}
RASQAL_DEBUG1("rasqal_init_triples_match done\n");
return 0;
}
int
rasqal_raptor_init(rasqal_world* world) {
rasqal_set_triples_source_factory(world, rasqal_raptor_register_triples_source_factory, (void*)NULL);
return 0;
}
| 31.869436 | 157 | 0.690223 | [
"object"
] |
0907ad6e41d7754667edc53f3a61e463d8350893 | 24,790 | h | C | src/hg/hgTracks/imageV2.h | andypohl/kent | af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1 | [
"MIT"
] | 171 | 2015-04-22T15:16:02.000Z | 2022-03-18T20:21:53.000Z | src/hg/hgTracks/imageV2.h | andypohl/kent | af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1 | [
"MIT"
] | 60 | 2016-10-03T15:15:06.000Z | 2022-03-30T15:21:52.000Z | src/hg/hgTracks/imageV2.h | andypohl/kent | af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1 | [
"MIT"
] | 80 | 2015-04-16T10:39:48.000Z | 2022-03-29T16:36:30.000Z | // imageV2 - API for creating the image V2 features.
/* Copyright (C) 2014 The Regents of the University of California
* See kent/LICENSE or http://genome.ucsc.edu/license/ for licensing information. */
#ifndef IMAGEV2_H
#define IMAGEV2_H
// DRAG_SCROLL means dragging the image left-right to reposition the viewing window on the chrom.
// NOTE: 1x works fine and is released. Set IMAGEv2_DRAG_SCROLL_SZ > 1 (3=3x)
// to see hidden image while dragging.
#ifndef IMAGEv2_DRAG_SCROLL_SZ
#define IMAGEv2_DRAG_SCROLL_SZ 1
#endif
#if defined(IMAGEv2_DRAG_SCROLL_SZ) && (IMAGEv2_DRAG_SCROLL_SZ > 1)
#define IMAGEv2_SHORT_MAPITEMS
//#define IMAGEv2_SHORT_TOGGLE
//#define IMAGEv2_NO_LEFTLABEL_ON_FULL
// Because the sideLabel clipping will leave a no longer needed label
// aligned with the centerLabel, we will need to either: remove sideLabels
// (which otherwise work) OR add a new side-slice to match the centerlabel
#endif //defined(IMAGEv2_DRAG_SCROLL_SZ) && (IMAGEv2_DRAG_SCROLL_SZ > 1)
// CURRENT PROBLEMS with dragScroll > 1X:
// o Dynamic height for data/label based on image map currently works EXCEPT,
// occasionally does not resize. Consider resize while dragging!
// o next item feature '>>' arrows should check if items are in the wings
// o next exon feature '>>' arrows are only seen in the wings and only look beyond the wings
// UNCOMMENT USE_NAVIGATION_LINKS for so far experimental UI changes to replace buttons at top
// with more streamlined links
//#define USE_NAVIGATION_LINKS
extern struct imgBox *theImgBox; // Make this global for now to avoid huge rewrite
extern struct imgTrack *curImgTrack; // Make this global for now to avoid huge rewrite
/////////////////////////
// FLAT TRACKS
// A simplistic way of flattening the track list before building the image
// NOTE: Strategy is NOT to use imgBox->imgTracks, since this should be independent of imageV2
// These should probably be moved to hgTracks.h
/////////////////////////
struct flatTracks // List of tracks in image, flattened to promote subtracks
{
struct flatTracks *next; // Next on list.
struct track *track; // Track (the track list is still heirarchical
int order; // Image order: This keeps track of dragReorder
int maxHeight; // largest height among all windows in image.
};
void flatTracksAdd(struct flatTracks **flatTracks,struct track *track,struct cart *cart, struct slName *orderedWiggles);
// Adds one track into the flatTracks list
int flatTracksCmp(const void *va, const void *vb);
// Compare to sort on flatTrack->order
void flatTracksSort(struct flatTracks **flatTracks);
// This routine sorts the imgTracks then forces tight ordering, so new tracks wil go to the end
void flatTracksFree(struct flatTracks **flatTracks);
// Frees all memory used to support flatTracks (underlying tracks are untouched)
/////////////////////////
// JSON support. Eventually the whole imgTbl could be written out as JSON
void jsonTdbSettingsBuild(struct jsonElement *settings, struct track *track, boolean configurable);
// Creates then successively adds trackDb settings to the jsonTdbSettingsString
// Initially pass in NULL pointer to a dyString to properly begin building
void jsonTdbSettingsUse(struct jsonElement *settings);
// Closes and returns the contents of the jsonTdbSettingsString
/////////////////////////
// IMAGEv2
// The new way to do images
// Terms:
// "image box": The new version of the image on the html page. It is a table with rows that
// contain tracks which are made up of parts of images.
// "imgBox": This C struct contains all information to render the image box on the html page.
// "imgTbl": The HTML structure that contains individual track images.
// The javascript client controls the imgTbl.
// Thus cgi knows imgBox while html/js knows imgTbl.
// "image": A single png. An image may contain mutilple tracks.
// Even as a single track and image may contain a data image, centerLabel, sideLabel and button.
// "map": (or "mapSet") The image map for providing links to items in a data image.
// An image and map are a 1 to 1 pair and pixel coordinates are always image relative.
// "slice": (or "imgSlice") The cgi concept of the portion of an image that is sent to the
// html/js side. If we are sending a 3X sized image, the "slice" spans the entire 3X.
// Almost always a subset of an image, but possibly the whole image.
// Even if the image is of a single track, it will still be cut into data image,
// sideLabel and centerLabel slices.
// "sliceMap": The portion of a map that belongs to a slice. The pixel coordinates are always
// image relative, not slice relative.
// "portal": (or "imgPortal") The html/js concept of the portion of a data slice that is visible in
// the browser. Thus, if we are sending a 3X sized data image slice, the "portal" seen
// in the browser spans only 1X.
// "imgTrack": (or track image) The cgi side whole shabang for rendering one track. It contains
// track specific information and four slices: data, centerLabel, sideLabel and button
// The imgBox contains N imgTracks. Typically an ajax/JSON request gets a single
// imgTrack returned, which then is updated in the imgTbl containing multiple tracks.
// image box support: This can contain all the support variables that are global to the image box
// (like font size, box width, etc.). At this point, lets not talk structure
// or cgi vs. html/js but leave this container as a concept that we know
// needs filling.
// imgBox is the top level and contains all info to draw the image in HTML
// - contains slList of all imgTrack structs shown
// imgTrack contains all info to display one track/subtrack in the imgBox
// - contains 4 imgSlice structs (data, centerLabel, sideLabel, button)
// imgSlice contains all info to display a portion of an image file
// - contains 1 image struct
// image contains all information about an image file and associated map box
/////////////////////////
/////////////////////// Maps
struct mapItem // IMAGEv2: single map item in an image map.
{
struct mapItem *next; // slList
char *linkVar; // the get variables associated with the map link
char *title; // item title
int topLeftX; // in pixels relative to image
int topLeftY; // in pixels relative to image
int bottomRightX; // in pixels relative to image
int bottomRightY; // in pixels relative to image
char *id; // id; used by js right-click code to figure out what to do with
// a map item (usually mapName)
};
struct mapSet // IMAGEv2: full map for image OR partial map for slice
{
char *name; // to point an image to a map in HTML
struct image *parentImg; // points to the image this map belongs to
char *linkRoot; // the common or static portion of the link for the entire image
struct mapItem *items; // list of items
};
// To create map items which have mouse-over titles but no link, fill link with:
#define TITLE_BUT_NO_LINK "noLink"
struct mapSet *mapSetStart(char *name,struct image *img,char *linkRoot);
// Starts a map (aka mapSet) which is the seet of links and image locations used in HTML.
// Complete a map by adding items with mapItemAdd()
struct mapSet *mapSetUpdate(struct mapSet *map,char *name,struct image *img,char *linkRoot);
// Updates an existing map (aka mapSet)
struct mapItem *mapSetItemFind(struct mapSet *map,int topLeftX,int topLeftY,
int bottomRightX,int bottomRightY);
// Find a single mapItem based upon coordinates (within a pixel)
struct mapItem *mapSetItemUpdate(struct mapSet *map,struct mapItem *item,char *link,char *title,
int topLeftX,int topLeftY,int bottomRightX,int bottomRightY,
char *id);
// Update an already existing mapItem
struct mapItem *mapSetItemAdd(struct mapSet *map,char *link,char *title,int topLeftX,int topLeftY,
int bottomRightX,int bottomRightY, char *id);
// Add a single mapItem to a growing mapSet
struct mapItem *mapSetItemUpdateOrAdd(struct mapSet *map,char *link,char *title,
int topLeftX,int topLeftY,int bottomRightX,int bottomRightY,
char *id);
// Update or add a single mapItem
struct mapItem *mapSetItemFindOrAdd(struct mapSet *map,char *link,char *title,
int topLeftX,int topLeftY,int bottomRightX,int bottomRightY,
char *id);
// Finds or adds the map item
void mapItemFree(struct mapItem **pItem);
// frees all memory assocated with a single mapItem
boolean mapItemConsistentWithImage(struct mapItem *item,struct image *img,boolean verbose);
// Test whether a map item is consistent with the image it is supposed to be for
boolean mapSetIsComplete(struct mapSet *map,boolean verbose);
// Tests the completeness and consistency of this map (mapSet)
void mapSetFree(struct mapSet **pMap);
// frees all memory (including items) assocated with a single mapSet
/////////////////////// Images
struct image // IMAGEv2: single image which may have multiple imgSlices focused on it
{
struct image *next; // slList (Not yet used)
char *file; // name of file that hold the image
char *title; // image wide title
int width; // in pixels
int height; // in pixels
struct mapSet *map; // map assocated with this image (may be NULL)
};
struct image *imgCreate(char *png,char *title,int width,int height);
// Creates a single image container.
// A map map be added with imgMapStart(),mapSetItemAdd()
struct mapSet *imgMapStart(struct image *img,char *name,char *linkRoot);
// Starts a map associated with an image.
// Map items can then be added to the returned pointer with mapSetItemAdd()
struct mapSet *imgGetMap(struct image *img);
// Gets the map associated with this image.
// Map items can then be added to the map with mapSetItemAdd()
void imgFree(struct image **pImg);
// frees all memory assocated with an image (including a map)
/////////////////////// Slices
enum sliceType
{
stUnknown=0, // Invalid
stData=1, // Data or track slice of an image
stCenter=2, // Top or centerLabel slice of an image
stButton=3, // Config button (by separating from side label, can have
// separate image which is colored/zipped by javascript)
stSide=4, // Side or leftLabel slice of an image
stInvalid=5 // Invalid
};
#define stMaxSliceTypes stInvalid
struct imgSlice // IMAGEv2: the portion of an image that is displayable for one track
{
struct imgSlice *next; // slList
enum sliceType type; // Type of slice (currently only 3)
struct image *parentImg; // the actual image/png
char *title; // slice wide title
struct mapSet *map; // A slice specific map. It contains a subset of the img->map.
// Coordinates must be img relative NOT slice relative!
char *link; // If a slice has no map, it may have a whole slice link
int width; // in pixels (differs from img->width if img contains sideLabel)
int height; // in pixels (differs from img->height if
// img contains centerLabel and/or multiple tracks)
int offsetX; // offset from left (when img->width > slice->width)
int offsetY; // offset from top (when img->height > slice->height)
};
struct imgSlice *sliceCreate(enum sliceType type,struct image *img,char *title,
int width,int height,int offsetX,int offsetY);
// Creates of a slice which is a portion of an image.
// A slice specific map map be added with sliceMapStart(),mapSetItemAdd()
struct imgSlice *sliceUpdate(struct imgSlice *slice,enum sliceType type,struct image *img,
char *title,int width,int height,int offsetX,int offsetY);
// updates an already created slice
char *sliceTypeToString(enum sliceType type);
// Translate enum slice type to string
struct imgSlice *sliceAddLink(struct imgSlice *slice,char *link,char *title);
// Adds a slice wide link. The link and map are mutually exclusive
struct mapSet *sliceMapStart(struct imgSlice *slice,char *name,char *linkRoot);
// Adds a slice specific map to a slice of an image.
// Map items can then be added to the returned pointer with mapSetItemAdd()
struct mapSet *sliceGetMap(struct imgSlice *slice,boolean sliceSpecific);
// Gets the map associate with a slice which may be sliceSpecific or it may belong to the
// slices' image. Map items can then be added to the map returned with mapSetItemAdd().
struct mapSet *sliceMapFindOrStart(struct imgSlice *slice,char *name,char *linkRoot);
// Finds the slice specific map or starts it
struct mapSet *sliceMapUpdateOrStart(struct imgSlice *slice,char *name,char *linkRoot);
// Updates the slice specific map or starts it
boolean sliceIsConsistent(struct imgSlice *slice,boolean verbose);
// Test whether the slice and it's associated image and map are consistent with each other
void sliceFree(struct imgSlice **pSlice);
// frees all memory assocated with a slice
// (not including the image or a map belonging to the image)
/////////////////////// imgTracks
enum centerLabelSeen
{
clUnknown=0, // Invalid
clAlways=1, // Default is always seen
clNowSeen=2, // Conditionally and currently seen
clNotSeen=3 // Conditionally and currently unseen
};
struct imgTrack // IMAGEv2: imageBox contains list of displayed imageTracks
{
struct imgTrack *next; // slList
struct trackDb *tdb; // trackDb entry (should this be struct track* entry?)
char *name; // It is possible to have an imgTrack without a tdb,
// but then it must have a name
char *db; // Image for db (species) (assert imgTrack matches imgBox)
char *chrom; // Image for chrom (assert imgTrack matches imgBox)
long chromStart; // Image start (absolute, not portal position)
long chromEnd; // Image end (absolute, not portal position)
boolean plusStrand; // Image covers plus strand, not minus strand
boolean hasCenterLabel; // A track may have a center label but not show it
enum centerLabelSeen centerLabelSeen; // Conditionally displayed center labels are always
// there but sometimes hidden
boolean reorderable; // Is this track reorderable (by drag and drop) ?
boolean ajaxRetrieval; // This track needs to be retrieved via ajax
int order; // Image order: This keeps track of dragReorder
enum trackVisibility vis; // Current visibility of track image
struct imgSlice *slices; // Currently there should be four slices for every track:
// data, centerLabel, sideLabel, button
};
#define IMG_ANYORDER -2
#define IMG_FIXEDPOS -1
#define IMG_ORDERTOP 10000
#define IMG_ORDEREND 20000
#define IMG_ORDER_VAR "imgOrd"
struct imgTrack *imgTrackStart(struct trackDb *tdb,char *name,char *db,
char *chrom, long chromStart, long chromEnd, boolean plusStrand,
boolean hasCenterLabel, enum trackVisibility vis, int order);
// Starts an image track which will contain all image slices needed to render one track
// Must completed by adding slices with imgTrackAddSlice()
struct imgTrack *imgTrackUpdate(struct imgTrack *imgTrack,struct trackDb *tdb,char *name,
char *db,char *chrom, long chromStart, long chromEnd, boolean plusStrand,
boolean hasCenterLabel, enum trackVisibility vis, int order);
// Updates an already existing image track
void imgTrackMarkForAjaxRetrieval(struct imgTrack *imgTrack,boolean ajaxRetrieval);
// Updates the imgTrack to trigger an ajax callback from the html client to get this track
#define imgTrackMarkedForAjaxRetrieval(imgTrack) ((imgTrack)->ajaxRetrieval)
// Is this imgTrack marked for Ajax retrieval
#define imgTrackUpdateCenterLabelSeen(slice,seen) { (slice)->centerLabelSeen = (seen); }
// Center slices are occasionally unseen
int imgTrackOrderCmp(const void *va, const void *vb);
// Compare to sort on label.
struct imgSlice *imgTrackSliceAdd(struct imgTrack *imgTrack,enum sliceType type, struct image *img,
char *title,int width,int height,int offsetX,int offsetY);
// Adds slices to an image track. Expected are types: stData, stButton, stSide and stCenter
struct imgSlice *imgTrackSliceGetByType(struct imgTrack *imgTrack,enum sliceType type);
// Gets a specific slice already added to an image track.
// Expected are types: stData, stButton, stSide and stCenter
struct imgSlice *imgTrackSliceFindOrAdd(struct imgTrack *imgTrack,enum sliceType type,
struct image *img,char *title,int width,int height,
int offsetX,int offsetY);
// Find the slice or adds it
struct imgSlice *imgTrackSliceUpdateOrAdd(struct imgTrack *imgTrack,enum sliceType type,
struct image *img,char *title,int width,int height,
int offsetX,int offsetY);
// Updates the slice or adds it
int imgTrackCoordinates(struct imgTrack *imgTrack, int *leftX,int *topY,int *rightX,int *bottomY);
// Fills in topLeft x,y and bottomRight x,y coordinates, returning topY.
#define imgTrackTopY(imgTrack) imgTrackCoordinates(imgTrack,NULL,NULL,NULL,NULL)
// Returns the Y coordinate of the top of the track.
int imgTrackBottomY(struct imgTrack *imgTrack);
// Returns the Y coordinate of the bottom of the track.
struct mapSet *imgTrackGetMapByType(struct imgTrack *imgTrack,enum sliceType type);
// Gets the map assocated with a specific slice belonging to the imgTrack
int imgTrackAddMapItem(struct imgTrack *imgTrack,char *link,char *title,int topLeftX,int topLeftY,
int bottomRightX,int bottomRightY, char *id);
// Will add a map item it an imgTrack's appropriate slice's map
// Since a map item may span slices, the imgTrack is in the best position to determine where
// to put the map item.
// Returns count of map items added, which could be 0, 1 or more than one if item spans slices
// NOTE: Precedence is given to first map item when adding items with same coordinates!
boolean imgTrackIsComplete(struct imgTrack *imgTrack,boolean verbose);
// Tests the completeness and consistency of this imgTrack (including slices)
void imgTrackFree(struct imgTrack **pImgTrack);
// frees all memory assocated with an imgTrack (including slices)
/////////////////////// Image Box
struct imgBox // IMAGEv2: imageBox conatins all the definitions to draw an image in hgTracks
{
char *db; // database (species)
char *chrom; // chrom
long chromStart; // Image start (absolute, not portal position)
long chromEnd; // Image end (absolute, not portal position)
boolean plusStrand; // imgBox currently shows plus strand, not minus strand
struct image *images; // Contains all images for the imgBox. TEMPORARY: hgTracks creates
// it's current one image and I'll store it here
struct image *bgImg; // When track images are transparent, bgImage contains blue lines
// that are db coordinate granularity.
int width; // in pixels (note that portalWidth in visible position within
// image position in db coodinates)
boolean showSideLabel; // Initially display side label? (use 'plusStrand' for left/right)
int sideLabelWidth; // in pixels (note this is needed when setting up a portal
// and dragScrolling)
boolean showPortal; // Rather than showing the entire data range, only show a portion,
// and allow dragScrolling
double basesPerPixel; // number of bases covered by a single pixel
long portalStart; // initial visible portal within html image table (db coodinates)
// [May be obsoleted by js client]
long portalEnd; // initial visible portal within html image table (db coodinates)
// [May be obsoleted by js client]
int portalWidth; // in pixels (should be equal to the visible position of data slice)
struct imgTrack *imgTracks; // slList of all images to display
};
struct imgBox *imgBoxStart(char *db, char *chrom, long chromStart, long chromEnd,
boolean plusStrand, int sideLabelWidth, int width);
// Starts an imgBox which should contain all info needed to draw the hgTracks image with
// multiple tracks. The image box must be completed using imgBoxImageAdd() and imgBoxTrackAdd()
boolean imgBoxPortalDefine(struct imgBox *imgBox, long *chromStart, long *chromEnd,
int *imgWidth,double imageMultiple);
// Defines the portal of the imgBox. The portal is the initial viewable region when dragScroll
// is being used. The new chromStart,chromEnd and imgWidth are returned as OUTs, while the
// portal becomes the initial defined size
// Returns TRUE if successfully defined as having a portal.
boolean imgBoxPortalRemove(struct imgBox *imgBox, long *chromStart, long *chromEnd, int *imgWidth);
// Will redefine the imgBox as the portal dimensions and return the dimensions as OUTs.
// Returns TRUE if a portal was defined in the first place
boolean imgBoxPortalDimensions(struct imgBox *imgBox, long *chromStart, long *chromEnd,
int *imgWidth, int *sideLabelWidth,
long *portalStart, long *portalEnd, int *portalWidth,
double *basesPerPixel);
// returns the imgBox portal dimensions in the OUTs returns TRUE if portal defined
struct image *imgBoxImageAdd(struct imgBox *imgBox,char *png,char *title,int width,int height,
boolean backGround);
// Adds an image to an imgBox. The image may be extended with imgMapStart(),mapSetItemAdd()
struct image *imgBoxImageFind(struct imgBox *imgBox,char *png);
// Finds a specific image already added to this imgBox
struct imgTrack *imgBoxTrackAdd(struct imgBox *imgBox,struct trackDb *tdb,char *name,
enum trackVisibility vis,boolean hasCenterLabel,int order);
// Adds an imgTrack to an imgBox. The imgTrack needs to be extended with imgTrackAddSlice()
struct imgTrack *imgBoxTrackFind(struct imgBox *imgBox,struct trackDb *tdb,char *name);
// Finds a specific imgTrack already added to this imgBox
struct imgTrack *imgBoxTrackFindOrAdd(struct imgBox *imgBox,struct trackDb *tdb,char *name,
enum trackVisibility vis,boolean hasCenterLabel,int order);
// Find the imgTrack, or adds it if not found
struct imgTrack *imgBoxTrackUpdateOrAdd(struct imgBox *imgBox,struct trackDb *tdb,char *name,
enum trackVisibility vis,boolean hasCenterLabel,int order);
// Updates the imgTrack, or adds it if not found
void imgBoxTracksNormalizeOrder(struct imgBox *imgBox);
// This routine sorts the imgTracks
int imgBoxDropEmpties(struct imgBox *imgBox);
// Empty imageTracks (without slices) is not an error but they should be dropped.
// returns remaining current track count
boolean imgBoxIsComplete(struct imgBox *imgBox,boolean verbose);
// Tests the completeness and consistency of an imgBox.
void imgBoxFree(struct imgBox **pImgBox);
// frees all memory assocated with an imgBox (including images and imgTracks)
/////////////////////// imageV2 UI API
void imageBoxDraw(struct imgBox *imgBox);
// writes a entire imgBox including all tracks as HTML
#endif//ndef IMAGEV2_H
| 52.410148 | 120 | 0.67862 | [
"render"
] |
090f826819308c58bbaa811ea6c57cfd07afea69 | 3,692 | h | C | src/field.h | sara-nl/prace_topologies | 26b35ab27cf08062892ce9c20c9a046ac99f4338 | [
"MIT"
] | 4 | 2021-06-10T15:22:29.000Z | 2021-06-11T13:32:31.000Z | src/field.h | sara-nl/prace_topologies | 26b35ab27cf08062892ce9c20c9a046ac99f4338 | [
"MIT"
] | null | null | null | src/field.h | sara-nl/prace_topologies | 26b35ab27cf08062892ce9c20c9a046ac99f4338 | [
"MIT"
] | 1 | 2021-06-10T15:22:32.000Z | 2021-06-10T15:22:32.000Z | /*
* Copyright (c) 2021 Maksim Masterov, SURF
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef UNBALANCED_WORKLOAD_FIELD_H
#define UNBALANCED_WORKLOAD_FIELD_H
#include <vector>
#include <cmath>
#include "General/structs.h"
class Field {
public:
Field();
~Field();
/*!
* @brief Initialize the field.
* @param elts_loc Number of global elements.
* @param elts_glob Number of local elements.
*/
void initialize(IndicesIJ elts_loc, IndicesIJ elts_glob);
/*!
* @brief Generate the field.
*/
void generate();
/*!
* @brief Print field into the file.
* @param base_name Base name of the file.
*/
void print(std::string base_name);
/*!
* @brif Distribute the field across processes.
* Use the provided \e partitioning to distribute the field.
* @param partitioning Partitioning of the field.
* @param num_glob_elts Global number of elements.
* @param root_pid PID of the process that stores the field and partitioning.
*/
void distribute(int32_t* partitioning, int num_glob_elts, int root_pid);
/*!
* @brief Emulate some work by each process.
*/
double performDummyWork();
/*!
* @brief Get number of elements in the field.
*/
inline int getNumElts() {
return data.size();
}
/*!
* @brief Get reference to the field.
*/
inline std::vector<double>& getData() {
return data;
}
/*!
* @brief Get reference to a particular element in the field.
* @param n ID of the element.
* @return Reference to the element.
*/
inline double& operator()(int n) {
return data[n];
}
/*!
* @brief Get reference to a particular element in the field.
* @param i i-th index of the element.
* @param j j-th index of the element.
* @return Reference to the element.
*/
inline double& operator()(int i, int j) {
return data[getLocalID(i, j)];
}
/*!
* @brief Get local ID of the element.
* @param i i-th index of the element.
* @param j j-th index of the element.
* @return Local for a process ID.
*/
inline int getLocalID(int i, int j) {
return j + _elts_loc.j * i;
}
/*!
* @brief Evaluate the workload for the specified value.
* @param value Value to be used during the evaluation.
* @return Workload.
*/
inline double getLocalLoad(double value) {
return std::exp(15. * value);
}
private:
std::vector<double> data;
IndicesIJ _elts_loc;
IndicesIJ _elts_glob;
};
#endif //UNBALANCED_WORKLOAD_FIELD_H
| 28.84375 | 81 | 0.657909 | [
"vector"
] |
09135fdb282281923c548c32f40cadf2c0333007 | 1,979 | h | C | gxsetup/render.h | madd-games/glidix | 1510d9c3f159bee9d4aa942e715aedc78b7f827c | [
"BSD-2-Clause"
] | 98 | 2015-08-05T22:20:19.000Z | 2022-03-11T08:49:24.000Z | gxsetup/render.h | madd-games/glidix | 1510d9c3f159bee9d4aa942e715aedc78b7f827c | [
"BSD-2-Clause"
] | 5 | 2016-02-23T12:49:24.000Z | 2019-10-11T18:09:47.000Z | gxsetup/render.h | madd-games/glidix | 1510d9c3f159bee9d4aa942e715aedc78b7f827c | [
"BSD-2-Clause"
] | 11 | 2015-12-02T05:01:28.000Z | 2021-06-25T16:54:18.000Z | /*
Glidix Installer
Copyright (c) 2014-2017, Madd Games.
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 HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RENDER_H_
#define RENDER_H_
#include <inttypes.h>
#define COLOR_BACKGROUND 0x1F
#define COLOR_WINDOW 0x70
#define COLOR_SHADOW 0x01
#define COLOR_SELECTION 0x4F
#define COLOR_TEXTFIELD 0x07
#define COLOR_PROGRESS 0x0A
#define COLOR_SCROLLBAR 0x83
/**
* Render a window of the specified size, caption and status bar, and store the coordinates of its
* top-left corner in (*startX, *startY).
*/
void renderWindow(const char *status, const char *caption, int width, int height, int *startX, int *startY);
void setColor(uint8_t col);
void setCursor(uint8_t x, uint8_t y);
void clearScreen();
#endif
| 37.339623 | 108 | 0.778676 | [
"render"
] |
0914b7db4ebd18638a7d07ab8e58eabe8ce32ac9 | 10,392 | h | C | metadb/dbtypes.h | yux20000304/indexfs | e0b9a742e2fe9b231f06803a5af2e0c596e0d7c6 | [
"BSD-3-Clause"
] | 2 | 2021-05-29T07:27:23.000Z | 2022-02-26T18:16:07.000Z | metadb/dbtypes.h | yux20000304/indexfs | e0b9a742e2fe9b231f06803a5af2e0c596e0d7c6 | [
"BSD-3-Clause"
] | null | null | null | metadb/dbtypes.h | yux20000304/indexfs | e0b9a742e2fe9b231f06803a5af2e0c596e0d7c6 | [
"BSD-3-Clause"
] | 3 | 2021-01-18T03:42:53.000Z | 2022-01-02T14:50:03.000Z | // Copyright (c) 2014 The IndexFS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#ifndef _INDEXFS_METADB_TYPES_H_
#define _INDEXFS_METADB_TYPES_H_
#include <string.h>
#include <endian.h>
#include <stdint.h>
#include "metadb/fstat.h"
#include "common/gigaidx.h"
#include "common/common.h"
#include "common/logging.h"
#include "common/murmurhash3.h"
namespace indexfs {
// IndexFS features an unique metadata representation where each file system object
// (such as file, directory, as well as other special entities) is represented by a
// key-value pair stored in an underlying key-value store (such as LevelDB) using
// log-structured and indexed data structures (SSTables).
//
namespace mdb {
class MDBKey;
class MDBValue;
class MDBValueRef;
// In IndexFS, each file system object is represented by a key-value pair. The key
// is able to uniquely identify an object inside a global file system namespace.
//
// A typical key consists of the following three fields:
// 1) parent_id, 2) partition_id, 3) name_hash.
//
// Special keys do not have a partition_id.
//
// Since the size of the key will have significant effects on overall system
// performance, keys are designed to be as small as possible. Currently, each key
// consists of a 6-byte parent id, a 2-byte partition id, and an 8-byte name hash.
//
struct MDBKey {
int64_t GetParent() const; // Returns the parent id
int16_t GetPartition() const; // Returns the partition id
// Special key constructor.
// Creates a special key featuring a negative id.
//
MDBKey(int64_t special_id) {
DLOG_ASSERT(special_id < 0);
InitSpecial(special_id);
memset(GetNameHash(), 0, kHashSize);
}
// Normal key constructor.
// Creates an ordinary key consisting of a positive parent id,
// a partition id and an empty hash.
//
MDBKey(int64_t parent_id, int16_t partition_id) {
DLOG_ASSERT(parent_id >= 0);
Init(parent_id, partition_id);
memset(GetNameHash(), 0, kHashSize);
}
// Normal key constructor.
// Creates an ordinary key consisting of a positive parent id,
// a partition id and a hash deduced from the specified file name.
//
MDBKey(int64_t parent_id,
int16_t partition_id,
const std::string &name) {
DLOG_ASSERT(parent_id >= 0);
Init(parent_id, partition_id);
MurmurHash3_x64_128(name.data(), name.length(), 0, GetNameHash());
}
// Returns the overall size of the key, which currently is a
// fixed value.
//
inline size_t GetKeySize() const {
return kTotalSize;
}
// Returns the size of the name hash inside the key, which currently is
// a fixed value.
//
inline size_t GetHashSize() const {
return kHashSize;
}
// Returns the size of the prefix (directory id + partition id) inside
// the key, which currently is a fixed value.
//
inline size_t GetPrefixSize() const {
return kPrefixSize;
}
// Returns true iff the key has a special id.
//
inline bool IsSpecial() const {
return (rep_[0] & 0x80) == 0x80;
}
// Returns true iff the key has a special partition id.
//
inline bool IsSystemPartition() const {
return (!IsSpecial()) && (rep_[6] & 0x80) == 0x80;
}
// Returns a pointer to the name hash inside the key.
//
inline char* GetNameHash() {
return reinterpret_cast<char*>(rep_ + kPrefixSize);
}
// Returns a constant pointer to the name hash inside the key.
//
inline const char* GetNameHash() const {
return reinterpret_cast<const char*>(rep_ + kPrefixSize);
}
// Returns a Slice object backed by the raw memory of the key.
//
inline Slice ToSlice() {
return Slice(reinterpret_cast<char*>(rep_), kTotalSize);
}
// Returns the length (in bytes) of the raw key representation.
//
size_t size() const { return kTotalSize; }
// Returns a pointer to the beginning of the raw key representation.
//
const char* data() const { return reinterpret_cast<const char*>(rep_); }
private:
enum {
kPrefixSize = 8, kHashSize = 8, kTotalSize = kPrefixSize + kHashSize,
};
// --------------------------------------------------
// Internal Representation (in bit)
// --------------------------------------------------
// [0, 0] -> type bit: 0=normal_key, 1=special_key
// [1, 47] -> parent_id (6 bytes)
// [48, 48] -> type bit: 0=normal_partition, 1=system_partition
// [49, 63] -> partition_id (2 bytes)
// [64, 191] -> name_hash (as many as 16 bytes)
// --------------------------------------------------
unsigned char rep_[24]; // Capable of holding a 16-byte name hash.
void Init(int64_t parent_id, int16_t partition_id); // Initializes a normal key.
void InitSpecial(int64_t special_id); // Initializes a special key with a special id.
};
// Retrieves the parent id from the key representation.
//
inline int64_t MDBKey::GetParent() const {
int64_t result;
memcpy(&result, rep_, sizeof(result));
result = be64toh(result);
return result >= 0 ? result >> 16 : result;
}
// Retrieves the partition id from the key representation.
//
inline int16_t MDBKey::GetPartition() const {
int64_t result;
memcpy(&result, rep_, sizeof(result));
result = be64toh(result);
return result >= 0 ? static_cast<int16_t>(result & 0xFFFF) : 0;
}
// Updates the key representation with the given information.
//
inline void MDBKey::Init(int64_t parent_id, int16_t partition_id) {
int64_t id = (parent_id << 16) | (partition_id & 0xFFFF);
id = htobe64(id);
memcpy(rep_, &id, sizeof(id));
}
// Updates the key representation with the given special id.
//
inline void MDBKey::InitSpecial(int64_t special_id) {
int64_t id = htobe64(special_id);
memcpy(rep_, &id, sizeof(id));
}
// In IndexFS, each file system object is represented by a key-value pair. The value
// stores various file system attributes related to the object, such as its INODE number,
// file name, file size, permission bits, owner identity, zeroth server (for directories),
// and file contents (for small files).
//
// Since the size of the value will have significant effects on overall system
// performance, values are designed to be as small as possible.
// Now, each value consists of a fixed 64 bytes header, 3 length fields each sizing from 1
// to 4 bytes, and 3 raw data fields for file name, storage path, and file data respectively.
//
struct MDBValue {
void SetFileStat(const FileStat &file_stat); // Reset file attributes
FileStat* operator->() { return GetFileStat(); }
MDBValue(const char* buffer, size_t length) :
name_(NULL), path_(NULL), data_(NULL), name_size_(0), path_size_(0), data_size_(0),
size_(0), rep_(NULL) {
Slice raw_bytes(buffer, length);
Unmarshall(raw_bytes);
}
MDBValue(const std::string &name=std::string(),
const std::string &path=std::string(),
const std::string &data=std::string()) :
name_(NULL), path_(NULL), data_(NULL), name_size_(0), path_size_(0), data_size_(0),
size_(0), rep_(NULL) {
Init(name, path, data);
}
~MDBValue();
inline Slice GetName() {
return Slice(name_, name_size_);
}
inline Slice GetStoragePath() {
return Slice(path_, path_size_);
}
inline Slice GetEmbeddedData() {
return Slice(data_, data_size_);
}
inline FileStat* GetFileStat() {
return reinterpret_cast<FileStat*>(rep_);
}
inline Slice ToSlice() {
return Slice(reinterpret_cast<char*>(rep_), size_);
}
// Create a new MDB value based on an exiting value but with partially updated embedded data
//
MDBValue(const MDBValueRef &base, size_t offset, size_t size, const char* data);
// Returns the length (in bytes) of the value.
//
size_t size() const { return size_; }
// Returns a pointer to the beginning of the value.
//
const char* data() const { return reinterpret_cast<const char*>(rep_); }
private:
enum {
kFileStatSize = sizeof(FileStat), /* 64 bytes */
};
// Transient helper fields
char* name_;
char* path_;
char* data_;
uint32_t name_size_;
uint32_t path_size_;
uint32_t data_size_;
// --------------------------------------------------
// Internal Representation
// --------------------------------------------------
// FileStat | NameLen | PathLen | DataLen | ..DATA..
// --------------------------------------------------
size_t size_;
unsigned char* rep_;
void Init(const Slice &name=Slice(),
const Slice &path=Slice(),
const Slice &data=Slice());
void Unmarshall(const Slice &raw_bytes);
// No copying allowed
MDBValue(const MDBValue&);
MDBValue& operator=(const MDBValue&);
};
inline MDBValue::~MDBValue() {
if (rep_ != NULL) {
delete rep_;
}
}
inline void MDBValue::SetFileStat(const FileStat &file_stat) {
memcpy(rep_, &file_stat, kFileStatSize);
}
// A read-only reference to a piece of memory to be interpreted as an MDBValue
// object. This helper structure is introduced to reduce unnecessary memory copy.
//
struct MDBValueRef {
~MDBValueRef() { /* empty */ }
const FileStat* operator->() const { return GetFileStat(); }
MDBValueRef(const Slice& slice) :
name_(NULL), path_(NULL), data_(NULL), name_size_(0), path_size_(0), data_size_(0),
size_(slice.size()), rep_(slice.data()) {
Unmarshall();
}
MDBValueRef(const char* rep, size_t size) :
name_(NULL), path_(NULL), data_(NULL), name_size_(0), path_size_(0), data_size_(0),
size_(size), rep_(rep) {
Unmarshall();
}
inline Slice GetName() const {
return Slice(name_, name_size_);
}
inline Slice GetStoragePath() const {
return Slice(path_, path_size_);
}
inline Slice GetEmbeddedData() const {
return Slice(data_, data_size_);
}
inline const FileStat* GetFileStat() const {
return reinterpret_cast<const FileStat*>(rep_);
}
private:
void Unmarshall(); // re-construct in-memory representation
char* name_;
char* path_;
char* data_;
uint32_t name_size_;
uint32_t path_size_;
uint32_t data_size_;
size_t size_;
const char* rep_;
friend class MDBValue;
// No copying allowed
MDBValueRef(const MDBValueRef&);
MDBValueRef& operator=(const MDBValueRef&);
};
} /* namespace mdb */
} /* namespace indexfs */
#endif /* _INDEXFS_METADB_TYPES_H_ */
| 28.393443 | 94 | 0.668399 | [
"object"
] |
0914d0c31a60dc7f2c85930927f475549186d9f6 | 958 | h | C | third/include/atlas/singleton.h | galaxyeye/pioneer | cfc3aa3c4917b19000753ea3144bded79380d289 | [
"Apache-2.0"
] | 4 | 2017-05-12T07:37:17.000Z | 2019-11-14T10:52:28.000Z | third/include/atlas/singleton.h | galaxyeye/pioneer | cfc3aa3c4917b19000753ea3144bded79380d289 | [
"Apache-2.0"
] | null | null | null | third/include/atlas/singleton.h | galaxyeye/pioneer | cfc3aa3c4917b19000753ea3144bded79380d289 | [
"Apache-2.0"
] | 7 | 2017-06-21T03:35:51.000Z | 2020-10-14T04:58:26.000Z | /*
* singleton.h
*
* Created on: Apr 8, 2013
* Author: vincent ivincent.zhang@gmail.com
*/
#ifndef ATLAS_SINGLETON_H_
#define ATLAS_SINGLETON_H_
#include <memory>
#include <mutex>
namespace atlas {
// A thread safe singleton in C++11,
// the managed object can be constructed with arguments.
// The managed object can be used by reference or a shared_ptr.
template<typename T>
class singleton {
public:
~singleton() = default;
static T& ref() { return *ptr(); }
static auto ptr() -> std::shared_ptr<T> {
std::call_once(_only_one, __init);
return _value;
}
private:
static void __init() {
_value = std::make_shared<T>();
}
private:
static std::shared_ptr<T> _value;
static std::once_flag _only_one;
};
template<typename T> std::shared_ptr<T> singleton<T>::_value;
template<typename T> std::once_flag singleton<T>::_only_one;
} // atlas
#endif /* SINGLETON_H_ */
| 19.16 | 65 | 0.653445 | [
"object"
] |
091e1017e5651ea8e2b2f734ffac17211c9aedc9 | 3,841 | h | C | fred2/fredrender.h | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 307 | 2015-04-10T13:27:32.000Z | 2022-03-21T03:30:38.000Z | fred2/fredrender.h | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 2,231 | 2015-04-27T10:47:35.000Z | 2022-03-31T19:22:37.000Z | fred2/fredrender.h | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 282 | 2015-01-05T12:16:57.000Z | 2022-03-28T04:45:11.000Z | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
#include "globalincs/pstypes.h"
#include "physics/physics.h"
#define BRIEFING_LOOKAT_POINT_ID 99999
extern int Aa_gridlines; //!< Bool. If nonzero, draw anti-aliased gridlines
extern int player_start1; //!< Object index of the player start
extern int Editing_mode; //!< Enum. The edit mode. 0 = Select; 1 = Select and Move; 2 = Select and Rotate
extern int Control_mode; //!< Bool. Control mode. 0 = Camera/Viewpoint control. 1 = Object control
extern int Show_grid; //!< Bool. If nonzero, draw the grid
extern int Show_grid_positions; //!< Bool. If nonzero, draw an elevation line from each object to the grid.
extern int Show_coordinates; //!< Bool. If nonzero, draw the coordinates of each object on their label
extern int Show_outlines; //!< Bool. If nonzero, draw each object's mesh. If models are shown, highlight them in white.
extern bool Draw_outlines_on_selected_ships; // If a ship is selected, don't draw the mesh lines that would normally be drawn
extern int Show_stars; //!< Bool. If nonzero, draw the starfield, nebulas, and suns. Might also handle skyboxes
extern int Single_axis_constraint; //!< Bool. If nonzero, constrain movement to one axis
extern int Show_distances; //!< Bool. If nonzero, draw lines between each object and display their distance on the middle of each line
extern int Universal_heading; //!< Bool. Unknown.
extern int Flying_controls_mode; //!< Bool. Unknown.
extern int Group_rotate; //!< Bool. If nonzero, each object rotates around the leader. If zero. rotate
extern int Show_horizon; //!< Bool. If nonzero, draw a line representing the horizon (XZ plane)
extern int Lookat_mode; //!< Bool. Unknown.
extern int True_rw; //!< Unsigned. The width of the render area
extern int True_rh; //!< Unsigned. The height of the render area
extern int Fixed_briefing_size; //!< Bool. If nonzero then expand the briefing preview as much as we can, maintaining the aspect ratio.
extern vec3d Constraint; //!< Which axis (or axes) we can move/rotate on
extern vec3d Anticonstraint; //!< Which axis (or axes) we can't move/rotate on
extern physics_info view_physics; //!< Physics info of the camera/controlled object
extern vec3d view_pos;
extern vec3d eye_pos;
extern matrix view_orient;
extern matrix eye_orient;
/**
* @brief Initializes the renderer.
*
* @details Called every time a new mission is created (and erasing old mission from memory). New mission should be
* blank at this point.
*/
void fred_render_init();
/**
* @brief Handler for Mouse movement
*
* @param[in] btn Bitfield of mousebuttons
* @param[in] mdx X delta
* @param[in] mdy Y delta
*/
void move_mouse(int btn, int mdx, int mdy);
/**
* @brief Handler for OnIdle. Does a game frame within the editor
*/
void game_do_frame();
/**
* @brief Handler for OnPaint. Renders the game frame
*/
void render_frame();
/**
* @brief Reset the angles of the controlled object to be "wings level" with the grid, either the camera or the selection
*/
void level_controlled();
/**
* @brief Similar to level_controlled, aligns the controlled object to the closest axis
*/
void verticalize_controlled();
/**
* @brief Finds the closest object or waypoint under the mouse cursor and returns its index.
*
* @param[in] cx X coordinate on the viewport
* @param[in] cy Y coordinate on the viewport
*
* @return Object index number of the object, if any. or
* @return -1 if no object found
*/
int select_object(int cx, int cy);
| 42.208791 | 143 | 0.709971 | [
"mesh",
"render",
"object"
] |
0929432fb33639d210e9b9be6acf61ab41592367 | 8,598 | h | C | src/RodinExternal/MMG/Cast.h | carlos-brito-pacheco/rodin | f2c946b290ebb2487a21c617de01be91a0692c72 | [
"BSL-1.0"
] | 1 | 2021-12-02T19:04:38.000Z | 2021-12-02T19:04:38.000Z | src/RodinExternal/MMG/Cast.h | cbritopacheco/rodin | f2c946b290ebb2487a21c617de01be91a0692c72 | [
"BSL-1.0"
] | null | null | null | src/RodinExternal/MMG/Cast.h | cbritopacheco/rodin | f2c946b290ebb2487a21c617de01be91a0692c72 | [
"BSL-1.0"
] | null | null | null | /*
* Copyright Carlos BRITO PACHECO 2021 - 2022.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at
* https://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef RODIN_RODININTEGRATION_MMG_CAST_H
#define RODIN_RODININTEGRATION_MMG_CAST_H
#include "Rodin/Cast.h"
#include "Rodin/Mesh/ForwardDecls.h"
#include "Rodin/Variational/ForwardDecls.h"
#include "Rodin/Variational/H1.h"
#include "Rodin/Variational/GridFunction.h"
#include "Rodin/Variational/FiniteElementSpace.h"
#include "Utility.h"
#include "ScalarSolution2D.h"
#include "ScalarSolution3D.h"
#include "ScalarSolutionS.h"
#include "VectorSolution2D.h"
#include "VectorSolution3D.h"
#include "VectorSolutionS.h"
#include "Common.h"
#include "ForwardDecls.h"
namespace Rodin
{
// ---- mmg2d -------------------------------------------------------------
/**
* MMG::Mesh2D -> Rodin::Mesh<>
*/
template <>
template <>
Rodin::Mesh<Traits::Serial>
Cast<External::MMG::Mesh2D>::to<Rodin::Mesh<>>() const;
/**
* Rodin::Mesh<Traits::Serial> -> MMG::Mesh2D
*/
template <>
template <>
External::MMG::Mesh2D
Cast<Rodin::Mesh<Traits::Serial>>::to<External::MMG::Mesh2D>() const;
/**
* Rodin::Variational::GridFunction<FEC, Traits::Serial> -> MMG::IncompleteScalarSolution2D
*/
template <class FEC>
class ADLCaster<
Variational::GridFunction<FEC, Traits::Serial>, External::MMG::ScalarSolution2D>
{
public:
ADLCaster(External::MMG::Mesh2D& mesh)
: m_mesh(mesh)
{}
External::MMG::ScalarSolution2D cast(
const Variational::GridFunction<FEC, Traits::Serial>& src)
{
assert(src.getFiniteElementSpace().getVectorDimension() == 1);
External::MMG::ScalarSolution2D res(m_mesh);
External::MMG::Rodin_GridFunction_To_MMG5_Sol(src, res.getHandle());
return res;
}
private:
External::MMG::Mesh2D& m_mesh;
};
/**
* Rodin::Variational::GridFunction<FEC, Traits::Serial> -> MMG::VectorSolution2D
*/
template <class FEC>
class ADLCaster<
Variational::GridFunction<FEC, Traits::Serial>, External::MMG::VectorSolution2D>
{
public:
ADLCaster(External::MMG::Mesh2D& mesh)
: m_mesh(mesh)
{}
External::MMG::VectorSolution2D cast(
const Variational::GridFunction<FEC, Traits::Serial>& src)
{
assert(src.getFiniteElementSpace().getVectorDimension() == 2);
External::MMG::VectorSolution2D res(m_mesh);
External::MMG::Rodin_GridFunction_To_MMG5_Sol(src, res.getHandle());
return res;
}
private:
External::MMG::Mesh2D& m_mesh;
};
/**
* MMG::ScalarSolution2D -> Rodin::Variational::GridFunction<Variational::H1, Traits::Serial>
*/
template <class FEC>
class ADLCaster<External::MMG::ScalarSolution2D, Variational::GridFunction<FEC, Traits::Serial>>
{
public:
ADLCaster(Variational::FiniteElementSpace<FEC>& mesh)
: m_fes(mesh)
{}
Variational::GridFunction<FEC, Traits::Serial> cast(
const External::MMG::ScalarSolution2D& src)
{
Variational::GridFunction<FEC> res(m_fes);
External::MMG::MMG5_Sol_To_Rodin_GridFunction(src.getHandle(), res);
return res;
}
private:
Variational::FiniteElementSpace<FEC>& m_fes;
};
// ---- mmg3d -------------------------------------------------------------
/**
* MMG::Mesh3D -> Rodin::Mesh<>
*/
template <>
template <>
Rodin::Mesh<>
Cast<External::MMG::Mesh3D>::to<Rodin::Mesh<Traits::Serial>>() const;
/**
* Rodin::Mesh<> -> MMG::Mesh3D
*/
template <>
template <>
External::MMG::Mesh3D
Cast<Rodin::Mesh<Traits::Serial>>::to<External::MMG::Mesh3D>() const;
/**
* MMG::ScalarSolution3D -> Rodin::Variational::GridFunction<Variational::H1, Traits::Serial>
*/
template <class FEC>
class ADLCaster<External::MMG::ScalarSolution3D, Variational::GridFunction<FEC, Traits::Serial>>
{
public:
ADLCaster(Variational::FiniteElementSpace<FEC>& mesh)
: m_fes(mesh)
{}
Variational::GridFunction<FEC, Traits::Serial> cast(
const External::MMG::ScalarSolution3D& src)
{
Variational::GridFunction<FEC> res(m_fes);
External::MMG::MMG5_Sol_To_Rodin_GridFunction(src.getHandle(), res);
return res;
}
private:
Variational::FiniteElementSpace<FEC>& m_fes;
};
template <class FEC>
class ADLCaster<
Variational::GridFunction<FEC, Traits::Serial>, External::MMG::ScalarSolution3D>
{
public:
ADLCaster(External::MMG::Mesh3D& mesh)
: m_mesh(mesh)
{}
External::MMG::ScalarSolution3D cast(
const Variational::GridFunction<FEC, Traits::Serial>& src)
{
assert(src.getFiniteElementSpace().getVectorDimension() == 1);
External::MMG::ScalarSolution3D res(m_mesh);
External::MMG::Rodin_GridFunction_To_MMG5_Sol(src, res.getHandle());
return res;
}
private:
External::MMG::Mesh3D& m_mesh;
};
template <class FEC>
class ADLCaster<
Variational::GridFunction<FEC, Traits::Serial>, External::MMG::VectorSolution3D>
{
public:
ADLCaster(External::MMG::Mesh3D& mesh)
: m_mesh(mesh)
{}
External::MMG::VectorSolution3D cast(
const Variational::GridFunction<FEC, Traits::Serial>& src)
{
assert(src.getFiniteElementSpace().getVectorDimension() == 3);
External::MMG::VectorSolution3D res(m_mesh);
External::MMG::Rodin_GridFunction_To_MMG5_Sol(src, res.getHandle());
return res;
}
private:
External::MMG::Mesh3D& m_mesh;
};
// ---- mmgs --------------------------------------------------------------
/**
* MMG::SurfaceMesh -> Rodin::Mesh<>.
*/
template <>
template <>
Rodin::Mesh<>
Cast<External::MMG::MeshS>::to<Rodin::Mesh<>>() const;
/**
* Rodin::Mesh<> -> MMG::SurfaceMesh
*/
template <>
template <>
External::MMG::MeshS
Cast<Rodin::Mesh<Traits::Serial>>::to<External::MMG::MeshS>() const;
/**
* MMG::ScalarSolutionS -> Rodin::Variational::GridFunction<Variational::H1, Traits::Serial>
*/
template <class FEC>
class ADLCaster<External::MMG::ScalarSolutionS, Variational::GridFunction<FEC, Traits::Serial>>
{
public:
ADLCaster(Variational::FiniteElementSpace<FEC>& mesh)
: m_fes(mesh)
{}
Variational::GridFunction<FEC, Traits::Serial> cast(
const External::MMG::ScalarSolutionS& src)
{
Variational::GridFunction<FEC> res(m_fes);
External::MMG::MMG5_Sol_To_Rodin_GridFunction(src.getHandle(), res);
return res;
}
private:
Variational::FiniteElementSpace<FEC>& m_fes;
};
template <class FEC>
class ADLCaster<
Variational::GridFunction<FEC, Traits::Serial>, External::MMG::ScalarSolutionS>
{
public:
ADLCaster(External::MMG::MeshS& mesh)
: m_mesh(mesh)
{}
External::MMG::ScalarSolutionS cast(
const Variational::GridFunction<FEC, Traits::Serial>& src)
{
assert(src.getFiniteElementSpace().getVectorDimension() == 1);
External::MMG::ScalarSolutionS res(m_mesh);
External::MMG::Rodin_GridFunction_To_MMG5_Sol(src, res.getHandle());
return res;
}
private:
External::MMG::MeshS& m_mesh;
};
template <class FEC>
class ADLCaster<
Variational::GridFunction<FEC, Traits::Serial>, External::MMG::VectorSolutionS>
{
public:
ADLCaster(External::MMG::MeshS& mesh)
: m_mesh(mesh)
{}
External::MMG::VectorSolutionS cast(
const Variational::GridFunction<FEC, Traits::Serial>& src)
{
assert(src.getFiniteElementSpace().getVectorDimension() == 3);
External::MMG::VectorSolutionS res(m_mesh);
External::MMG::Rodin_GridFunction_To_MMG5_Sol(src, res.getHandle());
return res;
}
private:
External::MMG::MeshS& m_mesh;
};
}
#endif
| 29.648276 | 99 | 0.589439 | [
"mesh"
] |
093a343efde6656533fd4d0041ef8412397834f9 | 3,545 | h | C | model/webhook_response.h | ezmaxinc/eZmax-SDK-c | 725eab79d6311127a2d5bd731b978bce94142d69 | [
"curl",
"MIT"
] | null | null | null | model/webhook_response.h | ezmaxinc/eZmax-SDK-c | 725eab79d6311127a2d5bd731b978bce94142d69 | [
"curl",
"MIT"
] | null | null | null | model/webhook_response.h | ezmaxinc/eZmax-SDK-c | 725eab79d6311127a2d5bd731b978bce94142d69 | [
"curl",
"MIT"
] | null | null | null | /*
* webhook_response.h
*
* A webhook object
*/
#ifndef _webhook_response_H_
#define _webhook_response_H_
#include <string.h>
#include "../external/cJSON.h"
#include "../include/list.h"
#include "../include/keyValuePair.h"
#include "../include/binary.h"
typedef struct webhook_response_t webhook_response_t;
// Enum EWEBHOOKMODULE for webhook_response
typedef enum { ezmax_api_definition__full_webhook_response_EWEBHOOKMODULE_NULL = 0, ezmax_api_definition__full_webhook_response_EWEBHOOKMODULE_Ezsign, ezmax_api_definition__full_webhook_response_EWEBHOOKMODULE_Management } ezmax_api_definition__full_webhook_response_EWEBHOOKMODULE_e;
char* webhook_response_e_webhook_module_ToString(ezmax_api_definition__full_webhook_response_EWEBHOOKMODULE_e e_webhook_module);
ezmax_api_definition__full_webhook_response_EWEBHOOKMODULE_e webhook_response_e_webhook_module_FromString(char* e_webhook_module);
// Enum EWEBHOOKEZSIGNEVENT for webhook_response
typedef enum { ezmax_api_definition__full_webhook_response_EWEBHOOKEZSIGNEVENT_NULL = 0, ezmax_api_definition__full_webhook_response_EWEBHOOKEZSIGNEVENT_DocumentCompleted, ezmax_api_definition__full_webhook_response_EWEBHOOKEZSIGNEVENT_FolderCompleted } ezmax_api_definition__full_webhook_response_EWEBHOOKEZSIGNEVENT_e;
char* webhook_response_e_webhook_ezsignevent_ToString(ezmax_api_definition__full_webhook_response_EWEBHOOKEZSIGNEVENT_e e_webhook_ezsignevent);
ezmax_api_definition__full_webhook_response_EWEBHOOKEZSIGNEVENT_e webhook_response_e_webhook_ezsignevent_FromString(char* e_webhook_ezsignevent);
// Enum EWEBHOOKMANAGEMENTEVENT for webhook_response
typedef enum { ezmax_api_definition__full_webhook_response_EWEBHOOKMANAGEMENTEVENT_NULL = 0, ezmax_api_definition__full_webhook_response_EWEBHOOKMANAGEMENTEVENT_UserCreated } ezmax_api_definition__full_webhook_response_EWEBHOOKMANAGEMENTEVENT_e;
char* webhook_response_e_webhook_managementevent_ToString(ezmax_api_definition__full_webhook_response_EWEBHOOKMANAGEMENTEVENT_e e_webhook_managementevent);
ezmax_api_definition__full_webhook_response_EWEBHOOKMANAGEMENTEVENT_e webhook_response_e_webhook_managementevent_FromString(char* e_webhook_managementevent);
typedef struct webhook_response_t {
char *pks_customer_code; // string
int pki_webhook_id; //numeric
ezmax_api_definition__full_webhook_response_EWEBHOOKMODULE_e e_webhook_module; //enum
ezmax_api_definition__full_webhook_response_EWEBHOOKEZSIGNEVENT_e e_webhook_ezsignevent; //enum
ezmax_api_definition__full_webhook_response_EWEBHOOKMANAGEMENTEVENT_e e_webhook_managementevent; //enum
char *s_webhook_url; // string
int b_webhook_test; //boolean
int b_webhook_skipsslvalidation; //boolean
char *s_webhook_emailfailed; // string
} webhook_response_t;
webhook_response_t *webhook_response_create(
char *pks_customer_code,
int pki_webhook_id,
ezmax_api_definition__full_webhook_response_EWEBHOOKMODULE_e e_webhook_module,
ezmax_api_definition__full_webhook_response_EWEBHOOKEZSIGNEVENT_e e_webhook_ezsignevent,
ezmax_api_definition__full_webhook_response_EWEBHOOKMANAGEMENTEVENT_e e_webhook_managementevent,
char *s_webhook_url,
int b_webhook_test,
int b_webhook_skipsslvalidation,
char *s_webhook_emailfailed
);
void webhook_response_free(webhook_response_t *webhook_response);
webhook_response_t *webhook_response_parseFromJSON(cJSON *webhook_responseJSON);
cJSON *webhook_response_convertToJSON(webhook_response_t *webhook_response);
#endif /* _webhook_response_H_ */
| 45.448718 | 321 | 0.880113 | [
"object"
] |
adcfe3a4c1dbe35dededbea3352e987caec7031f | 3,104 | h | C | src/EngineManaged/Bindings/Memory.h | akumetsuv/flood | e0d6647df9b7fac72443a0f65c0003b0ead7ed3a | [
"BSD-2-Clause"
] | null | null | null | src/EngineManaged/Bindings/Memory.h | akumetsuv/flood | e0d6647df9b7fac72443a0f65c0003b0ead7ed3a | [
"BSD-2-Clause"
] | null | null | null | src/EngineManaged/Bindings/Memory.h | akumetsuv/flood | e0d6647df9b7fac72443a0f65c0003b0ead7ed3a | [
"BSD-2-Clause"
] | null | null | null | /************************************************************************
*
* Flood Project © (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#pragma once
#include <Core/Memory.h>
namespace Flood
{
ref class Allocator;
ref class PoolAllocator;
ref class BumpAllocator;
ref class HeapAllocator;
public delegate System::IntPtr MemoryAllocateFunction(Flood::Allocator^, int size, int align);
public delegate void MemoryFreeFunction(Flood::Allocator^, System::IntPtr object);
public delegate void MemoryResetFunction(Flood::Allocator^);
/// <summary>
/// Interface for a custom memory allocator.
/// </summary>
public ref class Allocator
{
public:
property ::Allocator* NativePtr;
Allocator(::Allocator* native);
Allocator(System::IntPtr native);
property Flood::MemoryAllocateFunction^ Allocate;
property Flood::MemoryFreeFunction^ Deallocate;
property Flood::MemoryResetFunction^ Reset;
property System::String^ Group;
void Destroy();
void ResetMemory();
void SetGroup(System::String^ group);
Flood::Allocator^ CreatePool(int size);
Flood::Allocator^ CreateBump(int size);
Flood::Allocator^ CreateHeap();
Flood::Allocator^ CreateStack();
static Flood::Allocator^ GetHeap();
static Flood::Allocator^ GetStack();
static Flood::Allocator^ GetObject(System::IntPtr _49);
static void DumpInfo();
};
/// <summary>
/// Manages memory allocation using a fixed-size object pool. When a new
/// allocation is requested, we search for the first free object available and
/// return it.
/// </summary>
public ref class PoolAllocator
{
public:
property ::PoolAllocator* NativePtr;
PoolAllocator(::PoolAllocator* native);
PoolAllocator(System::IntPtr native);
property System::IntPtr Current;
};
/// <summary>
/// Manages memory allocations using a fixed-size buffer that can provide
/// allocations and deallocations in O(1). The allocated space in the buffer is
/// not re-used until the whole buffer is reset.
/// </summary>
public ref class BumpAllocator
{
public:
property ::BumpAllocator* NativePtr;
BumpAllocator(::BumpAllocator* native);
BumpAllocator(System::IntPtr native);
property System::IntPtr Start;
property System::IntPtr Current;
property unsigned int Size;
};
/// <summary>
/// Manages memory allocation using Doug Lea's malloc implementation. This is a
/// boundary-tag allocator that manages memory by keeping track of the
/// used/free memory blocks.
/// </summary>
public ref class HeapAllocator
{
public:
property ::HeapAllocator* NativePtr;
HeapAllocator(::HeapAllocator* native);
HeapAllocator(System::IntPtr native);
property System::IntPtr Space;
};
}
| 31.353535 | 98 | 0.625322 | [
"object"
] |
ade08c291d8d785a03d376b41508bb4837181e37 | 4,700 | h | C | src/nn/tensor/CpuTensor.h | krnflake/deeplearn | 51d517b882f16c0b3361baa1f79233fa2e1c517c | [
"MIT"
] | 19 | 2016-02-10T10:30:36.000Z | 2022-01-23T03:09:38.000Z | src/nn/tensor/CpuTensor.h | krnflake/deeplearn | 51d517b882f16c0b3361baa1f79233fa2e1c517c | [
"MIT"
] | null | null | null | src/nn/tensor/CpuTensor.h | krnflake/deeplearn | 51d517b882f16c0b3361baa1f79233fa2e1c517c | [
"MIT"
] | 3 | 2016-06-09T09:04:42.000Z | 2022-01-23T03:09:38.000Z | //
// Tensor class
//
// Copyright (c) 2016 Samuel Groß
//
#ifndef __CPU_TENSOR_H__
#define __CPU_TENSOR_H__
#include <vector>
#include <type_traits>
#include <memory>
#include <cstddef>
#include <iostream>
#include "nn/tensor/BaseTensor.h"
#include "nn/Initializer.h"
#include "ocl/Device.h"
#include "common/Common.h"
namespace nn {
class GPUTensor;
// A tensor located in host memory.
class CPUTensor : public BaseTensor<CPUTensor> {
public:
// A simple pointer is sufficient as iterator for our purposes.
typedef float* iterator;
typedef const float* const_iterator;
// Creates an empty tensor. Useful to declare local variables, then assign
// "real" values to them later on.
CPUTensor();
// Default constructor for a CPUTensor. Does not initialize its data.
explicit CPUTensor(const Shape& shape);
// Initialization constructor.
// Initializes all values using the provided initializer.
template <class Initializer>
CPUTensor(const Shape& shape, Initializer initializer) : BaseTensor(shape)
{
buffer_ = new float[size()];
Check(buffer_, "Out of memory");
for (size_t i = 0; i < size(); i++)
buffer_[i] = initializer();
}
// Destructor, frees the associated buffer if this isn't a view onto another tensor.
virtual ~CPUTensor();
// Copy constructor and assignment operator. See the comments in BaseTensor.h about these.
CPUTensor(const CPUTensor& other);
CPUTensor& operator=(const CPUTensor& other);
// Returns a string representation of this tensor.
std::string ToString() const;
// Element access operators.
//
// The number of provided indices must be equal to the rank of the tensor.
template <typename ...Index>
float& Element(Index... indices)
{
size_t linear_index = LinearIndex(0, 0, indices...);
return buffer_[linear_index];
}
template <typename ...Index>
float Element(Index... indices) const
{
size_t linear_index = LinearIndex(0, 0, indices...);
return buffer_[linear_index];
}
// operator() is used for convenient element access.
template <typename ...Index>
float& operator()(Index... indices)
{
return Element(indices...);
}
template <typename ...Index>
float operator()(Index... indices) const
{
return Element(indices...);
}
// Comparison operators.
//
// Two tensors are considered equal if their shape is equal and
// floatEq(x, y) is true for each pair of elements with same index.
bool operator==(const CPUTensor& other) const;
bool operator!=(const CPUTensor& other) const;
// Iterator support.
iterator begin() { return buffer_; }
iterator end() { return buffer_ + size(); }
const_iterator begin() const { return buffer_; }
const_iterator end() const { return buffer_ + size(); }
// Sets all elements to zero.
void Clear();
// Transfer the data of this tensor to a new tensor located on the GPU.
GPUTensor ToGPU() const;
private:
// Tensor view constructors.
CPUTensor(const CPUTensor& base, const Shape& new_shape);
CPUTensor(const CPUTensor& base, size_t index);
// Linear index calculation.
// Done with variadic templates so we get type safety as well as infinite number of arguments :)
inline size_t LinearIndex(size_t current_index, size_t current_dimension) const
{
Assert(current_index < size());
Assert(current_dimension == rank());
return current_index;
}
template <typename Head, typename ...Tail>
size_t LinearIndex(size_t current_index, size_t current_dimension, Head current, Tail... remaining) const
{
static_assert(std::is_integral<Head>::value, "Tensor indices must be integers.");
Assert(current_dimension < rank());
current_index *= shape(current_dimension);
current_index += current;
return LinearIndex(current_index, current_dimension + 1, remaining...);
}
// Transfer constructor.
// Creates a CPU tensor with the data and shape of the provided GPU tensor.
explicit CPUTensor(const GPUTensor& tensor);
// Underlying (host) buffer. Pointer is owned by this instance if !is_view().
float* buffer_;
friend class GPUTensor;
friend class BaseTensor;
};
// Make CPUTensors easily printable to various streams.
inline std::ostream& operator<<(std::ostream& os, const CPUTensor& tensor)
{
os << tensor.ToString();
return os;
}
// Define all CPUTensor operations
#define Tensor CPUTensor
#include "nn/tensor/TensorOps.h"
#undef Tensor
} // namespace nn
#endif
| 29.375 | 109 | 0.672979 | [
"shape",
"vector"
] |
ade9ad59bdbf983ceaa2e4ad622adeaebf44cd17 | 9,251 | h | C | third_party/kdtree/kdtree.h | Cognixion-inc/brainflow | 7a1ce71e59aa88fca18225ac10b5602ccc46c87c | [
"MIT"
] | 528 | 2020-04-27T06:52:12.000Z | 2022-03-31T03:22:38.000Z | third_party/kdtree/kdtree.h | Cognixion-inc/brainflow | 7a1ce71e59aa88fca18225ac10b5602ccc46c87c | [
"MIT"
] | 229 | 2020-04-24T15:54:52.000Z | 2022-03-21T17:52:49.000Z | third_party/kdtree/kdtree.h | Cognixion-inc/brainflow | 7a1ce71e59aa88fca18225ac10b5602ccc46c87c | [
"MIT"
] | 120 | 2020-05-24T18:10:37.000Z | 2022-03-17T19:50:52.000Z | #pragma once
#include <algorithm>
#include <exception>
#include <functional>
#include <math.h>
#include <numeric>
#include <vector>
namespace kdt
{
/** @brief k-d tree class.
*/
template <class PointT> class KDTree
{
public:
/** @brief The constructors.
*/
KDTree () : root_ (nullptr) {};
KDTree (const std::vector<PointT> &points) : root_ (nullptr)
{
build (points);
}
/** @brief The destructor.
*/
~KDTree ()
{
clear ();
}
/** @brief Re-builds k-d tree.
*/
void build (const std::vector<PointT> &points)
{
clear ();
points_ = points;
std::vector<int> indices (points.size ());
std::iota (std::begin (indices), std::end (indices), 0);
root_ = buildRecursive (indices.data (), (int)points.size (), 0);
}
/** @brief Clears k-d tree.
*/
void clear ()
{
clearRecursive (root_);
root_ = nullptr;
points_.clear ();
}
/** @brief Validates k-d tree.
*/
bool validate () const
{
try
{
validateRecursive (root_, 0);
}
catch (const Exception &)
{
return false;
}
return true;
}
/** @brief Searches the nearest neighbor.
*/
int nnSearch (const PointT &query, double *minDist = nullptr) const
{
int guess;
double _minDist = std::numeric_limits<double>::max ();
nnSearchRecursive (query, root_, &guess, &_minDist);
if (minDist)
*minDist = _minDist;
return guess;
}
/** @brief Searches k-nearest neighbors.
*/
std::vector<int> knnSearch (const PointT &query, int k) const
{
KnnQueue queue (k);
knnSearchRecursive (query, root_, queue, k);
std::vector<int> indices (queue.size ());
for (size_t i = 0; i < queue.size (); i++)
indices[i] = queue[i].second;
return indices;
}
/** @brief Searches neighbors within radius.
*/
std::vector<int> radiusSearch (const PointT &query, double radius) const
{
std::vector<int> indices;
radiusSearchRecursive (query, root_, indices, radius);
return indices;
}
private:
/** @brief k-d tree node.
*/
struct Node
{
int idx; //!< index to the original point
Node *next[2]; //!< pointers to the child nodes
int axis; //!< dimension's axis
Node () : idx (-1), axis (-1)
{
next[0] = next[1] = nullptr;
}
};
/** @brief k-d tree exception.
*/
class Exception : public std::exception
{
using std::exception::exception;
};
/** @brief Bounded priority queue.
*/
template <class T, class Compare = std::less<T>> class BoundedPriorityQueue
{
public:
BoundedPriorityQueue () = delete;
BoundedPriorityQueue (size_t bound) : bound_ (bound)
{
elements_.reserve (bound + 1);
};
void push (const T &val)
{
auto it = std::find_if (std::begin (elements_), std::end (elements_),
[&](const T &element) { return Compare () (val, element); });
elements_.insert (it, val);
if (elements_.size () > bound_)
elements_.resize (bound_);
}
const T &back () const
{
return elements_.back ();
};
const T &operator[] (size_t index) const
{
return elements_[index];
}
size_t size () const
{
return elements_.size ();
}
private:
size_t bound_;
std::vector<T> elements_;
};
/** @brief Priority queue of <distance, index> pair.
*/
using KnnQueue = BoundedPriorityQueue<std::pair<double, int>>;
/** @brief Builds k-d tree recursively.
*/
Node *buildRecursive (int *indices, int npoints, int depth)
{
if (npoints <= 0)
return nullptr;
const int axis = depth % PointT::DIM;
const int mid = (npoints - 1) / 2;
std::nth_element (indices, indices + mid, indices + npoints,
[&](int lhs, int rhs) { return points_[lhs][axis] < points_[rhs][axis]; });
Node *node = new Node ();
node->idx = indices[mid];
node->axis = axis;
node->next[0] = buildRecursive (indices, mid, depth + 1);
node->next[1] = buildRecursive (indices + mid + 1, npoints - mid - 1, depth + 1);
return node;
}
/** @brief Clears k-d tree recursively.
*/
void clearRecursive (Node *node)
{
if (node == nullptr)
return;
if (node->next[0])
clearRecursive (node->next[0]);
if (node->next[1])
clearRecursive (node->next[1]);
delete node;
}
/** @brief Validates k-d tree recursively.
*/
void validateRecursive (const Node *node, int depth) const
{
if (node == nullptr)
return;
const int axis = node->axis;
const Node *node0 = node->next[0];
const Node *node1 = node->next[1];
if (node0 && node1)
{
if (points_[node->idx][axis] < points_[node0->idx][axis])
throw Exception ();
if (points_[node->idx][axis] > points_[node1->idx][axis])
throw Exception ();
}
if (node0)
validateRecursive (node0, depth + 1);
if (node1)
validateRecursive (node1, depth + 1);
}
static double distance (const PointT &p, const PointT &q)
{
double dist = 0;
for (size_t i = 0; i < PointT::DIM; i++)
dist += (p[i] - q[i]) * (p[i] - q[i]);
return sqrt (dist);
}
/** @brief Searches the nearest neighbor recursively.
*/
void nnSearchRecursive (
const PointT &query, const Node *node, int *guess, double *minDist) const
{
if (node == nullptr)
return;
const PointT &train = points_[node->idx];
const double dist = distance (query, train);
if (dist < *minDist)
{
*minDist = dist;
*guess = node->idx;
}
const int axis = node->axis;
const int dir = query[axis] < train[axis] ? 0 : 1;
nnSearchRecursive (query, node->next[dir], guess, minDist);
const double diff = fabs (query[axis] - train[axis]);
if (diff < *minDist)
nnSearchRecursive (query, node->next[!dir], guess, minDist);
}
/** @brief Searches k-nearest neighbors recursively.
*/
void knnSearchRecursive (
const PointT &query, const Node *node, KnnQueue &queue, int k) const
{
if (node == nullptr)
return;
const PointT &train = points_[node->idx];
const double dist = distance (query, train);
queue.push (std::make_pair (dist, node->idx));
const int axis = node->axis;
const int dir = query[axis] < train[axis] ? 0 : 1;
knnSearchRecursive (query, node->next[dir], queue, k);
const double diff = fabs (query[axis] - train[axis]);
if ((int)queue.size () < k || diff < queue.back ().first)
knnSearchRecursive (query, node->next[!dir], queue, k);
}
/** @brief Searches neighbors within radius.
*/
void radiusSearchRecursive (
const PointT &query, const Node *node, std::vector<int> &indices, double radius) const
{
if (node == nullptr)
return;
const PointT &train = points_[node->idx];
const double dist = distance (query, train);
if (dist < radius)
indices.push_back (node->idx);
const int axis = node->axis;
const int dir = query[axis] < train[axis] ? 0 : 1;
radiusSearchRecursive (query, node->next[dir], indices, radius);
const double diff = fabs (query[axis] - train[axis]);
if (diff < radius)
radiusSearchRecursive (query, node->next[!dir], indices, radius);
}
Node *root_; //!< root node
std::vector<PointT> points_; //!< points
};
} // kdt | 28.640867 | 98 | 0.470436 | [
"vector"
] |
bc00939add09129f84de719ec5d8dc1eb8198048 | 1,138 | h | C | include/windows.h | DDinghoya/NX-Shell | 5a5067afeb6b18c0d2bb4d7b16f71899a768012a | [
"MIT"
] | 1 | 2022-01-22T15:42:37.000Z | 2022-01-22T15:42:37.000Z | include/windows.h | DDinghoya/NX-Shell | 5a5067afeb6b18c0d2bb4d7b16f71899a768012a | [
"MIT"
] | null | null | null | include/windows.h | DDinghoya/NX-Shell | 5a5067afeb6b18c0d2bb4d7b16f71899a768012a | [
"MIT"
] | null | null | null | #ifndef NX_SHELL_WINDOWS_H
#define NX_SHELL_WINDOWS_H
#include <switch.h>
#include <vector>
#include "imgui.h"
enum WINDOW_STATES {
WINDOW_STATE_FILEBROWSER = 0,
WINDOW_STATE_SETTINGS,
WINDOW_STATE_OPTIONS,
WINDOW_STATE_DELETE,
WINDOW_STATE_PROPERTIES,
WINDOW_STATE_IMAGEVIEWER,
WINDOW_STATE_ARCHIVEEXTRACT,
WINDOW_STATE_TEXTREADER
};
enum FS_SORT_STATE {
FS_SORT_ALPHA_ASC = 0,
FS_SORT_ALPHA_DESC,
FS_SORT_SIZE_ASC,
FS_SORT_SIZE_DESC
};
typedef struct {
std::vector<bool> checked;
std::vector<bool> checked_copy;
char cwd[FS_MAX_PATH + 1] = "";
u64 count = 0;
} WindowCheckboxData;
typedef struct {
WINDOW_STATES state = WINDOW_STATE_FILEBROWSER;
u64 selected = 0;
std::vector<FsDirectoryEntry> entries;
WindowCheckboxData checkbox_data;
s64 used_storage = 0;
s64 total_storage = 0;
} WindowData;
extern int sort;
namespace FileBrowser {
bool Sort(const FsDirectoryEntry &entryA, const FsDirectoryEntry &entryB);
}
namespace Windows {
void ResetCheckbox(WindowData &data);
void MainWindow(WindowData &data, u64 &key);
}
#endif
| 20.690909 | 78 | 0.730228 | [
"vector"
] |
bc14226e2ebbf18517c58281b832c3ee21be22ab | 2,074 | h | C | AAudioTrack2/src/main/cpp/ardour/pdb/convert.h | mgood7123/OboeTrack | 985cce37714e34ee862b9caa66b03ec02ac9b249 | [
"CC0-1.0"
] | 2 | 2021-04-05T19:09:16.000Z | 2021-04-05T19:14:41.000Z | AAudioTrack2/src/main/cpp/ardour/pdb/convert.h | mgood7123/OboeTrack | 985cce37714e34ee862b9caa66b03ec02ac9b249 | [
"CC0-1.0"
] | 1 | 2020-12-20T16:03:53.000Z | 2020-12-25T14:48:34.000Z | AAudioTrack2/src/main/cpp/ardour/pdb/convert.h | mgood7123/OboeTrack | 985cce37714e34ee862b9caa66b03ec02ac9b249 | [
"CC0-1.0"
] | 1 | 2020-12-21T12:04:47.000Z | 2020-12-21T12:04:47.000Z | /*
* Copyright (C) 2006-2017 Paul Davis <paul@linuxaudiosystems.com>
* Copyright (C) 2006 Taybin Rutkin <taybin@taybin.com>
* Copyright (C) 2009-2012 Carl Hetherington <carl@carlh.net>
* Copyright (C) 2016 Tim Mayberry <mojofunk@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef __pbd_convert_h__
#define __pbd_convert_h__
#include <stdint.h>
#include <string>
#include <vector>
#include "libpbd_visibility.h"
namespace PBD {
LIBPBD_API std::string short_version (std::string, std::string::size_type target_length);
LIBPBD_API int atoi (const std::string&);
LIBPBD_API int32_t atol (const std::string&);
LIBPBD_API int64_t atoll (const std::string&);
LIBPBD_API double atof (const std::string&);
LIBPBD_API std::string url_decode (std::string const &);
LIBPBD_API std::string capitalize (const std::string&);
LIBPBD_API std::string downcase (const std::string&);
LIBPBD_API const char* downcase (const char*);
// std::string length2string (const int32_t samples, const float sample_rate);
LIBPBD_API std::string length2string (const int64_t samples, const double sample_rate);
LIBPBD_API std::vector<std::string> internationalize (const char *, const char **);
LIBPBD_API bool strings_equal_ignore_case (const std::string& a, const std::string& b);
LIBPBD_API const char* sgettext (const char *, const char *);
} //namespace PBD
#endif /* __pbd_convert_h__ */
| 37.035714 | 89 | 0.752652 | [
"vector"
] |
bc18cbb8ea79562ce05401a5734d8310cf2ea938 | 13,051 | c | C | kernels/linux-2.6.24/crypto/async_tx/async_tx.c | liuhaozzu/linux | bdf9758cd23e34b5f53e8e6339d9b29348615e14 | [
"Apache-2.0"
] | null | null | null | kernels/linux-2.6.24/crypto/async_tx/async_tx.c | liuhaozzu/linux | bdf9758cd23e34b5f53e8e6339d9b29348615e14 | [
"Apache-2.0"
] | 1 | 2021-04-09T09:24:44.000Z | 2021-04-09T09:24:44.000Z | crypto/async_tx/async_tx.c | KylinskyChen/linuxCore_2.6.24 | 11e90b14386491cc80477d4015e0c8f673f6d020 | [
"MIT"
] | null | null | null | /*
* core routines for the asynchronous memory transfer/transform api
*
* Copyright © 2006, Intel Corporation.
*
* Dan Williams <dan.j.williams@intel.com>
*
* with architecture considerations by:
* Neil Brown <neilb@suse.de>
* Jeff Garzik <jeff@garzik.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <linux/kernel.h>
#include <linux/async_tx.h>
#ifdef CONFIG_DMA_ENGINE
static enum dma_state_client
dma_channel_add_remove(struct dma_client *client,
struct dma_chan *chan, enum dma_state state);
static struct dma_client async_tx_dma = {
.event_callback = dma_channel_add_remove,
/* .cap_mask == 0 defaults to all channels */
};
/**
* dma_cap_mask_all - enable iteration over all operation types
*/
static dma_cap_mask_t dma_cap_mask_all;
/**
* chan_ref_percpu - tracks channel allocations per core/opertion
*/
struct chan_ref_percpu {
struct dma_chan_ref *ref;
};
static int channel_table_initialized;
static struct chan_ref_percpu *channel_table[DMA_TX_TYPE_END];
/**
* async_tx_lock - protect modification of async_tx_master_list and serialize
* rebalance operations
*/
static spinlock_t async_tx_lock;
static struct list_head
async_tx_master_list = LIST_HEAD_INIT(async_tx_master_list);
/* async_tx_issue_pending_all - start all transactions on all channels */
void async_tx_issue_pending_all(void)
{
struct dma_chan_ref *ref;
rcu_read_lock();
list_for_each_entry_rcu(ref, &async_tx_master_list, node)
ref->chan->device->device_issue_pending(ref->chan);
rcu_read_unlock();
}
EXPORT_SYMBOL_GPL(async_tx_issue_pending_all);
/* dma_wait_for_async_tx - spin wait for a transcation to complete
* @tx: transaction to wait on
*/
enum dma_status
dma_wait_for_async_tx(struct dma_async_tx_descriptor *tx)
{
enum dma_status status;
struct dma_async_tx_descriptor *iter;
struct dma_async_tx_descriptor *parent;
if (!tx)
return DMA_SUCCESS;
/* poll through the dependency chain, return when tx is complete */
do {
iter = tx;
/* find the root of the unsubmitted dependency chain */
while (iter->cookie == -EBUSY) {
parent = iter->parent;
if (parent && parent->cookie == -EBUSY)
iter = iter->parent;
else
break;
}
status = dma_sync_wait(iter->chan, iter->cookie);
} while (status == DMA_IN_PROGRESS || (iter != tx));
return status;
}
EXPORT_SYMBOL_GPL(dma_wait_for_async_tx);
/* async_tx_run_dependencies - helper routine for dma drivers to process
* (start) dependent operations on their target channel
* @tx: transaction with dependencies
*/
void
async_tx_run_dependencies(struct dma_async_tx_descriptor *tx)
{
struct dma_async_tx_descriptor *dep_tx, *_dep_tx;
struct dma_device *dev;
struct dma_chan *chan;
list_for_each_entry_safe(dep_tx, _dep_tx, &tx->depend_list,
depend_node) {
chan = dep_tx->chan;
dev = chan->device;
/* we can't depend on ourselves */
BUG_ON(chan == tx->chan);
list_del(&dep_tx->depend_node);
tx->tx_submit(dep_tx);
/* we need to poke the engine as client code does not
* know about dependency submission events
*/
dev->device_issue_pending(chan);
}
}
EXPORT_SYMBOL_GPL(async_tx_run_dependencies);
static void
free_dma_chan_ref(struct rcu_head *rcu)
{
struct dma_chan_ref *ref;
ref = container_of(rcu, struct dma_chan_ref, rcu);
kfree(ref);
}
static void
init_dma_chan_ref(struct dma_chan_ref *ref, struct dma_chan *chan)
{
INIT_LIST_HEAD(&ref->node);
INIT_RCU_HEAD(&ref->rcu);
ref->chan = chan;
atomic_set(&ref->count, 0);
}
/**
* get_chan_ref_by_cap - returns the nth channel of the given capability
* defaults to returning the channel with the desired capability and the
* lowest reference count if the index can not be satisfied
* @cap: capability to match
* @index: nth channel desired, passing -1 has the effect of forcing the
* default return value
*/
static struct dma_chan_ref *
get_chan_ref_by_cap(enum dma_transaction_type cap, int index)
{
struct dma_chan_ref *ret_ref = NULL, *min_ref = NULL, *ref;
rcu_read_lock();
list_for_each_entry_rcu(ref, &async_tx_master_list, node)
if (dma_has_cap(cap, ref->chan->device->cap_mask)) {
if (!min_ref)
min_ref = ref;
else if (atomic_read(&ref->count) <
atomic_read(&min_ref->count))
min_ref = ref;
if (index-- == 0) {
ret_ref = ref;
break;
}
}
rcu_read_unlock();
if (!ret_ref)
ret_ref = min_ref;
if (ret_ref)
atomic_inc(&ret_ref->count);
return ret_ref;
}
/**
* async_tx_rebalance - redistribute the available channels, optimize
* for cpu isolation in the SMP case, and opertaion isolation in the
* uniprocessor case
*/
static void async_tx_rebalance(void)
{
int cpu, cap, cpu_idx = 0;
unsigned long flags;
if (!channel_table_initialized)
return;
spin_lock_irqsave(&async_tx_lock, flags);
/* undo the last distribution */
for_each_dma_cap_mask(cap, dma_cap_mask_all)
for_each_possible_cpu(cpu) {
struct dma_chan_ref *ref =
per_cpu_ptr(channel_table[cap], cpu)->ref;
if (ref) {
atomic_set(&ref->count, 0);
per_cpu_ptr(channel_table[cap], cpu)->ref =
NULL;
}
}
for_each_dma_cap_mask(cap, dma_cap_mask_all)
for_each_online_cpu(cpu) {
struct dma_chan_ref *new;
if (NR_CPUS > 1)
new = get_chan_ref_by_cap(cap, cpu_idx++);
else
new = get_chan_ref_by_cap(cap, -1);
per_cpu_ptr(channel_table[cap], cpu)->ref = new;
}
spin_unlock_irqrestore(&async_tx_lock, flags);
}
static enum dma_state_client
dma_channel_add_remove(struct dma_client *client,
struct dma_chan *chan, enum dma_state state)
{
unsigned long found, flags;
struct dma_chan_ref *master_ref, *ref;
enum dma_state_client ack = DMA_DUP; /* default: take no action */
switch (state) {
case DMA_RESOURCE_AVAILABLE:
found = 0;
rcu_read_lock();
list_for_each_entry_rcu(ref, &async_tx_master_list, node)
if (ref->chan == chan) {
found = 1;
break;
}
rcu_read_unlock();
pr_debug("async_tx: dma resource available [%s]\n",
found ? "old" : "new");
if (!found)
ack = DMA_ACK;
else
break;
/* add the channel to the generic management list */
master_ref = kmalloc(sizeof(*master_ref), GFP_KERNEL);
if (master_ref) {
/* keep a reference until async_tx is unloaded */
dma_chan_get(chan);
init_dma_chan_ref(master_ref, chan);
spin_lock_irqsave(&async_tx_lock, flags);
list_add_tail_rcu(&master_ref->node,
&async_tx_master_list);
spin_unlock_irqrestore(&async_tx_lock,
flags);
} else {
printk(KERN_WARNING "async_tx: unable to create"
" new master entry in response to"
" a DMA_RESOURCE_ADDED event"
" (-ENOMEM)\n");
return 0;
}
async_tx_rebalance();
break;
case DMA_RESOURCE_REMOVED:
found = 0;
spin_lock_irqsave(&async_tx_lock, flags);
list_for_each_entry_rcu(ref, &async_tx_master_list, node)
if (ref->chan == chan) {
/* permit backing devices to go away */
dma_chan_put(ref->chan);
list_del_rcu(&ref->node);
call_rcu(&ref->rcu, free_dma_chan_ref);
found = 1;
break;
}
spin_unlock_irqrestore(&async_tx_lock, flags);
pr_debug("async_tx: dma resource removed [%s]\n",
found ? "ours" : "not ours");
if (found)
ack = DMA_ACK;
else
break;
async_tx_rebalance();
break;
case DMA_RESOURCE_SUSPEND:
case DMA_RESOURCE_RESUME:
printk(KERN_WARNING "async_tx: does not support dma channel"
" suspend/resume\n");
break;
default:
BUG();
}
return ack;
}
static int __init
async_tx_init(void)
{
enum dma_transaction_type cap;
spin_lock_init(&async_tx_lock);
bitmap_fill(dma_cap_mask_all.bits, DMA_TX_TYPE_END);
/* an interrupt will never be an explicit operation type.
* clearing this bit prevents allocation to a slot in 'channel_table'
*/
clear_bit(DMA_INTERRUPT, dma_cap_mask_all.bits);
for_each_dma_cap_mask(cap, dma_cap_mask_all) {
channel_table[cap] = alloc_percpu(struct chan_ref_percpu);
if (!channel_table[cap])
goto err;
}
channel_table_initialized = 1;
dma_async_client_register(&async_tx_dma);
dma_async_client_chan_request(&async_tx_dma);
printk(KERN_INFO "async_tx: api initialized (async)\n");
return 0;
err:
printk(KERN_ERR "async_tx: initialization failure\n");
while (--cap >= 0)
free_percpu(channel_table[cap]);
return 1;
}
static void __exit async_tx_exit(void)
{
enum dma_transaction_type cap;
channel_table_initialized = 0;
for_each_dma_cap_mask(cap, dma_cap_mask_all)
if (channel_table[cap])
free_percpu(channel_table[cap]);
dma_async_client_unregister(&async_tx_dma);
}
/**
* async_tx_find_channel - find a channel to carry out the operation or let
* the transaction execute synchronously
* @depend_tx: transaction dependency
* @tx_type: transaction type
*/
struct dma_chan *
async_tx_find_channel(struct dma_async_tx_descriptor *depend_tx,
enum dma_transaction_type tx_type)
{
/* see if we can keep the chain on one channel */
if (depend_tx &&
dma_has_cap(tx_type, depend_tx->chan->device->cap_mask))
return depend_tx->chan;
else if (likely(channel_table_initialized)) {
struct dma_chan_ref *ref;
int cpu = get_cpu();
ref = per_cpu_ptr(channel_table[tx_type], cpu)->ref;
put_cpu();
return ref ? ref->chan : NULL;
} else
return NULL;
}
EXPORT_SYMBOL_GPL(async_tx_find_channel);
#else
static int __init async_tx_init(void)
{
printk(KERN_INFO "async_tx: api initialized (sync-only)\n");
return 0;
}
static void __exit async_tx_exit(void)
{
do { } while (0);
}
#endif
void
async_tx_submit(struct dma_chan *chan, struct dma_async_tx_descriptor *tx,
enum async_tx_flags flags, struct dma_async_tx_descriptor *depend_tx,
dma_async_tx_callback cb_fn, void *cb_param)
{
tx->callback = cb_fn;
tx->callback_param = cb_param;
/* set this new tx to run after depend_tx if:
* 1/ a dependency exists (depend_tx is !NULL)
* 2/ the tx can not be submitted to the current channel
*/
if (depend_tx && depend_tx->chan != chan) {
/* if ack is already set then we cannot be sure
* we are referring to the correct operation
*/
BUG_ON(depend_tx->ack);
tx->parent = depend_tx;
spin_lock_bh(&depend_tx->lock);
list_add_tail(&tx->depend_node, &depend_tx->depend_list);
if (depend_tx->cookie == 0) {
struct dma_chan *dep_chan = depend_tx->chan;
struct dma_device *dep_dev = dep_chan->device;
dep_dev->device_dependency_added(dep_chan);
}
spin_unlock_bh(&depend_tx->lock);
/* schedule an interrupt to trigger the channel switch */
async_trigger_callback(ASYNC_TX_ACK, depend_tx, NULL, NULL);
} else {
tx->parent = NULL;
tx->tx_submit(tx);
}
if (flags & ASYNC_TX_ACK)
async_tx_ack(tx);
if (depend_tx && (flags & ASYNC_TX_DEP_ACK))
async_tx_ack(depend_tx);
}
EXPORT_SYMBOL_GPL(async_tx_submit);
/**
* async_trigger_callback - schedules the callback function to be run after
* any dependent operations have been completed.
* @flags: ASYNC_TX_ACK, ASYNC_TX_DEP_ACK
* @depend_tx: 'callback' requires the completion of this transaction
* @cb_fn: function to call after depend_tx completes
* @cb_param: parameter to pass to the callback routine
*/
struct dma_async_tx_descriptor *
async_trigger_callback(enum async_tx_flags flags,
struct dma_async_tx_descriptor *depend_tx,
dma_async_tx_callback cb_fn, void *cb_param)
{
struct dma_chan *chan;
struct dma_device *device;
struct dma_async_tx_descriptor *tx;
if (depend_tx) {
chan = depend_tx->chan;
device = chan->device;
/* see if we can schedule an interrupt
* otherwise poll for completion
*/
if (device && !dma_has_cap(DMA_INTERRUPT, device->cap_mask))
device = NULL;
tx = device ? device->device_prep_dma_interrupt(chan) : NULL;
} else
tx = NULL;
if (tx) {
pr_debug("%s: (async)\n", __FUNCTION__);
async_tx_submit(chan, tx, flags, depend_tx, cb_fn, cb_param);
} else {
pr_debug("%s: (sync)\n", __FUNCTION__);
/* wait for any prerequisite operations */
if (depend_tx) {
/* if ack is already set then we cannot be sure
* we are referring to the correct operation
*/
BUG_ON(depend_tx->ack);
if (dma_wait_for_async_tx(depend_tx) == DMA_ERROR)
panic("%s: DMA_ERROR waiting for depend_tx\n",
__FUNCTION__);
}
async_tx_sync_epilog(flags, depend_tx, cb_fn, cb_param);
}
return tx;
}
EXPORT_SYMBOL_GPL(async_trigger_callback);
module_init(async_tx_init);
module_exit(async_tx_exit);
MODULE_AUTHOR("Intel Corporation");
MODULE_DESCRIPTION("Asynchronous Bulk Memory Transactions API");
MODULE_LICENSE("GPL");
| 25.79249 | 79 | 0.730365 | [
"transform"
] |
bc203a44ed12f24cfcef2c7eb8ca1ddd62c01567 | 2,531 | h | C | projects/NavMesh/NavMesh.h | emlowry/AIEFramework | 8f1dd02105237e72cfe303ec4c541eea7debd1f7 | [
"MIT"
] | null | null | null | projects/NavMesh/NavMesh.h | emlowry/AIEFramework | 8f1dd02105237e72cfe303ec4c541eea7debd1f7 | [
"MIT"
] | null | null | null | projects/NavMesh/NavMesh.h | emlowry/AIEFramework | 8f1dd02105237e72cfe303ec4c541eea7debd1f7 | [
"MIT"
] | null | null | null | #ifndef __NavMesh_H_
#define __NavMesh_H_
#include "Application.h"
#include <glm/glm.hpp>
#include <FBXFile.h>
#include <set>
#include <unordered_map>
// Derived application class that wraps up all globals neatly
class NavMesh : public Application
{
public:
NavMesh();
virtual ~NavMesh();
protected:
virtual bool onCreate(int a_argc, char* a_argv[]);
virtual void onUpdate(float a_deltaTime);
virtual void onDraw();
virtual void onDestroy();
struct NavNodeTri
{
NavNodeTri(const glm::vec3& a_v0,
const glm::vec3& a_v1,
const glm::vec3& a_v2);
NavNodeTri(const glm::vec3 a_vertices[3]);
void setup();
glm::vec3 toParametric(const glm::vec3& a_world) const;
glm::vec3 toParametric(float a_worldX,
float a_worldY,
float a_worldZ = 0) const;
glm::vec3 toWorld(const glm::vec3& a_parametric) const;
glm::vec3 toWorld(float a_parametricX,
float a_parametricY,
float a_parametricZ = 0) const;
glm::vec3 farthestPointAlongPath(const glm::vec3& a_start,
const glm::vec3& a_end) const;
glm::vec3 position;
glm::vec3 vertices[3];
glm::vec3 normal;
NavNodeTri* edgeTarget[3];
glm::mat4 parametricToWorld;
glm::mat4 worldToParametric;
};
struct PathNode
{
PathNode(NavNodeTri* a_node = nullptr,
PathNode* a_previous = nullptr);
PathNode(const glm::vec3& a_position,
NavNodeTri* a_node = nullptr,
PathNode* a_previous = nullptr);
float pathCost() const;
float costFrom(PathNode* a_node) const;
float pathCostFrom(PathNode* a_node) const;
bool lineOfSight(const glm::vec3& a_target) const;
NavNodeTri* node = nullptr;
PathNode* previous = nullptr;
glm::vec3 position;
};
std::vector<NavNodeTri*> m_graph;
std::vector<PathNode> m_path;
void buildNavMesh(FBXMeshNode* a_mesh,
std::vector<NavNodeTri*>& a_graph);
bool findPath(NavNodeTri* a_start,
NavNodeTri* a_end,
const std::vector<NavNodeTri*>& a_graph,
std::vector<PathNode>& a_path);
bool computingPathStep(PathNode* a_endNode,
std::set<PathNode*>& a_open,
std::set<PathNode*>& a_closed,
std::unordered_map<NavNodeTri*, PathNode>& a_nodes);
void smoothPath(std::vector<PathNode>& a_path);
void createOpenGLBuffers(FBXFile* a_fbx);
void cleanupOpenGLBuffers(FBXFile* a_fbx);
struct GLData
{
unsigned int vao, vbo, ibo;
};
FBXFile* m_sponza;
FBXFile* m_navMesh;
unsigned int m_shader;
glm::mat4 m_cameraMatrix;
glm::mat4 m_projectionMatrix;
};
#endif // __NavMesh_H_ | 24.336538 | 61 | 0.702094 | [
"vector"
] |
1af620e8731113fe869193947ee8ef9f46b6bf35 | 1,894 | c | C | lib/wizards/nalle/area/monsters/alamrot.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/nalle/area/monsters/alamrot.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/nalle/area/monsters/alamrot.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | inherit "obj/monster";
reset(arg) {
string chat_str, a_chat_str;
object armour,weapon;
::reset(arg);
if (arg) { return; }
set_race("gnome");
set_level(45 +random(5));
set_name("alamrot");
set_gender(1);
set_short("Alamrot, the noisy gnome");
set_long("Alamrot, a servant of Darvox, is here training his magic skills.\n"+
"His mental abilities and skills in alchemy are rare, and so,\n"+
"important to his master, Darvox.\n"+
"Alamrot's aura can be felt around him.\n");
set_al(-5);
set_log();
set_max_hp(query_hp() + 7500);
set_hp(query_max_hp());
set_str(query_str() + 50);
set_dex(query_dex() + 50);
set_int(query_int() + 50);
set_skill("mana control", 75);
set_skill("cast essence", 65);
set_skill("cast electric", 85);
set_skill("cast bolt", 100);
set_spell_chance(15, "exs zzt blt");
if (!chat_str) {
chat_str = allocate(2);
chat_str[0] = "Alamrot gigglesnorts at you and tugs on his chain.\n";
chat_str[1] = "Alamrot yells: 'Darvox really needs me!'\n";
}
if (!a_chat_str) {
a_chat_str = allocate(1);
a_chat_str[0] = "Alamrot shouts: 'You can't do this! It's not fair!'\n";
}
load_chat(5, chat_str);
load_a_chat(15, a_chat_str);
armour = clone_object("/wizards/nalle/area/eq/newgnomehat");
move_object(armour, this_object());
init_command("wear hat");
weapon = clone_object("wizards/nalle/area/eq/gnomesword");
move_object(weapon, this_object());
init_command("wield sword");
set_special(15);
}
special_move() {
object ob;
ob = this_object()->query_attack();
say("Alamrot throws a red potion at " +ob->query_name()+ ".\n", ob);
tell_object(ob, "Alamrot throws a potion at your feet. The explosion is painful.\n");
ob->hit_with_spell(150);
}
| 30.548387 | 88 | 0.62038 | [
"object"
] |
2106a2fd4935dd7f606aed7d992e9cee80f6475e | 13,409 | h | C | sdl_core/test/components/smart_objects/SmartObjectStressTest.h | APCVSRepo/android_packet | 5d4237234656b777cd9b0cae4731afea51986582 | [
"BSD-3-Clause"
] | 4 | 2016-09-21T12:36:24.000Z | 2020-10-29T01:45:03.000Z | sdl_core/test/components/smart_objects/SmartObjectStressTest.h | APCVSRepo/android_packet | 5d4237234656b777cd9b0cae4731afea51986582 | [
"BSD-3-Clause"
] | 7 | 2016-06-01T01:21:44.000Z | 2017-11-03T08:18:23.000Z | sdl_core/test/components/smart_objects/SmartObjectStressTest.h | APCVSRepo/android_packet | 5d4237234656b777cd9b0cae4731afea51986582 | [
"BSD-3-Clause"
] | 8 | 2017-08-29T10:51:50.000Z | 2021-03-24T10:19:11.000Z | // Copyright (c) 2013, Ford Motor Company
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the
// distribution.
//
// Neither the name of the Ford Motor Company nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef TEST_COMPONENTS_SMARTOBJECTS_SMARTOBJECTSTRESSTEST_H_
#define TEST_COMPONENTS_SMARTOBJECTS_SMARTOBJECTSTRESSTEST_H_
#include <sstream>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "smart_objects/smart_object.h"
//#define NO_INCLUSIVE_MAPS
//#define COPY_SUB_OBJECTS_WORKAROUND
namespace test { namespace components { namespace SmartObjects { namespace SmartObjectStressTest {
using namespace NsSmartDeviceLink::NsSmartObjects;
class StressTestHelper : public ::testing::Test
{
private:
char get_random_char() const
{
return static_cast<char>('A' + (rand()%52));
}
std::string to_string(const int value) const
{
std::ostringstream oss;
oss << value;
return oss.str();
}
std::string to_string(const double value) const
{
// Content is the same as in SmartObject::convert_double_to_string
std::stringstream ss;
ss << std::fixed << std::setprecision(10) << value; //convert double to string w fixed notation, hi precision
std::string s = ss.str(); //output to std::string
s.erase(s.find_last_not_of('0') + 1, std::string::npos); //remove trailing 000s (123.1200 => 123.12, 123.000 => 123.)
if(s[s.size()-1] == '.') {
s.erase(s.end()-1); //remove dangling decimal (123. => 123)
}
return s;
}
std::string to_string(const char ch) const
{
char buff[2];
sprintf(buff, "%c", ch);
return std::string(buff);
}
std::string to_string(const bool b) const
{
return std::string( (b) ? "true" : "false");
}
protected:
typedef std::map<std::string, std::string> VerificationMap;
VerificationMap mVerifyMap;
std::vector<std::string>split(const std::string &s, char delim) const
{
std::vector<std::string> elems;
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
std::string generate_key(const char *pPrefix, const int index) const
{
char buff[32];
sprintf(buff, "%s%d", pPrefix, index);
return std::string(buff);
}
void makeRandomObject(SmartObject &obj, const int size, std::string key_path)
{
int type_id = rand() % 8;
switch (type_id)
{
case 0: // int
{
int iVal = rand();
obj = iVal;
mVerifyMap[key_path] = to_string(iVal);
//std::cout << "Created int, value: " << iVal << std::endl;
break;
}
case 1: // bool
{
bool bVal = static_cast<bool>(rand()%2);
obj = bVal;
mVerifyMap[key_path] = to_string(bVal);
//std::cout << "Created bool, value: " << to_string(bVal) << std::endl;
break;
}
case 2: // double
{
double dVal = 100.0 / (rand()%200);
obj = dVal;
mVerifyMap[key_path] = to_string(dVal);
//std::cout << "Created double, value: " << dVal << std::endl;
break;
}
case 3: // char
{
char cVal = get_random_char();
obj = cVal;
mVerifyMap[key_path] = to_string(cVal);
//std::cout << "Created char, value: " << cVal << std::endl;
break;
}
case 4: // string
{
std::string strVal(rand()%200, get_random_char());
obj = strVal; // string with random char filled random size
mVerifyMap[key_path] = strVal;
//std::cout << "Created string, value: " << strVal << std::endl;
break;
}
case 5: // map
if (size <= 0)
break;
//std::cout << "Creating a map with size: " << size << std::endl;
mVerifyMap[key_path] = "map";
for (int i = 0; i < size; i++)
{
std::string key = generate_key("M", i);
#ifdef NO_INCLUSIVE_MAPS
obj[key] = key;
#else
obj[key] = SmartObject();
makeRandomObject(obj[key], size - 1, key_path + key + ' '); // recursion
#endif // MAP_WORKAROUND
}
break;
case 6: // array
if (size <= 0)
break;
//std::cout << "Creating an array with size: " << size << std::endl;
mVerifyMap[key_path] = "array";
for (int i = 0; i < size; i++)
{
obj[i] = SmartObject(); // just init it as an array
makeRandomObject(obj[i], size - 1, key_path + generate_key("A", i) + ' '); // recursion
}
break;
case 7: // binary
int dataSize = rand()%200;
char randomChar = get_random_char();
std::string strDataVal(dataSize, randomChar);
std::string strVal("c:");
strVal += strDataVal;
NsSmartDeviceLink::NsSmartObjects::SmartBinary binaryVal(dataSize, randomChar);
obj = binaryVal; // string with binary data filled with random chars
mVerifyMap[key_path] = strVal;
//std::cout << "Created string, value: " << strVal << std::endl;
break;
}
}
SmartObject get_object(SmartObject &rootObj, const std::string &path) const
{
std::vector<std::string> obj_tokens;
SmartObject lastObj = rootObj;
obj_tokens = split(path, ' ');
for (int i = 0; i < obj_tokens.size(); i++)
{
if (obj_tokens[i][0] == 'A') // array
{
int index = atoi(&(obj_tokens[i].c_str()[1])); // get integer skipping first char
#ifdef COPY_SUB_OBJECTS_WORKAROUND
lastObj = SmartObject(lastObj[index]);
#else
lastObj = lastObj[index]; // go to the child object
#endif
}
else if (obj_tokens[i][0] == 'M') // map
{
#ifdef COPY_SUB_OBJECTS_WORKAROUND
lastObj = SmartObject(lastObj[obj_tokens[i]]);
#else
lastObj = lastObj[obj_tokens[i]]; // go to the child object
#endif
}
else
{
//FAIL();
EXPECT_TRUE(false);
}
}
return lastObj;
}
};
/*
* The test creates the initial SmartObject and use it as an array for the next SmartObjects.
* Each next SmartObject is randomly assigned to some type.
* If one of the object happens to be a container it fills it with SmartObject of random type. The amount of these
* objects is the size of the parent container -1.
* The iteration continues until all nodes are simple SmartObjects (not arrays or maps)
*/
TEST_F(StressTestHelper, StressTest)
{
SmartObject objects;
const int size = 11;
for (int i = 0; i < size; i++)
{
SmartObject obj;
makeRandomObject(obj, size - 1, generate_key("A", i) + ' ');
objects[i] = obj;
}
for (VerificationMap::const_iterator it = mVerifyMap.begin(); it != mVerifyMap.end(); it++)
{
std::string value(it->second);
SmartObject obj = get_object(objects, it->first);
// Binary data check
if(!value.compare(0, 2, "c:"))
{
std::string etalonData = value.substr(2);
ASSERT_EQ(NsSmartDeviceLink::NsSmartObjects::SmartType_Binary, obj.getType());
NsSmartDeviceLink::NsSmartObjects::SmartBinary binaryData = obj.asBinary();
ASSERT_EQ(etalonData.size(), binaryData.size());
for (size_t i = 0; i < etalonData.size() ; ++i)
{ {
std::string etalonData = value.substr(2);
ASSERT_EQ(NsSmartDeviceLink::NsSmartObjects::SmartType_Binary, obj.getType());
NsSmartDeviceLink::NsSmartObjects::SmartBinary binaryData = obj.asBinary();
ASSERT_EQ(etalonData.size(), binaryData.size());
for (size_t i = 0; i < etalonData.size() ; ++i)
{
ASSERT_EQ(etalonData.at(i), binaryData.at(i));
}
continue;
}
ASSERT_EQ(etalonData.at(i), binaryData.at(i));
}
continue;
}
#ifdef NO_INCLUSIVE_MAPS
if (!value.compare("map"))
{
std::vector<std::string> path = split(it->first, ' ');
std::string map_value = path[path.size()-1];
ASSERT_EQ(map_value, static_cast<std::string>(obj));
continue;
}
#endif
if (value.compare("map") && value.compare("array"))
{
//std::cout << "Verification key: " << it->first << " Value: " << value << std::endl;
//std::cout << "Object Value: " << static_cast<std::string>(obj) << std::endl;
if (!value.compare("true"))
{
ASSERT_TRUE(obj.asBool());
}
else if (!value.compare("false"))
{
ASSERT_FALSE(obj.asBool());
}
else
{
ASSERT_EQ(value, obj.asString()) << "Object value is not correct. Object path: " << it->first;
}
}
}
}
TEST_F(StressTestHelper, ExtraManualDebugTest)
{
SmartObject obj;
obj[0] = false;
obj[1] = 0.869495;
obj[2] = true;
obj[3] = 'Q';
obj[4] = true;
obj[5] = 3.704;
obj[6] = SmartObject();
obj[6][0] = std::string("ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt");
obj[6][1] = 'K';
obj[6][2] = 0.735294;
obj[6][3] = 'I';
obj[6][4] = SmartObject();
obj[6][4]["M0"] = 0.59432;
SmartObject & refObj = obj[6][4];
refObj["M1"]["M0"]["M0"][0] = true;
// FIXME: Figure out why there's a trailing zero while converting from double to string
ASSERT_EQ("0.59432", get_object(obj, "A6 A4 M0").asString());
ASSERT_TRUE(get_object(obj, "A6 A4 M1 M0 M0 A0").asBool());
}
}}}}
#endif // TEST_COMPONENTS_SMARTOBJECTS_SMARTOBJECTSTRESSTEST_H_
| 37.350975 | 137 | 0.498471 | [
"object",
"vector"
] |
210d64afe61f9b08577b42ace44611213c7e2617 | 801 | h | C | pgf+/include/gf/reader/ToksSymbol.h | egladil/mscthesis | d6f0c9b1b1e73b749894405372f2edf01e746920 | [
"BSD-2-Clause"
] | 1 | 2019-05-03T18:00:39.000Z | 2019-05-03T18:00:39.000Z | pgf+/include/gf/reader/ToksSymbol.h | egladil/mscthesis | d6f0c9b1b1e73b749894405372f2edf01e746920 | [
"BSD-2-Clause"
] | null | null | null | pgf+/include/gf/reader/ToksSymbol.h | egladil/mscthesis | d6f0c9b1b1e73b749894405372f2edf01e746920 | [
"BSD-2-Clause"
] | null | null | null | //
// ToksSymbol.h
// pgf+
//
// Created by Emil Djupfeldt on 2012-06-25.
// Copyright (c) 2012 Chalmers University of Technology. All rights reserved.
//
#ifndef pgf__ToksSymbol_h
#define pgf__ToksSymbol_h
#include <string>
#include <vector>
#include <gf/reader/Symbol.h>
namespace gf {
namespace reader {
class ToksSymbol : public Symbol {
private:
std::vector<std::string> tokens;
public:
ToksSymbol(const std::vector<std::string>& tokens);
virtual ~ToksSymbol();
virtual const std::vector<std::string>& getTokens() const;
virtual bool isTerminal() const;
virtual std::string toString() const;
};
}
}
#endif
| 21.078947 | 78 | 0.563046 | [
"vector"
] |
2110336ef2a5317a0fc088fae27c598c10f7bef8 | 830 | h | C | OcrAutomator/XMP/MemoryXMPIO.h | labinnovationdocapost/ocrAutomator | 3c90c679ee88e5f773499fdd98fbf99c1bdec5a5 | [
"Apache-2.0"
] | 8 | 2018-04-10T14:03:47.000Z | 2019-10-20T09:46:12.000Z | OcrAutomator/XMP/MemoryXMPIO.h | labinnovationdocapost/ocrAutomator | 3c90c679ee88e5f773499fdd98fbf99c1bdec5a5 | [
"Apache-2.0"
] | 7 | 2018-04-10T13:27:29.000Z | 2020-08-07T14:58:00.000Z | OcrAutomator/XMP/MemoryXMPIO.h | labinnovationdocapost/ocrAutomator | 3c90c679ee88e5f773499fdd98fbf99c1bdec5a5 | [
"Apache-2.0"
] | 1 | 2020-03-06T12:36:47.000Z | 2020-03-06T12:36:47.000Z | #pragma once
#include <XMP_IO.hpp>
#include "Buffer/MemoryFileBuffer.h"
#include "TempXMPIO.h"
class MemoryXMPIO : XMP_IO
{
Docapost::IA::Tesseract::MemoryFileBuffer* mBuffer;
//std::vector<char>* buffer;
signed long long mPosition = 0;
bool mIsBufferRelease = false;
TempXMPIO* mTmpIO = nullptr;
public:
MemoryXMPIO(Docapost::IA::Tesseract::MemoryFileBuffer* buffer);
XMP_Uns32 Read(void* buffer, XMP_Uns32 count, bool readAll = false) override;
void Write(const void* buffer, XMP_Uns32 count) override;
XMP_Int64 Seek(XMP_Int64 offset, SeekMode mode) override;
XMP_Int64 Length() override;
Docapost::IA::Tesseract::MemoryFileBuffer* Buffer();
void Truncate(XMP_Int64 length) override;
XMP_IO* DeriveTemp() override;
void AbsorbTemp() override;
void DeleteTemp() override;
~MemoryXMPIO() override;
};
| 22.432432 | 78 | 0.754217 | [
"vector"
] |
2116dac13de87223ec25a02ffb0d56d73babad76 | 16,614 | c | C | movie/Output.c | scattering-central/CCP13 | e78440d34d0ac80d2294b131ca17dddcf7505b01 | [
"BSD-3-Clause"
] | null | null | null | movie/Output.c | scattering-central/CCP13 | e78440d34d0ac80d2294b131ca17dddcf7505b01 | [
"BSD-3-Clause"
] | null | null | null | movie/Output.c | scattering-central/CCP13 | e78440d34d0ac80d2294b131ca17dddcf7505b01 | [
"BSD-3-Clause"
] | 3 | 2017-09-05T15:15:22.000Z | 2021-01-15T11:13:45.000Z | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "constants.h"
#include "structures.h"
#include "prototypes.h"
void Output()
{
extern struct Info *VAR;
extern struct Myosin *MY;
extern struct C_Protein *CP;
extern struct Titin *TT;
extern struct Tropomyosin *TR;
extern struct Actin *AA;
extern struct BackBone *BB;
extern struct Constant Cnst;
extern struct Intensity *ID;
int Head,Level,h,k,l,Rad,MERID;
double psi;
double TOCF,TCIS,TCMS,TOCMF;
double TCA,TCM,TOM,TOA;
if(VAR->View) {
View_Output();
return;
}
if((VAR->Fourier_Diff) || (VAR->Reflections) || (VAR->Observed)) {
TCA = TCM = TOA = TOM = 0.0;
printf("\n Writing To Output Stream................ %s\n\n",VAR->Output_File);
for(l = 0;l<=ID->l_max;l++) {
for(h = -ID->h_max;h<=ID->h_max;h++) {
for(k = -ID->k_max;k<=ID->k_max;k++) {
Rad = abs(h*h+k*k+h*k);
if(Rad > ID->R_max) continue;
psi = atan2((2.0*k+h),Cnst.Root_t*h);
if((psi >= VAR->Max_Angle) || (psi < VAR->Min_Angle )) continue;
ID->Mul[Rad][l]++;
}
}
}
if(!VAR->Scale_Data) {
for(l = 0;l<=ID->l_max;l++) {
for(h = -ID->h_max;h<=ID->h_max;h++) {
for(k = -ID->k_max;k<=ID->k_max;k++) {
Rad = abs(h*h+k*k+h*k);
if(Rad > ID->R_max) continue;
psi = atan2((2.0*k+h),Cnst.Root_t*h);
if((psi >= VAR->Max_Angle) || (psi < VAR->Min_Angle )) continue;
if(ID->SD[Rad][l] == 0.0) continue;
if(VAR->Weighting)
ID->FD_Obs[h][k][l] = sqrt(ID->OI[Rad][l]*SQR(ID->FD_Cal[h][k][l])/ID->CI[Rad][l]);
else ID->FD_Obs[h][k][l] = sqrt(ID->OI[Rad][l]/(double)ID->Mul[Rad][l]);
if(Rad == 0) {
TCM += ID->FD_Cal[h][k][l];
TOM += ID->FD_Obs[h][k][l];
continue;
}
TCA += ID->FD_Cal[h][k][l];
TOA += ID->FD_Obs[h][k][l];
}
}
}
if(TCA == 0.0) VAR->Scale[OFFMERID] = 0.0;
else VAR->Scale[OFFMERID] = TOA/TCA;
if(TCM == 0.0) VAR->Scale[ONMERID] = 0.0;
else VAR->Scale[ONMERID] = TOM/TCM;
}
for(l = 0;l<=ID->l_max;l++) {
for(h = -ID->h_max;h<=ID->h_max;h++) {
for(k = -ID->k_max;k<=ID->k_max;k++) {
Rad = abs(h*h+k*k+h*k);
if(Rad > ID->R_max) continue;
if(!VAR->Scale_Data)
if(Rad == 0) continue;
psi = atan2((2.0*k+h),Cnst.Root_t*h);
if((psi >= VAR->Max_Angle) || (psi < VAR->Min_Angle )) continue;
if(ID->SD[Rad][l] == 0.0) continue;
if(Rad == 0)
MERID = ONMERID;
else MERID = OFFMERID;
if(VAR->Observed) {
fprintf(VAR->Output,"%3d %3d %3d %12.10e %12.10f\n",
h,k,l,ID->FD_Obs[h][k][l],ID->FD_Cal_Ph[h][k][l]);
}
if(VAR->Reflections) {
fprintf(VAR->Output,"%3d %3d %3d %12.10e %12.10f\n",
h,k,l,VAR->Scale[MERID]*ID->FD_Cal[h][k][l],
ID->FD_Cal_Ph[h][k][l]);
}
if(VAR->Fourier_Diff) {
fprintf(VAR->Output,"%3d %3d %3d ",h,k,l);
fprintf(VAR->Output,"%12.10e ",
ID->FD_Obs[h][k][l] - VAR->Scale[MERID]*ID->FD_Cal[h][k][l]);
fprintf(VAR->Output,"%12.10f\n",ID->FD_Cal_Ph[h][k][l]);
}
}
}
}
printf(" Meridional Scaling...................... %10.8e\n",VAR->Scale[ONMERID]);
printf(" Off-Meridional Scaling.................. %10.8e\n",VAR->Scale[OFFMERID]);
return;
}
if(VAR->HKLOutput) {
TOCF = TCIS = TCMS = TOCMF = 0.0;
printf("\n Writing To Output Stream................ %s\n\n",VAR->Output_File);
fprintf(VAR->Output,"BRAGG\n");
fprintf(VAR->Output,"CELL\t%6.2f\t%6.2f\t%6.2f\t90\t90\t120\n",VAR->U_Cl,VAR->U_Cl,VAR->Tot_Rep);
fprintf(VAR->Output,"DELTA 0.0\n");
if(!VAR->Scale_Data) {
for(l = 0;l<=ID->l_max;l++) {
for(h = -ID->h_max;h<=ID->h_max;h++) {
for(k = -ID->k_max;k<=ID->k_max;k++) {
Rad = abs(h*h+k*k+h*k);
if(Rad > ID->R_max) continue;
psi = atan2((2.0*k+h),Cnst.Root_t*h);
if((psi >= VAR->Max_Angle) || (psi < VAR->Min_Angle )) continue;
if(ID->SD[Rad][l] == 0.0) continue;
if(Rad == 0) {
TCMS += ID->CI[Rad][l];
TOCMF += ID->OI[Rad][l];
continue;
}
TCIS += ID->CI[Rad][l];
TOCF += ID->OI[Rad][l];
}
}
}
if(TCIS == 0.0) VAR->Scale[OFFMERID] = 0.0;
else VAR->Scale[OFFMERID] = TOCF/TCIS;
if(TCMS == 0.0) VAR->Scale[ONMERID] = 0.0;
else VAR->Scale[ONMERID] = TOCMF/TCMS;
}
for(l = 0;l<=ID->l_max;l++) {
for(Rad = 0;Rad<=ID->R_max;Rad++) {
if(ID->SD[Rad][l] == 0.0) continue;
if(Rad == 0) MERID = ONMERID;
else MERID = OFFMERID;
if(VAR->ccp13) fprintf(VAR->Output,"%3d %3d %3d 1.0 1 %e %e\n",
ID->h_i[Rad][l],ID->k_i[Rad][l],l,
VAR->Scale[MERID]*ID->CI[Rad][l],ID->SD[Rad][l]);
else fprintf(VAR->Output,"%3d %3d %3d %e\n",ID->h_i[Rad][l],ID->k_i[Rad][l],l,
VAR->Scale[MERID]*ID->CI[Rad][l]);
}
}
printf(" Meridional Scaling...................... %10.8e\n",VAR->Scale[ONMERID]);
printf(" Off-Meridional Scaling.................. %10.8e\n",VAR->Scale[OFFMERID]);
return;
}
if(VAR->Global) {
if(VAR->Myo) {
for(Head=1;Head<=MY->N_Hds;Head++) {
if(MY->Slew[Head].Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Slew[Head].Val/Cnst.DTR);
if(MY->Tilt[Head].Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Tilt[Head].Val/Cnst.DTR);
if(MY->Rot[Head].Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Rot[Head].Val/Cnst.DTR);
for(Level=1;Level<=MY->N_Crwns;Level++) {
if(MY->PSlew[Level][Head].Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->PSlew[Level][Head].Val/Cnst.DTR);
if(MY->PTilt[Level][Head].Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->PTilt[Level][Head].Val/Cnst.DTR);
if(MY->PRot[Level][Head].Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->PRot[Level][Head].Val/Cnst.DTR);
}
}
for(Level=1;Level<=MY->N_Crwns;Level++) {
if(MY->PRad[Level].Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->PRad[Level].Val);
if(MY->PAxial[Level].Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->PAxial[Level].Val);
if(MY->PAzi[Level].Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->PAzi[Level].Val/Cnst.DTR);
}
if(MY->Hd_Sp.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Hd_Sp.Val);
if(MY->Hd_An.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Hd_An.Val/Cnst.DTR);
if(MY->Rad.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Rad.Val);
if(MY->Lat.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Lat.Val/Cnst.DTR);
if(MY->Piv_Tilt1.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Piv_Tilt1.Val/Cnst.DTR);
if(MY->Piv_Slew1.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Piv_Slew1.Val/Cnst.DTR);
if(MY->Piv_Rot1.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Piv_Rot1.Val/Cnst.DTR);
if(MY->Piv_Tilt2.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Piv_Tilt2.Val/Cnst.DTR);
if(MY->Piv_Slew2.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Piv_Slew2.Val/Cnst.DTR);
if(MY->Piv_Rot2.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Piv_Rot2.Val/Cnst.DTR);
}
if(VAR->CPro) {
if(CP->Tilt.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Tilt.Val/Cnst.DTR);
if(CP->Pivot_Tilt.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Pivot_Tilt.Val/Cnst.DTR);
if(CP->Pivot_Slew.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Pivot_Slew.Val/Cnst.DTR);
if(CP->Azi.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Azi.Val/Cnst.DTR);
if(CP->Rad.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Rad.Val);
if(CP->Axial.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Axial.Val);
if(CP->Weight.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Weight.Val);
}
if(VAR->Titin) {
if(TT->Azi.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",TT->Azi.Val/Cnst.DTR);
if(TT->Rad.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",TT->Rad.Val);
if(TT->Weight.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",TT->Weight.Val);
}
if(VAR->BBone) if(BB->Model == 0) {
if(BB->Azi.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",BB->Azi.Val/Cnst.DTR);
}
if(VAR->Actin) {
if(AA->Weight.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",AA->Weight.Val);
}
if(VAR->Tropomyosin) {
if(TR->Weight.Stp > SMALL) fprintf(VAR->Output,"%6.2f ",TR->Weight.Val);
}
}
if((VAR->Torus) || (VAR->Simplex) || (VAR->Powell) || (VAR->Anneal) || (VAR->Replex)) {
if(VAR->Myo) {
for(Head=1;Head<=MY->N_Hds;Head++) {
if(MY->Slew[Head].Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Slew[Head].Val/Cnst.DTR);
if(MY->Tilt[Head].Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Tilt[Head].Val/Cnst.DTR);
if(MY->Rot[Head].Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Rot[Head].Val/Cnst.DTR);
for(Level=1;Level<=MY->N_Crwns;Level++) {
if(MY->PSlew[Level][Head].Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->PSlew[Level][Head].Val/Cnst.DTR);
if(MY->PTilt[Level][Head].Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->PTilt[Level][Head].Val/Cnst.DTR);
if(MY->PRot[Level][Head].Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->PRot[Level][Head].Val/Cnst.DTR);
}
}
for(Level=1;Level<=MY->N_Crwns;Level++) {
if(MY->PRad[Level].Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->PRad[Level].Val);
if(MY->PAxial[Level].Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->PAxial[Level].Val);
if(MY->PAzi[Level].Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->PAzi[Level].Val/Cnst.DTR);
}
if(MY->Hd_Sp.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Hd_Sp.Val);
if(MY->Hd_An.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Hd_An.Val/Cnst.DTR);
if(MY->Rad.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Rad.Val);
if(MY->Lat.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Lat.Val/Cnst.DTR);
if(MY->Piv_Tilt1.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Piv_Tilt1.Val/Cnst.DTR);
if(MY->Piv_Slew1.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Piv_Slew1.Val/Cnst.DTR);
if(MY->Piv_Rot1.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Piv_Rot1.Val/Cnst.DTR);
if(MY->Piv_Tilt2.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Piv_Tilt2.Val/Cnst.DTR);
if(MY->Piv_Slew2.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Piv_Slew2.Val/Cnst.DTR);
if(MY->Piv_Rot2.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",MY->Piv_Rot2.Val/Cnst.DTR);
}
if(VAR->CPro) {
if(CP->Tilt.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Tilt.Val/Cnst.DTR);
if(CP->Pivot_Tilt.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Pivot_Tilt.Val/Cnst.DTR);
if(CP->Pivot_Slew.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Pivot_Slew.Val/Cnst.DTR);
if(CP->Azi.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Azi.Val/Cnst.DTR);
if(CP->Rad.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Rad.Val);
if(CP->Axial.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Axial.Val);
if(CP->Weight.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",CP->Weight.Val);
}
if(VAR->Titin) {
if(TT->Azi.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",TT->Azi.Val/Cnst.DTR);
if(TT->Rad.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",TT->Rad.Val);
if(TT->Weight.Scl > SMALL) fprintf(VAR->Output,"%6.2f ",TT->Weight.Val);
}
if(VAR->BBone) if(BB->Model == 0) {
if(BB->Azi.Scl > SMALL) {
fprintf(VAR->Output,"%6.2f ",BB->Azi.Val/Cnst.DTR);
}
}
if(VAR->Actin) {
if(AA->Weight.Scl > SMALL) {
fprintf(VAR->Output,"%6.2f ",AA->Weight.Val);
}
}
if(VAR->Tropomyosin) {
if(TR->Weight.Scl > SMALL) {
fprintf(VAR->Output,"%6.2f ",TR->Weight.Val);
}
}
}
if(VAR->Least_Sq) {
if(VAR->Weighting) WLeast_SQR();
else Least_SQR();
fprintf(VAR->Output,"%5.3e %5.3e ",ID->R_Fac,ID->MR_Fac);
if(VAR->Scoring) fprintf(VAR->Output,"%d/%d %d/%d ",
ID->N_Ref-ID->MRD,
ID->N_Ref,
ID->NM_Ref-ID->MMRD,
ID->NM_Ref);
}
if(VAR->Cryst) {
if(VAR->Weighting) WCrystal();
else Crystal();
fprintf(VAR->Output,"%5.3e %5.3e ",ID->R_Fac,ID->MR_Fac);
if(VAR->Scoring) fprintf(VAR->Output,"%d/%d %d/%d ",
ID->N_Ref-ID->MRD,
ID->N_Ref,
ID->NM_Ref-ID->MMRD,
ID->NM_Ref);
}
if(VAR->Corr) {
Correlation();
fprintf(VAR->Output,"%5.3e %5.3e ",ID->C_Fac,ID->MC_Fac);
}
fprintf(VAR->Output,"\n");
return;
}
void Finish()
{
extern struct Info *VAR;
extern struct Constant Cnst;
extern struct Intensity *ID;
extern struct Tropomyosin *TR;
extern struct Actin *AA;
extern struct Myosin *MY;
extern struct C_Protein *CP;
extern struct Titin *TT;
extern struct BackBone *BB;
int Head,Level;
fprintf(VAR->Output,"\n");
if(VAR->Myo) {
fprintf(VAR->Output,"Myosin Parameters\n");
for(Head=1;Head<=MY->N_Hds;Head++) {
fprintf(VAR->Output,"\t Slew_%d = %15.10f\n",Head,MY->Slew[Head].Val/Cnst.DTR);
fprintf(VAR->Output,"\t Tilt_%d = %15.10f\n",Head,MY->Tilt[Head].Val/Cnst.DTR);
fprintf(VAR->Output,"\t Rot_%d = %15.10f\n",Head,MY->Rot[Head].Val/Cnst.DTR);
for(Level=1;Level<=MY->N_Crwns;Level++) {
fprintf(VAR->Output,"\t PSlew_%d%d = %15.10f\n",Level,Head,MY->PSlew[Level][Head].Val/Cnst.DTR);
fprintf(VAR->Output,"\t PTilt_%d%d = %15.10f\n",Level,Head,MY->PTilt[Level][Head].Val/Cnst.DTR);
fprintf(VAR->Output,"\t PRot_%d%d = %15.10f\n",Level,Head,MY->PRot[Level][Head].Val/Cnst.DTR);
}
}
for(Level=1;Level<=MY->N_Crwns;Level++) {
fprintf(VAR->Output,"\t PRad_%d = %15.10f\n",Level,MY->PRad[Level].Val);
fprintf(VAR->Output,"\t PAxial_%d = %15.10f\n",Level,MY->PAxial[Level].Val);
fprintf(VAR->Output,"\t PAzi_%d = %15.10f\n",Level,MY->PAzi[Level].Val/Cnst.DTR);
}
fprintf(VAR->Output,"\t Head Sep = %15.10f\n",MY->Hd_Sp.Val);
fprintf(VAR->Output,"\t Head Ang = %15.10f\n",MY->Hd_An.Val/Cnst.DTR);
fprintf(VAR->Output,"\t Radius = %15.10f\n",MY->Rad.Val);
fprintf(VAR->Output,"\t Latt Rot = %15.10f\n",MY->Lat.Val/Cnst.DTR);
fprintf(VAR->Output,"\tPivot Tilt1 = %15.10f\n",MY->Piv_Tilt1.Val/Cnst.DTR);
fprintf(VAR->Output,"\tPivot Slew1 = %15.10f\n",MY->Piv_Slew1.Val/Cnst.DTR);
fprintf(VAR->Output,"\tPivot Rot 1= %15.10f\n",MY->Piv_Rot1.Val/Cnst.DTR);
fprintf(VAR->Output,"\tPivot Tilt2 = %15.10f\n",MY->Piv_Tilt2.Val/Cnst.DTR);
fprintf(VAR->Output,"\tPivot Slew2 = %15.10f\n",MY->Piv_Slew2.Val/Cnst.DTR);
fprintf(VAR->Output,"\tPivot Rot 2= %15.10f\n",MY->Piv_Rot2.Val/Cnst.DTR);
}
if(VAR->CPro) {
fprintf(VAR->Output,"C-Protein Parameters\n");
fprintf(VAR->Output,"\t Tilt = %15.10f\n",CP->Tilt.Val/Cnst.DTR);
fprintf(VAR->Output,"\t P Tilt = %15.10f\n",CP->Pivot_Tilt.Val/Cnst.DTR);
if(CP->Pivot_Type == 2) {
fprintf(VAR->Output,"\t P Slew = %15.10f\n",CP->Pivot_Slew.Val/Cnst.DTR);
}
fprintf(VAR->Output,"\tAzimuth = %15.10f\n",CP->Azi.Val/Cnst.DTR);
fprintf(VAR->Output,"\t Radius = %15.10f\n",CP->Rad.Val);
fprintf(VAR->Output,"\t Weight = %15.10f\n",CP->Weight.Val);
fprintf(VAR->Output,"\t Axial = %15.10f\n",CP->Axial.Val);
}
if(VAR->Titin) {
fprintf(VAR->Output,"Titin Parameters\n");
fprintf(VAR->Output,"\tAzimuth = %15.10f\n",TT->Azi.Val/Cnst.DTR);
fprintf(VAR->Output,"\t Radius = %15.10f\n",TT->Rad.Val);
fprintf(VAR->Output,"\t Weight = %15.10f\n",TT->Weight.Val);
}
if(VAR->BBone) {
fprintf(VAR->Output,"BackBone Parameters\n");
fprintf(VAR->Output,"\tAzimuth = %15.10f\n",BB->Azi.Val/Cnst.DTR);
}
if(VAR->Actin) {
fprintf(VAR->Output,"Actin Parameters\n");
fprintf(VAR->Output,"\t Weight = %15.10f\n",AA->Weight.Val);
}
if(VAR->Tropomyosin) {
fprintf(VAR->Output,"Tropomyosin Parameters\n");
fprintf(VAR->Output,"\t Weight = %15.10f\n",TR->Weight.Val);
}
if((VAR->Simplex) || (VAR->Global) || (VAR->Anneal) || (VAR->Replex) || (VAR->Torus))
fprintf(VAR->Output,"\n No of iterations = %d\n",VAR->Iterations);
if((VAR->Least_Sq) && (!VAR->Weighting)) {
fprintf(VAR->Output,"\n R-Factor = %10.8e\n",ID->R_Fac);
fprintf(VAR->Output," MR-Factor = %10.8e\n",ID->MR_Fac);
}
if(VAR->Weighting) {
fprintf(VAR->Output,"\n Weighted R-Factor = %10.8e\n",ID->R_Fac);
fprintf(VAR->Output," Weighted MR-Factor = %10.8e\n",ID->MR_Fac);
}
if(VAR->Scoring) {
fprintf(VAR->Output,"\n Off Meridonal Score - %d/%d\n",ID->N_Ref-ID->MRD,ID->N_Ref);
fprintf(VAR->Output," Meridional Score - %d/%d\n",ID->NM_Ref-ID->MMRD,ID->NM_Ref);
}
if(VAR->Corr) {
fprintf(VAR->Output,"\n Correlation Factor = %10.8e\n",ID->C_Fac);
fprintf(VAR->Output," MCorrelation Factor = %10.8e\n",ID->MC_Fac);
}
}
| 42.930233 | 108 | 0.574877 | [
"model",
"3d"
] |
212604a5784ef0ac7d52e7b79c571749741dc539 | 9,951 | c | C | head/sys/dev/isci/scil/sci_base_logger.c | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | null | null | null | head/sys/dev/isci/scil/sci_base_logger.c | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | null | null | null | head/sys/dev/isci/scil/sci_base_logger.c | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | null | null | null | /*-
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2008 - 2011 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
* The full GNU General Public License is included in this distribution
* in the file called LICENSE.GPL.
*
* BSD LICENSE
*
* Copyright(c) 2008 - 2011 Intel Corporation. All rights reserved.
* 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 <sys/cdefs.h>
__FBSDID("$FreeBSD: soc2013/dpl/head/sys/dev/isci/scil/sci_base_logger.c 231418 2012-02-07 17:43:58Z jimharris $");
/**
* @file
*
* @brief This file contains the implementation for the base logger object.
* It provides the functionality necessary to enabling, disabling,
* constructing, etc. logger objects.
*/
#include <dev/isci/scil/sci_base_logger.h>
#ifdef SCI_LOGGING
//******************************************************************************
//* P R I V A T E M E T H O D S
//******************************************************************************
#define SCI_LOGGER_GET_OBJECT_MASK(logger, verbosity_level) \
(((SCI_BASE_LOGGER_T *)(logger))->object_mask[(verbosity_level)])
/**
* @brief This method is private to this object. It attempts to enable the
* supplied log objects for the supplied verbosity levels.
*
* @param[in] logger This parameter specifies the logger object for which
* to attempt to enable log object and verbosity levels.
* @param[in] log_object_mask This parameter specifies the log objects to
* attempt to enable.
* @param[in] verbosity_mask This parameter specifies the verbosity levels
* that are allowed to be enabled.
* @param[in] verbosity This parameter specifies the specific verbosity level
* to attempt to enable.
*
* @return none
*/
static
void sci_base_logger_enable_log_object(
SCI_LOGGER_HANDLE_T logger,
U32 log_object_mask,
U8 verbosity_mask,
U8 verbosity
)
{
// Enable the log objects for the error verbosity if errs are enabled.
if ( (1<<verbosity) & verbosity_mask)
{
SCI_LOGGER_GET_OBJECT_MASK(logger, verbosity) |= log_object_mask;
(((SCI_BASE_LOGGER_T *)(logger))->verbosity_mask |= (1<<verbosity) );
}
}
/**
* @brief This method is private to this object. It attempts to disable the
* supplied log objects for the supplied verbosity levels.
*
* @param[in] logger This parameter specifies the logger object for which
* to attempt to disable log object and verbosity levels.
* @param[in] log_object_mask This parameter specifies the log objects to
* attempt to disable.
* @param[in] verbosity_mask This parameter specifies the verbosity levels
* that are allowed to be disabled.
* @param[in] verbosity This parameter specifies the specific verbosity level
* to attempt to disable.
*
* @return none
*/
static
void sci_base_logger_disable_log_object(
SCI_LOGGER_HANDLE_T logger,
U32 log_object_mask,
U8 verbosity_mask,
U8 verbosity
)
{
if ( (1<<verbosity) & verbosity_mask)
{
SCI_LOGGER_GET_OBJECT_MASK(logger, verbosity) &= ~log_object_mask;
// If all of the objects in the object mask are disabled for this
// verbosity, then disable the verbosity as well.
if (SCI_LOGGER_GET_OBJECT_MASK(logger, verbosity) == 0)
(((SCI_BASE_LOGGER_T *)(logger))->verbosity_mask &= ~(1<<verbosity) );
}
}
//******************************************************************************
//* P U B L I C M E T H O D S
//******************************************************************************
U8 sci_logger_get_verbosity_mask(
SCI_LOGGER_HANDLE_T logger,
U32 log_object
)
{
U8 verbosity_mask = 0;
SCI_BASE_LOGGER_T * base_logger = (SCI_BASE_LOGGER_T *)logger;
if ( base_logger->object_mask[SCI_LOG_VERBOSITY_ERROR] & log_object )
verbosity_mask |= 1<<SCI_LOG_VERBOSITY_ERROR;
if ( base_logger->object_mask[SCI_LOG_VERBOSITY_WARNING] & log_object )
verbosity_mask |= 1<<SCI_LOG_VERBOSITY_WARNING;
if ( base_logger->object_mask[SCI_LOG_VERBOSITY_INFO] & log_object )
verbosity_mask |= 1<<SCI_LOG_VERBOSITY_INFO;
if ( base_logger->object_mask[SCI_LOG_VERBOSITY_TRACE] & log_object )
verbosity_mask |= 1<<SCI_LOG_VERBOSITY_TRACE;
if ( base_logger->object_mask[SCI_LOG_VERBOSITY_STATES] & log_object )
verbosity_mask |= 1<<SCI_LOG_VERBOSITY_TRACE;
return verbosity_mask;
}
// ---------------------------------------------------------------------------
U32 sci_logger_get_object_mask(
SCI_LOGGER_HANDLE_T logger,
U8 verbosity
)
{
// Ensure that a supported verbosity level was supplied.
if ( (SCI_LOG_VERBOSITY_ERROR == verbosity)
|| (SCI_LOG_VERBOSITY_WARNING == verbosity)
|| (SCI_LOG_VERBOSITY_INFO == verbosity)
|| (SCI_LOG_VERBOSITY_TRACE == verbosity)
|| (SCI_LOG_VERBOSITY_STATES == verbosity) )
{
return SCI_LOGGER_GET_OBJECT_MASK(logger, verbosity);
}
// An unsupported verbosity level was supplied. Simply return an empty
// log object mask.
return 0;
}
// ---------------------------------------------------------------------------
void sci_logger_enable(
SCI_LOGGER_HANDLE_T logger,
U32 log_object_mask,
U8 verbosity_mask
)
{
sci_base_logger_enable_log_object(
logger, log_object_mask, verbosity_mask, SCI_LOG_VERBOSITY_ERROR
);
sci_base_logger_enable_log_object(
logger, log_object_mask, verbosity_mask, SCI_LOG_VERBOSITY_WARNING
);
sci_base_logger_enable_log_object(
logger, log_object_mask, verbosity_mask, SCI_LOG_VERBOSITY_INFO
);
sci_base_logger_enable_log_object(
logger, log_object_mask, verbosity_mask, SCI_LOG_VERBOSITY_TRACE
);
sci_base_logger_enable_log_object(
logger, log_object_mask, verbosity_mask, SCI_LOG_VERBOSITY_STATES
);
}
// ---------------------------------------------------------------------------
void sci_logger_disable(
SCI_LOGGER_HANDLE_T logger,
U32 log_object_mask,
U8 verbosity_mask
)
{
sci_base_logger_disable_log_object(
logger, log_object_mask, verbosity_mask, SCI_LOG_VERBOSITY_ERROR
);
sci_base_logger_disable_log_object(
logger, log_object_mask, verbosity_mask, SCI_LOG_VERBOSITY_WARNING
);
sci_base_logger_disable_log_object(
logger, log_object_mask, verbosity_mask, SCI_LOG_VERBOSITY_INFO
);
sci_base_logger_disable_log_object(
logger, log_object_mask, verbosity_mask, SCI_LOG_VERBOSITY_TRACE
);
sci_base_logger_disable_log_object(
logger, log_object_mask, verbosity_mask, SCI_LOG_VERBOSITY_STATES
);
}
// ---------------------------------------------------------------------------
BOOL sci_logger_is_enabled(
SCI_LOGGER_HANDLE_T logger,
U32 log_object_mask,
U8 verbosity_level
)
{
SCI_BASE_LOGGER_T * base_logger = (SCI_BASE_LOGGER_T*) logger;
if ( (base_logger->verbosity_mask & (1<<verbosity_level))
&& (base_logger->object_mask[verbosity_level] & log_object_mask) )
return TRUE;
return FALSE;
}
//******************************************************************************
//* P R O T E C T E D M E T H O D S
//******************************************************************************
void sci_base_logger_construct(
SCI_BASE_LOGGER_T *this_logger
)
{
int index;
sci_base_object_construct(
&this_logger->parent, this_logger
);
this_logger->verbosity_mask = 0;
for (index = 0; index < SCI_BASE_LOGGER_MAX_VERBOSITY_LEVELS; index++)
{
this_logger->object_mask[index] = 0;
}
}
#endif // SCI_LOGGING
| 34.078767 | 115 | 0.65109 | [
"object"
] |
213b689b1fc67b99baa884af4d857b89730b7e7e | 2,174 | h | C | bcos-rpc/bcos-rpc/event/EventSubParams.h | xueying4402/FISCO-BCOS | 737e08752e8904c7c24e3737f8f46bf5327ef792 | [
"Apache-2.0"
] | 1 | 2022-03-06T10:46:12.000Z | 2022-03-06T10:46:12.000Z | bcos-rpc/bcos-rpc/event/EventSubParams.h | xueying4402/FISCO-BCOS | 737e08752e8904c7c24e3737f8f46bf5327ef792 | [
"Apache-2.0"
] | 25 | 2021-07-23T10:09:22.000Z | 2021-12-14T10:06:56.000Z | bcos-rpc/bcos-rpc/event/EventSubParams.h | xueying4402/FISCO-BCOS | 737e08752e8904c7c24e3737f8f46bf5327ef792 | [
"Apache-2.0"
] | 6 | 2021-06-17T08:32:02.000Z | 2021-10-31T11:59:44.000Z | /*
* Copyright (C) 2021 FISCO BCOS.
* SPDX-License-Identifier: Apache-2.0
* 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.
*
* @file EvenSubParams.h
* @author: octopus
* @date 2021-09-01
*/
#pragma once
#include <bcos-framework/interfaces/protocol/ProtocolTypeDef.h>
#include <bcos-rpc/event/Common.h>
#include <string>
#include <vector>
namespace bcos
{
namespace event
{
class EventSubParams
{
public:
using Ptr = std::shared_ptr<EventSubParams>;
using ConstPtr = std::shared_ptr<const EventSubParams>;
public:
int64_t fromBlock() const { return m_fromBlock; }
int64_t toBlock() const { return m_toBlock; }
const std::set<std::string>& addresses() const { return m_addresses; }
std::set<std::string>& addresses() { return m_addresses; }
const std::vector<std::set<std::string>>& topics() const { return m_topics; }
std::vector<std::set<std::string>>& topics() { return m_topics; }
void setFromBlock(int64_t _fromBlock) { m_fromBlock = _fromBlock; }
void setToBlock(int64_t _toBlock) { m_toBlock = _toBlock; }
void addAddress(const std::string& _address) { m_addresses.insert(_address); }
bool addTopic(std::size_t _index, const std::string& _topic)
{
if (_index >= EVENT_LOG_TOPICS_MAX_INDEX)
{
return false;
}
m_topics.resize(_index + 1);
m_topics[_index].insert(_topic);
return true;
}
private:
bcos::protocol::BlockNumber m_fromBlock = -1;
bcos::protocol::BlockNumber m_toBlock = -1;
std::set<std::string> m_addresses;
std::vector<std::set<std::string>> m_topics;
};
} // namespace event
} // namespace bcos | 31.970588 | 82 | 0.688592 | [
"vector"
] |
213f9bcb013fbaab050439571066cc920ef7b6cf | 1,348 | h | C | apps/vaporgui/VGeometry.h | khallock/VAPOR | ff7640fbe64aa9bd4c2c9c1020627e4dc6b78b9d | [
"BSD-3-Clause"
] | null | null | null | apps/vaporgui/VGeometry.h | khallock/VAPOR | ff7640fbe64aa9bd4c2c9c1020627e4dc6b78b9d | [
"BSD-3-Clause"
] | null | null | null | apps/vaporgui/VGeometry.h | khallock/VAPOR | ff7640fbe64aa9bd4c2c9c1020627e4dc6b78b9d | [
"BSD-3-Clause"
] | null | null | null | //
// ====================================
// VGeometry combines two or three VRanges,
// representing a 2D or 3D geometry.
// Note: this class is never supposed to be used beyond 2D and 3D cases.
// ====================================
//
class VGeometry : public QWidget
{
Q_OBJECT
public:
/* Constructor for 2D or 3D geometries.
Four floating point values imply a 2D geometry, while Six floating point
values imply a 3D geometry. All other numbers are illegal. */
VGeometry( QWidget* parent, int dim, const std::vector<float>& range );
/* Adjust the dimension and/or value ranges through this function.
Argument range must contain 4 or 6 values organized in the following order:
xmin, xmax, ymin, ymax, (zmin, zmax). */
void SetDimAndRange( int dim, const std::vector<float>& range );
/* The number of incoming values MUST match the current dimensionality.
I.e., 4 values for 2D widgets, and 6 values for 3D widgets. */
void SetCurrentValues( const std::vector<float>& vals );
void GetCurrentValues( std::vector<float>& vals ) const;
signals:
void _geometryChanged();
private slots:
void _respondChanges();
private:
int _dim;
VRange *_xrange, *_yrange, *_zrange;
QVBoxLayout* _layout;
};
| 34.564103 | 82 | 0.620178 | [
"geometry",
"vector",
"3d"
] |
21424e370fcd8356f5912ae28135fe22dbfd4043 | 12,349 | c | C | crypto_base64.c | bukka/php-crypto | 432e6c6deaf69ae454cb14499f3a29d88031616f | [
"PHP-3.01"
] | 72 | 2015-02-01T20:28:27.000Z | 2022-01-21T21:33:04.000Z | crypto_base64.c | bukka/php-crypto | 432e6c6deaf69ae454cb14499f3a29d88031616f | [
"PHP-3.01"
] | 24 | 2015-03-17T09:38:08.000Z | 2021-04-11T00:19:12.000Z | crypto_base64.c | bukka/php-crypto | 432e6c6deaf69ae454cb14499f3a29d88031616f | [
"PHP-3.01"
] | 16 | 2015-10-01T16:40:12.000Z | 2021-02-21T20:29:37.000Z | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 2013-2016 Jakub Zelenka |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Jakub Zelenka <bukka@php.net> |
+----------------------------------------------------------------------+
*/
#include "php.h"
#include "php_crypto.h"
#include "php_crypto_base64.h"
#include "zend_exceptions.h"
#include <openssl/evp.h>
PHP_CRYPTO_EXCEPTION_DEFINE(Base64)
PHP_CRYPTO_ERROR_INFO_BEGIN(Base64)
PHP_CRYPTO_ERROR_INFO_ENTRY(
ENCODE_UPDATE_FORBIDDEN,
"The object is already used for decoding"
)
PHP_CRYPTO_ERROR_INFO_ENTRY(
ENCODE_FINISH_FORBIDDEN,
"The object has not been intialized for encoding"
)
PHP_CRYPTO_ERROR_INFO_ENTRY(
DECODE_UPDATE_FORBIDDEN,
"The object is already used for encoding"
)
PHP_CRYPTO_ERROR_INFO_ENTRY(
DECODE_FINISH_FORBIDDEN,
"The object has not been intialized for decoding"
)
PHP_CRYPTO_ERROR_INFO_ENTRY(
DECODE_UPDATE_FAILED,
"Base64 decoded string does not contain valid characters"
)
PHP_CRYPTO_ERROR_INFO_ENTRY(
INPUT_DATA_LENGTH_HIGH,
"Input data length can't exceed max integer length"
)
PHP_CRYPTO_ERROR_INFO_END()
ZEND_BEGIN_ARG_INFO(arginfo_crypto_base64_data, 0)
ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_crypto_base64_no_args, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry php_crypto_base64_object_methods[] = {
PHP_CRYPTO_ME(
Base64, encode,
arginfo_crypto_base64_data,
ZEND_ACC_STATIC|ZEND_ACC_PUBLIC
)
PHP_CRYPTO_ME(
Base64, decode,
arginfo_crypto_base64_data,
ZEND_ACC_STATIC|ZEND_ACC_PUBLIC
)
PHP_CRYPTO_ME(
Base64, __construct,
arginfo_crypto_base64_no_args,
ZEND_ACC_CTOR|ZEND_ACC_PUBLIC
)
PHP_CRYPTO_ME(
Base64, encodeUpdate,
arginfo_crypto_base64_data,
ZEND_ACC_PUBLIC
)
PHP_CRYPTO_ME(
Base64, encodeFinish,
arginfo_crypto_base64_no_args,
ZEND_ACC_PUBLIC
)
PHP_CRYPTO_ME(
Base64, decodeUpdate,
arginfo_crypto_base64_data,
ZEND_ACC_PUBLIC
)
PHP_CRYPTO_ME(
Base64, decodeFinish,
arginfo_crypto_base64_no_args,
ZEND_ACC_PUBLIC
)
PHPC_FE_END
};
/* class entry */
PHP_CRYPTO_API zend_class_entry *php_crypto_base64_ce;
/* object handler */
PHPC_OBJ_DEFINE_HANDLER_VAR(crypto_base64);
/* {{{ crypto_base64 free object handler */
PHPC_OBJ_HANDLER_FREE(crypto_base64)
{
PHPC_OBJ_HANDLER_FREE_INIT(crypto_base64);
EVP_ENCODE_CTX_free(PHPC_THIS->ctx);
PHPC_OBJ_HANDLER_FREE_DESTROY();
}
/* }}} */
/* {{{ crypto_base64 create_ex object helper */
PHPC_OBJ_HANDLER_CREATE_EX(crypto_base64)
{
PHPC_OBJ_HANDLER_CREATE_EX_INIT(crypto_base64);
/* allocate encode context */
PHPC_THIS->ctx = EVP_ENCODE_CTX_new();
PHPC_OBJ_HANDLER_CREATE_EX_RETURN(crypto_base64);
}
/* }}} */
/* {{{ crypto_base64 create object handler */
PHPC_OBJ_HANDLER_CREATE(crypto_base64)
{
PHPC_OBJ_HANDLER_CREATE_RETURN(crypto_base64);
}
/* }}} */
/* {{{ crypto_base64 clone object handler */
PHPC_OBJ_HANDLER_CLONE(crypto_base64)
{
PHPC_OBJ_HANDLER_CLONE_INIT(crypto_base64);
PHPC_THAT->status = PHPC_THIS->status;
EVP_ENCODE_CTX_copy(PHPC_THAT->ctx, PHPC_THIS->ctx);
PHPC_OBJ_HANDLER_CLONE_RETURN();
}
/* }}} */
#define PHP_CRYPTO_DECLARE_BASE64_E_CONST(aconst) \
zend_declare_class_constant_long(php_crypto_base64_exception_ce, \
#aconst, sizeof(#aconst)-1, PHP_CRYPTO_BASE64_E(aconst) TSRMLS_CC)
/* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(crypto_base64)
{
zend_class_entry ce;
/* Base64 class */
INIT_CLASS_ENTRY(ce, PHP_CRYPTO_CLASS_NAME(Base64), php_crypto_base64_object_methods);
PHPC_CLASS_SET_HANDLER_CREATE(ce, crypto_base64);
php_crypto_base64_ce = PHPC_CLASS_REGISTER(ce);
PHPC_OBJ_INIT_HANDLERS(crypto_base64);
PHPC_OBJ_SET_HANDLER_OFFSET(crypto_base64);
PHPC_OBJ_SET_HANDLER_FREE(crypto_base64);
PHPC_OBJ_SET_HANDLER_CLONE(crypto_base64);
/* Base64Exception class */
PHP_CRYPTO_EXCEPTION_REGISTER(ce, Base64);
PHP_CRYPTO_ERROR_INFO_REGISTER(Base64);
return SUCCESS;
}
/* }}} */
/* {{{ php_crypto_base64_encode_init */
static inline void php_crypto_base64_encode_init(EVP_ENCODE_CTX *ctx)
{
EVP_EncodeInit(ctx);
}
/* }}} */
/* {{{ php_crypto_base64_encode_update */
static inline int php_crypto_base64_encode_update(
EVP_ENCODE_CTX *ctx, char *out, int *outl,
const char *in, phpc_str_size_t in_len TSRMLS_DC)
{
int inl;
/* check string length overflow */
if (php_crypto_str_size_to_int(in_len, &inl) == FAILURE) {
php_crypto_error(PHP_CRYPTO_ERROR_ARGS(Base64, INPUT_DATA_LENGTH_HIGH));
return FAILURE;
}
EVP_EncodeUpdate(ctx,
(unsigned char *) out, outl,
(const unsigned char *) in, inl);
return SUCCESS;
}
/* }}} */
/* {{{ php_crypto_base64_encode_finish */
static inline void php_crypto_base64_encode_finish(
EVP_ENCODE_CTX *ctx, char *out, int *outl)
{
EVP_EncodeFinal(ctx, (unsigned char *) out, outl);
}
/* }}} */
/* {{{ php_crypto_base64_decode_init */
static inline void php_crypto_base64_decode_init(EVP_ENCODE_CTX *ctx)
{
EVP_DecodeInit(ctx);
}
/* }}} */
/* {{{ php_crypto_base64_decode_update */
static inline int php_crypto_base64_decode_update(
EVP_ENCODE_CTX *ctx, char *out, int *outl,
const char *in, phpc_str_size_t in_len TSRMLS_DC)
{
int inl, rc;
/* check string length overflow */
if (php_crypto_str_size_to_int(in_len, &inl) == FAILURE) {
php_crypto_error(PHP_CRYPTO_ERROR_ARGS(Base64, INPUT_DATA_LENGTH_HIGH));
return FAILURE;
}
rc = EVP_DecodeUpdate(ctx,
(unsigned char *) out, outl,
(const unsigned char *) in, inl);
if (rc < 0) {
php_crypto_error(PHP_CRYPTO_ERROR_ARGS(Base64, DECODE_UPDATE_FAILED));
return FAILURE;
}
return SUCCESS;
}
/* }}} */
/* {{{ php_crypto_base64_decode_finish */
static inline void php_crypto_base64_decode_finish(EVP_ENCODE_CTX *ctx,
char *out, int *outl)
{
EVP_DecodeFinal(ctx, (unsigned char *) out, outl);
}
/* }}} */
/* {{{ proto string Crypto\Base64::encode(string $data)
Encodes string $data to base64 encoding */
PHP_CRYPTO_METHOD(Base64, encode)
{
char *in;
phpc_str_size_t in_len;
int real_len, final_len, update_len;
PHPC_STR_DECLARE(out);
EVP_ENCODE_CTX *ctx;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in, &in_len) == FAILURE) {
return;
}
ctx = EVP_ENCODE_CTX_new();
php_crypto_base64_encode_init(ctx);
real_len = EVP_ENCODE_LENGTH(in_len);
PHPC_STR_ALLOC(out, real_len);
if (php_crypto_base64_encode_update(
ctx, PHPC_STR_VAL(out), &update_len, in, in_len TSRMLS_CC) == FAILURE) {
PHPC_STR_RELEASE(out);
EVP_ENCODE_CTX_free(ctx);
RETURN_NULL();
}
php_crypto_base64_encode_finish(ctx, PHPC_STR_VAL(out) + update_len, &final_len);
EVP_ENCODE_CTX_free(ctx);
final_len += update_len;
if (real_len > final_len) {
PHPC_STR_REALLOC(out, final_len);
}
PHPC_STR_VAL(out)[final_len] = '\0';
PHPC_STR_RETURN(out);
}
/* {{{ proto string Crypto\Base64::decode(string $data)
Decodes base64 string $data to raw encoding */
PHP_CRYPTO_METHOD(Base64, decode)
{
char *in;
phpc_str_size_t in_len;
int real_len, update_len, final_len;
PHPC_STR_DECLARE(out);
EVP_ENCODE_CTX *ctx;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in, &in_len) == FAILURE) {
return;
}
ctx = EVP_ENCODE_CTX_new();
php_crypto_base64_decode_init(ctx);
real_len = EVP_DECODE_LENGTH(in_len);
PHPC_STR_ALLOC(out, real_len);
if (php_crypto_base64_decode_update(ctx, PHPC_STR_VAL(out),
&update_len, in, in_len TSRMLS_CC) == FAILURE) {
EVP_ENCODE_CTX_free(ctx);
RETURN_FALSE;
}
php_crypto_base64_decode_finish(ctx, PHPC_STR_VAL(out), &final_len);
final_len += update_len;
if (real_len > final_len) {
PHPC_STR_REALLOC(out, final_len);
}
EVP_ENCODE_CTX_free(ctx);
PHPC_STR_VAL(out)[final_len] = '\0';
PHPC_STR_RETURN(out);
}
/* {{{ proto Crypto\Base64::__construct()
Base64 constructor */
PHP_CRYPTO_METHOD(Base64, __construct)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
}
/* {{{ proto Crypto\Base64::encode(string $data)
Encodes block of characters from $data and saves the reminder of
the last block to the encoding context */
PHP_CRYPTO_METHOD(Base64, encodeUpdate)
{
char *in;
phpc_str_size_t in_len;
int update_len, real_len;
PHPC_STR_DECLARE(out);
PHPC_THIS_DECLARE(crypto_base64);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in, &in_len) == FAILURE) {
return;
}
PHPC_THIS_FETCH(crypto_base64);
if (PHPC_THIS->status == PHP_CRYPTO_BASE64_STATUS_DECODE) {
php_crypto_error(PHP_CRYPTO_ERROR_ARGS(Base64, ENCODE_UPDATE_FORBIDDEN));
RETURN_FALSE;
}
if (PHPC_THIS->status == PHP_CRYPTO_BASE64_STATUS_CLEAR) {
php_crypto_base64_encode_init(PHPC_THIS->ctx);
PHPC_THIS->status = PHP_CRYPTO_BASE64_STATUS_ENCODE;
}
real_len = EVP_ENCODE_LENGTH(in_len);
PHPC_STR_ALLOC(out, real_len);
if (php_crypto_base64_encode_update(PHPC_THIS->ctx,
PHPC_STR_VAL(out), &update_len, in, in_len TSRMLS_CC) == FAILURE) {
PHPC_STR_RELEASE(out);
RETURN_NULL();
}
if (real_len > update_len) {
PHPC_STR_REALLOC(out, update_len);
}
PHPC_STR_VAL(out)[update_len] = '\0';
PHPC_STR_RETURN(out);
}
/* {{{ proto Crypto\Base64::encodeFinish()
Encodes characters that left in the encoding context */
PHP_CRYPTO_METHOD(Base64, encodeFinish)
{
char out[PHP_CRYPTO_BASE64_ENCODING_SIZE_MIN+1];
int out_len;
PHPC_THIS_DECLARE(crypto_base64);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHPC_THIS_FETCH(crypto_base64);
if (PHPC_THIS->status != PHP_CRYPTO_BASE64_STATUS_ENCODE) {
php_crypto_error(PHP_CRYPTO_ERROR_ARGS(Base64, ENCODE_FINISH_FORBIDDEN));
RETURN_FALSE;
}
php_crypto_base64_encode_finish(PHPC_THIS->ctx, out, &out_len);
if (out_len == 0) {
RETURN_EMPTY_STRING();
}
out[out_len] = '\0';
PHPC_CSTRL_RETURN(out, out_len);
}
/* {{{ proto Crypto\Base64::decode(string $data)
Decodes block of characters from $data and saves the reminder
of the last block to the encoding context */
PHP_CRYPTO_METHOD(Base64, decodeUpdate)
{
char *in;
phpc_str_size_t in_len;
int update_len, real_len;
PHPC_STR_DECLARE(out);
PHPC_THIS_DECLARE(crypto_base64);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &in, &in_len) == FAILURE) {
return;
}
PHPC_THIS_FETCH(crypto_base64);
if (PHPC_THIS->status == PHP_CRYPTO_BASE64_STATUS_ENCODE) {
php_crypto_error(PHP_CRYPTO_ERROR_ARGS(Base64, DECODE_UPDATE_FORBIDDEN));
RETURN_FALSE;
}
if (PHPC_THIS->status == PHP_CRYPTO_BASE64_STATUS_CLEAR) {
php_crypto_base64_decode_init(PHPC_THIS->ctx);
PHPC_THIS->status = PHP_CRYPTO_BASE64_STATUS_DECODE;
}
real_len = EVP_DECODE_LENGTH(in_len);
PHPC_STR_ALLOC(out, real_len);
if (php_crypto_base64_decode_update(PHPC_THIS->ctx,
PHPC_STR_VAL(out), &update_len, in, in_len TSRMLS_CC) == FAILURE) {
PHPC_STR_RELEASE(out);
RETURN_FALSE;
}
if (real_len > update_len) {
PHPC_STR_REALLOC(out, update_len);
}
PHPC_STR_VAL(out)[update_len] = '\0';
PHPC_STR_RETURN(out);
}
/* {{{ proto Crypto\Base64::decodeFinish()
Decodes characters that left in the encoding context */
PHP_CRYPTO_METHOD(Base64, decodeFinish)
{
char buff[PHP_CRYPTO_BASE64_DECODING_SIZE_MIN];
int final_len;
PHPC_THIS_DECLARE(crypto_base64);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
PHPC_THIS_FETCH(crypto_base64);
if (PHPC_THIS->status != PHP_CRYPTO_BASE64_STATUS_DECODE) {
php_crypto_error(PHP_CRYPTO_ERROR_ARGS(Base64, DECODE_FINISH_FORBIDDEN));
RETURN_FALSE;
}
php_crypto_base64_decode_finish(PHPC_THIS->ctx, buff, &final_len);
if (final_len == 0) {
RETURN_EMPTY_STRING();
}
buff[final_len] = 0;
PHPC_CSTRL_RETURN(buff, final_len);
}
| 26.845652 | 87 | 0.726132 | [
"object"
] |
2144539295afaef2b0ac97a379723d4f771f3e76 | 4,290 | h | C | KinGrpcApi/gen/common/v3/Model.pbobjc.h | samdowd/kin-ios | 245babfe248f426d7920d86de3342de2a1582597 | [
"MIT"
] | null | null | null | KinGrpcApi/gen/common/v3/Model.pbobjc.h | samdowd/kin-ios | 245babfe248f426d7920d86de3342de2a1582597 | [
"MIT"
] | null | null | null | KinGrpcApi/gen/common/v3/Model.pbobjc.h | samdowd/kin-ios | 245babfe248f426d7920d86de3342de2a1582597 | [
"MIT"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: common/v3/model.proto
// This CPP symbol can be defined to use imports that match up to the framework
// imports needed when using CocoaPods.
#if !defined(GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS)
#define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
#import <Protobuf/GPBProtocolBuffers.h>
#else
#import "GPBProtocolBuffers.h"
#endif
#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION
#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
// @@protoc_insertion_point(imports)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CF_EXTERN_C_BEGIN
@class APBCommonV3Invoice;
@class APBCommonV3Invoice_LineItem;
NS_ASSUME_NONNULL_BEGIN
#pragma mark - APBCommonV3ModelRoot
/**
* Exposes the extension registry for this file.
*
* The base class provides:
* @code
* + (GPBExtensionRegistry *)extensionRegistry;
* @endcode
* which is a @c GPBExtensionRegistry that includes all the extensions defined by
* this file and all files that it depends on.
**/
@interface APBCommonV3ModelRoot : GPBRootObject
@end
#pragma mark - APBCommonV3StellarAccountId
typedef GPB_ENUM(APBCommonV3StellarAccountId_FieldNumber) {
APBCommonV3StellarAccountId_FieldNumber_Value = 1,
};
@interface APBCommonV3StellarAccountId : GPBMessage
/**
* The public key of accounts always starts with a G, so we
* ensure that the value starts with a G to prevent the secret
* key from being used.
**/
@property(nonatomic, readwrite, copy, null_resettable) NSString *value;
@end
#pragma mark - APBCommonV3TransactionHash
typedef GPB_ENUM(APBCommonV3TransactionHash_FieldNumber) {
APBCommonV3TransactionHash_FieldNumber_Value = 1,
};
@interface APBCommonV3TransactionHash : GPBMessage
/** The sha256 hash of a transaction. */
@property(nonatomic, readwrite, copy, null_resettable) NSData *value;
@end
#pragma mark - APBCommonV3InvoiceHash
typedef GPB_ENUM(APBCommonV3InvoiceHash_FieldNumber) {
APBCommonV3InvoiceHash_FieldNumber_Value = 1,
};
@interface APBCommonV3InvoiceHash : GPBMessage
/** The SHA-224 hash of the invoice. */
@property(nonatomic, readwrite, copy, null_resettable) NSData *value;
@end
#pragma mark - APBCommonV3Invoice
typedef GPB_ENUM(APBCommonV3Invoice_FieldNumber) {
APBCommonV3Invoice_FieldNumber_ItemsArray = 1,
};
@interface APBCommonV3Invoice : GPBMessage
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<APBCommonV3Invoice_LineItem*> *itemsArray;
/** The number of items in @c itemsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger itemsArray_Count;
@end
#pragma mark - APBCommonV3Invoice_LineItem
typedef GPB_ENUM(APBCommonV3Invoice_LineItem_FieldNumber) {
APBCommonV3Invoice_LineItem_FieldNumber_Title = 1,
APBCommonV3Invoice_LineItem_FieldNumber_Description_p = 2,
APBCommonV3Invoice_LineItem_FieldNumber_Amount = 3,
APBCommonV3Invoice_LineItem_FieldNumber_Sku = 4,
};
@interface APBCommonV3Invoice_LineItem : GPBMessage
@property(nonatomic, readwrite, copy, null_resettable) NSString *title;
@property(nonatomic, readwrite, copy, null_resettable) NSString *description_p;
/** The amount in quarks. */
@property(nonatomic, readwrite) int64_t amount;
/** The app SKU related to this line item, if applicable. */
@property(nonatomic, readwrite, copy, null_resettable) NSData *sku;
@end
#pragma mark - APBCommonV3InvoiceList
typedef GPB_ENUM(APBCommonV3InvoiceList_FieldNumber) {
APBCommonV3InvoiceList_FieldNumber_InvoicesArray = 1,
};
@interface APBCommonV3InvoiceList : GPBMessage
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<APBCommonV3Invoice*> *invoicesArray;
/** The number of items in @c invoicesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger invoicesArray_Count;
@end
NS_ASSUME_NONNULL_END
CF_EXTERN_C_END
#pragma clang diagnostic pop
// @@protoc_insertion_point(global_scope)
| 28.410596 | 125 | 0.804662 | [
"model"
] |
21590028c29890e7dcc736c534a513e669abae01 | 872 | h | C | lunch/YahooSearchKit.framework/Versions/A/Headers/YSLSearchProgressDelegate.h | meekapps/lunch | 1cb668f2ef986e29b7b00153252804197ea90d69 | [
"MIT"
] | null | null | null | lunch/YahooSearchKit.framework/Versions/A/Headers/YSLSearchProgressDelegate.h | meekapps/lunch | 1cb668f2ef986e29b7b00153252804197ea90d69 | [
"MIT"
] | null | null | null | lunch/YahooSearchKit.framework/Versions/A/Headers/YSLSearchProgressDelegate.h | meekapps/lunch | 1cb668f2ef986e29b7b00153252804197ea90d69 | [
"MIT"
] | null | null | null | //
// YSLSearchProgressDelegate.h
// YahooSearchKit
//
// Copyright (c) 2014 Yahoo! Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
@class YSLQueryRequest;
@protocol YSLSearchProtocol;
/**
* This is the delegate protocol that an object should comply to, to indicate search results processing progress in header
*/
@protocol YSLSearchProgressDelegate <NSObject>
/**
* Tells the delegate the progress of search results processing.
*
* @discussion This delegate method can be called to nofify the progress of the search results processing.
*
* @param progress progress value between 0 and 1
* @param request YSLQueryRequest object that corresponds to the progress of search results
*/
- (void) viewController:(UIViewController <YSLSearchProtocol> *)viewController updateProgress:(float)progress forRequest:(YSLQueryRequest*)request;
@end
| 30.068966 | 147 | 0.769495 | [
"object"
] |
216b20018163c09ba52def228b4e5bed715cbd9c | 464 | h | C | Examples/Blueprints/view/linkmediator.h | noeat/nodeedit | 35f290e45da3c2a5afb9f7752b24ffedd72336f3 | [
"MIT"
] | 1 | 2020-05-17T14:30:00.000Z | 2020-05-17T14:30:00.000Z | Examples/Blueprints/view/linkmediator.h | noeat/nodeedit | 35f290e45da3c2a5afb9f7752b24ffedd72336f3 | [
"MIT"
] | null | null | null | Examples/Blueprints/view/linkmediator.h | noeat/nodeedit | 35f290e45da3c2a5afb9f7752b24ffedd72336f3 | [
"MIT"
] | null | null | null | #pragma once
#include "pmvcpp.h"
#include <set>
#include <chrono>
class linkmediator : public PureMVC::Mediator
{
public:
linkmediator();
std::vector<int> listNotificationInterests() override;
void handleNotification(PureMVC::INotification* notification) override;
void onRegister() override;
void onRemove() override;
static const std::string NAME;
private:
char buff_[260];
std::set<int> flows_;
std::chrono::steady_clock::time_point flowtime_;
}; | 19.333333 | 72 | 0.75431 | [
"vector"
] |
2172336eef686b612ff533296b27f2d91965bea1 | 3,916 | c | C | src/pattern.c | ifplusor/actrie | 54e9aff441594fbcd30a936d4fbc300ad81007b9 | [
"BSD-3-Clause"
] | 8 | 2017-10-01T04:47:12.000Z | 2022-02-15T10:16:11.000Z | src/pattern.c | ifplusor/actrie | 54e9aff441594fbcd30a936d4fbc300ad81007b9 | [
"BSD-3-Clause"
] | null | null | null | src/pattern.c | ifplusor/actrie | 54e9aff441594fbcd30a936d4fbc300ad81007b9 | [
"BSD-3-Clause"
] | 4 | 2018-04-06T08:27:02.000Z | 2021-05-11T07:56:17.000Z | /**
* pattern.c
*
* @author James Yin <ywhjames@hotmail.com>
*/
#include "pattern.h"
void ptrn_clean(aobj id);
// clang-format off
ameta(ptrn,
FOUR_CHARS_TO_INT('P', 'T', 'R', 'N'),
ptrn_clean
);
// clang-format on
aobj ptrn_init(void* ptr, void* data) {
ptrn_t id = aobj_init(ptrn, ptr);
if (id) {
id->type = ptrn_type_empty;
id->desc = NULL;
}
return id;
}
void ptrn_clean(aobj id) {
if (TAGGED_AOBJECT(id)) {
ptrn_t ptrn = id;
switch (ptrn->type) {
case ptrn_type_dist: {
pdd_t pdd = ptrn->desc;
_release(pdd->head);
_release(pdd->tail);
afree(pdd);
break;
}
default: {
// 默认 ptrn->desc 也是 aobj
_release(ptrn->desc);
break;
}
}
}
}
// pure pattern
// ===========================
afunc_defn(ptrn, pure, aobj, dstr_t text) {
ptrn_t ptrn = aobj_alloc(ptrn_s, ptrn_init);
if (ptrn != NULL) {
ptrn->type = ptrn_type_pure;
_retain(text);
ptrn->desc = text;
}
return ptrn;
}
// alternative pattern
// ===========================
/**
* ptrn_cat - concatenate two patterns.
*
* after call this function, 'before' and 'after' object will be released,
* a new ptrn_cat object will be generated.
*/
afunc_defn(ptrn, cat, aobj, ptrn_t before, ptrn_t after) {
if (before == NULL || after == NULL) {
return NULL;
}
if (before->type == ptrn_type_alter) {
// reuse before
list_t con = before->desc;
while (con->cdr != NULL) {
con = con->cdr; // walk to tail
}
if (after->type == ptrn_type_alter) {
_retain(after->desc);
con->cdr = after->desc;
_release(after);
} else {
con->cdr = _alloc(list, cons, after, NULL);
_release(after);
}
return before;
} else {
if (after->type == ptrn_type_alter) {
// reuse after
ptrn_t ptrn = after->desc;
after->desc = _alloc(list, cons, before, ptrn);
_release(ptrn);
_release(before);
return after;
} else {
// alloc new ptrn
ptrn_t ptrn = aobj_alloc(ptrn_s, ptrn_init);
if (ptrn != NULL) {
ptrn->type = ptrn_type_alter;
list_t con = _alloc(list, cons, after, NULL);
ptrn->desc = _alloc(list, cons, before, con);
_release(con);
_release(before);
_release(after);
}
return ptrn;
}
}
}
// ambiguity pattern
// ===========================
/**
* ptrn_ambi -
*
* after call this function, 'center' and 'ambi' object will be released,
* a new ptrn_ambi object will be generated.
*/
afunc_defn(ptrn, ambi, aobj, ptrn_t center, ptrn_t ambi) {
ptrn_t ptrn = aobj_alloc(ptrn_s, ptrn_init);
if (ptrn != NULL) {
ptrn->type = ptrn_type_anti_ambi;
ptrn->desc = _alloc(list, cons, center, ambi);
_release(center);
_release(ambi);
}
return ptrn;
}
// antonym pattern
// ===========================
/**
* ptrn_anto -
*
* after call this function, 'center' and 'anto' object will be released,
* a new ptrn_anto object will be generated.
*/
afunc_defn(ptrn, anto, aobj, ptrn_t center, ptrn_t anto) {
ptrn_t ptrn = aobj_alloc(ptrn_s, ptrn_init);
if (ptrn != NULL) {
ptrn->type = ptrn_type_anti_anto;
ptrn->desc = _alloc(list, cons, center, anto);
_release(center);
_release(anto);
}
return ptrn;
}
// distance pattern
// ===========================
/**
* ptrn_dist -
*
* after call this function, 'head' and 'tail' object will be released,
* a new ptrn_dist object will be generated.
*/
afunc_defn(ptrn, dist, aobj, ptrn_t head, ptrn_t tail, ptrn_dist_type_e type, int min, int max) {
ptrn_t ptrn = aobj_alloc(ptrn_s, ptrn_init);
if (ptrn != NULL) {
ptrn->type = ptrn_type_dist;
pdd_t pdd = amalloc(sizeof(pdd_s));
pdd->head = head;
pdd->tail = tail;
pdd->type = type;
pdd->min = min;
pdd->max = max;
ptrn->desc = pdd;
}
return ptrn;
}
| 22.377143 | 97 | 0.57712 | [
"object"
] |
218862200513a9d6350870ff6e47ab3943e8cb1d | 17,725 | h | C | src/include/sys-context.h | iArnold/ren-c | 35418a15faf842499bcf51d0e066035b31a1bc53 | [
"Apache-2.0"
] | null | null | null | src/include/sys-context.h | iArnold/ren-c | 35418a15faf842499bcf51d0e066035b31a1bc53 | [
"Apache-2.0"
] | null | null | null | src/include/sys-context.h | iArnold/ren-c | 35418a15faf842499bcf51d0e066035b31a1bc53 | [
"Apache-2.0"
] | null | null | null | //
// File: %sys-context.h
// Summary: {context! defs AFTER %tmp-internals.h (see: %sys-context.h)}
// Project: "Rebol 3 Interpreter and Run-time (Ren-C branch)"
// Homepage: https://github.com/metaeducation/ren-c/
//
//=////////////////////////////////////////////////////////////////////////=//
//
// Copyright 2012 REBOL Technologies
// Copyright 2012-2018 Rebol Open Source Contributors
// REBOL is a trademark of REBOL Technologies
//
// See README.md and CREDITS.md for more information
//
// 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.
//
//=////////////////////////////////////////////////////////////////////////=//
//
// In Rebol terminology, a "context" is an abstraction which gives two
// parallel arrays, whose indices line up in a correspondence:
//
// * "keylist" - an array that contains TYPESET! values, but which have a
// symbol ID encoded as an extra piece of information for that key.
//
// * "varlist" - an array of equal length to the keylist, which holds an
// arbitrary REBVAL in each position that corresponds to its key.
//
// Contexts coordinate with words, which can have their VAL_WORD_CONTEXT()
// set to a context's series pointer. Then they cache the index of that
// word's symbol in the context's keylist, for a fast lookup to get to the
// corresponding var. The key is a typeset which has several flags
// controlling behaviors like whether the var is protected or hidden.
//
// !!! This "caching" mechanism is not actually "just a cache". Once bound
// the index is treated as permanent. This is why objects are "append only"
// because disruption of the index numbers would break the extant words
// with index numbers to that position. Ren-C might wind up undoing this by
// paying for the check of the symbol number at the time of lookup, and if
// it does not match consider it a cache miss and re-lookup...adjusting the
// index inside of the word. For efficiency, some objects could be marked
// as not having this property, but it may be just as efficient to check
// the symbol match as that bit.
//
// Frame key/var indices start at one, and they leave two REBVAL slots open
// in the 0 spot for other uses. With an ANY-CONTEXT!, the use for the
// "ROOTVAR" is to store a canon value image of the ANY-CONTEXT!'s REBVAL
// itself. This trick allows a single REBCTX* to be passed around rather
// than the REBVAL struct which is 4x larger, yet still reconstitute the
// entire REBVAL if it is needed.
//
//=//// VARLIST_FLAG_FRAME_FAILED /////////////////////////////////////////=//
//
// In the specific case of a frame being freed due to a failure, this mark
// is put on the context node. What this allows is for the system to account
// for which nodes are being GC'd due to lack of a rebRelease(), as opposed
// to those being GC'd due to failure.
//
// What this means is that the system can use managed handles by default
// while still letting "rigorous" code track cases where it made use of the
// GC facility vs. doing explicit tracking. Essentially, it permits a kind
// of valgrind/address-sanitizer way of looking at a codebase vs. just taking
// for granted that it will GC things.
//
#define VARLIST_FLAG_FRAME_FAILED \
ARRAY_FLAG_23
#ifdef NDEBUG
#define ASSERT_CONTEXT(c) cast(void, 0)
#else
#define ASSERT_CONTEXT(c) Assert_Context_Core(c)
#endif
#define CTX_VARLIST(c) \
(&(c)->varlist)
// There may not be any dynamic or stack allocation available for a stack
// allocated context, and in that case it will have to come out of the
// REBSER node data itself.
//
inline static REBVAL *CTX_ARCHETYPE(REBCTX *c) {
REBSER *varlist = SER(CTX_VARLIST(c));
if (not IS_SER_DYNAMIC(varlist))
return cast(REBVAL*, &varlist->content.fixed);
// If a context has its data freed, it must be converted into non-dynamic
// form if it wasn't already (e.g. if it wasn't a FRAME!)
//
assert(NOT_SER_INFO(varlist, SERIES_INFO_INACCESSIBLE));
return cast(REBVAL*, varlist->content.dynamic.data);
}
// CTX_KEYLIST is called often, and it's worth it to make it as fast as
// possible--even in an unoptimized build.
//
inline static REBARR *CTX_KEYLIST(REBCTX *c) {
if (not (LINK(c).keysource->header.bits & NODE_FLAG_CELL))
return ARR(LINK(c).keysource); // not a REBFRM, so use keylist
// If the context in question is a FRAME! value, then the ->phase
// of the frame presents the "view" of which keys should be visible at
// this phase. So if the phase is a specialization, then it should
// not show all the underlying function's keys...just the ones that
// are not hidden in the facade that specialization uses. Since the
// phase changes, a fixed value can't be put into the keylist...that is
// just the keylist of the underlying function.
//
REBVAL *archetype = CTX_ARCHETYPE(c);
assert(KIND_BYTE(archetype) == REB_FRAME);
return ACT_PARAMLIST(archetype->payload.any_context.phase);
}
static inline void INIT_CTX_KEYLIST_SHARED(REBCTX *c, REBARR *keylist) {
SET_SER_INFO(keylist, SERIES_INFO_SHARED_KEYLIST);
LINK(c).keysource = NOD(keylist);
}
static inline void INIT_CTX_KEYLIST_UNIQUE(REBCTX *c, REBARR *keylist) {
assert(NOT_SER_INFO(keylist, SERIES_INFO_SHARED_KEYLIST));
LINK(c).keysource = NOD(keylist);
}
// Navigate from context to context components. Note that the context's
// "length" does not count the [0] cell of either the varlist or the keylist.
// Hence it must subtract 1. Internally to the context building code, the
// real length of the two series must be accounted for...so the 1 gets put
// back in, but most clients are only interested in the number of keys/values
// (and getting an answer for the length back that was the same as the length
// requested in context creation).
//
#define CTX_LEN(c) \
(cast(REBSER*, (c))->content.dynamic.len - 1) // len > 1 => dynamic
#define CTX_ROOTKEY(c) \
cast(REBVAL*, SER(CTX_KEYLIST(c))->content.dynamic.data) // len > 1
#define CTX_TYPE(c) \
VAL_TYPE(CTX_ARCHETYPE(c))
// The keys and vars are accessed by positive integers starting at 1
//
#define CTX_KEYS_HEAD(c) \
SER_AT(REBVAL, SER(CTX_KEYLIST(c)), 1) // a CTX_KEY can't hold a RELVAL
inline static REBFRM *CTX_FRAME_IF_ON_STACK(REBCTX *c) {
REBNOD *keysource = LINK(c).keysource;
if (not (keysource->header.bits & NODE_FLAG_CELL))
return nullptr; // e.g. came from MAKE FRAME! or Encloser_Dispatcher
assert(NOT_SER_INFO(CTX_VARLIST(c), SERIES_INFO_INACCESSIBLE));
assert(IS_FRAME(CTX_ARCHETYPE(c)));
REBFRM *f = FRM(keysource);
assert(f->original); // inline Is_Action_Frame() to break dependency
return f;
}
inline static REBFRM *CTX_FRAME_MAY_FAIL(REBCTX *c) {
REBFRM *f = CTX_FRAME_IF_ON_STACK(c);
if (not f)
fail (Error_Frame_Not_On_Stack_Raw());
return f;
}
#define CTX_VARS_HEAD(c) \
SER_AT(REBVAL, SER(CTX_VARLIST(c)), 1) // may fail() if inaccessible
inline static REBVAL *CTX_KEY(REBCTX *c, REBCNT n) {
assert(NOT_SER_FLAG(c, SERIES_INFO_INACCESSIBLE));
assert(GET_SER_FLAG(c, ARRAY_FLAG_VARLIST));
assert(n != 0 and n <= CTX_LEN(c));
return cast(REBVAL*, cast(REBSER*, CTX_KEYLIST(c))->content.dynamic.data)
+ n;
}
inline static REBVAL *CTX_VAR(REBCTX *c, REBCNT n) {
assert(NOT_SER_FLAG(c, SERIES_INFO_INACCESSIBLE));
assert(GET_SER_FLAG(c, ARRAY_FLAG_VARLIST));
assert(n != 0 and n <= CTX_LEN(c));
return cast(REBVAL*, cast(REBSER*, c)->content.dynamic.data) + n;
}
inline static REBSTR *CTX_KEY_SPELLING(REBCTX *c, REBCNT n) {
return CTX_KEY(c, n)->extra.key_spelling;
}
inline static REBSTR *CTX_KEY_CANON(REBCTX *c, REBCNT n) {
return STR_CANON(CTX_KEY_SPELLING(c, n));
}
inline static REBSYM CTX_KEY_SYM(REBCTX *c, REBCNT n) {
return STR_SYMBOL(CTX_KEY_SPELLING(c, n)); // should be same as canon
}
//=////////////////////////////////////////////////////////////////////////=//
//
// ANY-CONTEXT! (`struct Reb_Any_Context`)
//
//=////////////////////////////////////////////////////////////////////////=//
//
// The Reb_Any_Context is the basic struct used currently for OBJECT!,
// MODULE!, ERROR!, and PORT!. It builds upon the context datatype REBCTX,
// which permits the storage of associated KEYS and VARS.
//
inline static void FAIL_IF_INACCESSIBLE_CTX(REBCTX *c) {
if (GET_SER_INFO(c, SERIES_INFO_INACCESSIBLE)) {
if (CTX_TYPE(c) == REB_FRAME)
fail (Error_Do_Expired_Frame_Raw()); // !!! different error?
fail (Error_Series_Data_Freed_Raw());
}
}
inline static REBCTX *VAL_CONTEXT(const REBCEL *v) {
assert(ANY_CONTEXT_KIND(CELL_KIND(v)));
assert(not v->payload.any_context.phase or CELL_KIND(v) == REB_FRAME);
REBCTX *c = CTX(v->payload.any_context.varlist);
FAIL_IF_INACCESSIBLE_CTX(c);
return c;
}
inline static void INIT_VAL_CONTEXT(REBVAL *v, REBCTX *c) {
v->payload.any_context.varlist = CTX_VARLIST(c);
}
// Convenience macros to speak in terms of object values instead of the context
//
#define VAL_CONTEXT_VAR(v,n) \
CTX_VAR(VAL_CONTEXT(v), (n))
#define VAL_CONTEXT_KEY(v,n) \
CTX_KEY(VAL_CONTEXT(v), (n))
// The movement of the SELF word into the domain of the object generators
// means that an object may wind up having a hidden SELF key (and it may not).
// Ultimately this key may well occur at any position. While user code is
// discouraged from accessing object members by integer index (`pick obj 1`
// is an error), system code has historically relied upon this.
//
// During a transitional period where all MAKE OBJECT! constructs have a
// "real" SELF key/var in the first position, there needs to be an adjustment
// to the indexing of some of this system code. Some of these will be
// temporary, because not all objects will need a definitional SELF (just as
// not all functions need a definitional RETURN). Exactly which require it
// and which do not remains to be seen, so this macro helps review the + 1
// more easily than if it were left as just + 1.
//
#define SELFISH(n) \
((n) + 1)
// Common routine for initializing OBJECT, MODULE!, PORT!, and ERROR!
//
// A fully constructed context can reconstitute the ANY-CONTEXT! REBVAL
// that is its canon form from a single pointer...the REBVAL sitting in
// the 0 slot of the context's varlist.
//
static inline REBVAL *Init_Any_Context(
RELVAL *out,
enum Reb_Kind kind,
REBCTX *c
){
#if !defined(NDEBUG)
Extra_Init_Any_Context_Checks_Debug(kind, c);
#endif
UNUSED(kind);
assert(IS_ARRAY_MANAGED(CTX_VARLIST(c)));
assert(IS_ARRAY_MANAGED(CTX_KEYLIST(c)));
return Move_Value(out, CTX_ARCHETYPE(c));
}
#define Init_Object(out,c) \
Init_Any_Context((out), REB_OBJECT, (c))
#define Init_Port(out,c) \
Init_Any_Context((out), REB_PORT, (c))
#define Init_Frame(out,c) \
Init_Any_Context((out), REB_FRAME, (c))
//=////////////////////////////////////////////////////////////////////////=//
//
// COMMON INLINES (macro-like)
//
//=////////////////////////////////////////////////////////////////////////=//
//
// By putting these functions in a header file, they can be inlined by the
// compiler, rather than add an extra layer of function call.
//
#define Copy_Context_Shallow_Managed(src) \
Copy_Context_Shallow_Extra_Managed((src), 0)
// Returns true if the keylist had to be changed to make it unique.
//
#define Ensure_Keylist_Unique_Invalidated(context) \
Expand_Context_Keylist_Core((context), 0)
// Useful if you want to start a context out as NODE_FLAG_MANAGED so it does
// not have to go in the unmanaged roots list and be removed later. (Be
// careful not to do any evaluations or trigger GC until it's well formed)
//
#define Alloc_Context(kind,capacity) \
Alloc_Context_Core((kind), (capacity), SERIES_FLAGS_NONE)
//=////////////////////////////////////////////////////////////////////////=//
//
// LOCKING
//
//=////////////////////////////////////////////////////////////////////////=//
inline static void Deep_Freeze_Context(REBCTX *c) {
Protect_Context(
c,
PROT_SET | PROT_DEEP | PROT_FREEZE
);
Uncolor_Array(CTX_VARLIST(c));
}
inline static bool Is_Context_Deeply_Frozen(REBCTX *c) {
return GET_SER_INFO(c, SERIES_INFO_FROZEN);
}
//=////////////////////////////////////////////////////////////////////////=//
//
// ERROR! (uses `struct Reb_Any_Context`)
//
//=////////////////////////////////////////////////////////////////////////=//
//
// Errors are a subtype of ANY-CONTEXT! which follow a standard layout.
// That layout is in %boot/sysobj.r as standard/error.
//
// Historically errors could have a maximum of 3 arguments, with the fixed
// names of `arg1`, `arg2`, and `arg3`. They would also have a numeric code
// which would be used to look up a a formatting block, which would contain
// a block for a message with spots showing where the args were to be inserted
// into a message. These message templates can be found in %boot/errors.r
//
// Ren-C is exploring the customization of user errors to be able to provide
// arbitrary named arguments and message templates to use them. It is
// a work in progress, but refer to the FAIL native, the corresponding
// `fail()` C macro inside the source, and the various routines in %c-error.c
//
#define ERR_VARS(e) \
cast(ERROR_VARS*, CTX_VARS_HEAD(e))
#define VAL_ERR_VARS(v) \
ERR_VARS(VAL_CONTEXT(v))
#define Init_Error(v,c) \
Init_Any_Context((v), REB_ERROR, (c))
// Ports are unusual hybrids of user-mode code dispatched with native code, so
// some things the user can do to the internals of a port might cause the
// C code to crash. This wasn't very well thought out in R3-Alpha, but there
// was some validation checking. This factors out that check instead of
// repeating the code.
//
inline static void FAIL_IF_BAD_PORT(REBVAL *port) {
if (not ANY_CONTEXT(port))
fail (Error_Invalid_Port_Raw());
REBCTX *ctx = VAL_CONTEXT(port);
if (
CTX_LEN(ctx) < (STD_PORT_MAX - 1)
or not IS_OBJECT(CTX_VAR(ctx, STD_PORT_SPEC))
){
fail (Error_Invalid_Port_Raw());
}
}
// It's helpful to show when a test for a native port actor is being done,
// rather than just having the code say IS_HANDLE().
//
inline static bool Is_Native_Port_Actor(const REBVAL *actor) {
if (IS_HANDLE(actor))
return true;
assert(IS_OBJECT(actor));
return false;
}
//
// Steal_Context_Vars: C
//
// This is a low-level trick which mutates a context's varlist into a stub
// "free" node, while grabbing the underlying memory for its variables into
// an array of values.
//
// It has a notable use by DO of a heap-based FRAME!, so that the frame's
// filled-in heap memory can be directly used as the args for the invocation,
// instead of needing to push a redundant run of stack-based memory cells.
//
inline static REBCTX *Steal_Context_Vars(REBCTX *c, REBNOD *keysource) {
REBSER *stub = SER(c);
// Rather than memcpy() and touch up the header and info to remove
// SERIES_INFO_HOLD put on by Enter_Native(), or NODE_FLAG_MANAGED,
// etc.--use constant assignments and only copy the remaining fields.
//
REBSER *copy = Alloc_Series_Node(
SERIES_MASK_CONTEXT
| SERIES_FLAG_STACK
| SERIES_FLAG_FIXED_SIZE
);
copy->info = Endlike_Header(
FLAG_WIDE_BYTE_OR_0(0) // implicit termination, and indicates array
| FLAG_LEN_BYTE_OR_255(255) // indicates dynamic (varlist rule)
);
TRASH_POINTER_IF_DEBUG(copy->link_private.keysource); // needs update
memcpy(©->content, &stub->content, sizeof(union Reb_Series_Content));
copy->misc_private.meta = nullptr; // let stub have the meta
REBVAL *rootvar = cast(REBVAL*, copy->content.dynamic.data);
// Convert the old varlist that had outstanding references into a
// singular "stub", holding only the CTX_ARCHETYPE. This is needed
// for the ->binding to allow Derelativize(), see SPC_BINDING().
//
// Note: previously this had to preserve VARLIST_FLAG_FRAME_FAILED, but
// now those marking failure are asked to do so manually to the stub
// after this returns (hence they need to cache the varlist first).
//
stub->info = Endlike_Header(
SERIES_INFO_INACCESSIBLE // args memory now "stolen" by copy
| FLAG_WIDE_BYTE_OR_0(0) // width byte is 0 for array series
| FLAG_LEN_BYTE_OR_255(1) // not dynamic any more, new len is 1
);
REBVAL *single = cast(REBVAL*, &stub->content.fixed);
single->header.bits =
NODE_FLAG_NODE | NODE_FLAG_CELL | FLAG_KIND_BYTE(REB_FRAME);
INIT_BINDING(single, VAL_BINDING(rootvar));
single->payload.any_context.varlist = ARR(stub);
TRASH_POINTER_IF_DEBUG(single->payload.any_context.phase);
/* single->payload.any_context.phase = f->original; */ // !!! needed?
rootvar->payload.any_context.varlist = ARR(copy);
// Disassociate the stub from the frame, by degrading the link field
// to a keylist. !!! Review why this was needed, vs just nullptr
//
LINK(stub).keysource = keysource;
return CTX(copy);
}
| 38.11828 | 79 | 0.677913 | [
"object"
] |
5d82350d4fbc4ae723eedda9ee4b7c5cb01504b0 | 1,584 | h | C | introOpenGL_Barchid/src/application/GLApplication.h | Barchid/M3DS | 37505c7a23d43ee51ee43ea15fa6d3bc8693ae14 | [
"MIT"
] | 1 | 2019-12-10T01:59:15.000Z | 2019-12-10T01:59:15.000Z | introOpenGL_Barchid/src/application/GLApplication.h | Barchid/M3DS | 37505c7a23d43ee51ee43ea15fa6d3bc8693ae14 | [
"MIT"
] | null | null | null | introOpenGL_Barchid/src/application/GLApplication.h | Barchid/M3DS | 37505c7a23d43ee51ee43ea15fa6d3bc8693ae14 | [
"MIT"
] | 2 | 2020-02-27T18:13:54.000Z | 2022-02-24T14:37:22.000Z | #ifndef GLAPPLICATION_H
#define GLAPPLICATION_H
#include "GLWidget.h"
#include "Tools.h"
#include <string>
class GLApplication : public GLWidget {
Q_OBJECT
public:
GLApplication();
virtual ~GLApplication();
// exo 21 : init strip
void initStrip(int nbSlice,float xmin,float xmax,float ymin,float ymax);
// exo 23 : initRing
void initRing(int nbSlice,float r0,float r1);
/** ***** **/
/** GLApplication must implement these methods : */
virtual void initialize(); // initialiser application
virtual void update(); // mise à jour des données en 60fps
virtual void draw(); // mise à jour du tracé (juste après update())
virtual void resize(int width,int height); // callback quand on resize
/** ***** **/
virtual void leftPanel(int i, const std::string &s);
virtual QSize sizeHint() const {return QSize(1000,1000);}
/** ***** **/
GLuint initProgram(const std::string &filename);
void initTriangleBuffer();
void initTriangleVAO();
void initTexture();
private:
std::vector<float> _trianglePosition; // positions du triangle (pour VBO)
std::vector<float> _triangleColor; // couleuyrs du triangle
std::vector<float> _triangleTexCoord;
std::vector<unsigned int> _elementData;
float _coeff; // coefficient nécessaire à l'animation
bool _isGrowing;
GLuint _trianglePositionBuffer; // id du vbo pour position
GLuint _triangleColorBuffer; // id du vbo pour couleur
GLuint _triangleTexCoordBuffer;
GLuint _elementDataBuffer;
GLuint _triangleVAO;
GLuint _shader0;
GLuint _textureId;
};
#endif // GLAPPLICATION_H
| 25.967213 | 75 | 0.715278 | [
"vector"
] |
5d8d5548a43de7e1a8154ef539fc8fcda07d0fe6 | 792 | h | C | src/hausdorff/stop_condition.h | ZJUCADGeoSim/hausdorff | df9fdf0294d7efd4ec694ec5135487344e509231 | [
"MIT"
] | 13 | 2021-09-06T07:19:28.000Z | 2022-03-29T15:48:21.000Z | src/hausdorff/stop_condition.h | ZJUCADGeoSim/hausdorff | df9fdf0294d7efd4ec694ec5135487344e509231 | [
"MIT"
] | null | null | null | src/hausdorff/stop_condition.h | ZJUCADGeoSim/hausdorff | df9fdf0294d7efd4ec694ec5135487344e509231 | [
"MIT"
] | null | null | null | /*
State Key Lab of CAD&CG Zhejiang Unv.
Author:
Yicun Zheng (3130104113@zju.edu.cn)
Haoran Sun (hrsun@zju.edu.cn)
Jin Huang (hj@cad.zju.edu.cn)
Copyright (c) 2004-2021 <Jin Huang>
All rights reserved.
Licensed under the MIT License.
*/
#ifndef _STOP_CONDITION_H
#define _STOP_CONDITION_H
class absolute_error {};
class relative_error {};
template <typename error_type>
class stop_condition {
public:
stop_condition(double error) : error_(error) {}
bool operator()(double L, double U) {
return U - L < error_;
}
private:
double error_;
};
template <>
class stop_condition<relative_error> {
public:
stop_condition() {}
bool operator()(double L, double U) {
return U - L <= (U + L) / 2 * 0.01;
}
};
#endif | 18.857143 | 51 | 0.645202 | [
"cad"
] |
5d9447a73aadeefed0bc7b595383c6c07034b773 | 1,401 | c | C | projects/simulator/pthread_tests/pthread_mutex_lock.2-1.c | maurizioabba/rose | 7597292cf14da292bdb9a4ef573001b6c5b9b6c0 | [
"BSD-3-Clause"
] | 488 | 2015-01-09T08:54:48.000Z | 2022-03-30T07:15:46.000Z | projects/simulator2/pthread_tests/pthread_mutex_lock.2-1.c | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 174 | 2015-01-28T18:41:32.000Z | 2022-03-31T16:51:05.000Z | projects/simulator2/pthread_tests/pthread_mutex_lock.2-1.c | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 146 | 2015-04-27T02:48:34.000Z | 2022-03-04T07:32:53.000Z | /*
* Copyright (c) 2002, Intel Corporation. All rights reserved.
* Created by: bing.wei.liu REMOVE-THIS AT intel DOT com
* This file is licensed under the GPL license. For the full content
* of this license, see the COPYING file at the top level of this
* source tree.
* Test that pthread_mutex_lock()
* Upon succesful completion, it shall return a 0
*
*/
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include "posixtest.h"
int main()
{
pthread_mutex_t mutex;
int rc;
/* Initialize a mutex object with the default mutex attributes */
if((rc=pthread_mutex_init(&mutex,NULL)) != 0) {
fprintf(stderr,"Error at pthread_mutex_init(), rc=%d\n",rc);
return PTS_UNRESOLVED;
}
/* Lock the mutex using pthread_mutex_lock() */
if((rc=pthread_mutex_lock(&mutex)) == 0) {
pthread_mutex_unlock(&mutex);
printf("Test PASSED\n");
return PTS_PASS;
}
/* Check if returned values are tolerable */
else if(rc == EINVAL) {
fprintf(stderr,"Invalid mutex object\n");
return PTS_UNRESOLVED;
}
else if(rc == EAGAIN) {
fprintf(stderr,"The maximum number of recursive locks has been exceeded\n");
return PTS_UNRESOLVED;
}
else if(rc == EDEADLK) {
fprintf(stderr,"The current thread already owns the mutex\n");
return PTS_UNRESOLVED;
}
/* Any other returned value means the test failed */
else
{
printf("Test FAILED\n");
return PTS_FAIL;
}
}
| 24.578947 | 78 | 0.694504 | [
"object"
] |
5dd2615565e705477d8933a4ab9fdd1e566088a4 | 1,465 | h | C | Lepus3D/Source/RenderEngine.h | tomezpl/LepusEngine | 57b7e59e27464dbe91f300526a9b6975acd5ad93 | [
"MIT"
] | null | null | null | Lepus3D/Source/RenderEngine.h | tomezpl/LepusEngine | 57b7e59e27464dbe91f300526a9b6975acd5ad93 | [
"MIT"
] | 22 | 2017-08-25T23:27:54.000Z | 2019-12-02T13:35:40.000Z | Lepus3D/Source/RenderEngine.h | tomezpl/LepusEngine | 57b7e59e27464dbe91f300526a9b6975acd5ad93 | [
"MIT"
] | null | null | null | #pragma once
#ifndef LEPUS_GLEW_INCLUDED
#define LEPUS_GLEW_INCLUDED
#include <GL/glew.h>
#endif
#ifndef LEPUS_GLFW_INCLUDED
#define LEPUS_GLFW_INCLUDED
#include <GLFW/glfw3.h>
#endif
#include "Material.h"
#include "Vertex.h"
#include "Mesh.h"
#include "Transform.h"
#include "Camera.h"
#include "Scene.h"
namespace LepusEngine
{
namespace Lepus3D
{
class RenderEngine
{
private:
GLFWwindow* m_Window;
char* m_WindowName;
GLuint m_VBO, m_IBO, m_VAO;
unsigned long long m_eCount;
struct {
bool
window,
renderer;
} m_Ready;
GLuint m_TextureSet[16];
double m_LastFrameTime, m_ElapsedTime;
Camera* m_Cam;
public:
RenderEngine() { m_Ready = { false, false }; };
RenderEngine(char* windowName, unsigned short windowWidth, unsigned short windowHeight);
bool Init();
bool Init(char* windowName, unsigned short windowWidth, unsigned short windowHeight);
void StartScene(Camera* camera);
void DrawMesh(Mesh& mesh, Material& material, Transform& transform);
void DrawScene(Scene& scene);
GLFWwindow* GetWindowPtr() { return m_Window; };
void EndScene();
// Runs the window's event loop, returns false if window was closed
// Draws the current vertex buffer to the screen
bool Update();
// Returns the time it took to render the last frame
double LastFrameTime();
void DumpToFile(std::string filePath = "output.bmp");
void Shutdown();
~RenderEngine();
};
}
} | 23.629032 | 91 | 0.706485 | [
"mesh",
"render",
"transform"
] |
5dd509ed15b520d62962cc12c5d023f9880d70b2 | 12,810 | h | C | include/fl/ann/neurons.h | sguazt/fuzzylitex | a7d653dfa9c8ae7fd056748c8c7a9a0006c2c4c9 | [
"Apache-2.0"
] | 5 | 2017-05-29T05:32:53.000Z | 2020-12-13T14:03:10.000Z | include/fl/ann/neurons.h | sguazt/fuzzylitex | a7d653dfa9c8ae7fd056748c8c7a9a0006c2c4c9 | [
"Apache-2.0"
] | 1 | 2020-11-15T00:34:31.000Z | 2020-11-15T00:34:31.000Z | include/fl/ann/neurons.h | sguazt/fuzzylitex | a7d653dfa9c8ae7fd056748c8c7a9a0006c2c4c9 | [
"Apache-2.0"
] | 6 | 2018-02-05T10:43:19.000Z | 2021-01-13T18:04:23.000Z | /**
* \file fl/ann/neurons.h
*
* \brief Neurons for artificial neural networks
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright 2014 Marco Guazzone (marco.guazzone@gmail.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 FL_ANN_NEURONS_H
#define FL_ANN_NEURONS_H
#include <fl/ann/activation_functions.h>
#include <fl/ann/net_input_functions.h>
#include <fl/macro.h>
#include <fl/fuzzylite.h>
#include <limits>
#include <vector>
namespace fl { namespace ann {
template <typename T> class Connection;
template <typename T> class Layer;
/**
* General neuron model according to McCulloch-Pitts artificial neuron model.
*
* The artificial neuron is the basic processing unit of a neural network.
* The artificial neuron receives one or more inputs and one or more weights (one for each input), and produces an output.
* The inputs and weights are combined together by means of the <em>input function</em> (or <em>propagation function</em>) and the result is passed through a non-linear function known as an <em>activation function</em> (or <em>transfer function</em>).
* The input function usually is the sum of the product of each input with the corresponding weigth, but other input functions are possible.
* The activation function usually has a sigmoid shape, but it may also take the form of other non-linear function (e.g., piecewise linear function or step function, just to name a few).
* Also, it is often monotonically increasing, continuous, differentiable and bounded.
*/
template <typename ValueT>
class Neuron
{
// private: typedef std::vector<Connection<ValueT>*> ConnectionContainer;
public: typedef ValueT ValueType;
/**
* Creates an artificial neuron with the weighted-sum function as input function
* and the step function as activation function.
* This is the original McCulloch-Pitts neuron model.
*/
public: explicit Neuron(Layer<ValueT>* p_layer = fl::null)
: p_inpFunc_(new WeightedSumNetInputFunction<ValueT>()),
p_actFunc_(new StepActivationFunction<ValueT>()),
p_layer_(p_layer),
netIn_(std::numeric_limits<ValueT>::quiet_NaN()),
out_(std::numeric_limits<ValueT>::quiet_NaN()),
// err_(std::numeric_limits<ValueT>::quiet_NaN()),
hasBias_(false),
biasWeight_(0)
{
//FL_DEBUG_TRACE("In Neuron's constructor (" << this << ")");//XXX
}
/// Creates an artificial neuron with the given input and activation functions
public: Neuron(NetInputFunction<ValueT>* p_inpFunc, ActivationFunction<ValueT>* p_actFunc, Layer<ValueT>* p_layer = fl::null)
: p_inpFunc_(p_inpFunc),
p_actFunc_(p_actFunc),
p_layer_(p_layer),
netIn_(std::numeric_limits<ValueT>::quiet_NaN()),
out_(std::numeric_limits<ValueT>::quiet_NaN()),
// err_(std::numeric_limits<ValueT>::quiet_NaN()),
hasBias_(false),
biasWeight_(0)
{
//FL_DEBUG_TRACE("In Neuron's constructor (" << this << ")");//XXX
if (!p_inpFunc_.get())
{
FL_THROW2(std::invalid_argument, "Input function cannot be null");
}
if (!p_actFunc_.get())
{
FL_THROW2(std::invalid_argument, "Activation function cannot be null");
}
}
public: virtual ~Neuron()
{
this->clear();
}
public: void clear()
{
this->reset();
this->clearInputConnections();
this->clearOutputConnections();
p_inpFunc_.reset();
p_actFunc_.reset();
p_layer_ = fl::null;
}
public: void reset()
{
//FL_DEBUG_TRACE("In Neuron's reset (" << this << ")");//XXX
netIn_ = out_
// = err_
= std::numeric_limits<ValueT>::quiet_NaN();
hasBias_ = false;
biasWeight_ = 0;
// Reset output connections
std::vector<Connection<ValueT>*> outConns = this->outputConnections();
for (typename std::vector<Connection<ValueT>*>::iterator connIt = outConns.begin(),
connEndIt = outConns.end();
connIt != connEndIt;
++connIt)
{
Connection<ValueT>* p_conn = *connIt;
// check: null
FL_DEBUG_ASSERT( p_conn );
p_conn->reset();
}
}
public: void setNetInputFunction(NetInputFunction<ValueT>* p_func)
{
if (!p_func)
{
FL_THROW2(std::invalid_argument, "Input function cannot be null");
}
p_inpFunc_.reset(p_func);
}
public: NetInputFunction<ValueT>* getNetInputFunction() const
{
return p_inpFunc_.get();
}
public: void setActivationFunction(ActivationFunction<ValueT>* p_func)
{
if (!p_func)
{
FL_THROW2(std::invalid_argument, "Activation function cannot be null");
}
p_actFunc_.reset(p_func);
}
public: ActivationFunction<ValueT>* getActivationFunction() const
{
return p_actFunc_.get();
}
public: void setLayer(Layer<ValueT>* p_layer)
{
p_layer_ = p_layer;
}
public: Layer<ValueT>* getLayer() const
{
return p_layer_;
}
public: void addInputConnection(Neuron<ValueT>* p_fromNeuron, ValueT weight)
{
FL_DEBUG_ASSERT( p_layer_ );
FL_DEBUG_ASSERT( p_layer_->getNetwork() );
p_layer_->getNetwork()->connect(p_fromNeuron, this, weight);
}
public: void eraseInputConnection(Neuron<ValueT>* p_fromNeuron)
{
FL_DEBUG_ASSERT( p_layer_ );
FL_DEBUG_ASSERT( p_layer_->getNetwork() );
p_layer_->getNetwork()->disconnect(p_fromNeuron, this);
}
public: std::vector<Connection<ValueT>*> inputConnections() const
{
FL_DEBUG_ASSERT( p_layer_ );
FL_DEBUG_ASSERT( p_layer_->getNetwork() );
return p_layer_->getNetwork()->inputConnections(this);
}
public: void clearInputConnections()
{
FL_DEBUG_ASSERT( p_layer_ );
FL_DEBUG_ASSERT( p_layer_->getNetwork() );
p_layer_->getNetwork()->disconnectTo(this);
}
public: void addOutputConnection(Neuron<ValueT>* p_toNeuron, ValueT weight)
{
FL_DEBUG_ASSERT( p_layer_ );
FL_DEBUG_ASSERT( p_layer_->getNetwork() );
p_layer_->getNetwork()->connect(this, p_toNeuron, weight);
}
public: void eraseOutputConnection(Neuron<ValueT>* p_toNeuron)
{
FL_DEBUG_ASSERT( p_layer_ );
FL_DEBUG_ASSERT( p_layer_->getNetwork() );
p_layer_->getNetwork()->disconnect(this, p_toNeuron);
}
public: std::vector<Connection<ValueT>*> outputConnections() const
{
FL_DEBUG_ASSERT( p_layer_ );
FL_DEBUG_ASSERT( p_layer_->getNetwork() );
return p_layer_->getNetwork()->outputConnections(this);
}
public: void clearOutputConnections()
{
FL_DEBUG_ASSERT( p_layer_ );
FL_DEBUG_ASSERT( p_layer_->getNetwork() );
p_layer_->getNetwork()->disconnectFrom(this);
}
/// Sets the net input for this neuron
public: void setNetInput(ValueT v)
{
netIn_ = v;
}
/// Gets the net input of this neuron
public: ValueT getNetInput() const
{
return netIn_;
}
/// Returns the input values to this neuron
public: std::vector<ValueT> inputs() const
{
std::vector<ValueT> ins;
const std::vector<Connection<ValueT>*> inConns = this->inputConnections();
for (typename std::vector<Connection<ValueT>*>::const_iterator connIt = inConns.begin(),
connEndIt = inConns.end();
connIt != connEndIt;
++connIt)
{
const Connection<ValueT>* p_conn = *connIt;
// check: null
FL_DEBUG_ASSERT( p_conn );
ins.push_back(p_conn->getFromNeuron()->getOutput());
}
return ins;
}
/// Sets the weight of this neuron's input connections to the values specified by the iterator range [\a first, \a last).
public: template <typename IterT>
void weights(IterT weightFirst, IterT weightLast)
{
const std::vector<Connection<ValueT>*> inConns = this->inputConnections();
for (typename std::vector<Connection<ValueT>*>::iterator connIt = inConns.begin(),
connEndIt = inConns.end();
connIt != connEndIt && weightFirst != weightLast;
++connIt)
{
Connection<ValueT>* p_conn = *connIt;
// check: null
FL_DEBUG_ASSERT( p_conn );
p_conn->setWeight(*weightFirst);
++weightFirst;
}
}
/// Returns the weight values to this neuron
public: std::vector<ValueT> weights() const
{
std::vector<ValueT> ws;
const std::vector<Connection<ValueT>*> inConns = this->inputConnections();
for (typename std::vector<Connection<ValueT>*>::const_iterator connIt = inConns.begin(),
connEndIt = inConns.end();
connIt != connEndIt;
++connIt)
{
const Connection<ValueT>* p_conn = *connIt;
// check: null
FL_DEBUG_ASSERT( p_conn );
ws.push_back(p_conn->getWeight());
}
return ws;
}
/// Calculates neuron's output
public: virtual ValueT process()
{
// check: null
FL_DEBUG_ASSERT( p_inpFunc_.get() );
FL_DEBUG_ASSERT( p_actFunc_.get() );
std::vector<ValueT> ins = this->inputs();
std::vector<ValueT> ws = this->weights();
if (hasBias_)
{
ins.push_back(1);
ws.push_back(biasWeight_);
}
////[XXX]
//#ifdef FL_DEBUG
//std::cerr << "(neuron: " << this << ") Inputs: [";
//std::copy(ins.begin(), ins.end(), std::ostream_iterator<ValueT>(std::cerr, ", "));
//std::cerr << "]," << std::endl;
//std::cerr << "(neuron: " << this << ") Weights: [";
//std::copy(ws.begin(), ws.end(), std::ostream_iterator<ValueT>(std::cerr, ", "));
//std::cerr << "]" << std::endl;
//#endif // FL_DEBUG
////[/XXX]
netIn_ = p_inpFunc_->eval(ins.begin(), ins.end(), ws.begin(), ws.end());
////[XXX]
//#ifdef FL_DEBUG
//std::cerr << "(neuron: " << this << ") net input: " << netIn_ << std::endl;
//#endif // FL_DEBUG
////[/XXX]
out_ = p_actFunc_->eval(netIn_);
////[XXX]
//#ifdef FL_DEBUG
//std::cerr << "(neuron: " << this << ") output: " << out_ << std::endl;
//#endif // FL_DEBUG
////[/XXX]
return out_;
}
public: ValueT getOutput() const
{
return out_;
}
protected: void setOutput(ValueT v)
{
out_ = v;
}
// public: void setError(ValueT v)
// {
// err_ = v;
// }
// public: ValueT getError() const
// {
// return err_;
// }
public: void setHasBias(bool v)
{
hasBias_ = v;
}
public: bool hasBias() const
{
return hasBias_;
}
public: void setBias(ValueT wb)
{
biasWeight_ = wb;
}
public: ValueT getBias() const
{
return biasWeight_;
}
private: FL_unique_ptr< NetInputFunction<ValueT> > p_inpFunc_; ///< The input function
private: FL_unique_ptr< ActivationFunction<ValueT> > p_actFunc_; ///< The activation function
private: Layer<ValueT>* p_layer_; ///< The layer containing this neuron
private: ValueT netIn_; ///< The input for this neuron received from the net input function
private: ValueT out_; ///< The output of this neuron
// private: ValueT err_; //< The error term
private: bool hasBias_; ///< Tells if this neuron has a bias connection
private: ValueT biasWeight_; ///< The weight associated to the bias connection
}; // Neuron
///**
// * A bias neuron is a neuron whose output value is always 1
// *
// * \author Marco Guazzone (marco.guazzone@gmail.com)
// */
//template <typename ValueT>
//class BiasNeuron: public Neuron<ValueT>
//{
// private: typedef Neuron<ValueT> BaseType;
//
// private: static const std::vector<Connection<ValueT>*> emptyConnections;
//
//
// public: BiasNeuron(Layer<ValueT>* p_layer = fl::null)
// : BaseType(new ConstantNetInputFunction<ValueT>(1), new LinearActivationFunction<ValueT>(1), p_layer)
// {
//FL_DEBUG_TRACE("In BiasNeuron's constructor (" << this << ")");//XXX
// this->setNetInput(1);
// this->process();
// }
//
// public: ValueT process()
// {
// const ValueT out = this->getActivationFunction()->eval(this->getNetInput());
// this->setOutput(out);
//
// return out;
// }
//
// public: bool isDummy() const
// {
// return true;
// }
//}; // BiasNeuron
/**
* A neuron that can be used in the input layer of a neural network
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*/
template <typename ValueT>
class InputNeuron: public Neuron<ValueT>
{
private: typedef Neuron<ValueT> BaseType;
//private: static const std::vector<Connection<ValueT>*> emptyConnections;
public: explicit InputNeuron(Layer<ValueT>* p_layer = fl::null)
: BaseType(new WeightedSumNetInputFunction<ValueT>(), new PureLinearActivationFunction<ValueT>(), p_layer)
{
//FL_DEBUG_TRACE("In InputNeuron's constructor (" << this << ")");//XXX
}
public: void setInput(ValueT v)
{
this->setNetInput(v);
this->process();
}
public: ValueT getInput() const
{
return this->getNetInput();
}
public: ValueT process()
{
const ValueT out = this->getActivationFunction()->eval(this->getInput());
this->setOutput(out);
return out;
}
}; // InputNeuron
}} // Namespace fl::ann
#endif // FL_ANN_NEURONS_H
| 25.568862 | 251 | 0.686339 | [
"shape",
"vector",
"model"
] |
5dddb8488250e8a7f410c4e625d318bbd7c07b36 | 302 | h | C | XB/Classes/XBPlan/PlanDetail/View/XBPlanDetailMedalTableViewCell.h | shuaiwang007/privateDemo | ca953d05c31bb89810f53156a7033c86acf90dde | [
"Apache-2.0"
] | null | null | null | XB/Classes/XBPlan/PlanDetail/View/XBPlanDetailMedalTableViewCell.h | shuaiwang007/privateDemo | ca953d05c31bb89810f53156a7033c86acf90dde | [
"Apache-2.0"
] | null | null | null | XB/Classes/XBPlan/PlanDetail/View/XBPlanDetailMedalTableViewCell.h | shuaiwang007/privateDemo | ca953d05c31bb89810f53156a7033c86acf90dde | [
"Apache-2.0"
] | null | null | null | //
// XBPlanDetailMedalTableViewCell.h
// XB
//
// Created by 王化强 on 2017/3/2.
// Copyright © 2017年 whqfor. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "XBPlanDetailModel.h"
@interface XBPlanDetailMedalTableViewCell : UITableViewCell
- (void)setCellWithModel:(XBBadge *)model;
@end
| 17.764706 | 59 | 0.728477 | [
"model"
] |
3454dbfa3cd1fa95d1fde01c8cc6c50d95ed7065 | 43,627 | h | C | c_include/windows_win7_orig/ws2def.h | stuta/Luajit-Tcp-Server | d89228c170debca554c3bc71b200b1e62ccdeb9e | [
"BSD-3-Clause"
] | 24 | 2015-01-15T16:28:33.000Z | 2020-07-16T03:38:37.000Z | c_include/windows_win7_orig/ws2def.h | stuta/Luajit-Tcp-Server | d89228c170debca554c3bc71b200b1e62ccdeb9e | [
"BSD-3-Clause"
] | null | null | null | c_include/windows_win7_orig/ws2def.h | stuta/Luajit-Tcp-Server | d89228c170debca554c3bc71b200b1e62ccdeb9e | [
"BSD-3-Clause"
] | 9 | 2017-03-08T18:22:42.000Z | 2022-01-18T15:16:56.000Z | # 1 "c_include/windows/original/ws2def.h"
#define __STDC__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __STDC_HOSTED__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __GNUC__ 4
# 1 "c_include/windows/original/ws2def.h"
#define __GNUC_MINOR__ 8
# 1 "c_include/windows/original/ws2def.h"
#define __GNUC_PATCHLEVEL__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __VERSION__ "4.8.1 20130328 (prerelease)"
# 1 "c_include/windows/original/ws2def.h"
#define __ATOMIC_RELAXED 0
# 1 "c_include/windows/original/ws2def.h"
#define __ATOMIC_SEQ_CST 5
# 1 "c_include/windows/original/ws2def.h"
#define __ATOMIC_ACQUIRE 2
# 1 "c_include/windows/original/ws2def.h"
#define __ATOMIC_RELEASE 3
# 1 "c_include/windows/original/ws2def.h"
#define __ATOMIC_ACQ_REL 4
# 1 "c_include/windows/original/ws2def.h"
#define __ATOMIC_CONSUME 1
# 1 "c_include/windows/original/ws2def.h"
#define __pic__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __PIC__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __FINITE_MATH_ONLY__ 0
# 1 "c_include/windows/original/ws2def.h"
#define __SIZEOF_INT__ 4
# 1 "c_include/windows/original/ws2def.h"
#define __SIZEOF_LONG__ 4
# 1 "c_include/windows/original/ws2def.h"
#define __SIZEOF_LONG_LONG__ 8
# 1 "c_include/windows/original/ws2def.h"
#define __SIZEOF_SHORT__ 2
# 1 "c_include/windows/original/ws2def.h"
#define __SIZEOF_FLOAT__ 4
# 1 "c_include/windows/original/ws2def.h"
#define __SIZEOF_DOUBLE__ 8
# 1 "c_include/windows/original/ws2def.h"
#define __SIZEOF_LONG_DOUBLE__ 16
# 1 "c_include/windows/original/ws2def.h"
#define __SIZEOF_SIZE_T__ 8
# 1 "c_include/windows/original/ws2def.h"
#define __CHAR_BIT__ 8
# 1 "c_include/windows/original/ws2def.h"
#define __BIGGEST_ALIGNMENT__ 16
# 1 "c_include/windows/original/ws2def.h"
#define __ORDER_LITTLE_ENDIAN__ 1234
# 1 "c_include/windows/original/ws2def.h"
#define __ORDER_BIG_ENDIAN__ 4321
# 1 "c_include/windows/original/ws2def.h"
#define __ORDER_PDP_ENDIAN__ 3412
# 1 "c_include/windows/original/ws2def.h"
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
# 1 "c_include/windows/original/ws2def.h"
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
# 1 "c_include/windows/original/ws2def.h"
#define __SIZEOF_POINTER__ 8
# 1 "c_include/windows/original/ws2def.h"
#define __SIZE_TYPE__ long long unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __PTRDIFF_TYPE__ long long int
# 1 "c_include/windows/original/ws2def.h"
#define __WCHAR_TYPE__ short unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __WINT_TYPE__ short unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __INTMAX_TYPE__ long long int
# 1 "c_include/windows/original/ws2def.h"
#define __UINTMAX_TYPE__ long long unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __CHAR16_TYPE__ short unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __CHAR32_TYPE__ unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __SIG_ATOMIC_TYPE__ int
# 1 "c_include/windows/original/ws2def.h"
#define __INT8_TYPE__ signed char
# 1 "c_include/windows/original/ws2def.h"
#define __INT16_TYPE__ short int
# 1 "c_include/windows/original/ws2def.h"
#define __INT32_TYPE__ int
# 1 "c_include/windows/original/ws2def.h"
#define __INT64_TYPE__ long long int
# 1 "c_include/windows/original/ws2def.h"
#define __UINT8_TYPE__ unsigned char
# 1 "c_include/windows/original/ws2def.h"
#define __UINT16_TYPE__ short unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __UINT32_TYPE__ unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __UINT64_TYPE__ long long unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __INT_LEAST8_TYPE__ signed char
# 1 "c_include/windows/original/ws2def.h"
#define __INT_LEAST16_TYPE__ short int
# 1 "c_include/windows/original/ws2def.h"
#define __INT_LEAST32_TYPE__ int
# 1 "c_include/windows/original/ws2def.h"
#define __INT_LEAST64_TYPE__ long long int
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_LEAST8_TYPE__ unsigned char
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_LEAST16_TYPE__ short unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_LEAST32_TYPE__ unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_LEAST64_TYPE__ long long unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __INT_FAST8_TYPE__ signed char
# 1 "c_include/windows/original/ws2def.h"
#define __INT_FAST16_TYPE__ short int
# 1 "c_include/windows/original/ws2def.h"
#define __INT_FAST32_TYPE__ int
# 1 "c_include/windows/original/ws2def.h"
#define __INT_FAST64_TYPE__ long long int
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_FAST8_TYPE__ unsigned char
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_FAST16_TYPE__ short unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_FAST32_TYPE__ unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_FAST64_TYPE__ long long unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __INTPTR_TYPE__ long long int
# 1 "c_include/windows/original/ws2def.h"
#define __UINTPTR_TYPE__ long long unsigned int
# 1 "c_include/windows/original/ws2def.h"
#define __GXX_ABI_VERSION 1002
# 1 "c_include/windows/original/ws2def.h"
#define __SCHAR_MAX__ 127
# 1 "c_include/windows/original/ws2def.h"
#define __SHRT_MAX__ 32767
# 1 "c_include/windows/original/ws2def.h"
#define __INT_MAX__ 2147483647
# 1 "c_include/windows/original/ws2def.h"
#define __LONG_MAX__ 2147483647L
# 1 "c_include/windows/original/ws2def.h"
#define __LONG_LONG_MAX__ 9223372036854775807LL
# 1 "c_include/windows/original/ws2def.h"
#define __WCHAR_MAX__ 65535
# 1 "c_include/windows/original/ws2def.h"
#define __WCHAR_MIN__ 0
# 1 "c_include/windows/original/ws2def.h"
#define __WINT_MAX__ 65535
# 1 "c_include/windows/original/ws2def.h"
#define __WINT_MIN__ 0
# 1 "c_include/windows/original/ws2def.h"
#define __PTRDIFF_MAX__ 9223372036854775807LL
# 1 "c_include/windows/original/ws2def.h"
#define __SIZE_MAX__ 18446744073709551615ULL
# 1 "c_include/windows/original/ws2def.h"
#define __INTMAX_MAX__ 9223372036854775807LL
# 1 "c_include/windows/original/ws2def.h"
#define __INTMAX_C(c) c ## LL
# 1 "c_include/windows/original/ws2def.h"
#define __UINTMAX_MAX__ 18446744073709551615ULL
# 1 "c_include/windows/original/ws2def.h"
#define __UINTMAX_C(c) c ## ULL
# 1 "c_include/windows/original/ws2def.h"
#define __SIG_ATOMIC_MAX__ 2147483647
# 1 "c_include/windows/original/ws2def.h"
#define __SIG_ATOMIC_MIN__ (-__SIG_ATOMIC_MAX__ - 1)
# 1 "c_include/windows/original/ws2def.h"
#define __INT8_MAX__ 127
# 1 "c_include/windows/original/ws2def.h"
#define __INT16_MAX__ 32767
# 1 "c_include/windows/original/ws2def.h"
#define __INT32_MAX__ 2147483647
# 1 "c_include/windows/original/ws2def.h"
#define __INT64_MAX__ 9223372036854775807LL
# 1 "c_include/windows/original/ws2def.h"
#define __UINT8_MAX__ 255
# 1 "c_include/windows/original/ws2def.h"
#define __UINT16_MAX__ 65535
# 1 "c_include/windows/original/ws2def.h"
#define __UINT32_MAX__ 4294967295U
# 1 "c_include/windows/original/ws2def.h"
#define __UINT64_MAX__ 18446744073709551615ULL
# 1 "c_include/windows/original/ws2def.h"
#define __INT_LEAST8_MAX__ 127
# 1 "c_include/windows/original/ws2def.h"
#define __INT8_C(c) c
# 1 "c_include/windows/original/ws2def.h"
#define __INT_LEAST16_MAX__ 32767
# 1 "c_include/windows/original/ws2def.h"
#define __INT16_C(c) c
# 1 "c_include/windows/original/ws2def.h"
#define __INT_LEAST32_MAX__ 2147483647
# 1 "c_include/windows/original/ws2def.h"
#define __INT32_C(c) c
# 1 "c_include/windows/original/ws2def.h"
#define __INT_LEAST64_MAX__ 9223372036854775807LL
# 1 "c_include/windows/original/ws2def.h"
#define __INT64_C(c) c ## LL
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_LEAST8_MAX__ 255
# 1 "c_include/windows/original/ws2def.h"
#define __UINT8_C(c) c
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_LEAST16_MAX__ 65535
# 1 "c_include/windows/original/ws2def.h"
#define __UINT16_C(c) c
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_LEAST32_MAX__ 4294967295U
# 1 "c_include/windows/original/ws2def.h"
#define __UINT32_C(c) c ## U
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_LEAST64_MAX__ 18446744073709551615ULL
# 1 "c_include/windows/original/ws2def.h"
#define __UINT64_C(c) c ## ULL
# 1 "c_include/windows/original/ws2def.h"
#define __INT_FAST8_MAX__ 127
# 1 "c_include/windows/original/ws2def.h"
#define __INT_FAST16_MAX__ 32767
# 1 "c_include/windows/original/ws2def.h"
#define __INT_FAST32_MAX__ 2147483647
# 1 "c_include/windows/original/ws2def.h"
#define __INT_FAST64_MAX__ 9223372036854775807LL
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_FAST8_MAX__ 255
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_FAST16_MAX__ 65535
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_FAST32_MAX__ 4294967295U
# 1 "c_include/windows/original/ws2def.h"
#define __UINT_FAST64_MAX__ 18446744073709551615ULL
# 1 "c_include/windows/original/ws2def.h"
#define __INTPTR_MAX__ 9223372036854775807LL
# 1 "c_include/windows/original/ws2def.h"
#define __UINTPTR_MAX__ 18446744073709551615ULL
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_EVAL_METHOD__ 0
# 1 "c_include/windows/original/ws2def.h"
#define __DEC_EVAL_METHOD__ 2
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_RADIX__ 2
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_MANT_DIG__ 24
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_DIG__ 6
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_MIN_EXP__ (-125)
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_MIN_10_EXP__ (-37)
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_MAX_EXP__ 128
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_MAX_10_EXP__ 38
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_DECIMAL_DIG__ 9
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_MAX__ 3.40282346638528859812e+38F
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_MIN__ 1.17549435082228750797e-38F
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_EPSILON__ 1.19209289550781250000e-7F
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_DENORM_MIN__ 1.40129846432481707092e-45F
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_HAS_DENORM__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_HAS_INFINITY__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __FLT_HAS_QUIET_NAN__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_MANT_DIG__ 53
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_DIG__ 15
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_MIN_EXP__ (-1021)
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_MIN_10_EXP__ (-307)
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_MAX_EXP__ 1024
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_MAX_10_EXP__ 308
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_DECIMAL_DIG__ 17
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_MAX__ ((double)1.79769313486231570815e+308L)
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_MIN__ ((double)2.22507385850720138309e-308L)
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_HAS_DENORM__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_HAS_INFINITY__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __DBL_HAS_QUIET_NAN__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __LDBL_MANT_DIG__ 64
# 1 "c_include/windows/original/ws2def.h"
#define __LDBL_DIG__ 18
# 1 "c_include/windows/original/ws2def.h"
#define __LDBL_MIN_EXP__ (-16381)
# 1 "c_include/windows/original/ws2def.h"
#define __LDBL_MIN_10_EXP__ (-4931)
# 1 "c_include/windows/original/ws2def.h"
#define __LDBL_MAX_EXP__ 16384
# 1 "c_include/windows/original/ws2def.h"
#define __LDBL_MAX_10_EXP__ 4932
# 1 "c_include/windows/original/ws2def.h"
#define __DECIMAL_DIG__ 21
# 1 "c_include/windows/original/ws2def.h"
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
# 1 "c_include/windows/original/ws2def.h"
#define __LDBL_MIN__ 3.36210314311209350626e-4932L
# 1 "c_include/windows/original/ws2def.h"
#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
# 1 "c_include/windows/original/ws2def.h"
#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
# 1 "c_include/windows/original/ws2def.h"
#define __LDBL_HAS_DENORM__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __LDBL_HAS_INFINITY__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __LDBL_HAS_QUIET_NAN__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __DEC32_MANT_DIG__ 7
# 1 "c_include/windows/original/ws2def.h"
#define __DEC32_MIN_EXP__ (-94)
# 1 "c_include/windows/original/ws2def.h"
#define __DEC32_MAX_EXP__ 97
# 1 "c_include/windows/original/ws2def.h"
#define __DEC32_MIN__ 1E-95DF
# 1 "c_include/windows/original/ws2def.h"
#define __DEC32_MAX__ 9.999999E96DF
# 1 "c_include/windows/original/ws2def.h"
#define __DEC32_EPSILON__ 1E-6DF
# 1 "c_include/windows/original/ws2def.h"
#define __DEC32_SUBNORMAL_MIN__ 0.000001E-95DF
# 1 "c_include/windows/original/ws2def.h"
#define __DEC64_MANT_DIG__ 16
# 1 "c_include/windows/original/ws2def.h"
#define __DEC64_MIN_EXP__ (-382)
# 1 "c_include/windows/original/ws2def.h"
#define __DEC64_MAX_EXP__ 385
# 1 "c_include/windows/original/ws2def.h"
#define __DEC64_MIN__ 1E-383DD
# 1 "c_include/windows/original/ws2def.h"
#define __DEC64_MAX__ 9.999999999999999E384DD
# 1 "c_include/windows/original/ws2def.h"
#define __DEC64_EPSILON__ 1E-15DD
# 1 "c_include/windows/original/ws2def.h"
#define __DEC64_SUBNORMAL_MIN__ 0.000000000000001E-383DD
# 1 "c_include/windows/original/ws2def.h"
#define __DEC128_MANT_DIG__ 34
# 1 "c_include/windows/original/ws2def.h"
#define __DEC128_MIN_EXP__ (-6142)
# 1 "c_include/windows/original/ws2def.h"
#define __DEC128_MAX_EXP__ 6145
# 1 "c_include/windows/original/ws2def.h"
#define __DEC128_MIN__ 1E-6143DL
# 1 "c_include/windows/original/ws2def.h"
#define __DEC128_MAX__ 9.999999999999999999999999999999999E6144DL
# 1 "c_include/windows/original/ws2def.h"
#define __DEC128_EPSILON__ 1E-33DL
# 1 "c_include/windows/original/ws2def.h"
#define __DEC128_SUBNORMAL_MIN__ 0.000000000000000000000000000000001E-6143DL
# 1 "c_include/windows/original/ws2def.h"
#define __REGISTER_PREFIX__
# 1 "c_include/windows/original/ws2def.h"
#define __USER_LABEL_PREFIX__
# 1 "c_include/windows/original/ws2def.h"
#define __GNUC_GNU_INLINE__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __NO_INLINE__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_ATOMIC_BOOL_LOCK_FREE 2
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_ATOMIC_SHORT_LOCK_FREE 2
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_ATOMIC_INT_LOCK_FREE 2
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_ATOMIC_LONG_LOCK_FREE 2
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_ATOMIC_LLONG_LOCK_FREE 2
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
# 1 "c_include/windows/original/ws2def.h"
#define __GCC_ATOMIC_POINTER_LOCK_FREE 2
# 1 "c_include/windows/original/ws2def.h"
#define __PRAGMA_REDEFINE_EXTNAME 1
# 1 "c_include/windows/original/ws2def.h"
#define __SIZEOF_INT128__ 16
# 1 "c_include/windows/original/ws2def.h"
#define __SIZEOF_WCHAR_T__ 2
# 1 "c_include/windows/original/ws2def.h"
#define __SIZEOF_WINT_T__ 2
# 1 "c_include/windows/original/ws2def.h"
#define __SIZEOF_PTRDIFF_T__ 8
# 1 "c_include/windows/original/ws2def.h"
#define __amd64 1
# 1 "c_include/windows/original/ws2def.h"
#define __amd64__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __x86_64 1
# 1 "c_include/windows/original/ws2def.h"
#define __x86_64__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __ATOMIC_HLE_ACQUIRE 65536
# 1 "c_include/windows/original/ws2def.h"
#define __ATOMIC_HLE_RELEASE 131072
# 1 "c_include/windows/original/ws2def.h"
#define __k8 1
# 1 "c_include/windows/original/ws2def.h"
#define __k8__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __code_model_small__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __MMX__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __SSE__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __SSE2__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __SSE_MATH__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __SSE2_MATH__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __SEH__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __stdcall __attribute__((__stdcall__))
# 1 "c_include/windows/original/ws2def.h"
#define __fastcall __attribute__((__fastcall__))
# 1 "c_include/windows/original/ws2def.h"
#define __thiscall __attribute__((__thiscall__))
# 1 "c_include/windows/original/ws2def.h"
#define __cdecl __attribute__((__cdecl__))
# 1 "c_include/windows/original/ws2def.h"
#define _stdcall __attribute__((__stdcall__))
# 1 "c_include/windows/original/ws2def.h"
#define _fastcall __attribute__((__fastcall__))
# 1 "c_include/windows/original/ws2def.h"
#define _thiscall __attribute__((__thiscall__))
# 1 "c_include/windows/original/ws2def.h"
#define _cdecl __attribute__((__cdecl__))
# 1 "c_include/windows/original/ws2def.h"
#define __GXX_MERGED_TYPEINFO_NAMES 0
# 1 "c_include/windows/original/ws2def.h"
#define __GXX_TYPEINFO_EQUALITY_INLINE 0
# 1 "c_include/windows/original/ws2def.h"
#define __MSVCRT__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __MINGW32__ 1
# 1 "c_include/windows/original/ws2def.h"
#define _WIN32 1
# 1 "c_include/windows/original/ws2def.h"
#define __WIN32 1
# 1 "c_include/windows/original/ws2def.h"
#define __WIN32__ 1
# 1 "c_include/windows/original/ws2def.h"
#define WIN32 1
# 1 "c_include/windows/original/ws2def.h"
#define __WINNT 1
# 1 "c_include/windows/original/ws2def.h"
#define __WINNT__ 1
# 1 "c_include/windows/original/ws2def.h"
#define WINNT 1
# 1 "c_include/windows/original/ws2def.h"
#define _INTEGRAL_MAX_BITS 64
# 1 "c_include/windows/original/ws2def.h"
#define __MINGW64__ 1
# 1 "c_include/windows/original/ws2def.h"
#define __WIN64 1
# 1 "c_include/windows/original/ws2def.h"
#define __WIN64__ 1
# 1 "c_include/windows/original/ws2def.h"
#define WIN64 1
# 1 "c_include/windows/original/ws2def.h"
#define _WIN64 1
# 1 "c_include/windows/original/ws2def.h"
#define __declspec(x) __attribute__((x))
# 1 "c_include/windows/original/ws2def.h"
#define __DECIMAL_BID_FORMAT__ 1
# 1 "<command-line>"
#undef _REENTRANT
# 1 "c_include/windows/original/ws2def.h"
#define _WIN32_WINNT 0x0602
#define WINVER _WIN32_WINNT
#define WIN32_LEAN_AND_MEAN
#pragma comment (lib, "Ws2_32.lib")
/*++
Copyright (c) Microsoft Corporation. All rights reserved.
Module Name:
ws2def.h
Abstract:
This file contains the core definitions for the Winsock2
specification that can be used by both user-mode and
kernel mode modules.
This file is included in WINSOCK2.H. User mode applications
should include WINSOCK2.H rather than including this file
directly. This file can not be included by a module that also
includes WINSOCK.H.
Environment:
user mode or kernel mode
--*/
#define _WS2DEF_
# 45 "c_include/windows/original/ws2def.h"
#pragma warning(push)
#pragma warning(disable:4201)
#pragma warning(disable:4214)
//
// Allow Winsock components to disable PREfast errors.
//
# 62 "c_include/windows/original/ws2def.h"
#define WS2DEF_INLINE extern inline
# 1 "C:/Program Files (x86)/Microsoft SDKs/Windows/v7.0A/Include/inaddr.h" 1
/*++
Copyright (c) Microsoft Corporation
Module Name:
inaddr.h
Environment:
user mode or kernel mode
--*/
# 16 "C:/Program Files (x86)/Microsoft SDKs/Windows/v7.0A/Include/inaddr.h"
//
// IPv4 Internet address
// This is an 'on-wire' format structure.
//
typedef struct in_addr {
union {
struct { UCHAR s_b1,s_b2,s_b3,s_b4; } S_un_b;
struct { USHORT s_w1,s_w2; } S_un_w;
ULONG S_addr;
} S_un;
#define s_addr S_un.S_addr
#define s_host S_un.S_un_b.s_b2
#define s_net S_un.S_un_b.s_b1
#define s_imp S_un.S_un_w.s_w2
#define s_impno S_un.S_un_b.s_b4
#define s_lh S_un.S_un_b.s_b3
} IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR;
# 68 "c_include/windows/original/ws2def.h" 2
//#if(_WIN32_WINNT >= 0x0600)
//
// Address families.
//
typedef USHORT ADDRESS_FAMILY;
//#endif//(_WIN32_WINNT >= 0x0600)
//
// Although AF_UNSPEC is defined for backwards compatibility, using
// AF_UNSPEC for the "af" parameter when creating a socket is STRONGLY
// DISCOURAGED. The interpretation of the "protocol" parameter
// depends on the actual address family chosen. As environments grow
// to include more and more address families that use overlapping
// protocol values there is more and more chance of choosing an
// undesired address family when AF_UNSPEC is used.
//
#define AF_UNSPEC 0
#define AF_UNIX 1
#define AF_INET 2
#define AF_IMPLINK 3
#define AF_PUP 4
#define AF_CHAOS 5
#define AF_NS 6
#define AF_IPX AF_NS
#define AF_ISO 7
#define AF_OSI AF_ISO
#define AF_ECMA 8
#define AF_DATAKIT 9
#define AF_CCITT 10
#define AF_SNA 11
#define AF_DECnet 12
#define AF_DLI 13
#define AF_LAT 14
#define AF_HYLINK 15
#define AF_APPLETALK 16
#define AF_NETBIOS 17
#define AF_VOICEVIEW 18
#define AF_FIREFOX 19
#define AF_UNKNOWN1 20
#define AF_BAN 21
#define AF_ATM 22
#define AF_INET6 23
#define AF_CLUSTER 24
#define AF_12844 25
#define AF_IRDA 26
#define AF_NETDES 28
#define AF_TCNPROCESS 29
#define AF_TCNMESSAGE 30
#define AF_ICLFXBM 31
#define AF_BTH 32
#define AF_LINK 33
#define AF_MAX 34
//
// Socket types.
//
#define SOCK_STREAM 1
#define SOCK_DGRAM 2
#define SOCK_RAW 3
#define SOCK_RDM 4
#define SOCK_SEQPACKET 5
//
// Define a level for socket I/O controls in the same numbering space as
// IPPROTO_TCP, IPPROTO_IP, etc.
//
#define SOL_SOCKET 0xffff
//
// Define socket-level options.
//
#define SO_DEBUG 0x0001
#define SO_ACCEPTCONN 0x0002
#define SO_REUSEADDR 0x0004
#define SO_KEEPALIVE 0x0008
#define SO_DONTROUTE 0x0010
#define SO_BROADCAST 0x0020
#define SO_USELOOPBACK 0x0040
#define SO_LINGER 0x0080
#define SO_OOBINLINE 0x0100
#define SO_DONTLINGER (int)(~SO_LINGER)
#define SO_EXCLUSIVEADDRUSE ((int)(~SO_REUSEADDR))
#define SO_SNDBUF 0x1001
#define SO_RCVBUF 0x1002
#define SO_SNDLOWAT 0x1003
#define SO_RCVLOWAT 0x1004
#define SO_SNDTIMEO 0x1005
#define SO_RCVTIMEO 0x1006
#define SO_ERROR 0x1007
#define SO_TYPE 0x1008
#define SO_BSP_STATE 0x1009
#define SO_GROUP_ID 0x2001
#define SO_GROUP_PRIORITY 0x2002
#define SO_MAX_MSG_SIZE 0x2003
#define SO_CONDITIONAL_ACCEPT 0x3002
// connection is not ack-ed to the
// other side until conditional
// function returns CF_ACCEPT
#define SO_PAUSE_ACCEPT 0x3003
#define SO_COMPARTMENT_ID 0x3004
#define SO_RANDOMIZE_PORT 0x3005
#define SO_PORT_SCALABILITY 0x3006
//
// Base constant used for defining WSK-specific options.
//
#define WSK_SO_BASE 0x4000
//
// Options to use with [gs]etsockopt at the IPPROTO_TCP level.
//
#define TCP_NODELAY 0x0001
//
// Structure used to store most addresses.
//
typedef struct sockaddr {
ADDRESS_FAMILY sa_family; // Address family.
CHAR sa_data[14]; // Up to 14 bytes of direct address.
} SOCKADDR, *PSOCKADDR, FAR *LPSOCKADDR;
#define __CSADDR_DEFINED__
/*
* SockAddr Information
*/
typedef struct _SOCKET_ADDRESS {
__field_bcount(iSockaddrLength) LPSOCKADDR lpSockaddr;
INT iSockaddrLength;
} SOCKET_ADDRESS, *PSOCKET_ADDRESS, *LPSOCKET_ADDRESS;
/*
* Address list returned via SIO_ADDRESS_LIST_QUERY
*/
typedef struct _SOCKET_ADDRESS_LIST {
INT iAddressCount;
SOCKET_ADDRESS Address[1];
} SOCKET_ADDRESS_LIST, *PSOCKET_ADDRESS_LIST, FAR *LPSOCKET_ADDRESS_LIST;
#define SIZEOF_SOCKET_ADDRESS_LIST(AddressCount) (FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address) + AddressCount * sizeof(SOCKET_ADDRESS))
/*
* CSAddr Information
*/
typedef struct _CSADDR_INFO {
SOCKET_ADDRESS LocalAddr ;
SOCKET_ADDRESS RemoteAddr ;
INT iSocketType ;
INT iProtocol ;
} CSADDR_INFO, *PCSADDR_INFO, FAR * LPCSADDR_INFO ;
//
// Portable socket structure (RFC 2553).
//
//
// Desired design of maximum size and alignment.
// These are implementation specific.
//
#define _SS_MAXSIZE 128
#define _SS_ALIGNSIZE (sizeof(__int64))
//
// Definitions used for sockaddr_storage structure paddings design.
//
#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(USHORT))
#define _SS_PAD2SIZE (_SS_MAXSIZE - (sizeof(USHORT) + _SS_PAD1SIZE + _SS_ALIGNSIZE))
typedef struct sockaddr_storage {
ADDRESS_FAMILY ss_family; // address family
CHAR __ss_pad1[((sizeof(__int64)) - sizeof(USHORT))]; // 6 byte pad, this is to make
// implementation specific pad up to
// alignment field that follows explicit
// in the data structure
__int64 __ss_align; // Field to force desired structure
CHAR __ss_pad2[(128 - (sizeof(USHORT) + ((sizeof(__int64)) - sizeof(USHORT)) + (sizeof(__int64))))]; // 112 byte pad to achieve desired size;
// _SS_MAXSIZE value minus size of
// ss_family, __ss_pad1, and
// __ss_align fields is 112
} SOCKADDR_STORAGE_LH, *PSOCKADDR_STORAGE_LH, FAR *LPSOCKADDR_STORAGE_LH;
typedef struct sockaddr_storage_xp {
short ss_family; // Address family.
CHAR __ss_pad1[((sizeof(__int64)) - sizeof(USHORT))]; // 6 byte pad, this is to make
// implementation specific pad up to
// alignment field that follows explicit
// in the data structure
__int64 __ss_align; // Field to force desired structure
CHAR __ss_pad2[(128 - (sizeof(USHORT) + ((sizeof(__int64)) - sizeof(USHORT)) + (sizeof(__int64))))]; // 112 byte pad to achieve desired size;
// _SS_MAXSIZE value minus size of
// ss_family, __ss_pad1, and
// __ss_align fields is 112
} SOCKADDR_STORAGE_XP, *PSOCKADDR_STORAGE_XP, FAR *LPSOCKADDR_STORAGE_XP;
typedef SOCKADDR_STORAGE_LH SOCKADDR_STORAGE;
typedef SOCKADDR_STORAGE *PSOCKADDR_STORAGE, FAR *LPSOCKADDR_STORAGE;
/*
* WinSock 2 extension -- manifest constants for WSAIoctl()
*/
#define IOC_UNIX 0x00000000
#define IOC_WS2 0x08000000
#define IOC_PROTOCOL 0x10000000
#define IOC_VENDOR 0x18000000
/*
* WSK-specific IO control codes are Winsock2 codes with the highest-order
* 3 bits of the Vendor/AddressFamily-specific field set to 1.
*/
#define IOC_WSK (IOC_WS2|0x07000000)
#define _WSAIO(x,y) (IOC_VOID|(x)|(y))
#define _WSAIOR(x,y) (IOC_OUT|(x)|(y))
#define _WSAIOW(x,y) (IOC_IN|(x)|(y))
#define _WSAIORW(x,y) (IOC_INOUT|(x)|(y))
#define SIO_ASSOCIATE_HANDLE _WSAIOW(IOC_WS2,1)
#define SIO_ENABLE_CIRCULAR_QUEUEING _WSAIO(IOC_WS2,2)
#define SIO_FIND_ROUTE _WSAIOR(IOC_WS2,3)
#define SIO_FLUSH _WSAIO(IOC_WS2,4)
#define SIO_GET_BROADCAST_ADDRESS _WSAIOR(IOC_WS2,5)
#define SIO_GET_EXTENSION_FUNCTION_POINTER _WSAIORW(IOC_WS2,6)
#define SIO_GET_QOS _WSAIORW(IOC_WS2,7)
#define SIO_GET_GROUP_QOS _WSAIORW(IOC_WS2,8)
#define SIO_MULTIPOINT_LOOPBACK _WSAIOW(IOC_WS2,9)
#define SIO_MULTICAST_SCOPE _WSAIOW(IOC_WS2,10)
#define SIO_SET_QOS _WSAIOW(IOC_WS2,11)
#define SIO_SET_GROUP_QOS _WSAIOW(IOC_WS2,12)
#define SIO_TRANSLATE_HANDLE _WSAIORW(IOC_WS2,13)
#define SIO_ROUTING_INTERFACE_QUERY _WSAIORW(IOC_WS2,20)
#define SIO_ROUTING_INTERFACE_CHANGE _WSAIOW(IOC_WS2,21)
#define SIO_ADDRESS_LIST_QUERY _WSAIOR(IOC_WS2,22)
#define SIO_ADDRESS_LIST_CHANGE _WSAIO(IOC_WS2,23)
#define SIO_QUERY_TARGET_PNP_HANDLE _WSAIOR(IOC_WS2,24)
#define SIO_ADDRESS_LIST_SORT _WSAIORW(IOC_WS2,25)
#define SIO_RESERVED_1 _WSAIOW(IOC_WS2,26)
#define SIO_RESERVED_2 _WSAIOW(IOC_WS2,33)
//
// Constants and structures defined by the internet system (RFC 790)
//
//
// N.B. required for backwards compatability to support 0 = IP for the
// level argument to get/setsockopt.
//
#define IPPROTO_IP 0
//
// Protocols. The IPv6 defines are specified in RFC 2292.
//
typedef enum {
IPPROTO_HOPOPTS = 0, // IPv6 Hop-by-Hop options
IPPROTO_ICMP = 1,
IPPROTO_IGMP = 2,
IPPROTO_GGP = 3,
IPPROTO_IPV4 = 4,
IPPROTO_ST = 5,
IPPROTO_TCP = 6,
IPPROTO_CBT = 7,
IPPROTO_EGP = 8,
IPPROTO_IGP = 9,
IPPROTO_PUP = 12,
IPPROTO_UDP = 17,
IPPROTO_IDP = 22,
IPPROTO_RDP = 27,
IPPROTO_IPV6 = 41, // IPv6 header
IPPROTO_ROUTING = 43, // IPv6 Routing header
IPPROTO_FRAGMENT = 44, // IPv6 fragmentation header
IPPROTO_ESP = 50, // encapsulating security payload
IPPROTO_AH = 51, // authentication header
IPPROTO_ICMPV6 = 58, // ICMPv6
IPPROTO_NONE = 59, // IPv6 no next header
IPPROTO_DSTOPTS = 60, // IPv6 Destination options
IPPROTO_ND = 77,
IPPROTO_ICLFXBM = 78,
IPPROTO_PIM = 103,
IPPROTO_PGM = 113,
IPPROTO_L2TP = 115,
IPPROTO_SCTP = 132,
IPPROTO_RAW = 255,
IPPROTO_MAX = 256,
//
// These are reserved for internal use by Windows.
//
IPPROTO_RESERVED_RAW = 257,
IPPROTO_RESERVED_IPSEC = 258,
IPPROTO_RESERVED_IPSECOFFLOAD = 259,
IPPROTO_RESERVED_MAX = 260
} IPPROTO, *PIPROTO;
//
// Port/socket numbers: network standard functions
//
#define IPPORT_TCPMUX 1
#define IPPORT_ECHO 7
#define IPPORT_DISCARD 9
#define IPPORT_SYSTAT 11
#define IPPORT_DAYTIME 13
#define IPPORT_NETSTAT 15
#define IPPORT_QOTD 17
#define IPPORT_MSP 18
#define IPPORT_CHARGEN 19
#define IPPORT_FTP_DATA 20
#define IPPORT_FTP 21
#define IPPORT_TELNET 23
#define IPPORT_SMTP 25
#define IPPORT_TIMESERVER 37
#define IPPORT_NAMESERVER 42
#define IPPORT_WHOIS 43
#define IPPORT_MTP 57
/*
* Port/socket numbers: host specific functions
*/
#define IPPORT_TFTP 69
#define IPPORT_RJE 77
#define IPPORT_FINGER 79
#define IPPORT_TTYLINK 87
#define IPPORT_SUPDUP 95
/*
* UNIX TCP sockets
*/
#define IPPORT_POP3 110
#define IPPORT_NTP 123
#define IPPORT_EPMAP 135
#define IPPORT_NETBIOS_NS 137
#define IPPORT_NETBIOS_DGM 138
#define IPPORT_NETBIOS_SSN 139
#define IPPORT_IMAP 143
#define IPPORT_SNMP 161
#define IPPORT_SNMP_TRAP 162
#define IPPORT_IMAP3 220
#define IPPORT_LDAP 389
#define IPPORT_HTTPS 443
#define IPPORT_MICROSOFT_DS 445
#define IPPORT_EXECSERVER 512
#define IPPORT_LOGINSERVER 513
#define IPPORT_CMDSERVER 514
#define IPPORT_EFSSERVER 520
/*
* UNIX UDP sockets
*/
#define IPPORT_BIFFUDP 512
#define IPPORT_WHOSERVER 513
#define IPPORT_ROUTESERVER 520
/* 520+1 also used */
/*
* Ports < IPPORT_RESERVED are reserved for
* privileged processes (e.g. root).
*/
#define IPPORT_RESERVED 1024
#define IPPORT_REGISTERED_MIN IPPORT_RESERVED
#define IPPORT_REGISTERED_MAX 0xbfff
#define IPPORT_DYNAMIC_MIN 0xc000
#define IPPORT_DYNAMIC_MAX 0xffff
/*
* Definitions of bits in internet address integers.
* On subnets, the decomposition of addresses to host and net parts
* is done according to subnet mask, not the masks here.
*
* N.B. RFC-compliant definitions for host-order elements are named IN_xxx,
* while network-order elements are named IN4_xxx.
*/
#define IN_CLASSA(i) (((LONG)(i) & 0x80000000) == 0)
#define IN_CLASSA_NET 0xff000000
#define IN_CLASSA_NSHIFT 24
#define IN_CLASSA_HOST 0x00ffffff
#define IN_CLASSA_MAX 128
#define IN_CLASSB(i) (((LONG)(i) & 0xc0000000) == 0x80000000)
#define IN_CLASSB_NET 0xffff0000
#define IN_CLASSB_NSHIFT 16
#define IN_CLASSB_HOST 0x0000ffff
#define IN_CLASSB_MAX 65536
#define IN_CLASSC(i) (((LONG)(i) & 0xe0000000) == 0xc0000000)
#define IN_CLASSC_NET 0xffffff00
#define IN_CLASSC_NSHIFT 8
#define IN_CLASSC_HOST 0x000000ff
#define IN_CLASSD(i) (((long)(i) & 0xf0000000) == 0xe0000000)
#define IN_CLASSD_NET 0xf0000000
#define IN_CLASSD_NSHIFT 28
#define IN_CLASSD_HOST 0x0fffffff
#define IN_MULTICAST(i) IN_CLASSD(i)
#define INADDR_ANY (ULONG)0x00000000
#define INADDR_LOOPBACK 0x7f000001
#define INADDR_BROADCAST (ULONG)0xffffffff
#define INADDR_NONE 0xffffffff
//
// Scope ID definition
//
typedef enum {
ScopeLevelInterface = 1,
ScopeLevelLink = 2,
ScopeLevelSubnet = 3,
ScopeLevelAdmin = 4,
ScopeLevelSite = 5,
ScopeLevelOrganization = 8,
ScopeLevelGlobal = 14,
ScopeLevelCount = 16
} SCOPE_LEVEL;
typedef struct {
union {
struct {
ULONG Zone : 28;
ULONG Level : 4;
};
ULONG Value;
};
} SCOPE_ID, *PSCOPE_ID;
#define SCOPEID_UNSPECIFIED_INIT { 0 }
//
// IPv4 Socket address, Internet style
//
typedef struct sockaddr_in {
ADDRESS_FAMILY sin_family;
USHORT sin_port;
IN_ADDR sin_addr;
CHAR sin_zero[8];
} SOCKADDR_IN, *PSOCKADDR_IN;
//
// Datalink (MAC) address
//
// If you don't use the entire sdl_data field, then fill it starting with the low
// bytes...
//
typedef struct sockaddr_dl {
ADDRESS_FAMILY sdl_family;
UCHAR sdl_data[8];
UCHAR sdl_zero[4];
} SOCKADDR_DL, *PSOCKADDR_DL;
#define IOCPARM_MASK 0x7f
#define IOC_VOID 0x20000000
#define IOC_OUT 0x40000000
#define IOC_IN 0x80000000
#define IOC_INOUT (IOC_IN|IOC_OUT)
/* 0x20000000 distinguishes new &
old ioctl's */
#define _IO(x,y) (IOC_VOID|((x)<<8)|(y))
#define _IOR(x,y,t) (IOC_OUT|(((long)sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|(y))
#define _IOW(x,y,t) (IOC_IN|(((long)sizeof(t)&IOCPARM_MASK)<<16)|((x)<<8)|(y))
/*
* WinSock 2 extension -- WSABUF and QOS struct, include qos.h
* to pull in FLOWSPEC and related definitions
*/
typedef struct _WSABUF {
ULONG len; /* the length of the buffer */
__field_bcount(len) CHAR FAR *buf; /* the pointer to the buffer */
} WSABUF, FAR * LPWSABUF;
/*
* WSAMSG -- for WSASendMsg
*/
typedef struct _WSAMSG {
__field_bcount(namelen) LPSOCKADDR name; /* Remote address */
INT namelen; /* Remote address length */
LPWSABUF lpBuffers; /* Data buffer array */
ULONG dwBufferCount; /* Number of elements in the array */
WSABUF Control; /* Control buffer */
ULONG dwFlags; /* Flags */
} WSAMSG, *PWSAMSG, * FAR LPWSAMSG;
/*
* Layout of ancillary data objects in the control buffer (RFC 2292).
*/
#define _WSACMSGHDR cmsghdr
typedef struct cmsghdr {
SIZE_T cmsg_len;
INT cmsg_level;
INT cmsg_type;
/* followed by UCHAR cmsg_data[] */
} WSACMSGHDR, *PWSACMSGHDR, FAR *LPWSACMSGHDR;
typedef WSACMSGHDR CMSGHDR, *PCMSGHDR;
/*
* Alignment macros for header and data members of
* the control buffer.
*/
#define WSA_CMSGHDR_ALIGN(length) ( ((length) + TYPE_ALIGNMENT(WSACMSGHDR)-1) & (~(TYPE_ALIGNMENT(WSACMSGHDR)-1)) )
#define WSA_CMSGDATA_ALIGN(length) ( ((length) + MAX_NATURAL_ALIGNMENT-1) & (~(MAX_NATURAL_ALIGNMENT-1)) )
#define CMSGHDR_ALIGN WSA_CMSGHDR_ALIGN
#define CMSGDATA_ALIGN WSA_CMSGDATA_ALIGN
/*
* WSA_CMSG_FIRSTHDR
*
* Returns a pointer to the first ancillary data object,
* or a null pointer if there is no ancillary data in the
* control buffer of the WSAMSG structure.
*
* LPCMSGHDR
* WSA_CMSG_FIRSTHDR (
* LPWSAMSG msg
* );
*/
#define WSA_CMSG_FIRSTHDR(msg) ( ((msg)->Control.len >= sizeof(WSACMSGHDR)) ? (LPWSACMSGHDR)(msg)->Control.buf : (LPWSACMSGHDR)NULL )
#define CMSG_FIRSTHDR WSA_CMSG_FIRSTHDR
/*
* WSA_CMSG_NXTHDR
*
* Returns a pointer to the next ancillary data object,
* or a null if there are no more data objects.
*
* LPCMSGHDR
* WSA_CMSG_NEXTHDR (
* LPWSAMSG msg,
* LPWSACMSGHDR cmsg
* );
*/
#define WSA_CMSG_NXTHDR(msg,cmsg) ( ((cmsg) == NULL) ? WSA_CMSG_FIRSTHDR(msg) : ( ( ((PUCHAR)(cmsg) + WSA_CMSGHDR_ALIGN((cmsg)->cmsg_len) + sizeof(WSACMSGHDR) ) > (PUCHAR)((msg)->Control.buf) + (msg)->Control.len ) ? (LPWSACMSGHDR)NULL : (LPWSACMSGHDR)((PUCHAR)(cmsg) + WSA_CMSGHDR_ALIGN((cmsg)->cmsg_len)) ) )
# 746 "c_include/windows/original/ws2def.h"
#define CMSG_NXTHDR WSA_CMSG_NXTHDR
/*
* WSA_CMSG_DATA
*
* Returns a pointer to the first byte of data (what is referred
* to as the cmsg_data member though it is not defined in
* the structure).
*
* Note that RFC 2292 defines this as CMSG_DATA, but that name
* is already used by wincrypt.h, and so Windows has used WSA_CMSG_DATA.
*
* PUCHAR
* WSA_CMSG_DATA (
* LPWSACMSGHDR pcmsg
* );
*/
#define WSA_CMSG_DATA(cmsg) ( (PUCHAR)(cmsg) + WSA_CMSGDATA_ALIGN(sizeof(WSACMSGHDR)) )
/*
* WSA_CMSG_SPACE
*
* Returns total size of an ancillary data object given
* the amount of data. Used to allocate the correct amount
* of space.
*
* SIZE_T
* WSA_CMSG_SPACE (
* SIZE_T length
* );
*/
#define WSA_CMSG_SPACE(length) (WSA_CMSGDATA_ALIGN(sizeof(WSACMSGHDR) + WSA_CMSGHDR_ALIGN(length)))
#define CMSG_SPACE WSA_CMSG_SPACE
/*
* WSA_CMSG_LEN
*
* Returns the value to store in cmsg_len given the amount of data.
*
* SIZE_T
* WSA_CMSG_LEN (
* SIZE_T length
* );
*/
#define WSA_CMSG_LEN(length) (WSA_CMSGDATA_ALIGN(sizeof(WSACMSGHDR)) + length)
#define CMSG_LEN WSA_CMSG_LEN
/*
* Definition for flags member of the WSAMSG structure
* This is in addition to other MSG_xxx flags defined
* for recv/recvfrom/send/sendto.
*/
#define MSG_TRUNC 0x0100
#define MSG_CTRUNC 0x0200
#define MSG_BCAST 0x0400
#define MSG_MCAST 0x0800
//
// Flags used in "hints" argument to getaddrinfo()
// - AI_ADDRCONFIG is supported starting with Vista
// - default is AI_ADDRCONFIG ON whether the flag is set or not
// because the performance penalty in not having ADDRCONFIG in
// the multi-protocol stack environment is severe;
// this defaulting may be disabled by specifying the AI_ALL flag,
// in that case AI_ADDRCONFIG must be EXPLICITLY specified to
// enable ADDRCONFIG behavior
//
#define AI_PASSIVE 0x00000001
#define AI_CANONNAME 0x00000002
#define AI_NUMERICHOST 0x00000004
#define AI_NUMERICSERV 0x00000008
#define AI_ALL 0x00000100
#define AI_ADDRCONFIG 0x00000400
#define AI_V4MAPPED 0x00000800
#define AI_NON_AUTHORITATIVE 0x00004000
#define AI_SECURE 0x00008000
#define AI_RETURN_PREFERRED_NAMES 0x00010000
#define AI_FQDN 0x00020000
#define AI_FILESERVER 0x00040000
//
// Structure used in getaddrinfo() call
//
typedef struct addrinfo
{
int ai_flags; // AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST
int ai_family; // PF_xxx
int ai_socktype; // SOCK_xxx
int ai_protocol; // 0 or IPPROTO_xxx for IPv4 and IPv6
size_t ai_addrlen; // Length of ai_addr
char * ai_canonname; // Canonical name for nodename
__field_bcount(ai_addrlen) struct sockaddr * ai_addr; // Binary address
struct addrinfo * ai_next; // Next structure in linked list
}
ADDRINFOA, *PADDRINFOA;
typedef struct addrinfoW
{
int ai_flags; // AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST
int ai_family; // PF_xxx
int ai_socktype; // SOCK_xxx
int ai_protocol; // 0 or IPPROTO_xxx for IPv4 and IPv6
size_t ai_addrlen; // Length of ai_addr
PWSTR ai_canonname; // Canonical name for nodename
__field_bcount(ai_addrlen) struct sockaddr * ai_addr; // Binary address
struct addrinfoW * ai_next; // Next structure in linked list
}
ADDRINFOW, *PADDRINFOW;
typedef struct addrinfoexA
{
int ai_flags; // AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST
int ai_family; // PF_xxx
int ai_socktype; // SOCK_xxx
int ai_protocol; // 0 or IPPROTO_xxx for IPv4 and IPv6
size_t ai_addrlen; // Length of ai_addr
char *ai_canonname; // Canonical name for nodename
struct sockaddr *ai_addr; // Binary address
void *ai_blob;
size_t ai_bloblen;
LPGUID ai_provider;
struct addrinfoexA *ai_next; // Next structure in linked list
} ADDRINFOEXA, *PADDRINFOEXA, *LPADDRINFOEXA;
typedef struct addrinfoexW
{
int ai_flags; // AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST
int ai_family; // PF_xxx
int ai_socktype; // SOCK_xxx
int ai_protocol; // 0 or IPPROTO_xxx for IPv4 and IPv6
size_t ai_addrlen; // Length of ai_addr
PWSTR ai_canonname; // Canonical name for nodename
__field_bcount(ai_addrlen) struct sockaddr *ai_addr; // Binary address
__field_ecount(ai_bloblen) void *ai_blob;
size_t ai_bloblen;
LPGUID ai_provider;
struct addrinfoexW *ai_next; // Next structure in linked list
} ADDRINFOEXW, *PADDRINFOEXW, *LPADDRINFOEXW;
//
// Flags for getaddrinfo()
//
// Name Spaces
#define NS_ALL (0)
#define NS_SAP (1)
#define NS_NDS (2)
#define NS_PEER_BROWSE (3)
#define NS_SLP (5)
#define NS_DHCP (6)
#define NS_TCPIP_LOCAL (10)
#define NS_TCPIP_HOSTS (11)
#define NS_DNS (12)
#define NS_NETBT (13)
#define NS_WINS (14)
#define NS_NLA (15)
#define NS_BTH (16)
#define NS_NBP (20)
#define NS_MS (30)
#define NS_STDA (31)
#define NS_NTDS (32)
#define NS_EMAIL (37)
#define NS_PNRPNAME (38)
#define NS_PNRPCLOUD (39)
#define NS_X500 (40)
#define NS_NIS (41)
#define NS_NISPLUS (42)
#define NS_WRQ (50)
#define NS_NETDES (60)
//
// Flags for getnameinfo()
//
#define NI_NOFQDN 0x01
#define NI_NUMERICHOST 0x02
#define NI_NAMEREQD 0x04
#define NI_NUMERICSERV 0x08
#define NI_DGRAM 0x10
#define NI_MAXHOST 1025
#define NI_MAXSERV 32
#pragma warning(pop)
| 29.418071 | 311 | 0.729044 | [
"object"
] |
3459edfab5d9cafccccdd0e244ae3f411b18da56 | 4,039 | h | C | groups/lsp/lspcore/lspcore_lexer.h | dgoffredo/bdelisp | ea1411cd99aa69605f0a8281fe3be89db09c4aac | [
"blessing"
] | null | null | null | groups/lsp/lspcore/lspcore_lexer.h | dgoffredo/bdelisp | ea1411cd99aa69605f0a8281fe3be89db09c4aac | [
"blessing"
] | null | null | null | groups/lsp/lspcore/lspcore_lexer.h | dgoffredo/bdelisp | ea1411cd99aa69605f0a8281fe3be89db09c4aac | [
"blessing"
] | null | null | null | #ifndef INCLUDED_LSPCORE_LEXER
#define INCLUDED_LSPCORE_LEXER
#include <bdlpcre_regex.h>
#include <bsl_cstddef.h>
#include <bsl_iosfwd.h>
#include <bsl_string_view.h>
#include <bsl_utility.h>
#include <bsl_vector.h>
#include <lspcore_linecounter.h>
namespace BloombergLP {
namespace bslma {
class Allocator;
} // namespace bslma
} // namespace BloombergLP
namespace lspcore {
namespace bdlpcre = BloombergLP::bdlpcre;
namespace bslma = BloombergLP::bslma;
namespace bslstl = BloombergLP::bslstl;
struct LexerToken {
// This 'struct' represents a lexical chunk of text input. It contains a
// 'string_view' of the relevant chunk of text, as well as the text's
// position in the input.
enum Kind {
e_INVALID, // the "not a token" token
e_WHITESPACE,
e_EOF,
e_TRUE,
e_FALSE,
e_STRING,
e_BYTES,
e_DOUBLE,
e_DECIMAL64,
e_INT32,
e_INT64,
e_SYMBOL,
e_OPEN_PARENTHESIS,
e_CLOSE_PARENTHESIS,
e_OPEN_SQUARE_BRACKET,
e_CLOSE_SQUARE_BRACKET,
e_OPEN_CURLY_BRACE,
e_CLOSE_CURLY_BRACE,
e_OPEN_SET_BRACE,
e_QUOTE,
e_QUASIQUOTE,
e_UNQUOTE,
e_UNQUOTE_SPLICING,
e_SYNTAX,
e_QUASISYNTAX,
e_UNSYNTAX,
e_UNSYNTAX_SPLICING,
e_COMMENT_LINE,
e_COMMENT_DATUM,
e_COMMENT_SHEBANG,
e_DATE,
e_TIME,
e_DATETIME,
e_DATETIME_INTERVAL,
e_ERROR_TAG,
e_USER_DEFINED_TYPE_TAG,
e_PAIR_SEPARATOR
};
// Return a pointer to a null-terminated string containing the name of
// the specified token 'kind'. The behavior is undefined unless 'kind'
// is one of the enumerated values.
static const char* toAscii(Kind kind);
Kind kind;
bsl::string_view text;
bsl::size_t offset; // from the beginning of the input
// Lines and columns are numbered starting at one, with the exception of
// newline characters, which are considered to occupy column zero.
// '(beginLine, beginColumn)' refers to the first character of 'text'.
// '(endLine, endColumn)' refers to the character following the last
// character of 'text'.
bsl::size_t beginLine;
bsl::size_t beginColumn;
bsl::size_t endLine;
bsl::size_t endColumn;
LexerToken();
};
// Insert the specified 'token' into the specified 'stream'. Return a
// reference providing modifiable access to 'stream'. Note that the format
// is unspecified and is intended for use in debugging.
bsl::ostream& operator<<(bsl::ostream& stream, const LexerToken& token);
// TODO: document
class Lexer {
bsl::vector<bsl::pair<bsl::size_t, bsl::size_t> > d_results;
bdlpcre::RegEx d_tokenRegex;
bdlpcre::RegEx d_symbolRegex;
bsl::string_view d_subject;
bsl::size_t d_offset;
LineCounter d_position;
LexerToken d_extra; // in case the previous 'next' found two tokens
public:
// TODO: document
explicit Lexer(bslma::Allocator* allocator = 0);
// TODO: document
// TODO: in particular, that the data referred to by 'subject' must
// live until either this object is destroyed or reset is called again.
int reset(bsl::string_view subject);
// Scan the next token in the current subject. On success, assign the
// scanned token through the specified 'token' and return zero. If
// there is no more input, then assign a token of kind 'e_EOF'. If
// input remains but a token cannot be scanned, return a nonzero value
// without assigning through 'token'.
int next(LexerToken* token);
// TODO: document
bsl::size_t offset() const;
// TODO: document
bsl::size_t line() const;
// TODO: document
bsl::size_t column() const;
};
} // namespace lspcore
#endif
| 30.141791 | 76 | 0.636544 | [
"object",
"vector"
] |
346c5022e07216283d44ef40892ab6c6b54f8280 | 3,011 | h | C | src/parallel/Scatter.h | NicoSchlw/tandem | 3a08b5a7ae391c1675c5cbfdad77260d4a0115cc | [
"BSD-3-Clause"
] | 4 | 2021-11-03T17:11:00.000Z | 2022-02-16T07:51:01.000Z | src/parallel/Scatter.h | NicoSchlw/tandem | 3a08b5a7ae391c1675c5cbfdad77260d4a0115cc | [
"BSD-3-Clause"
] | 12 | 2020-05-18T14:51:13.000Z | 2021-12-16T12:56:31.000Z | src/parallel/Scatter.h | NicoSchlw/tandem | 3a08b5a7ae391c1675c5cbfdad77260d4a0115cc | [
"BSD-3-Clause"
] | 2 | 2020-10-23T08:04:42.000Z | 2021-11-15T12:23:59.000Z | #ifndef SCATTER_20200715_H
#define SCATTER_20200715_H
#include "interface/BlockVector.h"
#include "parallel/MPITraits.h"
#include "parallel/ScatterPlan.h"
#include "parallel/SparseBlockVector.h"
#include "tensor/Tensor.h"
#include <mpi.h>
#include <cassert>
#include <cstddef>
#include <memory>
#include <vector>
namespace tndm {
class Scatter {
public:
using byte_t = unsigned char;
Scatter(std::shared_ptr<ScatterPlan> topo) : topo_(std::move(topo)) {
requests_.resize(topo_->recv_blocks().size() + topo_->send_blocks().size(),
MPI_REQUEST_NULL);
}
template <typename T>
auto recv_prototype(std::size_t block_size,
std::size_t alignment = SparseBlockVector<T>::DefaultAlignment) const {
return SparseBlockVector<T>(topo_->recv_indices(), block_size, alignment);
}
template <typename T> void begin_scatter(BlockVector const& x, SparseBlockVector<T>& y) {
static_assert(std::is_same_v<BlockVector::value_type, T>,
"Basic type of x and y must match");
assert(x.block_size() == y.block_size());
const auto mpiType = mpi_type_t<T>();
std::size_t bs = x.block_size();
auto const resizeIfNecessary = [](std::vector<byte_t>& buffer, std::size_t size) {
std::size_t requiredSize = sizeof(T) * size;
if (requiredSize > buffer.size()) {
buffer.resize(requiredSize);
}
};
resizeIfNecessary(send_buffer_, bs * topo_->send_indices().size());
T* sendBuf = reinterpret_cast<T*>(send_buffer_.data());
std::size_t requestNo = 0;
for (auto const& block : topo_->recv_blocks()) {
int size = block.count * bs;
MPI_Irecv(&y.data()[block.offset * bs], size, mpiType, block.source_or_dest, 0,
topo_->comm(), &requests_[requestNo++]);
}
auto x_handle = x.begin_access_readonly();
for (std::size_t i = 0; i < topo_->send_indices().size(); ++i) {
auto idx = topo_->send_indices()[i];
auto block = x_handle.subtensor(slice{}, idx);
memcpy(&sendBuf[i * bs], block.data(), bs * sizeof(T));
}
x.end_access_readonly(x_handle);
for (auto const& block : topo_->send_blocks()) {
int size = block.count * bs;
MPI_Isend(&sendBuf[block.offset * bs], size, mpiType, block.source_or_dest, 0,
topo_->comm(), &requests_[requestNo++]);
}
assert(requestNo == requests_.size());
}
void test_scatter() {
int flag;
MPI_Testall(requests_.size(), requests_.data(), &flag, MPI_STATUSES_IGNORE);
}
void wait_scatter() { MPI_Waitall(requests_.size(), requests_.data(), MPI_STATUSES_IGNORE); }
private:
std::shared_ptr<ScatterPlan> topo_;
std::vector<MPI_Request> requests_;
std::vector<byte_t> send_buffer_;
};
} // namespace tndm
#endif // SCATTER_20200715_H
| 33.455556 | 97 | 0.612089 | [
"vector"
] |
3485eadf92061aca778c635f60e11e3a9599ba53 | 2,215 | c | C | frameworks/C/libreactor/src/main.c | TaurusMindset/FrameworkBenchmarks | 8cbf35a5f5f551d5ba76d805506958cfe78317c2 | [
"BSD-3-Clause"
] | 1 | 2020-07-16T05:01:32.000Z | 2020-07-16T05:01:32.000Z | frameworks/C/libreactor/src/main.c | TaurusMindset/FrameworkBenchmarks | 8cbf35a5f5f551d5ba76d805506958cfe78317c2 | [
"BSD-3-Clause"
] | null | null | null | frameworks/C/libreactor/src/main.c | TaurusMindset/FrameworkBenchmarks | 8cbf35a5f5f551d5ba76d805506958cfe78317c2 | [
"BSD-3-Clause"
] | 2 | 2018-03-22T00:37:28.000Z | 2018-03-22T00:56:57.000Z | #include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <err.h>
#include <dynamic.h>
#include <reactor.h>
#include <clo.h>
#include "setup.h"
#include "helpers.h"
#define JSON_PREAMBLE "HTTP/1.1 200 OK\r\n"\
"Server: libreactor\r\n"\
"Content-Type: application/json\r\n"
#define TEXT_PREAMBLE "HTTP/1.1 200 OK\r\n"\
"Server: libreactor\r\n"\
"Content-Type: text/plain\r\n"
void plaintext(server_context *context, char *response)
{
static const segment text_preamble = { .base = TEXT_PREAMBLE, .size = sizeof(TEXT_PREAMBLE) - 1 };
write_response(&context->session->stream, text_preamble, segment_string(response));
}
void json(server_context *context, clo *json_object)
{
static const segment json_preamble = { .base = JSON_PREAMBLE, .size = sizeof(JSON_PREAMBLE) - 1 };
static char json_string[4096];
(void) clo_encode(json_object, json_string, sizeof(json_string));
write_response(&context->session->stream, json_preamble, segment_string(json_string));
}
static core_status server_handler(core_event *event)
{
static char hello_string[] = "Hello, World!";
static char default_string[] = "Hello from libreactor!\n";
static clo_pair json_pair[] = {{ .string = "message", .value = { .type = CLO_STRING, .string = "Hello, World!" }}};
static clo json_object[] = {{ .type = CLO_OBJECT, .object = json_pair }};
server *server = event->state;
server_context *context = (server_context *) event->data;
if (event->type == SERVER_REQUEST){
if (segment_equal(context->request.target, segment_string("/json"))){
json(context, json_object);
}
else if (segment_equal(context->request.target, segment_string("/plaintext"))){
plaintext(context, hello_string);
}
else{
plaintext(context, default_string);
}
return CORE_OK;
}
else {
warn("error");
server_destruct(server);
return CORE_ABORT;
}
}
int main()
{
server s;
setup();
core_construct(NULL);
server_construct(&s, server_handler, &s);
server_open(&s, 0, 8080);
core_loop(NULL);
core_destruct(NULL);
} | 28.037975 | 117 | 0.665463 | [
"object"
] |
34878e1f1df935bab6e35b17ff49eccad983fec6 | 1,074 | h | C | toolboxes/mri/hyper/CSIOperator.h | roopchansinghv/gadgetron | fb6c56b643911152c27834a754a7b6ee2dd912da | [
"MIT"
] | 1 | 2022-02-22T21:06:36.000Z | 2022-02-22T21:06:36.000Z | toolboxes/mri/hyper/CSIOperator.h | apd47/gadgetron | 073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2 | [
"MIT"
] | null | null | null | toolboxes/mri/hyper/CSIOperator.h | apd47/gadgetron | 073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2 | [
"MIT"
] | null | null | null | /*
* CSIOperator.h
*
* Created on: Nov 10, 2014
* Author: dch
*/
#ifndef CSIOPERATOR_H_
#define CSIOPERATOR_H_
#include "linearOperator.h"
#include "cuNDArray.h"
namespace Gadgetron {
template <class T> class CSIOperator: public Gadgetron::linearOperator<cuNDArray<complext<T>>> {
public:
CSIOperator();
CSIOperator(T dtt, T dte);
virtual ~CSIOperator();
virtual void mult_M(cuNDArray<complext<T>>* in, cuNDArray<complext<T>>* out,bool accumulate );
virtual void mult_MH(cuNDArray<complext<T>>* in, cuNDArray<complext<T>>* out,bool accumulate );
void set_senseOp(boost::shared_ptr<linearOperator<cuNDArray<complext<T>>>> op){ senseOp = op;}
void set_frequencies(std::vector<T>& freq);
cuNDArray<T> get_frequencies(){
return frequencies;
}
T get_echotime(){ return dte_;}
T get_pointtime(){return dtt_;}
protected:
boost::shared_ptr<linearOperator<cuNDArray<complext<T>>>> senseOp;
T dte_; //Time between echoes
T dtt_; //Time between k-space points
cuNDArray<T> frequencies;
};
} /* namespace Gadgetron */
#endif /* CSIOPERATOR_H_ */
| 23.866667 | 96 | 0.724395 | [
"vector"
] |
348a69ec50f66be3ad99b014d2db0d11f5103c22 | 51,181 | c | C | Microsoft/SAMPLES/status/multithr/status.c | tig/Tigger | 8e06d117a5b520c5fc9e37a710bf17aa51a9958c | [
"MIT",
"Unlicense"
] | 1 | 2021-08-02T01:36:43.000Z | 2021-08-02T01:36:43.000Z | Microsoft/SAMPLES/status/status.c | mdileep/Tigger | 8e06d117a5b520c5fc9e37a710bf17aa51a9958c | [
"MIT",
"Unlicense"
] | null | null | null | Microsoft/SAMPLES/status/status.c | mdileep/Tigger | 8e06d117a5b520c5fc9e37a710bf17aa51a9958c | [
"MIT",
"Unlicense"
] | 1 | 2022-01-04T21:13:01.000Z | 2022-01-04T21:13:01.000Z | /************************************************************************
*
* Project: Windows Sample Applications
*
* Module: status.c
*
* Author(s): Charles E. Kindel, Jr. (ckindel)
*
* Remarks:
* This module contains all functions used to display a 3d looking
* status line (window) within a parent window.
*
* STATUS is a 'Single Source' custom control. That is, it will
* compile and work correctly on both Win16 (3.1) and Win32.
*
* Revisions:
* 01.00.000 9/25/91 cek Made into a sample
* 02.00.000 1/3/92 cek Make compatible with Win32
* 02.01.000 4/18/92 cek Fixed SysColor() stuff
* 02.02.000 5/6/92 cek Fixed flasing
* 02.03.000 5/12/92 cek Merged with another version
* 02.04.000 11/12/92 cek Added some comments.
*
************************************************************************/
//#include "PRECOMP.H"
//#define IN_A_DLL
#if 1
#define _WINDLL
#define STRICT
#define SHADOWSTUFF // define this if we're not linking to tdutil
#include <windows.h>
#include <windowsx.h>
#include <wdb.h>
#include "status.h"
#endif
/*************************************************************************
* Local Defines
*************************************************************************/
#define MAX_STATLEN 128
//
// The handle that is passed to CreateMsgWindow is stored in the
// cbWndExtra part of the child window. This flag is used to
// retrieve that data:
//
#define NUM_EXTRABYTES (sizeof(LPVOID) + sizeof(HFONT))
#define GWL_LPSTATUS 0
#define GWW_HFONT (GWL_LPSTATUS + sizeof(LPVOID))
#define LINEWIDTH ((int)1)
#define SW_ERR ((LRESULT)(-1))
/*************************************************************************
* Macros
*************************************************************************/
#define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
/*
* These macros all act on window longs. They will all work in both
* Win16 and Win32.
*/
#define GETSTYLE(hWnd) LOWORD( GetWindowLong( hWnd, GWL_STYLE ) )
#define GETLPSTATUS(hWnd) (LPSTATUS)GetWindowLong( hWnd, GWL_LPSTATUS )
#define SETLPSTATUS(hWnd,lp) (LPSTATUS)SetWindowLong( hWnd, GWL_LPSTATUS, (LONG)lp )
/*
* Since the size of HFONT and HINSTANCE change between 16 and 32 we
* need different macros
*/
#ifndef WIN32
#define GETHINST(hwnd) (HINSTANCE)GetWindowWord( hwnd, GWW_HINSTANCE )
#define GETHFONT(hWnd) (HFONT)GetWindowWord( hWnd, GWW_HFONT )
#define SETHFONT(hWnd,hf) (HFONT)SetWindowWord( hWnd, GWW_HFONT, (WORD)hf )
#define GETID(hWnd) (WORD)GetWindowWord( hWnd, GWW_ID )
#define GALLOC(cb) GlobalAllocPtr( GHND, cb )
#define GFREE(lp) GlobalFreePtr( lp )
#else
#define GETHINST(hwnd) (HINSTANCE)GetWindowLong( hwnd, GWL_HMODULE )
#define GETHFONT(hWnd) (HFONT)GetWindowLong( hWnd, GWW_HFONT )
#define SETHFONT(hWnd,hf) (HFONT)SetWindowLong( hWnd, GWW_HFONT, (LONG)hf )
#define GETID(hWnd) (WORD)GetWindowLong( hWnd, GWL_ID )
#define GALLOC(cb) malloc(cb)
#define GFREE(lp) free(lp)
#endif
/************************************************************************
* Local data structures
************************************************************************/
// structure for status boxes
typedef struct tagSTATBOX
{
RECT rect ; // coordinates of Stat Box or msg
COLORREF rgbColor ; // Color of text
WORD wJustify ;
BOOL fColorSet : 1 ; // Is the color set?
BOOL fBorder : 1 ;
BOOL fTouched : 1 ; // TRUE if CurStat has changed since
// last WM_PAINT
BOOL fOwnerDraw : 1 ;
/* These last two are not used by msg */
LONG wWidth ; // Width of box in pixels
char szCurStat[MAX_STATLEN] ;// Current status
} STATBOX, *PSTATBOX, FAR *LPSTATBOX ;
//
// MSG/STATLINE data structures
//
// This structure is the main instance data structure for STATUS.
// All information about the message (msg) and stat boxes is contained
// here. The first element of rgStatBox is the msg.
//
typedef struct tagSTATUS
{
WORD wNumStats ; // Number of status boxes
GLOBALHANDLE hszDefault ;
BOOL fNoMsg ;
STATBOX rgStatBox[1] ; // rgStat[0] is for msg
} STATUS, *PSTATUS, FAR *LPSTATUS ;
/************************************************************************
* Internal APIs and data structures for MSG/STATLINES
************************************************************************/
static BOOL NEAR PASCAL IsRectInRect( LPRECT lpR1, LPRECT lpR2 ) ;
static BOOL NEAR PASCAL StatusCreate( HWND hWnd, LPCREATESTRUCT lp ) ;
/*
* wID is always 16 bits since it must be packed in wParam or lParam as
* a notification code.
*/
static void NEAR PASCAL StatusInvalidate( HWND hWnd, WORD wID ) ;
static void NEAR PASCAL StatusPaint( HWND hWnd ) ;
static BOOL NEAR PASCAL CheckClick( HWND, LPARAM, LPWORD ) ;
static int NEAR PASCAL StatGetWidth( HWND hWnd, LPSTR lpszText ) ;
static BOOL NEAR PASCAL DrawItem( HWND hwnd, LPPAINTSTRUCT lpps,
LPSTATBOX lpStatBox, UINT uiID, LPSTR lpszText ) ;
LRESULT WINAPI
fnStatus( HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam ) ;
/*************************************************************************
* Local Variables
*************************************************************************/
UINT wExtraSpace = 1 ;
/*************************************************************************
* window class names
*************************************************************************/
char szStatusClassName[] = SZ_STATUSCLASSNAME ;
/*************************************************************************
* BOOL WINAPI StatusInit( HINSTANCE hPrev, HINSTANCE hInstance )
*
* Description:
*
* Registers the window class.
*
* Comments:
*
*************************************************************************/
BOOL WINAPI StatusInit( HINSTANCE hPrev, HINSTANCE hInstance, LPSTR lpszClassName )
{
WNDCLASS wc ;
if (!hPrev)
{
//
// Register the Child Windows class
//
#ifdef IN_A_DLL
wc.style = CS_DBLCLKS |
CS_VREDRAW |
CS_HREDRAW |
CS_GLOBALCLASS ;
#else
wc.style = CS_DBLCLKS |
CS_VREDRAW |
CS_HREDRAW ;
#endif
wc.lpfnWndProc = (WNDPROC)fnStatus ;
wc.cbClsExtra = 0 ;
//
// cbWndExtra holds a handle to the STATUS structure
//
wc.cbWndExtra = NUM_EXTRABYTES ;
wc.hInstance = hInstance ;
wc.hIcon = NULL ;
wc.hCursor = LoadCursor( NULL, IDC_ARROW ) ;
wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1) ;
wc.lpszMenuName = NULL ;
if (lpszClassName)
wc.lpszClassName = lpszClassName ;
else
wc.lpszClassName = szStatusClassName ;
if (RegisterClass( &wc ))
/*
* always return true. Register class will return failure if
* the class was already registerd, but that's no big deal because
* we have used a very unique class name (haven't we?).
*/
return TRUE ;
}
return TRUE ;
}/* StatusInit() */
/************************************************************************
* LPARAM WINAPI
* fnStatus( HWND hWnd, int iMessage, WPARAM wParam, LPARAM lParam ) ;
*
* Description:
* Default window proc for message line window.
*
* Comments:
*
************************************************************************/
LRESULT WINAPI fnStatus( HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam )
{
LPSTATUS lpStatus ;
LRESULT lRetVal = 0L ;
switch (wMsg)
{
case WM_CREATE :
if (!StatusCreate( hWnd, (LPCREATESTRUCT)lParam ))
return SW_ERR ;
break ;
case ST_GETHEIGHT:
{
HDC hDC ;
HFONT hFont ;
TEXTMETRIC tm ;
if (hDC = GetDC (hWnd))
{
hFont = SelectObject( hDC, GETHFONT( hWnd ) ) ;
GetTextMetrics( hDC, &tm ) ;
SelectObject( hDC, hFont ) ;
ReleaseDC (hWnd, hDC) ;
return (LRESULT)(LONG)(tm.tmHeight + tm.tmExternalLeading +
(LINEWIDTH * 4) + wExtraSpace +
(GetSystemMetrics( SM_CYBORDER ) * 2)) ;
}
else
{
return 0L ;
}
}
break ;
case ST_GETSTATUSWIDTH:
return MAKELRESULT( StatGetWidth( hWnd, (LPSTR)lParam ), 0 ) ;
break ;
case ST_SETSTATBOXSIZE:
lpStatus = GETLPSTATUS( hWnd ) ;
if (lpStatus)
{
if ((WORD)wParam < lpStatus->wNumStats)
{
lpStatus->rgStatBox[(WORD)wParam+1].wWidth = (LONG)lParam ;
StatusInvalidate( hWnd, (WORD)0xFFFF ) ;
InvalidateRect( hWnd, NULL, TRUE ) ;
}
else
lRetVal = SW_ERR ;
}
else
return SW_ERR ;
break ;
case ST_SETCOLOR:
lpStatus = GETLPSTATUS( hWnd ) ;
if (lpStatus)
{
if ((int)wParam == -1)
{
lpStatus->rgStatBox[0].fTouched = TRUE ;
lpStatus->rgStatBox[0].fColorSet = TRUE ;
lpStatus->rgStatBox[0].rgbColor = (COLORREF)lParam ;
StatusInvalidate( hWnd, 0 ) ;
}
else
{
if ((WORD)wParam < lpStatus->wNumStats)
{
lpStatus->rgStatBox[(WORD)wParam+1].fTouched = TRUE ;
lpStatus->rgStatBox[(WORD)wParam+1].fColorSet = TRUE ;
lpStatus->rgStatBox[(WORD)wParam+1].rgbColor = (COLORREF)lParam ;
StatusInvalidate( hWnd, (WORD)(LOWORD( wParam ) + 1) ) ;
}
else
lRetVal = SW_ERR ;
}
}
else
return SW_ERR ;
break ;
case WM_SETTEXT :
{
UINT cb = GetWindowTextLength( hWnd ) ;
/* Minimize flashing */
if (cb)
{
LPSTR lpszText = GlobalAllocPtr( GHND, cb + 1 ) ;
if (lpszText)
{
GetWindowText( hWnd, lpszText, cb + 1 ) ;
if (lstrcmp( lpszText, (LPSTR)lParam ) != 0)
{
if ((lpStatus = GETLPSTATUS( hWnd )) && !lpStatus->fNoMsg)
{
lpStatus->rgStatBox[0].fTouched = TRUE ;
StatusInvalidate( hWnd, 0 ) ;
}
}
GlobalFreePtr( lpszText ) ;
}
}
}
return DefWindowProc( hWnd, wMsg, wParam, lParam ) ;
case ST_SETSTATBOX :
lpStatus = GETLPSTATUS( hWnd ) ;
if (lpStatus &&
(WORD)wParam < lpStatus->wNumStats &&
lstrlen( (LPSTR)lParam ) < MAX_STATLEN &&
lstrcmp( (LPSTR)lParam,
lpStatus->rgStatBox[(WORD)wParam+1].szCurStat ) != 0)
{
lpStatus->rgStatBox[(WORD)wParam+1].fTouched = TRUE ;
lstrcpy( lpStatus->rgStatBox[(WORD)wParam+1].szCurStat, (LPSTR)lParam ) ;
StatusInvalidate( hWnd, (WORD)(LOWORD( wParam ) + 1) ) ;
}
else
return SW_ERR ;
break ;
case ST_SETBORDER: // wParam == -1 is message line
lpStatus = GETLPSTATUS( hWnd ) ;
if (lpStatus)
{
if ((int)wParam == -1)
lpStatus->rgStatBox[0].fBorder = (BOOL)LOWORD( lParam ) ? TRUE : FALSE ;
else
{
if ((WORD)wParam < lpStatus->wNumStats)
{
lpStatus->rgStatBox[(WORD)wParam+1].fBorder = (BOOL)LOWORD( (LONG)lParam ) ? TRUE : FALSE ;
}
else
lRetVal = SW_ERR ;
}
StatusInvalidate( hWnd, (WORD)0xFFFF ) ;
InvalidateRect( hWnd, NULL, TRUE ) ;
UpdateWindow( hWnd ) ;
}
else
return SW_ERR ;
break ;
case ST_SETJUSTIFY:
lpStatus = GETLPSTATUS( hWnd ) ;
if (lpStatus)
{
if ((int)wParam == -1)
{
lpStatus->rgStatBox[0].wJustify = LOWORD( lParam ) ;
lpStatus->rgStatBox[0].fTouched = TRUE ;
StatusInvalidate( hWnd, 0 ) ;
}
else
{
if ((WORD)wParam < lpStatus->wNumStats)
{
lpStatus->rgStatBox[(WORD)wParam+1].wJustify = LOWORD( lParam ) ;
lpStatus->rgStatBox[(WORD)wParam+1].fTouched = TRUE ;
}
else
lRetVal = SW_ERR ;
StatusInvalidate( hWnd, (WORD)(LOWORD( wParam ) + 1) ) ;
}
UpdateWindow( hWnd ) ;
}
else
return SW_ERR ;
break ;
case ST_SETOWNERDRAW:
lpStatus = GETLPSTATUS( hWnd ) ;
if (lpStatus)
{
if ((int)wParam == -1)
{
lpStatus->rgStatBox[0].fOwnerDraw = (BOOL)LOWORD( lParam ) ? TRUE : FALSE ;
lpStatus->rgStatBox[0].fTouched = TRUE ;
StatusInvalidate( hWnd, 0 ) ;
}
else
{
if ((WORD)wParam < lpStatus->wNumStats)
{
lpStatus->rgStatBox[(WORD)wParam+1].fOwnerDraw = (BOOL)LOWORD( lParam ) ? TRUE : FALSE ;
lpStatus->rgStatBox[(WORD)wParam+1].fTouched = TRUE ;
}
else
lRetVal = SW_ERR ;
StatusInvalidate( hWnd, (WORD)(LOWORD( wParam ) + 1) ) ;
}
UpdateWindow( hWnd ) ;
}
else
return SW_ERR ;
break ;
case ST_GETSTATBOXRECT:
lpStatus = GETLPSTATUS( hWnd ) ;
if (lpStatus)
{
RECT rc ;
if ((int)wParam == -1)
(int)wParam = 0 ;
else
(int)wParam++ ;
if (lpStatus->rgStatBox[wParam].fBorder)
{
rc.top = lpStatus->rgStatBox[wParam].rect.top + (int)wExtraSpace ;
rc.bottom = lpStatus->rgStatBox[wParam].rect.bottom - (int)LINEWIDTH ;
rc.left = lpStatus->rgStatBox[wParam].rect.left + (int)(LINEWIDTH) ;
rc.right = lpStatus->rgStatBox[wParam].rect.right - (int)(LINEWIDTH) ;
}
else
{
rc.top = lpStatus->rgStatBox[wParam].rect.top + (int)wExtraSpace - 1 ;
rc.bottom = lpStatus->rgStatBox[wParam].rect.bottom - (int)LINEWIDTH + 1 ;
rc.left = lpStatus->rgStatBox[wParam].rect.left ;
rc.right = lpStatus->rgStatBox[wParam].rect.right ;
}
*(LPRECT)lParam = rc ;
}
else
return SW_ERR ;
break ;
case ST_SETDEFAULTTEXT:
/*
* This message allows you to set the default text that
* is used by the message bar. Whenever the window text
* is set to "" the default text will be displayed.
*/
if (!lParam)
return SW_ERR ;
if (lpStatus = GETLPSTATUS( hWnd ))
{
if (lpStatus->hszDefault)
{
GlobalFree( lpStatus->hszDefault ) ;
}
if (lpStatus->hszDefault = GlobalAlloc( GHND,
lstrlen( (LPSTR)lParam ) + 1 ))
{
LPSTR lpsz = GlobalLock( lpStatus->hszDefault ) ;
lstrcpy( lpsz, (LPSTR)lParam ) ;
GlobalUnlock( lpStatus->hszDefault ) ;
}
if (!lpStatus->fNoMsg)
{
lpStatus->rgStatBox[0].fTouched = TRUE ;
StatusInvalidate( hWnd, 0 ) ;
}
}
else
return SW_ERR ;
break ;
case WM_MBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
case WM_LBUTTONDBLCLK:
{
WORD wID ;
if (!IsWindowEnabled( hWnd ))
return 0L ;
if (CheckClick( hWnd, lParam, &wID ))
{
//
// Post a message to the parent. We used to send
// wParam as the LOWORD of lParam instead of hWnd. but
// as of Win 3.1 we discovered that this is frowned upon
// and 3.1 debug tells us so. Since this is a sample,
// and we really shouldn't do anything illegal we will comply.
//
// Thus you want to find out the key states on the double
// click, add a new ST_ message like ST_GETLASTCOMMANDINFO
// or some such.
//
#ifndef WIN32
PostMessage( GetParent( hWnd ), WM_COMMAND, (WPARAM)GETID( hWnd ),
(LPARAM)MAKELONG( hWnd, wID ) ) ;
#else
PostMessage( GetParent( hWnd ), WM_COMMAND,
(WPARAM)MAKELONG( GETID( hWnd ), wID ),
(LPARAM)hWnd ) ;
#endif
}
}
return 0L ;
case WM_SIZE:
StatusInvalidate( hWnd, (WORD)0xFFFF ) ;
break ;
case WM_PAINT :
StatusPaint( hWnd ) ;
break ;
case WM_GETFONT:
return MAKELRESULT( GETHFONT( hWnd ), 0 ) ;
case WM_SETFONT:
{
HFONT hFontOld = GETHFONT( hWnd ) ;
if (wParam)
SETHFONT( hWnd, wParam ) ;
if (lParam)
{
StatusInvalidate( hWnd, (WORD)0xFFFF ) ;
InvalidateRect( hWnd, NULL, TRUE ) ;
}
return MAKELRESULT( hFontOld, 0 ) ;
}
break ;
case WM_DESTROY :
//
// Get the handle from the Window extra bytes
//
lpStatus = GETLPSTATUS( hWnd ) ;
// free the memory
//
if (lpStatus)
{
if (lpStatus->hszDefault)
GlobalFree( lpStatus->hszDefault ) ;
GFREE( lpStatus ) ;
}
break ;
default :
return DefWindowProc( hWnd, wMsg, wParam, lParam ) ;
} // switch (wMsg)
return lRetVal ;
} /* fnStatus() */
/*************************************************************************
* WORD WINAPI StatGetWidth( HWND hWnd, LPSTR lpszText )
*
* Description:
*
*
*
* Comments:
*
*************************************************************************/
int NEAR PASCAL StatGetWidth( HWND hWnd, LPSTR lpszText )
{
if (!hWnd)
{
return FALSE ;
}
if (lstrlen( lpszText ))
{
LPSTATUS lpStatus ;
HDC hDC ;
HANDLE hFont ;
int nWidth ;
//
// get the global handle from the window extra bytes
//
lpStatus = GETLPSTATUS( hWnd ) ;
if (!lpStatus)
return 0 ;
if (hDC = GetDC (hWnd))
{
#ifdef WIN32
SIZE size ;
#endif
hFont = SelectObject( hDC, GETHFONT( hWnd ) ) ;
// Get Width
#ifndef WIN32
nWidth = LOWORD( GetTextExtent( hDC,
(LPSTR)lpszText, lstrlen( lpszText ) ) );
#else
GetTextExtentPoint( hDC, (LPSTR)lpszText, lstrlen( lpszText ), &size ) ;
nWidth = size.cx ;
#endif
SelectObject( hDC, hFont ) ;
ReleaseDC( hWnd, hDC ) ;
}
else
{
return LINEWIDTH * 4 ;
}
return nWidth + (int)(LINEWIDTH * 4) ;
}
return (int)LINEWIDTH * 4 ;
}/* StatGetWidth() */
/************************************************************************
* Internal APIs and data structures for MSG/STATLINES
************************************************************************/
/*************************************************************************
* static BOOL StatusCreate( HWND hWnd, LPCREATESTRUCT lpCS )
*
* Description:
* Handles the WM_CREATE message.
*
* Returns FALSE if something went wrong.
*
* Comments:
*
*************************************************************************/
static BOOL NEAR PASCAL StatusCreate( HWND hWnd, LPCREATESTRUCT lpCS )
{
LPSTATUS lpStatus ;
UINT i ;
WORD wNumStats ;
if (lpCS->lpCreateParams)
wNumStats = *(LPWORD)lpCS->lpCreateParams ;
else
wNumStats = 0 ;
//
// Allocate the memory for the stat boxes and message line
//
if (!(lpStatus = GALLOC( sizeof( STATUS ) +
(sizeof( STATBOX ) * wNumStats) )))
{
return FALSE ;
}
//
// Get structure and do some setting up
//
lpStatus->wNumStats = wNumStats ;
if (lpCS->lpszName)
lpStatus->fNoMsg = FALSE ;
else
lpStatus->fNoMsg = TRUE ;
lpStatus->rgStatBox[0].wJustify = DT_LEFT ;
lpStatus->rgStatBox[0].rgbColor = GetSysColor( COLOR_BTNTEXT ) ;
lpStatus->rgStatBox[0].fTouched = TRUE ;
lpStatus->rgStatBox[0].fBorder = FALSE ;
lpStatus->rgStatBox[0].fOwnerDraw = FALSE ;
lpStatus->rgStatBox[0].fColorSet = FALSE ;
for (i = 0 ; i < lpStatus->wNumStats ; i++)
{
lpStatus->rgStatBox[i+1].wJustify = DT_CENTER ;
lpStatus->rgStatBox[i+1].fTouched = TRUE ;
lpStatus->rgStatBox[i+1].fBorder = TRUE ;
lpStatus->rgStatBox[i+1].fColorSet = FALSE ;
lpStatus->rgStatBox[i+1].fOwnerDraw = FALSE ;
lpStatus->rgStatBox[i+1].rgbColor = GetSysColor( COLOR_BTNTEXT ) ;
}
//
// Store the handle in the window extra bytes at GWW_LPSTATUS
//
SETLPSTATUS( hWnd, lpStatus ) ;
SETHFONT( hWnd, GetStockObject( SYSTEM_FONT ) ) ;
return TRUE ;
}
/* StatusCreate() */
/*************************************************************************
* static void StatusInvalidate( HWND hWnd, WORD wID )
*
* Description:
* Invalidates the specified element of the status line. The message
* part is 0, and the first stat box is 1. Setting wID to (WORD)0xFFFF
* invalidates the entire status line, forcing a complete redraw and
* and re-calculation.
*
* Type/Parameter
* Description
* HWND hWNd
* Window handle.
*
* WORD wID
* ID of the element to be invalidated, 0 = message, 1 = 1st stat
* box, 2 = 2nd stat box, etc... (UINT)-1 = recalc and invalidate all.
*
* Return Value
* Returns one of the following values:
*
* Value
* Meaning
*
*
* Comments:
*
*************************************************************************/
static void NEAR PASCAL StatusInvalidate( HWND hWnd, WORD wID )
{
LPSTATUS lpStatus ;
LPSTATBOX rgStatBox ;
WORD i ;
RECT rc ;
if (hWnd == 0)
return ;
lpStatus= GETLPSTATUS( hWnd ) ;
if (lpStatus == 0)
{
DP1( hWDB, "StatusInvalidate : lpStatus == NULL!" ) ;
return ;
}
rgStatBox = &lpStatus->rgStatBox[0] ;
if (wID == (WORD)0xFFFF)
{
int wHeight ;
RECT rc ;
HDC hDC ;
HANDLE hFont ;
TEXTMETRIC tm ;
//
// Figure out where the window should be
//
// Calculate all rects and store them
if (hDC = GetDC (hWnd))
{
hFont = SelectObject( hDC, GETHFONT( hWnd ) ) ;
GetTextMetrics( hDC, &tm ) ;
SelectObject( hDC, hFont ) ;
ReleaseDC (hWnd, hDC) ;
}
else
{
return ;
}
wHeight = tm.tmHeight +
tm.tmExternalLeading + (LINEWIDTH * 4)+wExtraSpace ;
//
// Set the rects for all boxes
//
// start with MsgLine
//
GetClientRect( hWnd, &rc ) ;
// Move in from the edges
rc.left += LINEWIDTH * 6 ;
rc.top += LINEWIDTH * 2 ;
rc.bottom -= LINEWIDTH * 2 ;
rc.right -= LINEWIDTH * 6 ;
//
// Depending on whether there is a message, we handle things a bit
// differently. If there is a message then we make the stat boxes
// flush right, calculating from right to left.
// If, however, there is going to be no message, then we must make
// the statboxes flush left, calculating from left to right...
//
if (lpStatus->fNoMsg)
{
// Calculate from left to right
//
for (i = 0 ; i < lpStatus->wNumStats ; i++)
{
rgStatBox[i+1].rect.left = rc.left ;
rgStatBox[i+1].rect.top = rc.top ;
rgStatBox[i+1].rect.bottom = rc.bottom ;
rgStatBox[i+1].rect.right = rc.left + (int)rgStatBox[i+1].wWidth +
(int)(2 * LINEWIDTH) ;
rc.left = rgStatBox[i+1].rect.right + (int)(2 * LINEWIDTH) ;
rgStatBox[i+1].fTouched = TRUE ;
}
}
else
{
DP5( hWDB, "fNoMsg == FALSE" ) ;
// Calculate from right to left.
//
for (i = lpStatus->wNumStats ; i > 0 ; i--)
{
rgStatBox[i].rect.right = rc.right ;
//
// left - 2*lw for border.
//
rgStatBox[i].rect.left = rc.right - (int)rgStatBox[i].wWidth -
(int)(2 * LINEWIDTH) ;
rgStatBox[i].rect.top = rc.top ;
rgStatBox[i].rect.bottom = rc.bottom ;
rc.right = rgStatBox[i].rect.left - (int)(LINEWIDTH * 2) ;
rgStatBox[i].fTouched = TRUE ;
}
if (lpStatus->wNumStats)
rgStatBox[0].rect.right = rc.right - (int)(LINEWIDTH * 9) ;
else
rgStatBox[0].rect.right = rc.right - (int)(LINEWIDTH * 4) ;
rgStatBox[0].rect.top = rc.top ;
rgStatBox[0].rect.bottom = rc.bottom ;
rgStatBox[0].rect.left = rc.left ;
rgStatBox[0].fTouched = TRUE ;
}
//
// Invalidate the whole window
//
// InvalidateRect( hWnd, NULL, TRUE ) ;
} // if INVALIDATEALL
else
{
DP5( hWDB, "StatusInvalidate : ID Passed in" ) ;
//
// Invalidate the ID passed in
//
if ((!lpStatus->fNoMsg) && wID == 0 && rgStatBox[0].fTouched)
{
rc.top = rgStatBox[0].rect.top + LINEWIDTH ;
rc.left = rgStatBox[0].rect.left + LINEWIDTH ;
rc.bottom = rgStatBox[0].rect.bottom - LINEWIDTH ;
rc.right = rgStatBox[0].rect.right - LINEWIDTH ;
InvalidateRect( hWnd, (LPRECT)&rc, TRUE ) ;
}
if (lpStatus->wNumStats && wID > 0 && rgStatBox[wID].fTouched)
{
rc.top = rgStatBox[wID].rect.top + LINEWIDTH ;
rc.left = rgStatBox[wID].rect.left + LINEWIDTH ;
rc.bottom = rgStatBox[wID].rect.bottom - LINEWIDTH ;
rc.right = rgStatBox[wID].rect.right - LINEWIDTH ;
InvalidateRect( hWnd, (LPRECT)&rc, TRUE ) ;
}
}
}
/* StatusInvalidate() */
/*************************************************************************
* static void StatusPaint( HWND hWnd )
*
* Description:
*
* Handles painting.
*
* Comments:
*
*************************************************************************/
static void NEAR PASCAL StatusPaint( HWND hWnd )
{
LPSTATUS lpStatus ;
LPSTATBOX rgStatBox ;
int i ;
HANDLE hFont ;
RECT r1 ;
RECT r2 ;
COLORREF rgbBtnFace ;
PAINTSTRUCT ps ;
TEXTMETRIC tm ;
GetClientRect( hWnd, &r1 ) ;
lpStatus = GETLPSTATUS( hWnd ) ;
if (lpStatus == 0)
return ;
if (!BeginPaint( hWnd, &ps ))
return ;
if (!RectVisible( ps.hdc, &r1 ))
{
EndPaint( hWnd, &ps ) ;
return ;
}
rgbBtnFace = GetSysColor( COLOR_BTNFACE ) ;
if (lpStatus)
rgStatBox = &lpStatus->rgStatBox[0] ;
else
{
DP1( hWDB, "StatusPaint : lpStatus is NULL!" ) ;
EndPaint( hWnd, &ps ) ;
return ;
}
// Select font
hFont = SelectObject( ps.hdc, GETHFONT( hWnd ) ) ;
GetTextMetrics( ps.hdc, &tm ) ;
SetBkColor( ps.hdc, GetNearestColor( ps.hdc, rgbBtnFace ) ) ;
SetBkMode( ps.hdc, TRANSPARENT ) ;
//
// See if the entire area needs to be painted
//
if (IsRectInRect( &r1, &ps.rcPaint ))
{
HPEN hPen ;
hPen = CreatePen( PS_SOLID, 1, GetSysColor( COLOR_WINDOWFRAME ) ) ;
DP5( hWDB, "Paint entire area" ) ;
if (lpStatus->wNumStats)
{
int n ;
//
// Draw the main
//
if (lpStatus->fNoMsg)
{
// around stat boxes
tdDraw3DRect( ps.hdc, &r1, LINEWIDTH, DRAW3D_OUT ) ;
}
else
{
n = rgStatBox[0].rect.right + (int)(LINEWIDTH * 5) ;
r2.top = r1.top ;
r2.bottom = r1.bottom ;
r2.left = n + 1 ;
r2.right = r1.right ;
r1.right = n ;
// msgline
tdDraw3DRect( ps.hdc, &r1, LINEWIDTH, DRAW3D_OUT ) ;
// around stat boxes
tdDraw3DRect( ps.hdc, &r2, LINEWIDTH, DRAW3D_OUT ) ;
}
//
// Message
//
if ((!lpStatus->fNoMsg) && rgStatBox[0].fBorder)
{
CopyRect( &r2, &rgStatBox[0].rect ) ;
tdDraw3DRect( ps.hdc, &r2, LINEWIDTH, DRAW3D_IN ) ;
}
//
// stat boxes
//
for (i = 0 ; i < (int)lpStatus->wNumStats ; i++)
{
if (rgStatBox[i+1].fBorder)
{
CopyRect( &r2, &rgStatBox[i+1].rect ) ;
tdDraw3DRect( ps.hdc, &r2, LINEWIDTH, DRAW3D_IN ) ;
}
}
if (!lpStatus->fNoMsg)
{
hPen = SelectObject( ps.hdc, hPen ) ;
#ifndef WIN32
MoveTo( ps.hdc, n, 0 ) ;
#else
MoveToEx( ps.hdc, n, 0, NULL ) ;
#endif
LineTo( ps.hdc, n, r1.bottom ) ;
hPen = SelectObject( ps.hdc, hPen ) ;
}
}
else
{
//
// msgline only
//
tdDraw3DRect( ps.hdc, &r1, LINEWIDTH, DRAW3D_OUT ) ;
if (rgStatBox[0].fBorder)
{
CopyRect( &r1, &rgStatBox[0].rect ) ;
tdDraw3DRect( ps.hdc, &r1, LINEWIDTH, DRAW3D_IN ) ;
}
}
DeleteObject( hPen ) ;
}
if (!lpStatus->fNoMsg)
{
UINT ui = GetWindowTextLength( hWnd ) ;
LPSTR lpszText = GlobalAllocPtr( GHND, ui + 1 ) ;
if (lpszText)
{
GetWindowText( hWnd, lpszText, ui + 1 ) ;
if (lstrlen(lpszText) || !lpStatus->hszDefault)
DrawItem( hWnd, &ps, &rgStatBox[0], (UINT)-1, lpszText ) ;
else
{
LPSTR lpsz = GlobalLock( lpStatus->hszDefault) ;
DrawItem( hWnd, &ps, &rgStatBox[0], (UINT)-1, lpsz ) ;
GlobalUnlock( lpStatus->hszDefault ) ;
}
GlobalFreePtr( lpszText ) ;
}
}
for (i = 0 ; i < (int)lpStatus->wNumStats ; i++)
DrawItem( hWnd, &ps, &rgStatBox[i+1], i, NULL ) ;
SelectObject( ps.hdc, hFont ) ;
EndPaint( hWnd, &ps ) ;
}/* StatusPaint() */
/****************************************************************
* BOOL NEAR PASCAL DrawItem( HWND hwnd, LPPAINTSTRUCT lpps,
* LPSTATBOX lpStatBox, UINT uiID, LPSTR lpszText )
*
* Description:
*
* This routine draws a given statbox at the x,y offset.
*
* It is also used to draw the msg, and generates the
* ownerdraw messages if needed.
*
* Comments:
*
****************************************************************/
static BOOL NEAR PASCAL DrawItem( HWND hwnd, LPPAINTSTRUCT lpps,
LPSTATBOX lpStatBox, UINT uiID, LPSTR lpszText )
{
RECT r1 ;
if (lpStatBox->fOwnerDraw)
{
if (lpStatBox->fBorder)
{
r1.top = lpStatBox->rect.top + (int)wExtraSpace ;
r1.bottom = lpStatBox->rect.bottom - (int)LINEWIDTH ;
r1.left = lpStatBox->rect.left + (int)(LINEWIDTH) ;
r1.right = lpStatBox->rect.right - (int)(LINEWIDTH) ;
}
else
{
r1.top = lpStatBox->rect.top + (int)wExtraSpace - 1 ;
r1.bottom = lpStatBox->rect.bottom - (int)LINEWIDTH + 1 ;
r1.left = lpStatBox->rect.left ;
r1.right = lpStatBox->rect.right ;
}
if (IsRectInRect( &r1, &lpps->rcPaint ))
{
DRAWITEMSTRUCT dis ;
dis.CtlType = ODT_STATUS ;
dis.CtlID = GetWindowID(hwnd) ;
dis.itemID = uiID ;
dis.itemAction = ODA_DRAWENTIRE ;
dis.itemState = 0 ;
dis.hwndItem = hwnd ;
dis.hDC = lpps->hdc ;
dis.rcItem = r1 ;
if (lpszText)
dis.itemData = (DWORD)lpszText ;
else
dis.itemData = (DWORD)lpStatBox->szCurStat ;
if (SendMessage( GetParent( hwnd ), WM_DRAWITEM, GetWindowID( hwnd ),
(LPARAM)(LPDRAWITEMSTRUCT)&dis ))
lpStatBox->fTouched = FALSE ;
}
return TRUE ;
}
r1.top = lpStatBox->rect.top + (int)wExtraSpace - 1 ;
r1.bottom = lpStatBox->rect.bottom - (int)LINEWIDTH + 1 ;
r1.left = lpStatBox->rect.left + (int)(LINEWIDTH*3) ;
r1.right = lpStatBox->rect.right - (int)(LINEWIDTH*3) ;
if (lpStatBox->fTouched ||
IsRectInRect( &r1, &lpps->rcPaint ))
{
if (lpStatBox->fColorSet)
SetTextColor( lpps->hdc, lpStatBox->rgbColor ) ;
else
SetTextColor( lpps->hdc, GetSysColor( COLOR_BTNTEXT ) ) ;
//
// Draw each stat box
//
if (lpszText)
{
DP( hWDB, "lpszText = %s", (LPSTR) lpszText ) ;
DrawText( lpps->hdc, lpszText, -1, &r1,
DT_SINGLELINE |
// DT_NOCLIP |
DT_TOP |
DT_NOPREFIX |
lpStatBox->wJustify ) ;
}
else
{
DrawText( lpps->hdc, lpStatBox->szCurStat, -1, &r1,
DT_SINGLELINE |
DT_NOCLIP |
DT_TOP |
DT_NOPREFIX |
lpStatBox->wJustify ) ;
}
lpStatBox->fTouched = FALSE ;
}
return TRUE ;
} /* DrawItem() */
/*************************************************************************
* static BOOL CheckClick( HWND, LONG, LPUINT ) ;
*
* Description:
*
* Type/Parameter
* Description
*
* Return Value
* Returns one of the following values:
*
* Value
* Meaning
*
*
* Comments:
*
*************************************************************************/
static BOOL NEAR PASCAL CheckClick( HWND hWnd, LPARAM lParam, LPWORD lpwID )
{
LPSTATUS lpStatus ;
LPSTATBOX rgStatBox ;
short n ;
int x, y ;
if (!hWnd)
{
return FALSE ;
}
//
// get the global handle from the window extra bytes
//
lpStatus = GETLPSTATUS( hWnd ) ;
if (lpStatus)
{
rgStatBox = &lpStatus->rgStatBox[0] ;
}
else
return FALSE ;
x = LOWORD( lParam ) ;
y = HIWORD( lParam ) ;
if (x >= rgStatBox[0].rect.left &&
x <= rgStatBox[0].rect.right &&
y >= rgStatBox[0].rect.top &&
y <= rgStatBox[0].rect.bottom)
{
*lpwID = (WORD)0xFFFF ;
return TRUE ;
}
for (n = 0 ; n < (short)lpStatus->wNumStats ; n++)
if (x >= rgStatBox[n+1].rect.left &&
x <= rgStatBox[n+1].rect.right &&
y >= rgStatBox[n+1].rect.top &&
y <= rgStatBox[n+1].rect.bottom)
{
*lpwID = n ;
return TRUE ;
}
return FALSE ;
}/* CheckClick() */
/************************************************************************
* static BOOL IsRectInRect( LPRECT lpR1, LPRECT lpR2 ) ;
*
* Description:
* Tests if lpR2 is in lpR1.
*
*
* Comments:
*
************************************************************************/
static BOOL NEAR PASCAL IsRectInRect( LPRECT lpR1, LPRECT lpR2 )
{
HRGN hrgn ;
BOOL bInRect ;
if (hrgn = CreateRectRgn( lpR1->left, lpR1->top, lpR1->right, lpR1->bottom ))
{
bInRect = RectInRegion( hrgn, lpR2 ) ;
DeleteObject( hrgn ) ;
}
else
bInRect = TRUE ;
return bInRect ;
}/* IsRectInRect() */
#ifdef SHADOWSTUFF
#define SHADOWWIDTH 1
/** VOID WINAPI tdDraw3DRect( HDC, LPRECT, UINT, UINT )
*
* DESCRIPTION:
* Draws a 3D rectangle that is shaded. wFlags can be used to
* control how the rectangle looks.
*
* ARGUMENTS:
* HDC hDC : Handle to the device context that will be
* used to display the rectangle.
*
* RECT rect : A rectangle describing the dimensions of
* the rectangle in device coordinates.
*
* UINT wShadowWidth : Width of the shadow in device coordinates.
*
* UINT wFlags : The following flags may be passed to describe
* the style of the rectangle:
*
* DRAW3D_IN : The shadow is drawn such that
* the box appears to be sunk in to the screen.
* This is default if 0 is passed.
*
* DRAW3D_OUT : The shadow is drawn such that
* the box appears to be sticking out of the
* screen.
*
* RETURN (VOID WINAPI):
* The 3D looking rectangle will have been drawn into the DC.
*
* NOTES:
*
** cjp */
VOID WINAPI tdDraw3DRect( HDC hDC, LPRECT lpRect,
UINT wShadowWidth, UINT wFlags )
{
/* sanity check--don't work if you don't have to! */
if ( !wShadowWidth || !RectVisible( hDC, lpRect ) )
return ;
/* draw the top line */
tdDraw3DLine( hDC, lpRect->left, lpRect->top,
lpRect->right - lpRect->left,
wShadowWidth, DRAW3D_TOPLINE | wFlags ) ;
/* right line */
tdDraw3DLine( hDC, lpRect->right, lpRect->top,
lpRect->bottom - lpRect->top,
wShadowWidth, DRAW3D_RIGHTLINE | wFlags ) ;
/* bottom line */
tdDraw3DLine( hDC, lpRect->left, lpRect->bottom,
lpRect->right - lpRect->left,
wShadowWidth, DRAW3D_BOTTOMLINE | wFlags ) ;
/* left line */
tdDraw3DLine( hDC, lpRect->left, lpRect->top,
lpRect->bottom - lpRect->top,
wShadowWidth, DRAW3D_LEFTLINE | wFlags ) ;
} /* Draw3DRect() */
/** VOID WINAPI tdDraw3DLine( HDC hDC, UINT x, UINT y, UINT nLen,
*
* DESCRIPTION:
* Draws a 3D line that can be used to make a 3D box.
*
* ARGUMENTS:
* HDC hDC : Handle to the device context that will be
* used to display the 3D line.
*
* UINT x, y : Coordinates of the beginning of the line.
* These coordinates are in device UINTs and
* represent the _outside_ most point. Horiz-
* ontal lines are drawn from left to right and
* vertical lines are drawn from top to bottom.
*
* UINT wShadowWidth : Width of the shadow in device coordinates.
*
* UINT wFlags : The following flags may be passed to
* describe the style of the 3D line:
*
* DRAW3D_IN : The shadow is drawn such that
* the box appears to be sunk in to the screen.
* This is default if 0 is passed.
*
* DRAW3D_OUT : The shadow is drawn such that
* the box appears to be sticking out of the
* screen.
*
* DRAW3D_TOPLINE, _BOTTOMLINE, _LEFTLINE, and
* _RIGHTLINE : Specifies that a "top",
* "Bottom", "Left", or"Right" line is to be
* drawn.
*
* RETURN (VOID WINAPI):
* The line will have been drawn into the DC.
*
* NOTES:
*
** cjp */
VOID WINAPI tdDraw3DLine( HDC hDC, UINT x, UINT y, UINT nLen,
UINT wShadowWidth, UINT wFlags )
{
HBRUSH hOldBrush ;
HBRUSH hBrush ;
HPEN hOldPen ;
BOOL fDark ;
POINT Point[ 4 ] ; /* define a polgon with 4 points */
/* if width is zero, don't do nothin'! */
if ( !wShadowWidth )
return ;
/* if width is 1 use lines instead of polygons */
if (wShadowWidth == 1 /*|| bMonochrome*/)
{
tdDraw3DLine1( hDC, x, y, nLen, wFlags ) ;
return ;
}
/* define shape of polygon--origin is always the same */
Point[0].x = x ;
Point[0].y = y ;
/* To do this we'll simply draw a polygon with four sides, using
* the appropriate brush. I dare you to ask me why this isn't a
* switch/case!
*/
if ( wFlags & DRAW3D_TOPLINE )
{
/* across to right */
Point[1].x = x + nLen - (wShadowWidth == 1 ? 1 : 0) ;
Point[1].y = y ;
/* down/left */
Point[2].x = x + nLen - wShadowWidth ;
Point[2].y = y + wShadowWidth ;
/* accross to left */
Point[3].x = x + wShadowWidth ;
Point[3].y = y + wShadowWidth ;
/* select 'dark' brush if 'in'--'light' for 'out' */
fDark = ( wFlags & DRAW3D_IN ) ? TRUE : FALSE ;
}
/* possibly the bottom? */
else if ( wFlags & DRAW3D_BOTTOMLINE )
{
/* across to right */
Point[1].x = x + nLen ;
Point[1].y = y ;
/* up/left */
Point[2].x = x + nLen - wShadowWidth ;
Point[2].y = y - wShadowWidth ;
/* accross to left */
Point[3].x = x + wShadowWidth ;
Point[3].y = y - wShadowWidth ;
/* select 'light' brush if 'in' */
fDark = ( wFlags & DRAW3D_IN ) ? FALSE : TRUE ;
}
/* ok, it's gotta be left? */
else if ( wFlags & DRAW3D_LEFTLINE )
{
/* down */
Point[1].x = x ;
Point[1].y = y + nLen - (wShadowWidth == 1 ? 1 : 0) ;
/* up/right */
Point[2].x = x + wShadowWidth ;
Point[2].y = y + nLen - wShadowWidth ;
/* down */
Point[3].x = x + wShadowWidth ;
Point[3].y = y + wShadowWidth ;
/* select 'dark' brush if 'in'--'light' for 'out' */
fDark = ( wFlags & DRAW3D_IN ) ? TRUE : FALSE ;
}
/* well maybe it's for the right side? */
else if ( wFlags & DRAW3D_RIGHTLINE )
{
/* down */
Point[1].x = x ;
Point[1].y = y + nLen ;
/* up/left */
Point[2].x = x - wShadowWidth ;
Point[2].y = y + nLen - wShadowWidth ;
/* up */
Point[3].x = x - wShadowWidth ;
Point[3].y = y + wShadowWidth ;
/* select 'light' brush if 'in' */
fDark = ( wFlags & DRAW3D_IN ) ? FALSE : TRUE ;
}
/* bad drugs? */
else return ;
/* select NULL_PEN for no borders */
hOldPen = SelectObject( hDC, GetStockObject( NULL_PEN ) ) ;
/* select the appropriate color for the fill */
if ( fDark )
hBrush = CreateSolidBrush( GetNearestColor( hDC,
tdGetShadowColor( GetBkColor( hDC ) ) ) ) ;
else
hBrush = CreateSolidBrush( GetNearestColor( hDC,
tdGetHighlightColor( GetBkColor( hDC ) ) ) ) ;
hOldBrush = SelectObject( hDC, hBrush ) ;
/* finally, draw the dern thing */
Polygon( hDC, (LPPOINT)&Point, 4 ) ;
/* restore what we killed */
SelectObject( hDC, hOldBrush ) ;
DeleteObject( hBrush ) ;
SelectObject( hDC, hOldPen ) ;
} /*tdDraw3DLine() */
/****************************************************************
* VOID WINAPI
* tdDraw3DLine1( HDC hDC, UINT x, UINT y, UINT nLen, UINT wFlags )
*
* Description:
*
* Does the same thing astdDraw3DLine but for single width lines.
*
* Comments:
*
****************************************************************/
VOID WINAPI
tdDraw3DLine1( HDC hDC, UINT x, UINT y, UINT nLen, UINT wFlags )
{
BOOL fDark ;
RECT rc ;
COLORREF rgbOld ;
if ( wFlags & DRAW3D_TOPLINE )
{
rc.left = x ;
rc.right = rc.left + nLen - 1 ;
rc.top = y ;
rc.bottom = y + 1 ;
fDark = ( wFlags & DRAW3D_IN ) ? TRUE : FALSE ;
}
/* possibly the bottom? */
else if ( wFlags & DRAW3D_BOTTOMLINE )
{
rc.left = x ;
rc.right = rc.left + nLen - 1 ;
rc.top = y - 1 ;
rc.bottom = y ;
fDark = ( wFlags & DRAW3D_IN ) ? FALSE : TRUE ;
}
/* ok, it's gotta be left? */
else if ( wFlags & DRAW3D_LEFTLINE )
{
rc.left = x ;
rc.right = x + 1 ;
rc.top = y ;
rc.bottom = y + nLen ;
fDark = ( wFlags & DRAW3D_IN ) ? TRUE : FALSE ;
}
/* well maybe it's for the right side? */
else if ( wFlags & DRAW3D_RIGHTLINE )
{
rc.left = x - 1 ;
rc.right = x ;
rc.top = y ;
rc.bottom = y + nLen ;
fDark = ( wFlags & DRAW3D_IN ) ? FALSE : TRUE ;
}
/* bad drugs? */
else return ;
/* select the appropriate color for the fill */
if ( fDark /*|| bMonochrome*/ )
rgbOld = SetBkColor( hDC,
GetNearestColor( hDC, tdGetShadowColor( GetBkColor( hDC ) ) ) ) ;
else
rgbOld = SetBkColor( hDC,
GetNearestColor( hDC, tdGetHighlightColor( GetBkColor( hDC ) ) ) ) ;
/* finally, draw the dern thing */
ExtTextOut( hDC, x, y, ETO_OPAQUE, &rc, NULL, 0, NULL ) ;
SetBkColor( hDC, rgbOld ) ;
} /* tdDraw3DLine1() */
/****************************************************************
* COLORREF WINAPI tdGetHighLightColor( COLORREF rgb )
*
* Description:
*
* This function returns the highlight color that corresponds
* to the given rgb value. If there is no "high intensity"
* color that matches, white is used (or yellow if the color
* is white).
*
* Comments:
*
****************************************************************/
COLORREF WINAPI tdGetHighlightColor( COLORREF rgb )
{
BYTE cRed, cGreen, cBlue ;
if (rgb == RGBLTRED ||
rgb == RGBLTGREEN ||
rgb == RGBLTBLUE ||
rgb == RGBLTMAGENTA ||
rgb == RGBLTCYAN ||
rgb == RGBLTGRAY ||
rgb == RGBYELLOW)
return RGBWHITE ;
if (rgb == RGBWHITE)
return RGBLTGRAY ;
if (rgb == RGBBLACK || rgb == RGBGRAY)
return RGBLTGRAY ;
cRed = (BYTE)(rgb & 0x000000FF) ;
cGreen = (BYTE)((rgb & 0x0000FF00) >> 8) ;
cBlue = (BYTE)((rgb & 0x00FF0000) >> 16) ;
if (cRed == 128)
cRed += 64 ;
if (cGreen == 128)
cGreen += 64 ;
if (cBlue == 128)
cBlue += 64 ;
return RGB( cRed, cGreen, cBlue ) ;
} /* tdGetHighlightColor() */
/****************************************************************
* COLORREF WINAPI tdGetShadowColor( COLORREF rgb )
*
* Description:
*
* Returns an appropriate shadow color for the given rgb.
*
* Comments:
*
****************************************************************/
COLORREF WINAPI tdGetShadowColor( COLORREF rgb )
{
BYTE cRed, cGreen, cBlue ;
if (rgb == RGBBLACK)
return RGBGRAY ;
if (rgb == RGBRED ||
rgb == RGBGREEN ||
rgb == RGBBLUE ||
rgb == RGBBROWN ||
rgb == RGBMAGENTA ||
rgb == RGBCYAN ||
rgb == RGBWHITE ||
rgb == RGBGRAY)
return RGBBLACK ;
if (rgb == RGBLTGRAY)
return RGBGRAY ;
cRed = (BYTE)(rgb & 0x000000FF) ;
cGreen = (BYTE)((rgb & 0x0000FF00) >> 8) ;
cBlue = (BYTE)((rgb & 0x00FF0000) >> 16) ;
if (cRed > 128)
cRed -= 64 ;
if (cGreen > 128)
cGreen -= 64 ;
if (cBlue > 128)
cBlue -= 64 ;
return RGB( cRed, cGreen, cBlue ) ;
} /* tdGetShadowColor() */
/****************************************************************
* COLORREF WINAPI tdMapTextColor( COLORREF rgb )
*
* Description:
*
* Returns an appropriate text color for the given bg.
*
* Comments:
*
****************************************************************/
COLORREF WINAPI tdMapTextColor( COLORREF rgb )
{
return rgb = GetSysColor( COLOR_WINDOWTEXT ) ;
if (rgb == RGBRED ||
rgb == RGBGREEN ||
rgb == RGBBLUE ||
rgb == RGBBROWN ||
rgb == RGBMAGENTA ||
rgb == RGBGRAY ||
rgb == RGBBLACK)
return RGBWHITE ;
return RGBBLACK ;
} /* tdMapTextColor() */
#endif
/************************************************************************
* End of File: status.c
************************************************************************/
| 28.592737 | 110 | 0.46781 | [
"shape",
"3d"
] |
348bbe2313396c9e51958e01e4ff38a6259fbaa1 | 22,286 | c | C | code-samples/mandelbrot/do_fluid_movement/do_fluid_continuous_demo.c | Leo-Lee-L/terasic-de10-nano-kit | a7777d713c557691e566b0db6d9522de1e672034 | [
"MIT"
] | 81 | 2017-05-05T17:47:12.000Z | 2022-03-25T23:17:24.000Z | code-samples/mandelbrot/do_fluid_movement/do_fluid_continuous_demo.c | Leo-Lee-L/terasic-de10-nano-kit | a7777d713c557691e566b0db6d9522de1e672034 | [
"MIT"
] | 5 | 2018-12-16T02:36:04.000Z | 2022-03-16T01:40:38.000Z | code-samples/mandelbrot/do_fluid_movement/do_fluid_continuous_demo.c | Leo-Lee-L/terasic-de10-nano-kit | a7777d713c557691e566b0db6d9522de1e672034 | [
"MIT"
] | 40 | 2017-03-30T20:23:55.000Z | 2022-03-27T06:53:21.000Z | //
// Copyright (c) 2017 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <assert.h>
#include "do_fluid_movement/movement_functions.h"
#include "de10_init/de10_init.h"
#include "font_support/font_def_public.h"
#include "font_support/font_public.h"
#include "pix_map_routines/pix_map_base_routines.h"
#include "mandelbrot.h"
static struct abc_font_struct *g_banner_font = &cousine_bold_18;
static uint32_t g_banner_height;
static uint32_t g_banner_fps_width;
static uint32_t g_banner_cpu_width;
static uint32_t g_banner_current_offset;
static uint32_t g_banner_start_pixel;
static float g_latest_fps_value;
pthread_mutex_t g_fps_mutex;
pthread_cond_t g_fps_cond;
uint32_t g_fps_count;
static char *g_crawl_algo_str_ptr = NULL;
static char *g_crawl_hw_str_ptr = NULL;
static char *g_crawl_sw_str_ptr = NULL;
static uint32_t g_buffered_video_mode = 1;
static void * do_fps_banner_thread(void *arg);
static void * do_cpu_banner_thread(void *arg);
static void *do_banner_crawler_thread(void *arg);
// This routine is the loop overhead for the continuous demo.
// The coordinates below are some of the interesting points in the Mandelbrot
// set.
void do_fluid_continuous_demo(void) {
void *pixel_buf_ptr;
uint32_t pixmap_width = get_fb_width();
uint32_t pixmap_height = get_fb_height();
struct coordinates {
double x; // x_center
double y; // y_center
double dim_x; // x_dim(final zoom width of x axis)
int max_iterations; // max iterations
} demo_locations[NUMBER_OF_COORDINATES] = {
{-1.760, 0.0, 0.05, 500}, // 1
{-1.4781768172979355, 0.0, 0.01508731722831726, 50}, // 2
{-0.006125070457284523, -0.8077499668488658, 1.6338581430231508E-4, 500}, // 3
{-0.5570354129425543, 0.6352957489439464, 9.274065304888445E-4, 100}, // 4
{0.42450820043388005, 0.2075353308053001, 3.301533972620563E-4, 100}, // 5
{-0.7625592537807768, 0.08955441532683481, 4.171464390594348E-4, 200}, // 6
{0.35805511474609375, 0.6436386108398438, 0.0259552001953125, 50}, // 7
{-0.10489989636229237, 0.9278526131989105, 2.3876997962775084E-4, 500}, // 8
{-1.447650909, 0.000000000, 0.003, 500}, // 9
{-1.457741737, 0.000000000, 0.000366211, 500}, // 10
{-0.563892365, 0.667407990, 0.001464844, 500}, // 11
{-0.597400665, 0.663105011, 0.005859375, 500}, // 12
{-0.488316298, 0.609600782, 0.000122070, 700}, // 13
};
double previous_x = 0.25;
double previous_y = 0.0;
double next_x, next_y, next_dim_x;
int i, next_maxiterations;
uint32_t mandel_height;
int result;
pthread_t fps_banner_thread;
pthread_t cpu_banner_thread;
pthread_t banner_crawler_thread;
// configure hardware algorithm to start with
set_g_draw_with_hw(1);
g_crawl_algo_str_ptr = g_crawl_hw_str_ptr;
// calculate banner geometry
g_banner_height = g_banner_font[0].bounds_height;
if(g_banner_height & 0x01)
g_banner_height++;
g_banner_fps_width = get_string_line_width(g_banner_font,
(char *)"FPS:000.00");
g_banner_fps_width += BANNER_WIDTH_AIR;
g_banner_cpu_width = get_string_line_width(g_banner_font,
(char *)"XX algo %CPU:000.00");
g_banner_cpu_width += BANNER_WIDTH_AIR;
g_banner_current_offset = 0;
mandel_height = pixmap_height - g_banner_height;
g_banner_start_pixel = mandel_height * pixmap_width;
pixel_buf_ptr = get_g_mandelbrot_fb_map();
fill_pix_map_32(
(char *)(&((uint32_t *)pixel_buf_ptr)[g_banner_start_pixel]), // char *dest_ptr,
pixmap_width, // long dest_active_width,
g_banner_height, // long dest_active_height,
pixmap_width, // long dest_line_width,
0x00000000 // long fill_color
);
pixel_buf_ptr = get_g_spare_0_fb_map();
fill_pix_map_32(
(char *)(&((uint32_t *)pixel_buf_ptr)[g_banner_start_pixel]), // char *dest_ptr,
pixmap_width, // long dest_active_width,
g_banner_height, // long dest_active_height,
pixmap_width, // long dest_line_width,
0x00000000 // long fill_color
);
pixel_buf_ptr = get_g_spare_1_fb_map();
fill_pix_map_32(
(char *)(&((uint32_t *)pixel_buf_ptr)[g_banner_start_pixel]), // char *dest_ptr,
pixmap_width, // long dest_active_width,
g_banner_height, // long dest_active_height,
pixmap_width, // long dest_line_width,
0x00000000 // long fill_color
);
pixel_buf_ptr = get_g_mandelbrot_fb_map();
// start banner threads
if(g_buffered_video_mode == 1)
start_buffered_video();
g_fps_count = 0;
result = pthread_cond_init(&g_fps_cond, NULL);
assert(result == 0);
result = pthread_mutex_init(&g_fps_mutex, NULL);
assert(result == 0);
result = pthread_create(&fps_banner_thread, NULL, do_fps_banner_thread,
NULL);
assert(result == 0);
result = pthread_create(&cpu_banner_thread, NULL,
do_cpu_banner_thread, NULL);
assert(result == 0);
result = pthread_create(&banner_crawler_thread, NULL,
do_banner_crawler_thread, NULL);
assert(result == 0);
// do continuous loop
set_g_draw_interrupted(0);
while(1) {
for(i = 0; i < NUMBER_OF_COORDINATES; i++) {
/* read in the contents for the next zoom */
next_x = demo_locations[i].x;
next_y = demo_locations[i].y;
next_dim_x = demo_locations[i].dim_x;
next_maxiterations = demo_locations[i].max_iterations;
do_fluid_move(previous_x, previous_y, next_x, next_y,
pixel_buf_ptr, pixmap_width, mandel_height);
if(get_g_draw_interrupted() == 1)
break;
do_fluid_zoom_in(next_x, next_y, next_dim_x,
next_maxiterations, pixel_buf_ptr, pixmap_width,
mandel_height);
if(get_g_draw_interrupted() == 1)
break;
/* save off x and y to do the next move when the loop
rolls around */
previous_x = next_x;
previous_y = next_y;
}
if(get_g_draw_interrupted() == 1)
break;
}
result = pthread_cancel(fps_banner_thread);
assert(result == 0);
result = pthread_cancel(cpu_banner_thread);
assert(result == 0);
result = pthread_cancel(banner_crawler_thread);
assert(result == 0);
result = pthread_join(fps_banner_thread, NULL);
assert(result == 0);
result = pthread_join(cpu_banner_thread, NULL);
assert(result == 0);
result = pthread_join(banner_crawler_thread, NULL);
assert(result == 0);
if(g_buffered_video_mode == 1)
stop_buffered_video();
}
static void thread_cleanup_mutex_unlock(void *arg) {
pthread_mutex_t *mutex_ptr = (pthread_mutex_t *)arg;
int result;
result = pthread_mutex_unlock(mutex_ptr);
assert(result == 0);
}
static void thread_cleanup_free(void *arg) {
free(arg);
}
static void wait_fps_cond(void) {
int result;
uint32_t my_count;
result = pthread_mutex_lock(&g_fps_mutex);
assert(result == 0);
pthread_cleanup_push(thread_cleanup_mutex_unlock, &g_fps_mutex);
my_count = g_fps_count;
while(my_count == g_fps_count) {
result = pthread_cond_wait(&g_fps_cond,
&g_fps_mutex);
assert(result == 0);
}
pthread_cleanup_pop(1);
}
static void * do_fps_banner_thread(void *arg) {
uint32_t *offscreen_draw_buffer;
uint32_t *blend_buffer;
char string_buffer[FPS_STR_LEN];
int snprintf_length;
uint32_t *onscreen_buffer = (uint32_t *)get_g_mandelbrot_fb_map();
uint32_t pixmap_width = get_fb_width();
uint32_t start_pixel = g_banner_start_pixel;
(void)arg;
offscreen_draw_buffer = (uint32_t *)(malloc(sizeof(uint32_t) *
g_banner_fps_width * g_banner_height));
assert(offscreen_draw_buffer != NULL);
pthread_cleanup_push(thread_cleanup_free, offscreen_draw_buffer);
blend_buffer = (uint32_t *)(malloc(sizeof(uint32_t) * 64 * 64));
assert(blend_buffer != NULL);
pthread_cleanup_push(thread_cleanup_free, blend_buffer);
fill_pix_map_32(
(char *)(blend_buffer), // char *dest_ptr,
64, // long dest_active_width,
64, // long dest_active_height,
64, // long dest_line_width,
0x00000000 // long fill_color
);
while(1) {
snprintf_length = snprintf(string_buffer, FPS_STR_LEN,
"FPS:%3.2f", g_latest_fps_value);
assert(snprintf_length < FPS_STR_LEN);
fill_pix_map_32(
(char *)(offscreen_draw_buffer),// char *dest_ptr,
g_banner_fps_width, // long dest_active_width,
g_banner_height, // long dest_active_height,
g_banner_fps_width, // long dest_line_width,
0x00000000 // long fill_color
);
draw_string_line(
g_banner_font, // struct abc_font_struct *theFontStruct, // pointer to the font structure
offscreen_draw_buffer, // uint32_t *theDrawBuffer, // this is the buffer to draw the font into
g_banner_fps_width, // uint32_t theDrawBufferWidth, // this is the pixel line width of the draw buffer
blend_buffer, // uint32_t *theBlendBuffer, // this is the background blend buffer 64X64 32-bit words fill it with the background color 32-bit pixels RGBA format
0x00FFFFFF, // uint32_t theTextColor, // this is the color of the text we draw 32-bit word is this format [0BGR]
string_buffer, // char *the_string, // pointer to the string to draw
g_banner_height, // uint32_t under_line, // the horizontal line number above which the text will draw
g_banner_current_offset,// uint32_t start_x, // the vertical column number that text begins to draw
g_banner_fps_width // uint32_t max_width // maximum horizontal width to draw
);
onscreen_buffer = (uint32_t *)get_g_mandelbrot_fb_map();
copy_pix_map_32_to_32(
(char *)offscreen_draw_buffer, // char *src_ptr,
g_banner_fps_width, // long src_active_width,
g_banner_height, // long src_active_height,
g_banner_fps_width, // long src_line_width,
(char *)(&onscreen_buffer[start_pixel]),// char *dest_ptr,
pixmap_width // long dest_line_width
);
onscreen_buffer = (uint32_t *)get_g_spare_0_fb_map();
copy_pix_map_32_to_32(
(char *)offscreen_draw_buffer, // char *src_ptr,
g_banner_fps_width, // long src_active_width,
g_banner_height, // long src_active_height,
g_banner_fps_width, // long src_line_width,
(char *)(&onscreen_buffer[start_pixel]),// char *dest_ptr,
pixmap_width // long dest_line_width
);
onscreen_buffer = (uint32_t *)get_g_spare_1_fb_map();
copy_pix_map_32_to_32(
(char *)offscreen_draw_buffer, // char *src_ptr,
g_banner_fps_width, // long src_active_width,
g_banner_height, // long src_active_height,
g_banner_fps_width, // long src_line_width,
(char *)(&onscreen_buffer[start_pixel]),// char *dest_ptr,
pixmap_width // long dest_line_width
);
wait_fps_cond();
}
pthread_cleanup_pop(1);
pthread_cleanup_pop(1);
return(NULL);
}
void signal_fps_cond(void) {
int result;
result = pthread_mutex_lock(&g_fps_mutex);
assert(result == 0);
pthread_cleanup_push(thread_cleanup_mutex_unlock, &g_fps_mutex);
g_fps_count++;
result = pthread_cond_broadcast(&g_fps_cond);
assert(result == 0);
pthread_cleanup_pop(1);
}
static void * do_cpu_banner_thread(void *arg) {
float cpu_utilization = 0.0;
uint32_t *offscreen_draw_buffer;
uint32_t *blend_buffer;
char string_buffer[CPU_STR_LEN];
int snprintf_length;
uint32_t *onscreen_buffer = (uint32_t *)get_g_mandelbrot_fb_map();
uint32_t pixmap_width = get_fb_width();
uint32_t start_pixel = g_banner_start_pixel + g_banner_fps_width;
int offset_increment_flag = 1;
(void)arg;
offscreen_draw_buffer = (uint32_t *)(malloc(sizeof(uint32_t) *
g_banner_cpu_width * g_banner_height));
assert(offscreen_draw_buffer != NULL);
pthread_cleanup_push(thread_cleanup_free, offscreen_draw_buffer);
blend_buffer = (uint32_t *)(malloc(sizeof(uint32_t) * 64 * 64));
assert(blend_buffer != NULL);
pthread_cleanup_push(thread_cleanup_free, blend_buffer);
fill_pix_map_32(
(char *)(blend_buffer), // char *dest_ptr,
64, // long dest_active_width,
64, // long dest_active_height,
64, // long dest_line_width,
0x00000000 // long fill_color
);
init_cpu_load();
while(1) {
cpu_utilization = calculate_cpu_load();
snprintf_length = snprintf(string_buffer, CPU_STR_LEN,
"%s algo %%CPU:%0.2f",
(get_g_draw_with_hw()) ? "HW" : "SW",
cpu_utilization);
assert(snprintf_length < CPU_STR_LEN);
fill_pix_map_32(
(char *)(offscreen_draw_buffer),// char *dest_ptr,
g_banner_cpu_width, // long dest_active_width,
g_banner_height, // long dest_active_height,
g_banner_cpu_width, // long dest_line_width,
0x00000000 // long fill_color
);
draw_string_line(
g_banner_font, // struct abc_font_struct *theFontStruct, // pointer to the font structure
offscreen_draw_buffer, // uint32_t *theDrawBuffer, // this is the buffer to draw the font into
g_banner_cpu_width, // uint32_t theDrawBufferWidth, // this is the pixel line width of the draw buffer
blend_buffer, // uint32_t *theBlendBuffer, // this is the background blend buffer 64X64 32-bit words fill it with the background color 32-bit pixels RGBA format
0x00FFFFFF, // uint32_t theTextColor, // this is the color of the text we draw 32-bit word is this format [0BGR]
string_buffer, // char *the_string, // pointer to the string to draw
g_banner_height, // uint32_t under_line, // the horizontal line number above which the text will draw
g_banner_current_offset,// uint32_t start_x, // the vertical column number that text begins to draw
g_banner_cpu_width // uint32_t max_width // maximum horizontal width to draw
);
onscreen_buffer = (uint32_t *)get_g_mandelbrot_fb_map();
copy_pix_map_32_to_32(
(char *)offscreen_draw_buffer, // char *src_ptr,
g_banner_cpu_width, // long src_active_width,
g_banner_height, // long src_active_height,
g_banner_cpu_width, // long src_line_width,
(char *)(&onscreen_buffer[start_pixel]),// char *dest_ptr,
pixmap_width // long dest_line_width
);
onscreen_buffer = (uint32_t *)get_g_spare_0_fb_map();
copy_pix_map_32_to_32(
(char *)offscreen_draw_buffer, // char *src_ptr,
g_banner_cpu_width, // long src_active_width,
g_banner_height, // long src_active_height,
g_banner_cpu_width, // long src_line_width,
(char *)(&onscreen_buffer[start_pixel]),// char *dest_ptr,
pixmap_width // long dest_line_width
);
onscreen_buffer = (uint32_t *)get_g_spare_1_fb_map();
copy_pix_map_32_to_32(
(char *)offscreen_draw_buffer, // char *src_ptr,
g_banner_cpu_width, // long src_active_width,
g_banner_height, // long src_active_height,
g_banner_cpu_width, // long src_line_width,
(char *)(&onscreen_buffer[start_pixel]),// char *dest_ptr,
pixmap_width // long dest_line_width
);
sleep(1);
if(offset_increment_flag == 1) {
if(g_banner_current_offset < (BANNER_WIDTH_AIR - 2)) {
g_banner_current_offset++;
} else {
offset_increment_flag = 0;
g_banner_current_offset--;
}
} else {
if(g_banner_current_offset > 0) {
g_banner_current_offset--;
} else {
offset_increment_flag = 1;
g_banner_current_offset++;
}
}
signal_fps_cond();
}
pthread_cleanup_pop(1);
pthread_cleanup_pop(1);
return(NULL);
}
static void *do_banner_crawler_thread(void *arg) {
int i;
uint32_t *pixmap_buffer;
uint32_t pixmap_width;
uint32_t font_height;
uint32_t string_width;
uint32_t start_x;
uint32_t start_y;
uint32_t first_crawl_pixel;
const char *crawl_format_str;
char crawl_str[1024];
int snprintf_length;
uint32_t crawl_buffer_width;
uint32_t crawl_buffer_height;
uint32_t *crawl_offscreen_buffer;
uint32_t pre_crawl_width;
uint32_t onscreen_crawl_width;
uint32_t *blend_buffer;
char *last_crawl_algo_str_ptr;
(void)arg;
while(1) {
crawl_format_str =
"Mandelbrot fractal currently drawn with the %s algorithm. "
"Press the KEY0 push button to stop the demo and enter the menu. "
"Press the KEY1 push button to toggle between the hardware and "
"software computation algorithms.";
snprintf_length = snprintf(crawl_str, 1024,
crawl_format_str, g_crawl_algo_str_ptr);
assert(snprintf_length < 1024);
last_crawl_algo_str_ptr = g_crawl_algo_str_ptr;
pixmap_buffer = (uint32_t *)(get_g_mandelbrot_fb_map());
pixmap_width = get_fb_width();
font_height = g_banner_height;
pre_crawl_width = g_banner_fps_width + g_banner_cpu_width + 10;
assert(pre_crawl_width < pixmap_width);
onscreen_crawl_width = pixmap_width - pre_crawl_width;
assert(onscreen_crawl_width >= 200);
if(onscreen_crawl_width > 400)
onscreen_crawl_width = 400;
first_crawl_pixel = g_banner_start_pixel + pixmap_width -
onscreen_crawl_width;
string_width = get_string_line_width(
g_banner_font, // struct abc_font_struct *theFontStruct, // pointer to the font structure
crawl_str // char *the_string // pointer to the string to draw
);
crawl_buffer_width = (onscreen_crawl_width * 2) + string_width;
crawl_buffer_height = font_height;
crawl_offscreen_buffer = (uint32_t *)(malloc(sizeof(uint32_t) *
crawl_buffer_width * crawl_buffer_height));
assert(crawl_offscreen_buffer != NULL);
pthread_cleanup_push(thread_cleanup_free,
crawl_offscreen_buffer);
fill_pix_map_32(
(char *)crawl_offscreen_buffer, // char *dest_ptr,
crawl_buffer_width, // long dest_active_width,
crawl_buffer_height, // long dest_active_height,
crawl_buffer_width, // long dest_line_width,
0x00000000 // long fill_color
);
blend_buffer = (uint32_t *)(malloc(sizeof(uint32_t) * 64 * 64));
assert(blend_buffer != NULL);
pthread_cleanup_push(thread_cleanup_free, blend_buffer);
fill_pix_map_32(
(char *)(blend_buffer), // char *dest_ptr,
64, // long dest_active_width,
64, // long dest_active_height,
64, // long dest_line_width,
0x00000000 // long fill_color
);
start_x = onscreen_crawl_width;
start_y = font_height;
draw_string_line(
g_banner_font, // struct abc_font_struct *theFontStruct, // pointer to the font structure
crawl_offscreen_buffer, // uint32_t *theDrawBuffer, // this is the buffer to draw the font into
crawl_buffer_width, // uint32_t theDrawBufferWidth, // this is the pixel line width of the draw buffer
blend_buffer, // uint32_t *theBlendBuffer, // this is the background blend buffer 64X64 32-bit words fill it with the background color 32-bit pixels RGBA format
0x00FFFFFF, // uint32_t theTextColor, // this is the color of the text we draw 32-bit word is this format [0BGR]
crawl_str, // char *the_string, // pointer to the string to draw
start_y, // uint32_t under_line, // the horizontal line number above which the text will draw
start_x, // uint32_t start_x, // the vertical column number that text begins to draw
string_width + 1 // uint32_t max_width // maximum horizontal width to draw
);
while(1) {
for(i = 0 ; i < (int)(crawl_buffer_width -
onscreen_crawl_width) ; i++) {
pixmap_buffer =
(uint32_t *)get_g_mandelbrot_fb_map();
copy_pix_map_32_to_32(
(char *)(&crawl_offscreen_buffer[i]), // char *src_ptr,
onscreen_crawl_width, // long src_active_width,
crawl_buffer_height, // long src_active_height,
crawl_buffer_width, // long src_line_width,
(char *)(&pixmap_buffer[first_crawl_pixel]), // char *dest_ptr,
pixmap_width // long dest_line_width
);
pixmap_buffer =
(uint32_t *)get_g_spare_0_fb_map();
copy_pix_map_32_to_32(
(char *)(&crawl_offscreen_buffer[i]), // char *src_ptr,
onscreen_crawl_width, // long src_active_width,
crawl_buffer_height, // long src_active_height,
crawl_buffer_width, // long src_line_width,
(char *)(&pixmap_buffer[first_crawl_pixel]), // char *dest_ptr,
pixmap_width // long dest_line_width
);
pixmap_buffer =
(uint32_t *)get_g_spare_1_fb_map();
copy_pix_map_32_to_32(
(char *)(&crawl_offscreen_buffer[i]), // char *src_ptr,
onscreen_crawl_width, // long src_active_width,
crawl_buffer_height, // long src_active_height,
crawl_buffer_width, // long src_line_width,
(char *)(&pixmap_buffer[first_crawl_pixel]), // char *dest_ptr,
pixmap_width // long dest_line_width
);
usleep(10000);
if(last_crawl_algo_str_ptr !=
g_crawl_algo_str_ptr)
break;
};
if(last_crawl_algo_str_ptr !=
g_crawl_algo_str_ptr)
break;
};
pthread_cleanup_pop(1);
pthread_cleanup_pop(1);
}
return(NULL);
}
void set_g_latest_fps_value(float new_value) {
g_latest_fps_value = new_value;
}
char *get_g_crawl_algo_str_ptr(void) {
return(g_crawl_algo_str_ptr);
}
char *get_g_crawl_hw_str_ptr(void) {
return(g_crawl_hw_str_ptr);
}
char *get_g_crawl_sw_str_ptr(void) {
return(g_crawl_sw_str_ptr);
}
void set_g_crawl_algo_str_ptr(char *new_str_ptr) {
g_crawl_algo_str_ptr = new_str_ptr;
}
void set_g_crawl_hw_str_ptr(char *new_str_ptr) {
g_crawl_hw_str_ptr = new_str_ptr;
}
void set_g_crawl_sw_str_ptr(char *new_str_ptr) {
g_crawl_sw_str_ptr = new_str_ptr;
}
uint32_t get_g_banner_height(void) {
return(g_banner_height);
}
uint32_t get_g_banner_start_pixel(void) {
return(g_banner_start_pixel);
}
uint32_t get_g_buffered_video_mode(void) {
return(g_buffered_video_mode);
}
void set_g_buffered_video_mode(uint32_t new_mode) {
g_buffered_video_mode = new_mode;
}
| 32.534307 | 167 | 0.732343 | [
"geometry"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.